protected override object InternalVisit(GroupByClause node) { //node.GroupByOption return(new Func <Environment, IResultTable>((env) => { var selectedColumns = node.GroupingSpecifications.SelectMany(element => { return EvaluateExpression <Func <IResultTable, Selector[]> >(element, env)(env.CurrentTable); }).ToArray(); return new RecordTable(env.CurrentTable.TableName, selectedColumns, env.CurrentTable.Records) .Filter(Filter.Distinct); })); }
protected override object InternalVisit(OutputClause node) { return(new Func <Environment, Func <IResultTable, Selector[]> >( (env) => { return new Func <IResultTable, Selector[]>((table) => { return node.SelectColumns.SelectMany( (element) => { return EvaluateExpression <Func <IResultTable, Selector[]> >(element, env)(table); }).ToArray(); }); })); }
/**********************************************************************************************//** * Evaluates. * * \author Ilan Hindy * \date 29/09/2016 * * \param list1 The first list. * \param list2 The second list. * \param evaluateExpressionFunc The evaluate expression function. * * \return true if it succeeds, false if it fails. * . **************************************************************************************************/ private bool Evaluate(List <dynamic> list1, List <dynamic> list2, EvaluateExpression evaluateExpressionFunc) { if (list1.Count == 0 || list2.Count == 0) { return(false); } ListEvaluationModes evaluationMode = or[brp.ork.ListEvaluationMode]; switch (evaluationMode) { case ListEvaluationModes.AllTrueFromAllValuesToAllValues: return(EvaluateAllToAll(list1, list2, evaluateExpressionFunc)); case ListEvaluationModes.OneTrueFromAllValuesToAllValues: return(EvaluateAllToAll(list1, list2, evaluateExpressionFunc)); case ListEvaluationModes.AllTrueFromAllVluesPairs: return(EvaluateByPairs(list1, list2, evaluateExpressionFunc)); case ListEvaluationModes.OneTrueFromAllValuesPairs: return(EvaluateByPairs(list1, list2, evaluateExpressionFunc)); default: return(false); } }
/**********************************************************************************************//** * Evaluate by pairs. * * \author Ilan Hindy * \date 29/09/2016 * * \param list1 The first list. * \param list2 The second list. * \param evaluateExpressionFunc The evaluate expression function. * * \return true if it succeeds, false if it fails. * . **************************************************************************************************/ private bool EvaluateByPairs(List <dynamic> list1, List <dynamic> list2, EvaluateExpression evaluateExpressionFunc) { ListEvaluationModes evaluationMode = or[brp.ork.ListEvaluationMode]; if (list1.Count != list2.Count) { if (evaluationMode == ListEvaluationModes.AllTrueFromAllVluesPairs) { return(false); } } int count = Math.Min(list1.Count, list2.Count); List <Parameters> allPossiblePairs = new List <Parameters>(); for (int idx = 0; idx < count; idx++) { allPossiblePairs.Add(new Parameters() { parameter1 = list1[idx], parameter2 = list2[idx] }); } if (evaluationMode == ListEvaluationModes.AllTrueFromAllVluesPairs) { return(!allPossiblePairs.Any(pair => EvaluatePair(pair.parameter1, pair.parameter2, evaluateExpressionFunc) == false)); } else //evaluationMode == ListEvaluationModes.OneTrueFromAllValuesPairs { return(allPossiblePairs.Any(pair => EvaluatePair(pair.parameter1, pair.parameter2, evaluateExpressionFunc) == true)); } }
public void Check() //点击submit之后调用这个函数 { expression = GameObject.Find("InputField").GetComponent <GetInput>().formula; //读取输入的值 //判定是不是等于24 calculate_Result_string = Convert.ToString(EvaluateExpression.Calculate(expression)); calculate_Result_int = Convert.ToInt32(calculate_Result_string);//把结果转成int类型 if (calculate_Result_int == 24) { result = true; } //判定是不是只有数字和加减乘除和# for (int i = 0; i < expression.Length; i++) { if ((expression[i] < 48 || expression[i] > 57)) { if (expression[i] != '+' && expression[i] != '-' && expression[i] != '*' && expression[i] != '/' && expression[i] != '#' && expression[i] != '(' && expression[i] != ')' && expression[i] != '(' && expression[i] != ')') { symbol = false; } } } //判断是不是只用了给定的四个数 givenCard(); }
/**********************************************************************************************//** * Evaluate all to all. * * \author Ilan Hindy * \date 29/09/2016 * * \param list1 The first list. * \param list2 The second list. * \param evaluateExpressionFunc The evaluate expression function. * * \return true if it succeeds, false if it fails. * . **************************************************************************************************/ private bool EvaluateAllToAll(List <dynamic> list1, List <dynamic> list2, EvaluateExpression evaluateExpressionFunc) { ListEvaluationModes evaluationMode = or[brp.ork.ListEvaluationMode]; List <Parameters> allPossiblePairs = new List <Parameters>(); foreach (dynamic parameterFromList1 in list1) { foreach (dynamic parameterFromList2 in list2) { allPossiblePairs.Add(new Parameters() { parameter1 = parameterFromList1, parameter2 = parameterFromList2 }); } } if (evaluationMode == ListEvaluationModes.AllTrueFromAllValuesToAllValues) { return(!allPossiblePairs.Any(pair => EvaluatePair(pair.parameter1, pair.parameter2, evaluateExpressionFunc) == false)); } else // evaluationMode == ListEvaluationModes.OneTrueFromAllValuesToAllValues { return(allPossiblePairs.Any(pair => EvaluatePair(pair.parameter1, pair.parameter2, evaluateExpressionFunc) == true)); } }
public void FirstTry_Easy_Expression_With_Sum() { var eval = new EvaluateExpression(); int result = eval.FirstTry("(1+2)"); Assert.Equal(3, result); }
public void FirstTry_Easy_Expression_With_Division() { var eval = new EvaluateExpression(); int result = eval.FirstTry("(4 / 2)"); Assert.Equal(2, result); }
public void FirstTry_Complex_Expression() { var eval = new EvaluateExpression(); int result = eval.FirstTry("(1 + ((2 + 3) * (4 * 5)))"); Assert.Equal(101, result); }
public void FirstTry_Easy_Expression_With_Subtraction() { var eval = new EvaluateExpression(); int result = eval.FirstTry("(2 - 4)"); Assert.Equal(-2, result); }
public void FirstTry_Easy_Expression_With_Multiplication() { var eval = new EvaluateExpression(); int result = eval.FirstTry("(2 * 4)"); Assert.Equal(8, result); }
public object Any(EvaluateExpression request) { var wrapper = GetDomainWrapper(request); return(new EvaluateExpressionResponse { Result = wrapper.EvaluateExpression(request.Expression, request.IncludeJson) }); }
private DomainWrapper GetDomainWrapper(EvaluateExpression request) { var runner = LocalCache.GetScriptRunnerInfo(request.ScriptId); var wrapper = runner?.DomainWrapper; if (wrapper == null) { throw HttpError.NotFound("Script no longer exists on server"); } return(wrapper); }
/**********************************************************************************************//** * Evaluate pair. * * \author Ilan Hindy * \date 29/09/2016 * * \exception EvaluationException Thrown when an Evaluation error condition occurs. * * \param prm1 The first prm. * \param prm2 The second prm. * \param evaluateExpressionFunc The evaluate expression function. * * \return true if it succeeds, false if it fails. * . **************************************************************************************************/ private bool EvaluatePair(dynamic prm1, dynamic prm2, EvaluateExpression evaluateExpressionFunc) { try { return(evaluateExpressionFunc(prm1, prm2)); } catch (Exception e) { string operatorName = TypesUtility.GetKeyToString(or[brp.ork.Operator]); throw new EvaluationException("Error while evaluating " + operatorName + "(" + prm1.ToString() + "," + prm2.ToString() + ")" + "\n" + e.Message); } }
/**********************************************************************************************//** * Evaluates. * * \author Ilan Hindy * \date 29/09/2016 * * \param parameters Options for controlling the operation. * \param evaluateExpressionFunc The evaluate expression function. * * \return true if it succeeds, false if it fails. * . **************************************************************************************************/ private bool Evaluate(AttributeList parameters, EvaluateExpression evaluateExpressionFunc) { List <List <dynamic> > parametersValuesLists = CreateParametersLists(parameters); List <bool> evaluationResults = new List <bool>(); for (int idx = 0; idx < parametersValuesLists.Count - 1; idx++) { evaluationResults.Add(Evaluate(parametersValuesLists[idx], parametersValuesLists[idx + 1], evaluateExpressionFunc)); } return(EvaluateResults(evaluationResults)); }
public void EvaluateTest(string fileName, long expectedResponse) { //Arrange IEvaluateExpression _evaluateExpression = new EvaluateExpression(); decimal response = 0; string[] readFileLinesResponse = File.ReadAllLines(string.Concat(Environment.CurrentDirectory, fileName)); //Act TestDelegate code = (() => _evaluateExpression.Evaluate(ref readFileLinesResponse, ref response)); //Assert Assert.IsNotNull(code); }
private void Evaluate(EvaluateExpression request) { object result; try { result = request.Script ? _expressionEvaluator.ScriptEvaluate(request.Data) : _expressionEvaluator.Evaluate(request.Data); } catch (Exception e) { result = ErrorResult.From(e); } Sender.Tell(new EvaluationResult(result, result.GetType().IsPrimitive, false)); }
private string CreateServerRequest(XmlDocument req, int rowNum) { // string requestXPathHeader = ConfigurationManager.AppSettings["RequestXPathHeader"].ToString(); string requestXPathHeader = "server/requests/Session.setDocumentRq/"; lock (dataSet_InputProcess) { try { EvaluateExpression obj_evalE = new EvaluateExpression(); Dictionary <string, string> allInputCalculation = new Dictionary <string, string>(); foreach (DataRow dr in dataSet_InputProcess.Tables[mappingTableName].Rows) { if (dr["InputOutputType"].ToString() == "Input") { allInputCalculation.Add(dr["FieldName"].ToString(), dataSet_InputProcess.Tables[mainTableName].Rows[rowNum][dr["FieldName"].ToString()].ToString()); } } foreach (DataRow dr in dataSet_InputProcess.Tables[mappingTableName].Rows) { if ((dr["InputOutputType"].ToString() == "Input" || dr["InputOutputType"].ToString() == "CalculationInput") && (dr["XPath"].ToString() != "")) { req.SelectSingleNode(requestXPathHeader + dr["XPath"]).InnerText = dataSet_InputProcess.Tables[mainTableName].Rows[rowNum][dr["FieldName"].ToString()].ToString(); } } req.SelectSingleNode("server/requests/Session.setDocumentRq/session/data/policy/RequestNumber").InnerText = rowNum.ToString(); } catch (Exception ex) { } } //WriteLogs(req.OuterXml); //WriteLogs(rowNum.ToString()); return(req.OuterXml); }
static var Evaluate(dynamic exp1, dynamic op, dynamic exp2) { return(EvaluateExpression.Visit(exp1, op, exp2)); }
public static void Main() { // DistanceInLabyrinth.Solve(); EvaluateExpression.Solve(); }
//from ide protected override async Task <bool> AcceptCommand(MessageId sessionId, JObject args, CancellationToken token) { if (args["type"] == null) { return(false); } switch (args["type"].Value <string>()) { case "resume": { if (!contexts.TryGetValue(sessionId, out ExecutionContext context)) { return(false); } context.PausedOnWasm = false; if (context.CallStack == null) { return(false); } if (args["resumeLimit"] == null || args["resumeLimit"].Type == JTokenType.Null) { await OnResume(sessionId, token); return(false); } switch (args["resumeLimit"]["type"].Value <string>()) { case "next": await context.SdbAgent.Step(context.ThreadId, StepKind.Over, token); break; case "finish": await context.SdbAgent.Step(context.ThreadId, StepKind.Out, token); break; case "step": await context.SdbAgent.Step(context.ThreadId, StepKind.Into, token); break; } await SendResume(sessionId, token); return(true); } case "isAttached": case "attach": { var ctx = GetContextFixefox(sessionId); ctx.ThreadName = args["to"].Value <string>(); break; } case "source": { return(await OnGetScriptSource(sessionId, args["to"].Value <string>(), token)); } case "getBreakableLines": { return(await OnGetBreakableLines(sessionId, args["to"].Value <string>(), token)); } case "getBreakpointPositionsCompressed": { //{"positions":{"39":[20,28]},"from":"server1.conn2.child10/source27"} if (args["to"].Value <string>().StartsWith("dotnet://")) { var line = new JObject(); var offsets = new JArray(); offsets.Add(0); line.Add(args["query"]["start"]["line"].Value <string>(), offsets); var o = JObject.FromObject(new { positions = line, from = args["to"].Value <string>() }); await SendEventInternal(sessionId, "", o, token); return(true); } break; } case "setBreakpoint": { if (!contexts.TryGetValue(sessionId, out ExecutionContext context)) { return(false); } var req = JObject.FromObject(new { url = args["location"]["sourceUrl"].Value <string>(), lineNumber = args["location"]["line"].Value <int>() - 1, columnNumber = args["location"]["column"].Value <int>() }); var bp = context.BreakpointRequests.Where(request => request.Value.CompareRequest(req)).FirstOrDefault(); if (bp.Value != null) { bp.Value.UpdateCondition(args["options"]?["condition"]?.Value <string>()); await SendCommand(sessionId, "", args, token); return(true); } string bpid = Interlocked.Increment(ref context.breakpointId).ToString(); if (args["options"]?["condition"]?.Value <string>() != null) { req["condition"] = args["options"]?["condition"]?.Value <string>(); } var request = BreakpointRequest.Parse(bpid, req); bool loaded = context.Source.Task.IsCompleted; context.BreakpointRequests[bpid] = request; if (await IsRuntimeAlreadyReadyAlready(sessionId, token)) { DebugStore store = await RuntimeReady(sessionId, token); Log("verbose", $"BP req {args}"); await SetBreakpoint(sessionId, store, request, !loaded, false, token); } await SendCommand(sessionId, "", args, token); return(true); } case "removeBreakpoint": { if (!contexts.TryGetValue(sessionId, out ExecutionContext context)) { return(false); } Result resp = await SendCommand(sessionId, "", args, token); var reqToRemove = JObject.FromObject(new { url = args["location"]["sourceUrl"].Value <string>(), lineNumber = args["location"]["line"].Value <int>() - 1, columnNumber = args["location"]["column"].Value <int>() }); foreach (var req in context.BreakpointRequests.Values) { if (req.CompareRequest(reqToRemove)) { foreach (var bp in req.Locations) { var breakpoint_removed = await context.SdbAgent.RemoveBreakpoint(bp.RemoteId, token); if (breakpoint_removed) { bp.RemoteId = -1; bp.State = BreakpointState.Disabled; } } } } return(true); } case "prototypeAndProperties": case "slice": { var to = args?["to"].Value <string>().Replace("propertyIterator", ""); if (!DotnetObjectId.TryParse(to, out DotnetObjectId objectId)) { return(false); } var res = await RuntimeGetPropertiesInternal(sessionId, objectId, args, token); var variables = ConvertToFirefoxContent(res); var o = JObject.FromObject(new { ownProperties = variables, from = args["to"].Value <string>() }); if (args["type"].Value <string>() == "prototypeAndProperties") { o.Add("prototype", GetPrototype(objectId, args)); } await SendEvent(sessionId, "", o, token); return(true); } case "prototype": { if (!DotnetObjectId.TryParse(args?["to"], out DotnetObjectId objectId)) { return(false); } var o = JObject.FromObject(new { prototype = GetPrototype(objectId, args), from = args["to"].Value <string>() }); await SendEvent(sessionId, "", o, token); return(true); } case "enumSymbols": { if (!DotnetObjectId.TryParse(args?["to"], out DotnetObjectId objectId)) { return(false); } var o = JObject.FromObject(new { type = "symbolIterator", count = 0, actor = args["to"].Value <string>() + "symbolIterator" }); var iterator = JObject.FromObject(new { iterator = o, from = args["to"].Value <string>() }); await SendEvent(sessionId, "", iterator, token); return(true); } case "enumProperties": { //{"iterator":{"type":"propertyIterator","actor":"server1.conn19.child63/propertyIterator73","count":3},"from":"server1.conn19.child63/obj71"} if (!DotnetObjectId.TryParse(args?["to"], out DotnetObjectId objectId)) { return(false); } var res = await RuntimeGetPropertiesInternal(sessionId, objectId, args, token); var variables = ConvertToFirefoxContent(res); var o = JObject.FromObject(new { type = "propertyIterator", count = variables.Count, actor = args["to"].Value <string>() + "propertyIterator" }); var iterator = JObject.FromObject(new { iterator = o, from = args["to"].Value <string>() }); await SendEvent(sessionId, "", iterator, token); return(true); } case "getEnvironment": { if (!DotnetObjectId.TryParse(args?["to"], out DotnetObjectId objectId)) { return(false); } var ctx = GetContextFixefox(sessionId); if (ctx.CallStack == null) { return(false); } Frame scope = ctx.CallStack.FirstOrDefault(s => s.Id == objectId.Value); var res = await RuntimeGetPropertiesInternal(sessionId, objectId, args, token); var variables = ConvertToFirefoxContent(res); var o = JObject.FromObject(new { actor = args["to"].Value <string>() + "_0", type = "function", scopeKind = "function", function = new { displayName = scope.Method.Name }, bindings = new { arguments = new JArray(), variables }, from = args["to"].Value <string>() }); await SendEvent(sessionId, "", o, token); return(true); } case "frames": { ExecutionContext ctx = GetContextFixefox(sessionId); if (ctx.PausedOnWasm) { try { await GetFrames(sessionId, ctx, args, token); return(true); } catch (Exception) //if the page is refreshed maybe it stops here. { await SendResume(sessionId, token); return(true); } } //var ret = await SendCommand(sessionId, "frames", args, token); //await SendEvent(sessionId, "", ret.Value["result"]["fullContent"] as JObject, token); return(false); } case "evaluateJSAsync": { var context = GetContextFixefox(sessionId); if (context.CallStack != null) { var resultID = $"runtimeResult-{context.GetResultID()}"; var o = JObject.FromObject(new { resultID, from = args["to"].Value <string>() }); await SendEvent(sessionId, "", o, token); Frame scope = context.CallStack.First <Frame>(); var resolver = new MemberReferenceResolver(this, context, sessionId, scope.Id, logger); JObject retValue = await resolver.Resolve(args?["text"]?.Value <string>(), token); if (retValue == null) { retValue = await EvaluateExpression.CompileAndRunTheExpression(args?["text"]?.Value <string>(), resolver, token); } var osend = JObject.FromObject(new { type = "evaluationResult", resultID, hasException = false, input = args?["text"], from = args["to"].Value <string>() }); if (retValue["type"].Value <string>() == "object") { osend["result"] = JObject.FromObject(new { type = retValue["type"], @class = retValue["className"], description = retValue["description"], actor = retValue["objectId"], }); } else { osend["result"] = retValue["value"]; osend["resultType"] = retValue["type"]; osend["resultDescription"] = retValue["description"]; } await SendEvent(sessionId, "", osend, token); } else { var ret = await SendCommand(sessionId, "evaluateJSAsync", args, token); var o = JObject.FromObject(new { resultID = ret.FullContent["resultID"], from = args["to"].Value <string>() }); await SendEvent(sessionId, "", o, token); await SendEvent(sessionId, "", ret.FullContent, token); } return(true); } case "DotnetDebugger.getMethodLocation": { var ret = await GetMethodLocation(sessionId, args, token); ret.Value["from"] = "internal"; await SendEvent(sessionId, "", ret.Value, token); return(true); } default: return(false); } return(false); }
static var Evaluate(var exp1, var op, var exp2) { return(EvaluateExpression.Visit(exp1, op, exp2)); }
static void Main(string[] args) { #region Basics // Example Single-line Comment /* Example * Multiline * Comment */ //Hello World Console.WriteLine("Hello World"); //Get user input Console.Write("What's your name? "); string name = Console.ReadLine(); Console.WriteLine("Hello " + name); //Data Types bool canVote = true; char fumoffu = '%'; int maxInt = int.MaxValue; long maxLong = long.MaxValue; decimal maxDecimal = decimal.MaxValue; float maxFloat = float.MaxValue; double maxDouble = double.MaxValue; Console.WriteLine("Max Int: " + maxInt); //Implicit type variable declaration var sampleVar = "SampleString"; //You can't change its type after declaration though //sampleVar = 2; Console.WriteLine("sampleVar is a {0}", sampleVar.GetTypeCode()); Console.WriteLine("-------------------------------------------------------"); //Arithmetics Console.WriteLine("5 + 3 = " + (5 + 3)); Console.WriteLine("5 - 3 = " + (5 - 3)); Console.WriteLine("5 * 3 = " + (5 * 3)); Console.WriteLine("5 / 3 = " + (5 / 3)); Console.WriteLine("5.2 % 3 = " + (5.2 % 3)); int i = 0; Console.WriteLine("i++ = " + i++); Console.WriteLine("++i = " + ++i); Console.WriteLine("i-- = " + i--); Console.WriteLine("--i = " + --i); Console.WriteLine("-------------------------------------------------------"); //Some Math Static Functions //acos, asin, atan, atan2, cos, cosh, exp, log, sin, sinh, tan, tanh double num1 = 10.5; double num2 = 15; Console.WriteLine("Abs(num1): " + Math.Abs(num1)); Console.WriteLine("Ceiling(num1): " + Math.Ceiling(num1)); Console.WriteLine("Floor(num1): " + Math.Floor(num1)); Console.WriteLine("Max(num1, num2): " + Math.Max(num1, num2)); Console.WriteLine("Min(num1, num2): " + Math.Min(num1, num2)); Console.WriteLine("Pow(num1): " + Math.Pow(num1, num2)); Console.WriteLine("Round(num1): " + Math.Round(num1)); Console.WriteLine("Sqrt(num1): " + Math.Sqrt(num1)); Console.WriteLine("-------------------------------------------------------"); //Casting const double PI = 3.14; int intPI = (int)PI; //Generating Random Numbers Random rand = new Random(); Console.WriteLine("Random number between 1 and 10: " + rand.Next(1, 11)); #endregion #region Conditionals and Loops //Relational Operators: > < >= <= == != //Logical Operators: && (AND) || (OR) ^ (XOR) ! (NOT) int age = rand.Next(1, 101); Console.WriteLine(age); //IF statements if (age >= 5 && age <= 7) { Console.WriteLine("Go to Elementary School"); } else if (age > 7 && age < 13) { Console.WriteLine("Go to Middle School"); } else { Console.WriteLine("Go to High School"); } if (age < 14 || age > 67) { Console.WriteLine("You Shouldn't Work"); } Console.WriteLine("! true: " + !true); //Ternary - Condition ? ifTrue : ifFalse bool canDrive = age >= 18 ? true : false; switch (age) { case 0: Console.WriteLine("Infant"); break; case 1: case 2: Console.WriteLine("Toddler"); //Goto jumps to the code block you specify (It's gonna kick you out of the switch statement) goto Checkpoint1; default: Console.WriteLine("Child"); break; } Checkpoint1: Console.WriteLine("I'm printed from outside the switch statement"); Console.WriteLine("-------------------------------------------------------"); int j = 0; while (j < 10) { if (j == 7) { j++; continue; } //^^^ Jump back to the while header if (j == 9) { break; } //// ^^ Jump out of the loop if (j % 2 > 0) { Console.WriteLine(j); } j++; } Console.WriteLine("-------------------------------------------------------"); //DO While: The body of do is executed at least one time string guess; do { Console.WriteLine("Guess a number"); guess = Console.ReadLine(); } while (!guess.Equals("15")); Console.WriteLine("-------------------------------------------------------"); //FOR Loop: All the conditional and counter stuff is in the heading for (int k = 0; k < 10; k++) { if (k % 2 != 0) { Console.WriteLine(k); } } Console.WriteLine("-------------------------------------------------------"); //FOREACH: Used to iterate over list, arrays, maps and collections string randString = "Example Random String"; foreach (char c in randString) { Console.WriteLine(c); } Console.WriteLine("-------------------------------------------------------"); #endregion #region Strings & Arrays //Strings //Escape Sequences: Allow you to enter special chars in strings // \' \" \\ \b \n \t string sampleString = "Some random words"; //Prints wether a string is empty or null Console.WriteLine("Is Empty: " + String.IsNullOrEmpty(sampleString)); //Prints wether a string is null or filled with white space Console.WriteLine("Is Empty: " + String.IsNullOrWhiteSpace(sampleString)); Console.WriteLine("String Length: " + sampleString.Length); //Returns the position of a certain string/char inside of another string | returns -1 if it doesn't find it Console.WriteLine("Index of 'random': " + sampleString.IndexOf("random")); //Returns a substring of the parent string when given the index of the first letter and the length of the word Console.WriteLine("2nd word: " + sampleString.Substring(5, 6)); //Returns true if the parent string is equals to the argument string Console.WriteLine("Strings Equal: " + sampleString.Equals(randString)); //Returns true if the String starts with the argument string Console.WriteLine("Starts with \"Example Random\": " + randString.StartsWith("Example Random")); //Returns true if the String ends with the argument string Console.WriteLine("Ends with \"Example String\": " + randString.EndsWith("Example String")); //Removes white space at the beginning or at the end of a string sampleString = sampleString.Trim(); //TrimEnd TrimStart //Replaces a substring of the parent string with another string sampleString = sampleString.Replace("words", "characters"); //Removes a substring of length equals to the second parameter starting from the passed index (first parameter) sampleString = sampleString.Remove(0, 4); //Array of strings string[] words = new string[6] { "I", "Suck", "At", "Drawing", "Textures", ":(" }; //Join a string array into one single string Console.WriteLine("Joined String Array: " + String.Join(" ", words)); Console.WriteLine("-------------------------------------------------------"); //Formatting Strings string formatted = String.Format("{0:c} {1:00.00} {2:#.00} {3:0,0}", 4.99, 15.567, .56, 1000); Console.WriteLine("Formatted Strings examples: " + formatted); Console.WriteLine("-------------------------------------------------------"); //String Builder //Used when you want to edit a string without creating a new one StringBuilder sb = new StringBuilder(); //Append new strings - (AppendLine is the version that appends a \n at the end automatically) sb.Append("This is the first Sentence."); sb.AppendFormat("My Nick is {0} and I am a {1} developer", "Davoleo", "C#"); //Empties the whole StringBuilder Buffer //sb.Clear(); //Replaces a string with another one in all the occurrences in the StringBuilder sb.Replace("e", "E"); //Removes chars from index 5 (included) to index 7 (excluded) sb.Remove(5, 7); //Converts the StringBuilder to a String and writes it on the console Console.WriteLine(sb.ToString()); Console.WriteLine("-------------------------------------------------------"); //Arrays int[] randArray; int[] randFixedArray = new int[5]; int[] literalArray = { 1, 2, 3, 4, 5 }; //Returns the number of items in the array Console.WriteLine("Array Length: " + literalArray.Length); //Returns the first item of an array Console.WriteLine("First Item: " + literalArray[0]); //Loop through arrays //Classic For loop with array length for (int k = 0; k < literalArray.Length; k++) { Console.WriteLine("{0} : {1}", k, literalArray[k]); } //For Each foreach (int num in literalArray) { Console.WriteLine(num); } //Returns the index of a specific array element Console.WriteLine("Index of 3: " + Array.IndexOf(literalArray, 3)); string[] names = { "Shana", "Alastor", "Wilhelmina", "Decarabia", "Fecor", "Hecate", "Sydonnay" }; //Joins all the items of an array dividing them with a custom separator string nameCollectionString = string.Join(", ", names); names = nameCollectionString.Split(','); //Multidimensional Arrays //Two dimensional empty array of length 5*3 int[,] multArray = new int[5, 3]; //Literal Init int[,] multArray2 = { { 0, 1 }, { 2, 3 }, { 4, 5 } }; foreach (int num in multArray2) { Console.WriteLine(num); } Console.WriteLine("-------------------------------------------------------"); //Lists: Dynamic Arrays List <int> numList = new List <int>(); //Adds a Single item to the list numList.Add(5); numList.Add(15); numList.Add(25); //Adds a range of items to the list (in some kind of collection form) int[] numArray = { 1, 2, 3, 4 }; numList.AddRange(numArray); //Removes All the items in the list //numList.Clear(); //Init a list with an array (aka create a list from an array) List <int> numList2 = new List <int>(numArray); //Insert an item in a specific index numList.Insert(1, 10); //Removes the first occurance of the argument in the list, from the list numList.Remove(5); //Removes the item at the index 2 numList.RemoveAt(2); for (var l = 0; l < numList.Count; l++) { Console.WriteLine(numList[l]); } //Returns the index of the first occurance of the passed item (returns -1 if it doesn't find any) Console.WriteLine("4 is in index " + numList2.IndexOf(4)); Console.WriteLine("is 5 in the list " + numList.Contains(5)); List <string> stringList = new List <string>(new string[] { "Davoleo", "Matpac", "Pierknight" }); //case insensitive String comparison Console.WriteLine("Davoleo in list " + stringList.Contains("davoleo", StringComparer.OrdinalIgnoreCase)); //Sorts the list alphabetically or numerically depending on the contents numList.Sort(); Console.WriteLine("-------------------------------------------------------"); #endregion #region Exceptions //Exception Handling //Try and Catch Structure try { Console.Write("Divide 10 by "); int num = int.Parse(Console.ReadLine()); Console.WriteLine("10/{0} = {1}", num, 10 / num); } catch (DivideByZeroException e) { Console.WriteLine("Can't divide by 0"); //Prints the name of the exception Console.WriteLine(e.GetType().Name); //Prints a small description of the exception Console.WriteLine(e.Message); //Throws the same exception again //throw e; //Throws another new Exception throw new InvalidOperationException("Operation Failed", e); } catch (Exception e) { //This Catches all the exceptions Console.WriteLine(e.GetType().Name); Console.WriteLine(e.Message); } Console.WriteLine("-------------------------------------------------------"); #endregion #region OOP //Classes and Objects Animal botolo = new Animal(0.5, 6, "Meeer", "Botolo"); Console.WriteLine("{0} says {1}", botolo.Name, botolo.Sound); Console.WriteLine(botolo.ToString()); Console.WriteLine(Animal.GetCount()); Console.WriteLine("-------------------------------------------------------"); //Method Overloading test //This Calls the int version Console.WriteLine("1 + 25 = " + GetSum(1, 25)); //This Calls the double version //Passing parameters in another order Console.WriteLine("7.64 + 9.24 = " + GetSum(num2: 7.64, num1: 9.24)); Console.WriteLine("-------------------------------------------------------"); //Object Initializer - Assigning values to the fields manually Animal epicAnimal = new Animal() { Name = "Grover", Height = 13, Weight = 11, Sound = "GRRR" }; Console.WriteLine(epicAnimal.ToString()); Console.WriteLine("-------------------------------------------------------"); //Polymorphism Shape rect = new Rectangle(5, 8); Shape tri = new Triangle(8, 3); Shape circle = new Circle(5); //Array of different kinds of shapes Shape[] shapeArray = { rect, tri, circle }; foreach (var shape in shapeArray) { shape.LogShapeInfo(); } Console.WriteLine("***"); Console.WriteLine("Rect Area: " + rect.Area()); Console.WriteLine("Tri Area: " + tri.Area()); Console.WriteLine("Circle Area: " + circle.Area()); Console.WriteLine("tri is a Triangle: " + (tri is Triangle)); Console.WriteLine("rect is a Rectangle: " + ((rect as Rectangle) != null)); Console.WriteLine("-------------------------------------------------------"); //Operator Overloading for objects Rectangle combinedRectangle = new Rectangle(6, 10) + (Rectangle)rect; Console.WriteLine("combinedRectangle Area: " + combinedRectangle.Area()); Console.WriteLine("-------------------------------------------------------"); //Interfaces IElettronicDevice TV = TVRemote.GetDevice(); PowerButton powerButton = new PowerButton(TV); powerButton.Execute(); powerButton.Undo(); Console.WriteLine("-------------------------------------------------------"); //Generics - Classes that can be used with any kind of object SimpleMapEntry <int, string> davPass = new SimpleMapEntry <int, string>(333, "Davoleo"); davPass.ShowData(); //Generics work with multiple data types int firstInt = 5, secondInt = 4; GetSum(ref firstInt, ref secondInt); string firstString = firstInt.ToString(); string secondString = secondInt.ToString(); GetSum(ref firstString, ref secondString); Rectangle <int> rect1 = new Rectangle <int>(20, 50); Console.WriteLine(rect1.GetArea()); Rectangle <string> rect2 = new Rectangle <string>("20", "50"); Console.WriteLine(rect2.GetArea()); Console.WriteLine("-------------------------------------------------------"); Temperature waveTemp = Temperature.WARM; switch (waveTemp) { case Temperature.FREEZE: Console.WriteLine("Freezing Temperature"); break; case Temperature.LOW: Console.WriteLine("Low Temperature"); break; case Temperature.WARM: Console.WriteLine("Warm Temperature"); break; case Temperature.HOT: Console.WriteLine("Hot Temperature"); break; case Temperature.SEARING: Console.WriteLine("EPIC Temperature, everything Sublimates"); break; default: Console.WriteLine("Invalid Temperature"); break; } Console.WriteLine("-------------------------------------------------------"); //STRUCTS Customer davoleo = new Customer(); davoleo.createCustomer("Davoleo", 55.80, 111); davoleo.printInfo(); Console.WriteLine("-------------------------------------------------------"); //DELEGATES - Passing methods to other methods as parameters //Anonymous method of type EvaluateExpression EvaluateExpression add = delegate(double n1, double n2) { return(n1 + n2); }; //Direct Delegate Assignment EvaluateExpression substract = (n1, n2) => { return(n1 + n2); }; EvaluateExpression multiply = delegate(double n1, double n2) { return(n1 * n2); }; //Calls both the delegates EvaluateExpression subtractMultuply = substract + multiply; Console.WriteLine("5 + 10 = " + add(5, 10)); Console.WriteLine("5 * 10 = " + multiply(5, 10)); Console.WriteLine("Subtract & Multiply 10 & 4: " + subtractMultuply(10, 4)); //Lamda expressions - Anonymous functions Func <int, int, int> subtract = (x, y) => x - y; Console.WriteLine("5 - 10 = " + subtract.Invoke(5, 10)); List <int> nums = new List <int> { 3, 6, 9, 12, 15, 18, 21, 24, 27, 30 }; List <int> oddNumbers = nums.Where((n) => n % 2 == 1).ToList(); foreach (var oddNumber in oddNumbers) { Console.Write(oddNumber + ", "); } Console.WriteLine(); Console.WriteLine("-------------------------------------------------------"); #endregion #region File IO //File I/O //Access the current directory DirectoryInfo dir = new DirectoryInfo("."); DirectoryInfo davDir = new DirectoryInfo(@"C:\Users\Davoleo"); Console.WriteLine("Davoleo path: " + davDir.FullName); Console.WriteLine("Davoleo dir name " + davDir.Name); Console.WriteLine(davDir.Parent); Console.WriteLine(davDir.Attributes); Console.WriteLine(davDir.CreationTime); //Creates a directory Directory.CreateDirectory(@"D:\C#Data"); DirectoryInfo dataDir = new DirectoryInfo(@"D:\C#Data"); //Directory.Delete(@"D:\C#Data"); string dataPath = @"D:\C#Data"; Console.WriteLine("-------------------------------------------------------"); string[] nicks = { "Davoleo", "Matpac", "Pierknight", "gesudio" }; using (StreamWriter writer = new StreamWriter("nicknames.txt")) { foreach (var nick in nicks) { writer.WriteLine(nick); } } using (StreamReader reader = new StreamReader("nicknames.txt")) { string user; while ((user = reader.ReadLine()) != null) { Console.WriteLine(user); } } //Another Way of writing and reading File.WriteAllLines(dataPath + "\\nicknames.txt", nicks); Console.WriteLine(File.ReadAllBytes(dataPath + "\\nicknames.txt").ToString()); FileInfo[] textFiles = dataDir.GetFiles("*.txt", SearchOption.AllDirectories); Console.WriteLine("Matches: {0}" + textFiles.Length); Console.WriteLine(textFiles[0].Name + ", " + textFiles[0].Length); string fileStreamPath = @"D:\C#Data\streamtest.txt"; FileStream stream = File.Open(fileStreamPath, FileMode.Create); string randomString = "This is a random String"; byte[] randomStringByte = Encoding.Default.GetBytes(randString); stream.Write(randomStringByte, 0, randomStringByte.Length); stream.Position = 0; stream.Close(); string binaryPath = @"D:\C#Data\file.dat"; FileInfo datFile = new FileInfo(binaryPath); BinaryWriter binaryWriter = new BinaryWriter(datFile.OpenWrite()); string text = "Random Text"; age = 18; double height = 12398; binaryWriter.Write(text); binaryWriter.Write(age); binaryWriter.Write(height); binaryWriter.Close(); BinaryReader binaryReader = new BinaryReader(datFile.OpenRead()); Console.WriteLine(binaryReader.ReadString()); Console.WriteLine(binaryReader.ReadInt32()); Console.WriteLine(binaryReader.ReadDouble()); #endregion Console.WriteLine("-------------------------------------------------------"); //OOP Game test Warrior maximus = new Warrior("Maximus", 1000, 120, 40); Warrior bob = new Warrior("Bob", 1000, 120, 40); Console.WriteLine("Disabled"); //Battle.StartFight(maximus, bob); Console.WriteLine("-------------------------------------------------------"); //Collections ---- #region ArrayList //You can add different kind of objects ArrayLists ArrayList arrayList = new ArrayList(); arrayList.Add("Bob"); arrayList.Add(43); //Number of items in the arraylist Console.WriteLine("ArrayList Count: " + arrayList.Count); //Capacity is always double the count (?) Console.WriteLine("ArrayList Capacity: " + arrayList.Capacity); ArrayList arrayList2 = new ArrayList(); //Add an array to the ArrayList arrayList2.AddRange(new object[] { "Jeff", "Dave", "Egg", "Edge" }); arrayList.AddRange(arrayList2); //Sort items in natural order arrayList2.Sort(); //Reverse the order of items arrayList2.Reverse(); //Insert some item at a specific index arrayList2.Insert(1, "PI"); //Sub-Arraylist made of some of the items in the original arraylist ArrayList range = arrayList2.GetRange(0, 2); Console.WriteLine("arrayList object ---"); foreach (object o in arrayList) { Console.Write(o + "\t"); } Console.WriteLine(); Console.WriteLine("arrayList2 object ---"); foreach (object o in arrayList2) { Console.Write(o + "\t"); } Console.WriteLine(); Console.WriteLine("range object ----"); foreach (object o in range) { Console.Write(o + "\t"); } Console.WriteLine(); //Remove the item at the 0 index //arrayList2.RemoveAt(0); //Removes the first 2 items starting from index 0 //arrayList2.RemoveRange(0, 2); //Return the index of a specific object - if it doesn't find any it returns -1 Console.WriteLine("Index of Edge: " + arrayList2.IndexOf("Edge")); //Converting ArrayLists to arrays string[] array = (string[])arrayList2.ToArray(typeof(string)); //Converting back to Arraylist ArrayList listFromArray = new ArrayList(array); #endregion Console.WriteLine("-------------------------------------------------------"); #region Dictionary //Stores a list of key-value pairs Dictionary <string, string> langsProjs = new Dictionary <string, string>(); //Add A Key-Value Pair langsProjs.Add("C#", "CSharp-Test"); langsProjs.Add("Java", "Metallurgy 4: Reforged"); langsProjs.Add("Dart", "sample_flutter_app"); //Removes a Pair from a given key langsProjs.Remove("Dart"); //Number of pairs in the list Console.WriteLine("Count: " + langsProjs.Count); //Returns wether a key is present Console.WriteLine("C# is present: " + langsProjs.ContainsKey("C#")); //Gets the value of Java and outputs into a new string called test langsProjs.TryGetValue("Java", out string test); Console.WriteLine("Java: " + test); //Loop over all the pairs in the list Console.WriteLine("LOOP:"); foreach (KeyValuePair <string, string> pair in langsProjs) { Console.WriteLine($"{pair.Key} - {pair.Value}"); } //Empties the dictionary Completely langsProjs.Clear(); #endregion Console.WriteLine("-------------------------------------------------------"); #region Queue //Creates a new Empty Queue Queue queue = new Queue(); //Adds an item to the queue queue.Enqueue(1); queue.Enqueue(2); queue.Enqueue(3); //Loop over a queue foreach (object num in queue) { Console.Write(num + "\t"); } Console.WriteLine(); Console.WriteLine("is 3 in the queue: " + queue.Contains(3)); //Removes the first item and return it to you Console.WriteLine("Removes 1: " + queue.Dequeue()); //Returns the first item in the queue without removing it Console.WriteLine("Peek the firs num: " + queue.Peek()); //Empties the queue queue.Clear(); #endregion Console.WriteLine("-------------------------------------------------------"); #region Stack Stack stack = new Stack(); //Adds an item to the stack stack.Push(1); stack.Push(2); stack.Push(3); stack.Push(4); //Loop over a stack - items are returned in the opposite order foreach (var item in stack) { Console.WriteLine($"Item: {item}"); } //Returns the last item in the stack without removing it Console.WriteLine(stack.Peek()); //Returns the last item in the stack removing it Console.WriteLine(stack.Pop()); //Returns wether the stack contains an item or not Console.WriteLine(stack.Contains(3)); //Convert to an array and print it with the Join function Console.WriteLine(string.Join(", ", stack.ToArray())); //Empties the stack stack.Clear(); #endregion Console.WriteLine("-------------------------------------------------------"); #region LINQ EXTENSION METHODS //LINQ EXTENSION METHODS //Lamdas with Delegates Console.WriteLine("-- Lambda Expressions --"); doubleIt doubleIt = x => x * 2; Console.WriteLine($"5 * 2 = {doubleIt(5)}"); List <int> numberList = new List <int> { 1, 9, 2, 6, 3 }; //.Where() METHOD var evenList = numberList.Where(a => a % 2 == 0).ToList(); foreach (var k in evenList) { Console.Write(k + ", "); } Console.WriteLine(); //2nd Example of .Where() var rangeList = numberList.Where(x => x > 2 && x < 9).ToList(); foreach (var k in rangeList) { Console.Write(k + ", "); } Console.WriteLine(); //Coin flips (T = 0 or C = 1) List <int> coinFlips = new List <int>(); int flips = 0; while (flips < 100) { coinFlips.Add(rand.Next(0, 2)); flips++; } //Count method with predicate Console.WriteLine($"Testa Count: {coinFlips.Count(a => a == 0)}"); Console.WriteLine($"Croce Count: {coinFlips.Count(a => a == 1)}"); //.Select() METHOD var oneToTen = new List <int>(); oneToTen.AddRange(Enumerable.Range(1, 10)); var squares = oneToTen.Select(x => x * x); foreach (var k in squares) { Console.Write(k + ", "); } Console.WriteLine(); //.Zip() METHOD var listOne = new List <int> { 1, 3, 4 }; var listTwo = new List <int> { 4, 6, 8 }; var sumList = listOne.Zip(listTwo, (l1Value, l2Value) => l1Value + l2Value); foreach (var k in sumList) { Console.Write(k + ", "); } Console.WriteLine(); //.Aggregate() METHOD var nums1to5 = new List <int> { 1, 2, 3, 4, 5 }; Console.WriteLine("Sum of elements {0}", nums1to5.Aggregate((a, b) => a + b)); //.AsQueryable.Average() Method Console.WriteLine($"Average: {nums1to5.AsQueryable().Average()}"); //.All() Console.WriteLine($"All > 3 nums? {nums1to5.All(x => x > 3)}"); //.Any() Console.WriteLine($"Any num > 3? {nums1to5.Any(x => x > 3)}"); //.Distinct() var listWithDupes = new List <int> { 1, 2, 3, 2, 3 }; Console.WriteLine($"Distinct: {string.Join(", ", listWithDupes.Distinct())}"); //.Except() - Prints all the values that don't exist in the second list Console.WriteLine($"Except: {string.Join(", ", nums1to5.Except(listWithDupes))}"); //.Intersect() - Returns a list with common values between two lists Console.WriteLine($"Intersect: {string.Join(", ", nums1to5.Intersect(listWithDupes))}"); #endregion Console.WriteLine("-------------------------------------------------------"); #region Custom Collection Class AnimalFarm animals = new AnimalFarm(); animals[0] = new Animal("Wilbur"); animals[1] = new Animal("Templeton"); animals[2] = new Animal("Wally"); animals[3] = new Animal("ooooooooooooooooooooooooeuf"); foreach (Animal animal in animals) { Console.WriteLine(animal.Name); } Box box1 = new Box(2, 3, 4); Box box2 = new Box(5, 6, 7); Box boxSum = box1 + box2; Console.WriteLine($"Box Sum: {boxSum}"); Console.WriteLine($"Box -> Int: {(int) box1}"); Console.WriteLine($"Int -> Box: {(Box) 4}"); //Anonymous type object var anonymous = new { Name = "Mr Unknown", Status = 312 }; Console.WriteLine("{0} status is {1}", anonymous.Name, anonymous.Status); #endregion Console.WriteLine("-------------------------------------------------------"); #region LINQ //Stands for Launguage Integrated Query - Provides tools to work with data QueryStringArray(); QueryIntArray(); QueryArrayList(); QueryCollection(); QueryAnimalData(); #endregion Console.WriteLine("-------------------------------------------------------"); #region Threads //Threading allows to execute operation on a different workflow instead of the Main one //The workflow continuously and quickly changes thread to Thread thread = new Thread(Print1); thread.Start(); for (int k = 0; k < 1000; k++) { Console.Write(0); } Console.WriteLine(); int counter = 1; for (int k = 0; k < 10; k++) { Console.WriteLine(counter); //Slow down the current thread of some time in ms Thread.Sleep(500); counter++; } Console.WriteLine("Thread Ended"); BankAccount account = new BankAccount(10); Thread[] threads = new Thread[15]; Thread.CurrentThread.Name = "main"; for (int k = 0; k < threads.Length; k++) { Thread smolThread = new Thread(account.IssueWidthDraw); smolThread.Name = k.ToString(); threads[k] = smolThread; } foreach (var smolThread in threads) { Console.WriteLine("Thread {0} Alive: {1}", smolThread.Name, smolThread.IsAlive); smolThread.Start(); Console.WriteLine("Thread {0} Alive: {1}", smolThread.Name, smolThread.IsAlive); } Console.WriteLine("Current Priority: " + Thread.CurrentThread.Priority); Console.WriteLine($"Thread {Thread.CurrentThread.Name} Ending"); // Passing data to threads through lambda expressions new Thread(() => { countTo(5); countTo(8); }).Start(); #endregion Console.WriteLine("-------------------------------------------------------"); #region Serialization Animal dummyDum = new Animal(45, 25, "Roar", "Dum"); Stream dummyStream = File.Open("AnimalData.dat", FileMode.Create); BinaryFormatter binaryFormatter = new BinaryFormatter(); binaryFormatter.Serialize(dummyStream, dummyDum); dummyStream.Close(); dummyDum = null; dummyStream = File.Open("AnimalData.dat", FileMode.Open); binaryFormatter = new BinaryFormatter(); dummyDum = (Animal)binaryFormatter.Deserialize(dummyStream); dummyStream.Close(); Console.WriteLine("Dummy Dum from binary: " + dummyDum.ToString()); dummyDum.Weight = 33; XmlSerializer xmlSerializer = new XmlSerializer(typeof(Animal)); using (TextWriter tw = new StreamWriter(@"D:\C#Data\dummy-dum.xml")) { xmlSerializer.Serialize(tw, dummyDum); } dummyDum = null; XmlSerializer xmlDeserializer = new XmlSerializer(typeof(Animal)); TextReader txtReader = new StreamReader(@"D:\C#Data\dummy-dum.xml"); object obj = xmlDeserializer.Deserialize(txtReader); dummyDum = (Animal)obj; txtReader.Close(); Console.WriteLine("Dummy Dum from XML: " + dummyDum.ToString()); #endregion }
protected override object InternalVisit(QuerySpecification node) { //TODO:node.ForClause //TODO:node.HavingClause //TODO:node.OffsetClause //TODO:node.OrderByClause var env = Database.GlobalEnvironment.NewChild(); //this returns multiple tables because of the joins and whatever List <IResultTable> tables = new List <IResultTable>(Visit <IEnumerable <IResultTable> >(node.FromClause, new IResultTable[0])); while (tables.Count > 1) { var first = tables[0]; tables.RemoveAt(0); var second = tables[0]; tables.RemoveAt(0); tables.Insert(0, new CrossJoinedTable(first, second)); } if (tables.Count != 0) { env.CurrentTable = tables.First(); } var top = EvaluateExpression <TopResult>(node.TopRowFilter, env); var predicate = EvaluateExpression <Func <IResultRow, bool> >(node.WhereClause, env, row => true); env.CurrentTable = env.CurrentTable.Filter((r) => Filter.Where(r, predicate)); //check to see if the selectors are aggregate functions. var grouppedData = EvaluateExpression <IResultTable>(node.GroupByClause, env, Table.Empty); var selectedColumns = node.SelectElements.SelectMany(element => { return(EvaluateExpression <Func <IResultTable, Selector[]> >(element, env)(env.CurrentTable)); }).ToArray(); IResultTable result; var aggregates = node.SelectElements.Select(e => e.ContainsAggregate()).ToArray(); if (aggregates.Any(e => e) || node.GroupByClause != null) { //i have aggregates. result = new RecordTable(env.CurrentTable.TableName, selectedColumns, grouppedData.Records); } else { result = new RecordTable(env.CurrentTable.TableName, selectedColumns, env.CurrentTable.Records); } if (node.UniqueRowFilter == UniqueRowFilter.Distinct) { result = result.Filter(Filter.Distinct); } if (top != null) { result = result.Filter((r) => Filter.Top(r, top)); } return(new SQLExecutionResult(result.Records.Count(), result)); }
public void Run() { ListNode intersection = new ListNode() { val = 4, next = new ListNode() { val = 5, next = new ListNode() { val = 6 } } }; ListNode root = new ListNode() { val = 1, next = new ListNode() { val = 2, next = new ListNode() { val = 3, next = intersection } } }; ListNode root2 = new ListNode() { val = 7, next = new ListNode() { val = 8, next = intersection } }; int[] query_type = new int[] { 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0 }; int[] key = new int[] { 5, 4, 1, 2, 2, 2, 3, 2, 5, 4, 4, 2, 4, 3, 5 }; int[] value = new int[] { 5, 3, 4, 4, 1, 4, 5, 1, 2, 3, 3, 3, 3, 1, 3 }; ListNode circular = new ListNode() { val = 16 }; circular.next = new ListNode() { val = 8, next = new ListNode() { val = 4, next = new ListNode() { val = 2, next = circular } } }; //ListNode circular = new ListNode() { val = 2 }; //circular.next = new ListNode() //{ // val = 2, // next = circular //}; //AlternativeNodeSplit.alternativeSplit(BuildLL(new int[] { 1, 2, 3, 4, 5 })); var solution // = ReverseLL.reverse(root); // = ZipLL.zip_given_linked_list(root); // = LRUCache.implement_LRU_cache(3, query_type, key, value); //= BalancedParenthesis.find_max_length_of_matching_parentheses("(((())(()"); // = MaxNumberInSlidingWindow.max_in_sliding_window(new int[] { 0 }, 1); // = LLIntersection.find_intersection(root, root2); // = FindMedian.find_median(circular.next); // = SwapKthNode.swap_nodes(BuildLL(new int[] { 1, 2, 3, 4, 5, 6, 7 }), 3); // = MinStack.min_stack(new int[] { 10, 5, 0, -1, 0, -1, 0 }); //= DutchSort.Sort(BuildLL(new int[] { 2, 3, 1, 5, 10, 1, 2 }), 2); // = AddTwoNumbers.AddTwoNumbersMain(Utils.BuildList(new int[] { 7, 2, 4, 3 }), Utils.BuildList(new int[] { 5, 6, 4 })); // = ValidExpression.HasMatchingParantheses("((1+2)*3*)"); // = ReverseInGroups.reverse_linked_list_in_groups_of_k(Utils.BuildList(new int[] { 1, 2, 3, 4, 5, 6, 7,8}), 3); // = MergeSortLL.MergeSort(Utils.BuildList(new int[] { 5, 3, 1, 4, 2, 5, 6 })); // = Partition.PartitionMain(Utils.BuildList(new int[] { 1, 4, 3, 2, 5, 2}), 3); = EvaluateExpression.Evaluate("((2 + 3) * 2 / 10)"); }