private void RemoveAlternativeBtn_Click(object sender, RoutedEventArgs e) { Alternative alternative = (Alternative)((Button)sender).DataContext; viewModel.RemoveAlternative(alternative); }
public void OnSocket() { #region DEFAULT ON socketIO.On("open", (SocketIOEvent ev) => { Debug.Log("conectou " + ev.data); }); socketIO.On("close", (SocketIOEvent ev) => { Debug.Log("Disconnected."); }); socketIO.On("error", (SocketIOEvent ev) => { Debug.Log("error" + ev.data); }); #endregion socketIO.On("pergunta", (SocketIOEvent ev) => { Debug.Log("PERGUNTA"); QuestionMap map = Mapper.MapCreate <QuestionMap>(ev.data.ToString(), new QuestionMap()); #region MAP List <Alternative> alt = new List <Alternative>(); for (int i = 0; i < map.alternativas.Count; i++) { Alternative newAlt = new Alternative(); newAlt.atributo1 = new Attribute() { score = map.alternativas[i].atributo1, attributeName = "FORÇA" }; newAlt.atributo2 = new Attribute() { score = map.alternativas[i].atributo2, attributeName = "SAÚDE" }; newAlt.atributo3 = new Attribute() { score = map.alternativas[i].atributo3, attributeName = "HEMAN" }; newAlt.atributo4 = new Attribute() { score = map.alternativas[i].atributo4, attributeName = "EU" }; newAlt.atributo5 = new Attribute() { score = map.alternativas[i].atributo5, attributeName = "TENHO" }; newAlt.texto = map.alternativas[i].texto; alt.Add(newAlt); } Question question = new Question() { titulo = map.titulo, id = map.id, alternativas = alt }; #endregion ScreenGameManager.Instance.ReceiverAnswer(question); ScreenGameManager.Instance.GameStart(); Pagination.Instance.OpenPage(1); }); socketIO.On("home", (SocketIOEvent ev) => { Debug.Log("HOME"); Pagination.Instance.OpenPage(0); }); socketIO.On("ranking", (SocketIOEvent ev) => { Debug.Log("RANKING"); ScreenGameRequest.Instance.LoadTeamsPositions(); Pagination.Instance.OpenPage(2); }); socketIO.On("media", (SocketIOEvent ev) => { Debug.Log("Media"); //var data = JsonConvert.DeserializeObject<string>(ev.data.ToString()); ScreenGameRequest.Instance.LoadMedias(ev.data.ToString().Substring(1, ev.data.ToString().Length - 2)); Pagination.Instance.OpenPage(3); }); socketIO.On("tempo", (SocketIOEvent ev) => { Debug.Log("TEMPO"); string temp = JsonConvert.DeserializeObject <string>(ev.data.ToString()); ScreenGameManager.Instance.UpdateTime(temp); }); socketIO.On("tela-instrucoes", (SocketIOEvent ev) => { Debug.Log("INSTRUCOES"); Pagination.Instance.OpenPage(4); }); }
public void OnSocket() { #region DEFAULT ON socketIO.On("open", (SocketIOEvent ev) => { Debug.Log("conectou " + ev.data); }); socketIO.On("close", (SocketIOEvent ev) => { Debug.Log("Disconnected."); }); socketIO.On("error", (SocketIOEvent ev) => { Debug.Log("error" + ev.data); }); #endregion socketIO.On("pergunta", (SocketIOEvent ev) => { Debug.Log("PERGUNTA"); QuestionMap map = Mapper.MapCreate <QuestionMap>(ev.data.ToString(), new QuestionMap()); Dictionary <string, string> dir = new Dictionary <string, string>() { { "estado", "pergunta" }, { "time", TeamsController.Instance.myTeam.teamName } }; SockeEmitEstado(dir); #region MAP List <Alternative> alt = new List <Alternative>(); Debug.Log(map.alternativas.Count); for (int i = 0; i < map.alternativas.Count; i++) { Alternative newAlt = new Alternative(); newAlt.atributo1 = new Attribute() { score = map.alternativas[i].atributo1, attributeName = "FORÇA" }; newAlt.atributo2 = new Attribute() { score = map.alternativas[i].atributo2, attributeName = "SAÚDE" }; newAlt.atributo3 = new Attribute() { score = map.alternativas[i].atributo3, attributeName = "HEMAN" }; newAlt.atributo4 = new Attribute() { score = map.alternativas[i].atributo4, attributeName = "EU" }; newAlt.atributo5 = new Attribute() { score = map.alternativas[i].atributo5, attributeName = "TENHO" }; newAlt.texto = map.alternativas[i].texto; alt.Add(newAlt); } Question question = new Question() { titulo = map.titulo, id = map.id, alternativas = alt }; #endregion GameManager.Instance.ReceiverAnswer(question); GameManager.Instance.GameStart(); Pagination.Instance.OpenPage(2); }); socketIO.On("resposta", (SocketIOEvent ev) => { Debug.Log("RESPOSTA"); Dictionary <string, string> dir = new Dictionary <string, string>() { { "estado", "resposta" }, { "time", TeamsController.Instance.myTeam.teamName } }; SockeEmitEstado(dir); GameManager.Instance.RespostaActive(); }); socketIO.On("home", (SocketIOEvent ev) => { Debug.Log("HOME"); Dictionary <string, string> dir = new Dictionary <string, string>() { { "estado", "home" }, { "time", TeamsController.Instance.myTeam.teamName } }; SockeEmitEstado(dir); Pagination.Instance.OpenPage(1); }); socketIO.On("tela-instrucoes", (SocketIOEvent ev) => { Debug.Log("INSTRUCOES"); Dictionary <string, string> dir = new Dictionary <string, string>() { { "estado", "tela-instrucoes" }, { "time", TeamsController.Instance.myTeam.teamName } }; SockeEmitEstado(dir); Pagination.Instance.OpenPage(4); }); socketIO.On("ranking", (SocketIOEvent ev) => { Debug.Log("RANKING"); Dictionary <string, string> dir = new Dictionary <string, string>() { { "estado", "ranking" }, { "time", TeamsController.Instance.myTeam.teamName } }; SockeEmitEstado(dir); GameRequest.Instance.LoadTeamPostion(); Pagination.Instance.OpenPage(5); }); socketIO.On("pontos", (SocketIOEvent ev) => { Debug.Log("PONTOS"); Dictionary <string, string> dir = new Dictionary <string, string>() { { "estado", "pontos" }, { "time", TeamsController.Instance.myTeam.teamName } }; SockeEmitEstado(dir); GameManager.Instance.ViewPontos(); }); socketIO.On("tempo", (SocketIOEvent ev) => { Debug.Log("TEMPO"); string temp = JsonConvert.DeserializeObject <string>(ev.data.ToString()); Debug.Log(temp); GameManager.Instance.UpdateTime(temp); }); }
/// <summary> /// Encodes multi-part content /// </summary> /// <param name="Content">Multi-part content.</param> /// <param name="Boundary">Boundary to use.</param> /// <returns>Encoded multi-part content.</returns> public static byte[] Encode(IEnumerable <EmbeddedContent> Content, string Boundary) { using (MemoryStream ms = new MemoryStream()) { StringBuilder Header = new StringBuilder(); foreach (EmbeddedContent Alternative in Content) { Alternative.AssertEncoded(); Header.Clear(); Header.Append("\r\n--"); Header.Append(Boundary); Header.Append("\r\nContent-Transfer-Encoding: "); Header.Append(Alternative.TransferEncoding); Header.Append("\r\nContent-Type: "); Header.Append(Alternative.ContentType); if (!string.IsNullOrEmpty(Alternative.Name)) { Header.Append("; name=\""); Header.Append(Alternative.Name.Replace("\"", "\\\"")); Header.Append("\""); } if (Alternative.Disposition != ContentDisposition.Unknown || !string.IsNullOrEmpty(Alternative.FileName)) { Header.Append("\r\nContent-Disposition: "); switch (Alternative.Disposition) { case ContentDisposition.Inline: Header.Append("inline"); break; case ContentDisposition.Attachment: default: Header.Append("attachment"); break; } if (!string.IsNullOrEmpty(Alternative.FileName)) { Header.Append("; filename=\""); Header.Append(Alternative.FileName.Replace("\"", "\\\"")); Header.Append("\""); } } if (!string.IsNullOrEmpty(Alternative.ID)) { Header.Append("\r\nContent-ID: "); Header.Append(Alternative.ID); } if (!string.IsNullOrEmpty(Alternative.Description)) { Header.Append("\r\nContent-Description: "); Header.Append(Alternative.Description); } Header.Append("\r\n\r\n"); byte[] HeaderBin = Encoding.ASCII.GetBytes(Header.ToString()); ms.Write(HeaderBin, 0, HeaderBin.Length); ms.Write(Alternative.Raw, 0, Alternative.Raw.Length); } return(ms.ToArray()); } }
public Sign(Alternative alternative) : base(alternative) { }
public AlternativeUtility(Alternative alternative, double utility) { Alternative = alternative; Utility = utility; }
public bool writerEnable(Alternative alt) { throw new NotImplementedException(); }
/// <summary> /// Player unlocked an option /// </summary> /// <param name="alternativeId">Alternative identifier.</param> /// <param name="optionId">Option identifier.</param> /// <param name="type">Alternative type.</param> public void Unlocked(string alternativeId, string optionId, Alternative type) { tracker.setResponse(optionId); tracker.Trace(Tracker.Verb.Unlocked.ToString().ToLower(), type.ToString().ToLower(), alternativeId); }
/// <summary> /// Player selected an option in a presented alternative /// </summary> /// <param name="alternativeId">Alternative identifier.</param> /// <param name="optionId">Option identifier.</param> /// <param name="type">Alternative type.</param> public void Selected(string alternativeId, string optionId, bool correct, Alternative type) { tracker.setResponse(optionId); tracker.setSuccess(correct); tracker.Trace(Tracker.Verb.Selected.ToString().ToLower(), type.ToString().ToLower(), alternativeId); }
public HexadecimalDigit([NotNull] Alternative element) : base(element) { }
/// <summary> /// Initializes a new instance of the LeafKP class. /// </summary> /// <param name="strs">List of strings</param> /// <param name="alts">List of Alternatives</param> public LeafKP(Symbol[] strs, Alternative[] alts) { this.DefaultTokens = strs; this.Alternatives = alts; }
/// <summary> /// Builds search program for alternative from scheduled search plans of the alternative cases /// </summary> public static SearchProgram BuildSearchProgram( IGraphModel model, LGSPMatchingPattern matchingPattern, Alternative alternative, bool parallelized, bool emitProfiling) { String rulePatternClassName = NamesOfEntities.RulePatternClassName(matchingPattern.name, matchingPattern.PatternGraph.Package, !(matchingPattern is LGSPRulePattern)); // build combined list of namesOfPatternGraphsOnPathToEnclosedPatternpath // from the namesOfPatternGraphsOnPathToEnclosedPatternpath of the alternative cases // also build combined lists of matching pattern class type names and nested independents List <string> namesOfPatternGraphsOnPathToEnclosedPatternpath = new List <string>(); List <string> matchingPatternClassTypeNames = new List <string>(); List <Dictionary <PatternGraph, bool> > nestedIndependents = new List <Dictionary <PatternGraph, bool> >(); for (int i = 0; i < alternative.alternativeCases.Length; ++i) { PatternGraph altCase = alternative.alternativeCases[i]; foreach (String name in altCase.patternGraphsOnPathToEnclosedPatternpath) { if (!namesOfPatternGraphsOnPathToEnclosedPatternpath.Contains(name)) { namesOfPatternGraphsOnPathToEnclosedPatternpath.Add(name); } } ExtractNestedIndependents(matchingPatternClassTypeNames, nestedIndependents, matchingPattern, altCase); } // build outermost search program operation, create the list anchor starting its program SearchProgram searchProgram = new SearchProgramOfAlternative( rulePatternClassName, namesOfPatternGraphsOnPathToEnclosedPatternpath, "myMatch", matchingPatternClassTypeNames, nestedIndependents, parallelized); searchProgram.OperationsList = new SearchProgramList(searchProgram); SearchProgramOperation insertionPoint = searchProgram.OperationsList; // initialize task/result-pushdown handling in subpattern matcher InitializeSubpatternMatching initialize = new InitializeSubpatternMatching(InitializeFinalizeSubpatternMatchingType.Normal); insertionPoint = insertionPoint.Append(initialize); // build alternative matching search programs, one per case for (int i = 0; i < alternative.alternativeCases.Length; ++i) { PatternGraph altCase = alternative.alternativeCases[i]; ScheduledSearchPlan scheduledSearchPlan = altCase.schedulesIncludingNegativesAndIndependents[0]; string inlinedPatternClassName = rulePatternClassName; string pathPrefixInInlinedPatternClass = scheduledSearchPlan.PatternGraph.pathPrefix; string unprefixedNameInInlinedPatternClass = scheduledSearchPlan.PatternGraph.name; if (alternative.originalAlternative != null) { inlinedPatternClassName = alternative.originalSubpatternEmbedding.matchingPatternOfEmbeddedGraph.GetType().Name; pathPrefixInInlinedPatternClass = alternative.originalAlternative.pathPrefix + alternative.originalAlternative.name + "_"; unprefixedNameInInlinedPatternClass = alternative.originalAlternative.alternativeCases[i].name; } SearchProgramBodyBuilder builder = new SearchProgramBodyBuilder( SearchProgramType.AlternativeCase, model, rulePatternClassName, null, null, null, altCase, emitProfiling, parallelized, 0 ); AlternativeCaseMatching alternativeCaseMatching = new AlternativeCaseMatching( pathPrefixInInlinedPatternClass, unprefixedNameInInlinedPatternClass, inlinedPatternClassName, builder.wasIndependentInlined(altCase, 0)); alternativeCaseMatching.OperationsList = new SearchProgramList(alternativeCaseMatching); SearchProgramOperation continuationPointAfterAltCase = insertionPoint.Append(alternativeCaseMatching); // at level of the current alt case insertionPoint = alternativeCaseMatching.OperationsList; insertionPoint = insertVariableDeclarations(insertionPoint, altCase); // start building with first operation in scheduled search plan builder.BuildScheduledSearchPlanOperationIntoSearchProgram( 0, insertionPoint); // back to level of alt cases insertionPoint = continuationPointAfterAltCase; // save matches found by alternative case to get clean start for matching next alternative case if (i < alternative.alternativeCases.Length - 1) { NewMatchesListForFollowingMatches newMatchesList = new NewMatchesListForFollowingMatches(true); insertionPoint = insertionPoint.Append(newMatchesList); } searchProgram.ArrayPerElementMethods += builder.arrayPerElementMethodBuilder.ToString(); } // finalize task/result-pushdown handling in subpattern matcher FinalizeSubpatternMatching finalize = new FinalizeSubpatternMatching(InitializeFinalizeSubpatternMatchingType.Normal); insertionPoint = insertionPoint.Append(finalize); return(searchProgram); }
private static void Main(string[] args) { try { Thread.CurrentThread.CurrentCulture = new CultureInfo("en-us"); DateTime dBegin = DateTime.Now; string source = ""; string blockvar = ""; //string[] myArgs = new string[4] { "-c-10", "-l-C", "-p-config.xml", "-s-ForTests" }; HelpText help = new HelpText(); ArgsParser aParser = new ArgsParser(args); Console.Title = "Test Generator"; if (args.Length == 0) { Console.WriteLine(help.Hello()); //Console.WriteLine("Для выхода нажмите любую клавишу"); Console.SetCursorPosition(0, 0); Console.ReadKey(); return; } if (!aParser.Prove()) { Console.WriteLine("Устраните пожалуйста ошибки и повторите запуск."); Console.WriteLine("Запуск Генератора без параметров приведет к появлению Справки."); Console.ReadKey(); return; } Console.WriteLine("Параметры заданы корректно."); Console.WriteLine("Начинается процесс генерации."); string subDirName = DateTime.Now.ToString("hh-mm-ss-dd-MM-yyyy"); Grammar mGrammar; ConfigParser parser = new ConfigParser(aParser.configTest, "validating/members.xml"); blockvar = parser.blockvars(); StreamReader reader = new StreamReader(aParser.grammarTest); source = reader.ReadToEnd(); using (StreamWriter writer = new StreamWriter(/*Path.GetTempPath()+*/ "tmpGrammar.txt")) { writer.WriteLine(source); writer.WriteLine(blockvar); writer.WriteLine(parser.blockstats()); } mGrammar = Grammar.FromTextFile(/*Path.GetTempPath() + */ "tmpGrammar.txt"); mGrammar.mTransductor = new transductor(); string exMessage; string s = ""; int totalPassed = 0; int totalFailed = 0; int count_of_ex; for (int i = 1; i <= aParser.countTest; i++) { count_of_ex = 0; // Console.WriteLine("deep1"); do { exMessage = ""; try { s = Alternative.Print(mGrammar.Generate()); //Console.WriteLine("deep2"); } catch (Exception ex) { exMessage = ex.Message; count_of_ex++; //Console.WriteLine("deep"); if (count_of_ex == 10) { Console.WriteLine("Генератор сообщает:"); Console.WriteLine("Слишком большая глубина вложенности. Тест не может быть гарантированно корректным."); Console.WriteLine( "Попробуйте настроить конфигурационный файл так, чтобы встречалось меньше вложенных конструкций."); Console.ReadKey(); return; } } } while (exMessage == "Слишком большая глубина вложенности. Тест не может быть гарантированно корректным."); replaceHolding sFormat = new replaceHolding(s, parser.inds, parser.arrayLength(), parser.IndexCount()); string tmp; tmp = sFormat.PrintText(); string tmpFileName = /*Path.GetTempPath() + "\\*/ "tmpName.c"; using (StreamWriter tmpFile = File.CreateText(tmpFileName)) { tmpFile.WriteLine(tmp); } FileInfo fSize = new FileInfo(tmpFileName); int Size = (int)fSize.Length; int TimeToExit = 0; ProcessStartInfo proc = new ProcessStartInfo("MinGW/bin/gcc.exe", tmpFileName); proc.RedirectStandardError = true; proc.UseShellExecute = false; Process p = Process.Start(proc); //p.WaitForExit(10000); while (!p.HasExited) { TimeToExit++; //Console.WriteLine(TimeToExit); } string warningString = p.StandardError.ReadToEnd(); Console.WriteLine(warningString); //p.Dispose(); if (warningString.Contains("error")) { Console.WriteLine("failed"); totalFailed++; continue; } else { Console.WriteLine("passed"); totalPassed++; if (Size > 50 * 1024) { Console.WriteLine("too long"); continue; } } p.Dispose(); File.Delete(tmpFileName); if (aParser.spathTest != "undefined") { DirectoryInfo mainDir = new DirectoryInfo(aParser.spathTest); if (mainDir.Exists) { //DirectoryInfo subDir = mainDir.CreateSubdirectory(DateTime.Today.ToString("dd-mM-yyyy")); DirectoryInfo subDir = mainDir.CreateSubdirectory(subDirName); using ( StreamWriter curFile = File.CreateText(subDir.ToString() + "\\" + aParser.SetFileName(aParser.countTest, i) + ".c")) { curFile.WriteLine(tmp); Console.WriteLine("--" + i + "--"); } } } else { Console.WriteLine(tmp); Console.WriteLine("--" + i + "--"); } //File.Delete(Path.GetTempPath() + "tmpGrammar.txt"); //File.Delete("tmpGrammar.txt"); File.Delete("a.exe"); } DateTime dEnd = DateTime.Now; TimeSpan total = dEnd - dBegin; string totalReport = "На генерацию затрачено "; if (total.Hours != 0) { totalReport += total.Hours + " ч. "; } if (total.Minutes != 0) { totalReport += total.Minutes + " мин. "; } if (total.Seconds != 0) { totalReport += total.Seconds + " сек. "; } Console.WriteLine(totalReport); Console.WriteLine("Попытка сгенерировать: " + aParser.countTest); Console.WriteLine("Из них правильных: " + totalPassed); Console.WriteLine("Из них неправильных: " + totalFailed); //Console.WriteLine(dBegin.ToLongTimeString()); //Console.WriteLine(dEnd.ToLongTimeString()); //Console.WriteLine(total.TotalSeconds); //Console.WriteLine(total.Seconds); Console.WriteLine("Генерация тестов завершена."); Console.WriteLine("Для выхода нажмите любую клавишу..."); Console.ReadKey(); } catch (Exception myEx) { Console.WriteLine("Ошибка генерации. Проверьте корректность входных данных."); Console.WriteLine("Для выхода нажмите любую клавишу..."); Console.WriteLine("Генератор сообщает:"); Console.WriteLine(myEx.Message); Console.ReadKey(); return; } }
public override bool enable(Alternative alt) { throw new NotImplementedException(); }
public override Boolean enable(Alternative alt) { return(channel.readerEnable(alt)); }
internal int SignalChoice(Alternative alt) { lock (lockObject) { if (choiceStatus == choiceState.INACTIVE) return -1; int index = indices[alt]; if (choiceStatus == choiceState.WAITING) { choiceStatus = choiceState.INACTIVE; Monitor.Pulse(lockObject); selected = index; return choiceThreadId; } if (traverseIndex > fairIndex) { if (index > traverseIndex || index < fairIndex) return -1; } else { if (index > traverseIndex && index < fairIndex) return -1; } choiceStatus = choiceState.INACTIVE; selected = index; return choiceThreadId; } }
public void AddAlternative(Alternative alternative) { alternatives.Add(alternative); }
private static void UpdateSubContainers(DesignPrimitivesWrapper de, Container rootContainerType, DesignModel rootDesignModel, Dictionary <CyPhy.Port, PortInstance> cyphyPorts2PortInstances, Dictionary <CyPhy.Port, ContainerPort> containerPorts, List <Connection> connectionsToBeVisited, Dictionary <CyPhy.SimpleFormula, ContainerCalculation> simpleFormulas, Dictionary <CyPhy.ValueFlowTarget, AVM.META.Design.ValueType> valueInstances, Dictionary <CyPhy.Port, StructuralInterfaceInstance> innerStructuralPortInstances, Dictionary <CyPhy.Port, ContainerStructuralInterface> containerStructuralPortInstances) { System.Diagnostics.Debug.WriteLine(de.Path); // Init list if (rootContainerType.ContainerPorts == null) { rootContainerType.ContainerPorts = new List <ContainerPort>(); } rootContainerType.ComponentInstances = new List <ComponentInstance>(); // Add Powerflows, JointStrucutres and ValueFlows for later steps connectionsToBeVisited.AddRange(de.ValueFlows); #region Handle ComponentRefs var componentRefs = de.ComponentRefs; foreach (var compRef in componentRefs) { var isComponent = false; try { var c = compRef.Referred.Component; // line above throws an exception if it is not a component isComponent = true; } catch { } if (compRef != null && isComponent) { CyPhy.Component comp = compRef.Referred.Component; System.Diagnostics.Debug.WriteLine(comp.Path); ComponentInstance compInst = Component2ComponentInstance(comp); rootContainerType.ComponentInstances.AddItem(compInst); compInst.Name = compRef.Name; //compInst.id = GetOrSetID(compRef); //compInst.id = compRef.Guid.ToString(); String instanceGUID = compRef.Attributes.InstanceGUID; // Set this value if not set if (String.IsNullOrWhiteSpace(instanceGUID)) { compRef.Attributes.InstanceGUID = compRef.Guid.ToString(); instanceGUID = compRef.Attributes.InstanceGUID; } compInst.id = compRef.Attributes.InstanceGUID; String s_SrcDesignSpaceContainerID = GetDesignSpaceSourceObjectID(compRef); if (!String.IsNullOrWhiteSpace(s_SrcDesignSpaceContainerID)) { compInst.SrcDesignSpaceContainerID = s_SrcDesignSpaceContainerID; } // Update Component's PortInstances compInst.PortInstances = new List <PortInstance>(); foreach (CyPhy.Port port in comp.Children.PortCollection) { #if TRACK_PORT_ID var portInst = new PortInstance { IDinSourceModel = port.ID }; #else var portInst = new PortInstance { IDinSourceModel = port.Attributes.ID }; #endif //var portInst = new PortInstance { IDinSourceModel = port.ID }; compInst.PortInstances.AddItem(portInst); if (!cyphyPorts2PortInstances.ContainsKey(port)) { cyphyPorts2PortInstances.Add(port, portInst); // Update Ports list } } // Convert parameters foreach (var p in comp.Children.ParameterCollection) { double result = 0; double.TryParse(p.Attributes.Value, out result); var componentNamedValueInstance = new ComponentNamedValueInstance { IDinComponentModel = p.Attributes.ID, Value = result }; compInst.NamedValueInstances.AddItem(componentNamedValueInstance); if (valueInstances.ContainsKey(p)) { continue; } valueInstances.Add(p, componentNamedValueInstance); } // Convert properties foreach (var p in comp.Children.PropertyCollection) { double result = 0; double.TryParse(p.Attributes.Value, out result); var componentNamedValueInstance = new ComponentNamedValueInstance { IDinComponentModel = p.Attributes.ID, Value = result }; compInst.NamedValueInstances.AddItem(componentNamedValueInstance); if (valueInstances.ContainsKey(p)) { continue; } valueInstances.Add(p, componentNamedValueInstance); } } } #endregion #region Handle Component instances List <CyPhy.Component> lcChildComps = de.Components; foreach (CyPhy.Component comp in lcChildComps) { System.Diagnostics.Debug.WriteLine(comp.Path); ComponentInstance compInst = Component2ComponentInstance(comp); rootContainerType.ComponentInstances.AddItem(compInst); // Update Component's PortInstances compInst.PortInstances = new List <PortInstance>(); foreach (CyPhy.Port port in comp.Children.PortCollection) { #if TRACK_PORT_ID var structPort = new StructuralInterfaceInstance { IDinSourceModel = port.ID }; #else var structPort = new StructuralInterfaceInstance { IDinSourceModel = port.Attributes.ID }; #endif if (!innerStructuralPortInstances.ContainsKey(port)) { innerStructuralPortInstances.Add(port, structPort); compInst.StructuralInterfaceInstances.Add(structPort); } #if TRACK_PORT_ID var portInst = new PortInstance { IDinSourceModel = port.ID }; #else var portInst = new PortInstance { IDinSourceModel = port.Attributes.ID }; #endif compInst.PortInstances.AddItem(portInst); if (!cyphyPorts2PortInstances.ContainsKey(port)) { cyphyPorts2PortInstances.Add(port, portInst); // Update Ports list } } // Convert parameters foreach (var p in comp.Children.ParameterCollection) { double result = 0; double.TryParse(p.Attributes.Value, out result); var componentNamedValueInstance = new ComponentNamedValueInstance { IDinComponentModel = p.Attributes.ID, Value = result }; compInst.NamedValueInstances.AddItem(componentNamedValueInstance); if (valueInstances.ContainsKey(p)) { continue; } valueInstances.Add(p, componentNamedValueInstance); } // Convert properties foreach (var p in comp.Children.PropertyCollection) { double result = 0; double.TryParse(p.Attributes.Value, out result); var componentNamedValueInstance = new ComponentNamedValueInstance { IDinComponentModel = p.Attributes.ID, Value = result }; compInst.NamedValueInstances.AddItem(componentNamedValueInstance); if (valueInstances.ContainsKey(p)) { continue; } valueInstances.Add(p, componentNamedValueInstance); } } #endregion // Recursively add all ContainerTypes from sub-DesignEntities rootContainerType.Containers = new List <Container>(); var ldeDesignEntityChildren = de.ComponentAssemblies.Cast <CyPhy.DesignEntity>().ToList(); ldeDesignEntityChildren.AddRange(de.DesignContainers); foreach (CyPhy.DesignEntity subDE in ldeDesignEntityChildren) { Container subRootContainerType; if (subDE is CyPhy.DesignContainer && (subDE as CyPhy.DesignContainer).Attributes.ContainerType == CyPhyClasses.DesignContainer.AttributesClass.ContainerType_enum.Compound) { subRootContainerType = new Compound(); } else if (subDE is CyPhy.DesignContainer && (subDE as CyPhy.DesignContainer).Attributes.ContainerType == CyPhyClasses.DesignContainer.AttributesClass.ContainerType_enum.Alternative) { subRootContainerType = new Alternative(); } else if (subDE is CyPhy.DesignContainer && (subDE as CyPhy.DesignContainer).Attributes.ContainerType == CyPhyClasses.DesignContainer.AttributesClass.ContainerType_enum.Optional) { subRootContainerType = new Optional(); } else if (subDE is CyPhy.ComponentAssembly) { subRootContainerType = new Compound(); } else { continue; } subRootContainerType.Name = subDE.Name; subRootContainerType.id = GetOrSetID(subDE); rootContainerType.Containers.AddItem(subRootContainerType); UpdateSubContainers(new DesignPrimitivesWrapper(subDE), subRootContainerType, rootDesignModel, cyphyPorts2PortInstances, containerPorts, connectionsToBeVisited, simpleFormulas, valueInstances, innerStructuralPortInstances, containerStructuralPortInstances); } #region Elements on the current container // Convert simple formulas foreach (var sf in de.SimpleFormulas) { var containerCalculation = new ContainerCalculation(); rootContainerType.ContainerValues.AddItem(containerCalculation); simpleFormulas[sf] = containerCalculation; } // Add container ports (from ports) foreach (var port in de.Ports) { if (containerPorts.ContainsKey(port)) { continue; } var pi = new ContainerPort(); containerPorts.Add(port, pi); rootContainerType.ContainerPorts.AddItem(pi); } // Convert parameters foreach (var p in de.Parameters) { var containerNamedValue = new ContainerNamedValue { IsParameter = true, Value = p.Attributes.Value }; rootContainerType.ContainerValues.AddItem(containerNamedValue); if (valueInstances.ContainsKey(p)) { continue; } valueInstances.Add(p, containerNamedValue); } // Convert properties foreach (var p in de.Properties) { var containerNamedValue = new ContainerNamedValue { IsParameter = false, Value = p.Attributes.Value }; rootContainerType.ContainerValues.AddItem(containerNamedValue); if (valueInstances.ContainsKey(p)) { continue; } valueInstances.Add(p, containerNamedValue); } #endregion }
/** * Returns true if the event is ready. Otherwise, this enables the guard * for selection and returns false. * <P> * <I>Note: this method should only be called by the Alternative class</I> * * @param alt the Alternative class that is controlling the selection * @return true if and only if the event is ready */ Boolean enable(Alternative alt) { return(altingChannel.enable(alt)); }
// Only accept ComponentAssembly and DesignContainer public static DesignModel Convert(CyPhy.DesignEntity de) { if (!(de.Kind == "ComponentAssembly" || de.Kind == "DesignContainer")) { return(null); } ResetCache(); var dm = new DesignModel { Name = de.Name }; Container rootContainerType = null; if (de is CyPhy.ComponentAssembly) { String s_ID = (de as CyPhy.ComponentAssembly).Attributes.ConfigurationUniqueID; if (string.IsNullOrEmpty(s_ID)) { s_ID = Guid.NewGuid().ToString("B"); (de as CyPhy.ComponentAssembly).Attributes.ConfigurationUniqueID = s_ID; } if (s_ID.IndexOf("{") != 0) { // Add curly braces s_ID = string.Concat("{", s_ID, "}"); } dm.DesignID = s_ID; rootContainerType = new Compound(); } else if (de is CyPhy.DesignContainer) { dm.DesignID = (de as CyPhy.DesignContainer).Impl.GetGuidDisp(); switch (((CyPhy.DesignContainer)de).Attributes.ContainerType) { case CyPhyClasses.DesignContainer.AttributesClass.ContainerType_enum.Compound: rootContainerType = new Compound(); break; case CyPhyClasses.DesignContainer.AttributesClass.ContainerType_enum.Alternative: rootContainerType = new Alternative(); break; case CyPhyClasses.DesignContainer.AttributesClass.ContainerType_enum.Optional: rootContainerType = new Optional(); break; default: throw new ArgumentOutOfRangeException(); } } // Add single ContainerType for the root level Container dm.Containers.AddItem(rootContainerType); rootContainerType.Name = de.Name; rootContainerType.id = GetOrSetID(de); // Update DesignModel by calling recursive update method var innerPortInstances = new Dictionary <CyPhy.Port, PortInstance>(); var containerPortInstances = new Dictionary <CyPhy.Port, ContainerPort>(); var innerStructuralPortInstances = new Dictionary <CyPhy.Port, StructuralInterfaceInstance>(); var containerStructuralPortInstances = new Dictionary <CyPhy.Port, ContainerStructuralInterface>(); var connections = new List <Connection>(); var simpleFormulas = new Dictionary <CyPhy.SimpleFormula, ContainerCalculation>(); // Can contain: ContainerNamedValue/ContainerCalculation/ComponentNamedValueInstance var valueInstances = new Dictionary <CyPhy.ValueFlowTarget, AVM.META.Design.ValueType>(); UpdateSubContainers(new DesignPrimitivesWrapper(de), rootContainerType, dm, innerPortInstances, containerPortInstances, connections, simpleFormulas, valueInstances, innerStructuralPortInstances, containerStructuralPortInstances); #region Create AllPorts dictionary var allPorts = new Dictionary <CyPhy.Port, AbstractPort>(); foreach (var portInstance in innerPortInstances) { allPorts.Add(portInstance.Key, portInstance.Value); } foreach (var containerPort in containerPortInstances) { allPorts.Add(containerPort.Key, containerPort.Value); } #endregion #region Create AllStructuralPorts dictionary var allStructuralPorts = new Dictionary <CyPhy.Port, AbstractStructuralInterface>(); foreach (var abstractPortInstance in innerStructuralPortInstances) { allStructuralPorts.Add(abstractPortInstance.Key, abstractPortInstance.Value); } foreach (var abstractContainerPort in containerStructuralPortInstances) { allStructuralPorts.Add(abstractContainerPort.Key, abstractContainerPort.Value); } #endregion #region Join Structures -> PortConnectors // Pair construct //ConvertJoinStructures(dm, innerPortInstances, connections.OfType<CyPhy.JoinStructures>()); // Grouping construct //ConvertJoinStrucutresInGroups(GetStructuralPortGroups(allPorts, connections.OfType<CyPhy.JoinStructures>()), dm, allPorts); // Pair construct #endregion #region ValueFlow -> ValueConnector ConvertValueFlows(dm, connections.OfType <CyPhy.ValueFlow>(), simpleFormulas, allPorts, valueInstances); #endregion return(dm); }
/** * Enable this ALT as a guard within its parent ALT. This will enable all of its guards. */ public override Boolean enable(Alternative alt) { timeoutIndex = -1; for (int i = favourite; i < guard.Length; i++) { if ((preconditions == null) || (preconditions[i])) { if (guard[i].enable(alt)) { selected = i; return(true); } if (timers[i] != null) { if (timeoutIndex < 0) { timeoutIndex = i; minAlarm = timers[i].getAlarm(); } else { long a = timers[i].getAlarm(); if (a < minAlarm) { timeoutIndex = i; minAlarm = a; } } } else if (ialts[i] != null) { if (timeoutIndex < 0) { timeoutIndex = i; minAlarm = ialts[i].minAlarm; } else { long a = ialts[i].minAlarm; if (a < minAlarm) { timeoutIndex = i; minAlarm = a; } } } } } for (int i = 0; i < favourite; i++) { if ((preconditions == null) || (preconditions[i])) { if (guard[i].enable(alt)) { selected = i; return(true); } if (timers[i] != null) { if (timeoutIndex < 0) { timeoutIndex = i; minAlarm = timers[i].getAlarm(); } else { long a = timers[i].getAlarm(); if (a < minAlarm) { timeoutIndex = i; minAlarm = a; } } } else if (ialts[i] != null) { if (timeoutIndex < 0) { timeoutIndex = i; minAlarm = ialts[i].minAlarm; } else { long a = ialts[i].minAlarm; if (a < minAlarm) { timeoutIndex = i; minAlarm = a; } } } } } selected = -1; return(false); }
public override CodeBlockForAlt Epsilon(Alternative alt, bool outerMost) { return(Alternative(alt, outerMost)); }
public ControlCharacter([NotNull] Alternative element) : base(element) { }
public AlternativeNode this[Alternative alternative] { get { return(_nodes.OfType <AlternativeNode>().SingleOrDefault(x => x.Alternative == alternative)); } }
public override Boolean enable(Alternative alt) { syncDone = ab.enable(alt); return(syncDone); }
public bool Contains(Alternative alternative) { return(_nodes.OfType <AlternativeNode>().SingleOrDefault(x => x.Alternative == alternative) != null); }
public AlternativeNode(Alternative alternative) : this(alternative, 0M) { }
public AlternativeNodeViewModel(HierarchyViewModel hierarchy, Alternative alternative) : base(hierarchy) { Alternative = alternative; Name = alternative.Name; }
private void HandleAlternativesStart() { Alternative alternative = new Alternative(); AddElement(alternative); }
/// <summary> /// Player selected an option in a presented alternative /// </summary> /// <param name="alternativeId">Alternative identifier.</param> /// <param name="optionId">Option identifier.</param> /// <param name="type">Alternative type.</param> public void Selected(string alternativeId, string optionId, bool correct, Alternative type) { tracker.setResponse(optionId); tracker.setSuccess(correct); tracker.ActionTrace(Tracker.Verb.Selected.ToString().ToLower(), type.ToString().ToLower(), alternativeId); }
public Marker(Alternative alt, int pos, string lookahead) { Alternative = alt; Position = pos; Lookahead = lookahead; }
/// <summary> /// Player unlocked an option /// </summary> /// <param name="alternativeId">Alternative identifier.</param> /// <param name="optionId">Option identifier.</param> /// <param name="type">Alternative type.</param> public void Unlocked(string alternativeId, string optionId, Alternative type) { tracker.setResponse(optionId); tracker.ActionTrace(Tracker.Verb.Unlocked.ToString().ToLower(), type.ToString().ToLower(), alternativeId); }
public virtual void SetCurrentOuterMostAlt(Alternative currentOuterMostAlt) { this.currentOuterMostAlt = currentOuterMostAlt; }
public void RemoveAlternative(Alternative alternative) { _alternatives.Remove(alternative); RefreshAlternativeNodes(); }
private static void NT_Alternative(ref Rule rule) { String nonterminal = ""; String terminal = ""; Alternative alternative = new Alternative(); Rule groupRule = null; Rule optionalRule = null; Rule repetitionRule = null; for (;;) { switch (Syn.Interpret()) { case 0: return; case 1: // SEM rule.AddAlternative(alternative); break; case 2: Lex.GETnonterminalAttr(out nonterminal); break; case 3: // SEM alternative.AddSymbol(new Symbol(nonterminal, Symbol.Kind.NONTERMINAL)); break; case 4: Lex.GETterminalAttr(out terminal); break; case 5: // SEM alternative.AddSymbol(new Symbol(terminal, Symbol.Kind.TERMINAL)); break; case 6: // SEM groupRule = new Rule(); groupRule.NonTerminal = symbolNameGenerator.Generate(); rules.Add(groupRule); alternative.AddSymbol(new Symbol(groupRule.NonTerminal, Symbol.Kind.NONTERMINAL)); break; case 7: NT_Grouping(ref groupRule); break; case 8: // SEM optionalRule = new Rule(); optionalRule.NonTerminal = symbolNameGenerator.Generate(); // add empty alternative optionalRule.AddAlternative(new Alternative()); rules.Add(optionalRule); alternative.AddSymbol(new Symbol(optionalRule.NonTerminal, Symbol.Kind.NONTERMINAL)); break; case 9: NT_Optional(ref optionalRule); break; case 10: // SEM repetitionRule = new Rule(); repetitionRule.NonTerminal = symbolNameGenerator.Generate(); rules.Add(repetitionRule); alternative.AddSymbol(new Symbol(repetitionRule.NonTerminal, Symbol.Kind.NONTERMINAL)); break; case 11: NT_Repetition(ref repetitionRule); break; case 12: // SEM // add recursion to every alternative foreach (Alternative a in repetitionRule.GetAlternatives()) { a.AddSymbol(new Symbol(repetitionRule.NonTerminal, Symbol.Kind.NONTERMINAL)); } // add empty alternative repetitionRule.AddAlternative(new Alternative()); break; } // switch } // for }
private Alternative DrawAlternative(IRandomUtility randomUtility, int id = Constants.DEFAULT_VALUE, int observed = Constants.DEFAULT_VALUE) { Alternative chosenAlternative = null; var random = randomUtility.Uniform01(); foreach (var alternative in _alternatives.Where(a => a != null && a.Key == _key && a.Available)) { chosenAlternative = alternative; random -= alternative.Probability; if (random < 0) { break; } } if (Global.Configuration.TraceSimulatedChoiceOutcomes && _key != 0) { Global.PrintFile.WriteLine("> Key {0} Alternative {1} chosen for model {2}", _key, chosenAlternative == null ? Constants.DEFAULT_VALUE : chosenAlternative.Id, _title); } if (chosenAlternative != null && Global.Configuration.TestEstimationModelInApplicationMode && observed >= 0 && _tempWriter != null) { bool observedAvail = false; bool nonObservedAvail = false; double probObserved = -1; foreach (var alternative in _alternatives.Where(a => a != null && a.Key == _key)) { if (alternative.Id - 1 == observed) { observedAvail = alternative.Available; probObserved = alternative.Probability; } else if (!nonObservedAvail) { nonObservedAvail = alternative.Available; } } _tempWriter.Write("{0} {1} {2} {3}", id, observed, observedAvail && nonObservedAvail ? probObserved : -1, chosenAlternative.Id - 1); if (!observedAvail) { _nChosenNotAvail[observed]++; } else if (!nonObservedAvail) { _nChosenOnlyAvail[observed]++; } else { _nChosenAndAvail[observed]++; _nPredicted[chosenAlternative.Id - 1]++; } foreach (var alternative in _alternatives.Where(a => a != null && a.Key == _key)) { _tempWriter.Write(" {0}", alternative.Available ? alternative.Probability : -1); if (alternative.Available && observedAvail && nonObservedAvail) { _nAvailable[alternative.Id - 1]++; _totalProb[alternative.Id - 1] += alternative.Probability; } } _tempWriter.WriteLine(); } // if (chosenAlternative == null) { // chosenAlternative = _alternatives[0]; // Global.PrintFile.WriteLine("SimulateChoice.DrawAlternative had no available alternatives to choose from. Alternative 0 set as chosen, key is {0}",chosenAlternative.Key); // } return(chosenAlternative); }