// private Inputs expectedInputs; public Dialogue() { currentState = State.BEGIN; //dramaMaster = new Drama(); correctAnswers = new AnswerDatabase(); systemOutputs = new Outputs(); //expectedInputs = new Inputs(); userName = ""; beginningDialogue = 0; nextLevelDialogue = 0; enter = false; flag = false; cooperative = true; hasMetThreshold = true; }
/// <summary> /// Shows an error message to the user</summary> /// <param name="message">Error message</param> protected void ShowErrorMessage(string message) { Outputs.WriteLine(OutputMessageType.Warning, message); }
/// <summary> /// Gets the path name for a new document</summary> /// <param name="client">Document client</param> /// <returns>URI representing the new path, or null if the user cancelled</returns> protected virtual Uri GetNewDocumentUri(IDocumentClient client) { Uri uri = null; string fileName = client.Info.NewDocumentName; string extension = null; string directoryName = null; if (client.Info.Extensions.Length > 1) { if (string.IsNullOrEmpty(client.Info.DefaultExtension)) { // Since there are multiple possible extensions, ask the user to pick a filename. string path = PromptUserForNewFilePath(client, fileName, null); if (path != null) { try { if (File.Exists(path)) { File.Delete(path); } } catch (Exception e) { string message = string.Format( "Failed to delete: {0}. Exception: {1}", path, e); Outputs.WriteLine(OutputMessageType.Warning, message); } m_newDocumentPaths.Add(path); uri = new Uri(path, UriKind.RelativeOrAbsolute); return(uri); } } else { directoryName = client.Info.InitialDirectory; if (directoryName == null) { directoryName = FileDialogService.InitialDirectory; } extension = client.Info.DefaultExtension; } } if (client.Info.Extensions.Length >= 1) { // Since there is only one possible extension, we can choose the new name (e.g., "Untitled.xml"). directoryName = client.Info.InitialDirectory; if (directoryName == null) { directoryName = FileDialogService.InitialDirectory; } extension = client.Info.Extensions[0]; if (directoryName != null && extension != null) { int suffix; m_extensionSuffixes.TryGetValue(extension, out suffix); // check the name to make sure there is no existing file with the same name while (true) { string fullFileName = fileName; if (suffix > 0) { fullFileName += "(" + (suffix + 1) + ")"; } suffix++; fullFileName += extension; string fullPath = Path.Combine(directoryName, fullFileName); if (!FileDialogService.PathExists(fullPath)) { uri = new Uri(fullPath, UriKind.RelativeOrAbsolute); break; } } m_extensionSuffixes[extension] = suffix; } } return(uri); }
/// <summary> /// 发送数据 /// </summary> internal unsafe void BuildOutput() { if (IsSocket) { TcpStreamServer.ServerOutput.OutputLink head = null, end; TcpServer.SenderBuildInfo buildInfo = new TcpServer.SenderBuildInfo { SendBufferSize = Server.SendBufferPool.Size, IsClientAwaiter = Server.Attribute.IsClientAwaiter }; UnmanagedStream outputStream; try { if (Buffer.Buffer == null) Server.SendBufferPool.Get(ref Buffer); if (OutputSerializer == null) outputStream = (OutputSerializer = BinarySerialize.Serializer.YieldPool.Default.Pop() ?? new BinarySerialize.Serializer()).SetTcpServer(); else outputStream = OutputSerializer.Stream; int outputSleep = OutputSleep, currentOutputSleep; do { buildInfo.IsNewBuffer = 0; fixed (byte* dataFixed = Buffer.Buffer) { byte* start = dataFixed + Buffer.StartIndex; STREAM: using (outputStream) { if (outputStream.Data.Byte != start) outputStream.Reset(start, Buffer.Length); buildInfo.Clear(); outputStream.ByteSize = 0; currentOutputSleep = outputSleep; if ((head = Outputs.GetClear(out end)) == null) goto CHECK; LOOP: do { head = head.Build(this, ref buildInfo); if (buildInfo.IsSend != 0 || !ServerSocket.IsVerifyMethod) { if (head != null) Outputs.PushHead(ref head, end); goto SEND; } } while (head != null); if (!Outputs.IsEmpty) { head = Outputs.GetClear(out end); goto LOOP; } CHECK: if (currentOutputSleep >= 0) { Thread.Sleep(currentOutputSleep); if (!Outputs.IsEmpty) { head = Outputs.GetClear(out end); currentOutputSleep = 0; goto LOOP; } } if (outputStream.ByteSize == 0) { outputStream.Dispose(); goto END; } SEND: buildInfo.IsNewBuffer = setSendData(start); } switch (send()) { case TcpOpenServer.SendState.Asynchronous: return; case TcpOpenServer.SendState.Error: buildInfo.IsError = true; return; } if (!Outputs.IsEmpty) { if (buildInfo.IsNewBuffer == 0) goto STREAM; goto FIXEDEND; } END: //IsOutput = 0; if (IsSocket) { Interlocked.Exchange(ref IsOutput, 0); if (!Outputs.IsEmpty) { if (Interlocked.CompareExchange(ref IsOutput, 1, 0) == 0) { if (buildInfo.IsNewBuffer == 0) goto STREAM; goto FIXEDEND; } } else if (!IsSocket && Interlocked.CompareExchange(ref IsOutput, 1, 0) == 0) buildInfo.IsClose = true; } else buildInfo.IsClose = true; return; FIXEDEND:; } } while (buildInfo.IsNewBuffer != 0); } catch (Exception error) { Server.Log.Add(AutoCSer.Log.LogType.Error, error); buildInfo.IsError = true; } finally { if (buildInfo.IsError | buildInfo.IsClose) { if (buildInfo.IsError) closeSocket(); else close(); TcpStreamServer.ServerOutput.OutputLink.CancelLink(head); } } } else close(); }
private void calculateOutputs(Wallet.Wallet wallet) { if (Inputs != null) { long balance = BalanceHelper.GetBalanceOfAddresses(Inputs.Select(i => i.Key).ToArray()); Outputs.Add(new Output(wallet.NewAddress().Key, balance - TransactionFee - Outputs.Select(o => o.Amount).Sum())); } }
protected virtual void OnInitializing() { State = ExecutionState.Initializing; try { try { InitLog(); } catch (Exception e) { throw new Exception("InitLog threw", e); } try { _InitPartial(); } catch (Exception ex) { throw new Exception("_InitPartial threw", ex); } ValidateConfiguration(); #if cAlgo //if (Bot == null) //{ // throw new Exception("TEMP - Bot == null in OnInitializing()"); //} if (Bot != null && Bot.Indicators == null) { throw new Exception("Bot != null && Bot.Indicators == null in OnInitializing()"); } #endif if (EffectiveIndicators == null) { throw new Exception("EffectiveIndicators == null"); } if (!Outputs.Any()) { throw new Exception("!Outputs.Any(). Override Outputs."); } foreach (var child in Children.OfType <IIndicator>()) { #if !cAlgo if (child.Account == null) { // REvIEW - shouldn't be needed here? child.Account = this.Account; } child.Start(); #endif } State = ExecutionState.Ready; } catch (Exception) { State = ExecutionState.Uninitialized; throw; } }
public void PushValueOnOuput(double outputValue) { //Update values of output synapses Outputs.ForEach(output => output.Output = outputValue); }
/// <summary> /// Override to compile a RDBMS Table /// </summary> protected virtual void DoTable(IConfigSectionNode tableNode, Outputs outputs) { var tname = tableNode.Value; if (tname.IsNullOrWhiteSpace()) { m_CompileErrors.Add(new SchemaCompilationException(tableNode.RootPath, "Table name missing")); return; } var table = new RDBMSEntity(m_All, tableNode, RDBMSEntityType.Table, tname, tableNode.AttrByName(SHORT_NAME_ATTR).Value); TransformEntityName(table); var sb = outputs[RDBMSCompiler.TABLES_OUTPUT]; sb.AppendLine(GetStatementDelimiterScript(RDBMSEntityType.Table, true)); sb.AppendLine("-- {0}".Args( tableNode.AttrByName(SCRIPT_COMMENT_ATTR).ValueAsString("Table " + table.TransformedName))); sb.AppendLine("{0} {1}".Args( TransformKeywordCase("create table"), GetQuotedIdentifierName(RDBMSEntityType.Table, table.TransformedName) )); sb.AppendLine("("); var firstItem = true; foreach(var node in tableNode.Children) { if (node.IsSameName(COLUMN_SECTION)) { DoColumn(node, table, sb, ref firstItem, outputs); } else if (node.IsSameName(PRIMARY_KEY_SECTION)) { DoReadPrimaryKeySection(node, table); } else if (node.IsSameName(INDEX_SECTION)) { DoReadIndexSection(node, table); } else if (node.IsSameName(SCRIPT_INCLUDE_SECTION)) { IncludeScriptFile(node, outputs); sb.AppendLine(); } else if (node.IsSameName(SCRIPT_TEXT_SECTION)) { IncludeScriptText(node, outputs); sb.AppendLine(); } else m_CompileErrors.Add(new SchemaCompilationException(node.RootPath, "Unrecognized item inside '{0}' table section '{1}'".Args(tname, node.Name))); } DoPrimaryKeys(table, sb, ref firstItem); DoForeignKeys(table, sb, ref firstItem, outputs); sb.AppendLine(); sb.AppendLine(")"); var comment = tableNode.AttrByName(COMMENT_ATTR).Value; if (comment.IsNotNullOrWhiteSpace()) { sb.AppendLine(" {0} = {1}".Args(TransformKeywordCase("comment"), EscapeString(comment) )); } sb.AppendLine(GetStatementDelimiterScript(RDBMSEntityType.Table, false)); sb.AppendLine(); DoTableIndexes(table, outputs); }
/// <summary> /// 发送数据 /// </summary> internal unsafe void BuildOutput() { if (IsSocket) { TcpStreamServer.ServerOutput.OutputLink head = null, end; TcpServer.SenderBuildInfo buildInfo = new TcpServer.SenderBuildInfo { SendBufferSize = Server.SendBufferPool.Size, IsClientAwaiter = Server.Attribute.IsClientAwaiter }; UnmanagedStream outputStream; SocketError socketError; try { if (Buffer.Buffer == null) { Server.SendBufferPool.Get(ref Buffer); } if (OutputSerializer == null) { outputStream = (OutputSerializer = BinarySerialize.Serializer.YieldPool.Default.Pop() ?? new BinarySerialize.Serializer()).SetTcpServer(); } else { outputStream = OutputSerializer.Stream; } int outputSleep = OutputSleep, currentOutputSleep; do { buildInfo.IsNewBuffer = 0; fixed(byte *dataFixed = Buffer.Buffer) { byte *start = dataFixed + Buffer.StartIndex; currentOutputSleep = outputSleep; STREAM: using (outputStream) { RESET: if (outputStream.Data.Byte != start) { outputStream.Reset(start, Buffer.Length); } buildInfo.Clear(); outputStream.ByteSize = 0; if ((head = Outputs.GetClear(out end)) == null) { if (currentOutputSleep < 0) { goto CHECK; } Thread.Sleep(currentOutputSleep); if (Outputs.IsEmpty) { goto CHECK; } head = Outputs.GetClear(out end); currentOutputSleep = 0; } LOOP: do { head = head.Build(this, ref buildInfo); if (buildInfo.IsSend != 0 || !ServerSocket.IsVerifyMethod) { goto SETDATA; } }while (head != null); if (!Outputs.IsEmpty) { head = Outputs.GetClear(out end); goto LOOP; } if (!buildInfo.IsClientAwaiter) { if (currentOutputSleep >= 0) { Thread.Sleep(currentOutputSleep); if (!Outputs.IsEmpty) { head = Outputs.GetClear(out end); currentOutputSleep = 0; goto LOOP; } } } else { if (currentOutputSleep == int.MinValue) { currentOutputSleep = outputSleep; } if (currentOutputSleep >= 0) { Thread.Sleep(currentOutputSleep); } else { AutoCSer.Threading.ThreadYield.YieldOnly(); } if (!Outputs.IsEmpty) { head = Outputs.GetClear(out end); currentOutputSleep = 0; goto LOOP; } } CHECK: if (outputStream.ByteSize == 0) { goto DISPOSE; } SETDATA: buildInfo.IsNewBuffer = setSendData(start); SEND: if (IsSocket) { int sendSize = Socket.Send(sendData.Array, sendData.Start, sendData.Length, SocketFlags.None, out socketError); sendData.MoveStart(sendSize); if (sendData.Length == 0) { buildInfo.SendSizeLessCount = 0; if (buildInfo.IsNewBuffer == 0) { freeCopyBuffer(); if (head == null) { currentOutputSleep = int.MinValue; goto RESET; } if (outputStream.Data.Byte != start) { outputStream.Reset(start, Buffer.Length); } buildInfo.Clear(); outputStream.ByteSize = 0; //currentOutputSleep = outputSleep; goto LOOP; } CompressBuffer.TryFree(); if (head != null) { Outputs.PushHead(ref head, end); } //currentOutputSleep = outputSleep; goto DISPOSE; } if (socketError == SocketError.Success && (sendSize >= TcpServer.Server.MinSocketSize || (sendSize > 0 && buildInfo.SendSizeLessCount++ == 0))) { goto SEND; } buildInfo.IsError = true; } buildInfo.IsNewBuffer = 0; DISPOSE :; } if (buildInfo.IsNewBuffer == 0) { if (!buildInfo.IsError) { if (IsSocket) { //IsOutput = 0; Interlocked.Exchange(ref IsOutput, 0); if (!Outputs.IsEmpty) { if (Interlocked.CompareExchange(ref IsOutput, 1, 0) == 0) { goto STREAM; } } else if (!IsSocket && Interlocked.CompareExchange(ref IsOutput, 1, 0) == 0) { buildInfo.IsClose = true; } } else { buildInfo.IsClose = true; } } return; } } }while (buildInfo.IsNewBuffer != 0); } catch (Exception error) { Server.Log.Add(AutoCSer.Log.LogType.Error, error); buildInfo.IsError = true; } finally { if (buildInfo.IsError | buildInfo.IsClose) { if (buildInfo.IsError) { closeSocket(); } else { close(); } TcpStreamServer.ServerOutput.OutputLink.CancelLink(head); } } } else { close(); } }
//This is the main action invoker //If you want to work with Action Inputs and Outputs directly, please overload it //It is a reflection based method calling your Action(params) method implementation public virtual void ActionCaller() { var method = Host.Action.GetMethod(nameof(Action)); var named = Inputs.Where((pair, i) => pair.Key.LinkName != "") .ToList(); //Fill all named paramerters var ps = method.GetParameters().Select( param => { object result = param; if (Inputs.Any(pair => pair.Key.LinkName == param.Name)) { if (param.IsOut) { throw new Exception("Link LinkName shall be of action input parameter "); } var k = Inputs.First(pair => pair.Key.LinkName == param.Name); if (param.ParameterType.IsList()) { result = k.Value; } else { result = k.Value.First(); k.Value.RemoveAt(0); } Inputs.Remove(k.Key); } return(result); } ).ToArray(); //Fill all other paramerters for (var index = 0; index < ps.Length; index++) { var o = ps[index]; if (o is ParameterInfo) { var param = (ParameterInfo)o; if (param.IsOut) { ps[index] = null; continue; } if (param.ParameterType.IsList()) { var key = new LinkKey { LinkName = "", MarkType = param.ParameterType }; var value = Inputs.TryGetValue(key, out var pValue) ? pValue : throw new InvalidOperationException( $"Parameter of type {param.ParameterType.Name} was not found" ); var elementType = param.ParameterType.GenericTypeArguments.First(); var lo = value.ReflectionCast(elementType); //var values = value.Select(x => Dynamic.InvokeConvert(x, elementType, true)).ToList(); ps[index] = lo; Inputs.Remove(key); } else { var listType = typeof(List <>); var constructedListType = listType.MakeGenericType(param.ParameterType); var key = new LinkKey { LinkName = "", MarkType = constructedListType }; var results = Inputs.TryGetValue(key, out var pValue) ? pValue : throw new InvalidOperationException( $"Parameter of type {param.ParameterType.Name} was not found" ); ps[index] = results.First(); results.RemoveAt(0); if (results.Count == 0) { Inputs.Remove(key); } } } } var rp = method.Invoke(this, ps); var outs = new Dictionary <Type, List <MarkType> >(); Action <object> release = variable => { var marks = new List <MarkType>(); var isArray = variable.GetType().IsList(); Type type; if (isArray) { type = (variable as IEnumerable).AsQueryable().ElementType; } else { type = variable.GetType(); } if (outs.TryGetValue(type, out var value) && value != null) { marks = value; } if (variable.GetType().IsList()) { marks.AddRange((variable as IEnumerable).Cast <MarkType>().ToList()); } else { marks.Add((MarkType)variable); } outs[type] = marks; }; for (var index = 0; index < method.GetParameters().Length; index++) { var o = method.GetParameters()[index]; if (o.IsOut) { var variable = ps[index]; release(variable); } } if (method.ReturnType != typeof(void)) { release(rp); } Host.Links.Where(l => l.To.GetType() == typeof(Place)).ToList().ForEach( l => { var marks = new List <MarkType>(); if (outs.TryGetValue(l.What, out var value) && value != null) { marks = value; } else { throw new Exception("Transitions Action had to return Tout: " + l.What); } var key = (Place)l.To; // Use smart place key??? // TODO move key params into place, forget about place keyu! switch (l.CountStrategy) { case Link.Count.One: { var m = marks.First(); //m.Host = key; marks.Remove(m); if (Outputs.TryGetValue(key, out var added)) { added.Add(m); } else { added = new List <MarkType> { m }; Outputs.Add(key, added); } break; } case Link.Count.All: { //marks.MoveMarksTo(key); if (Outputs.TryGetValue(key, out var added)) { added.AddRange(marks); } else { Outputs.Add(key, marks); } marks.Clear(); break; } case Link.Count.Some: { var ms = marks.Take(l.CountStrategyAmmount).ToList(); //ms.MoveMarksTo(l.To); if (Outputs.TryGetValue(key, out var added)) { added.AddRange(ms); } else { Outputs.Add(key, ms); } marks.RemoveAll(m => ms.Contains(m)); break; } case Link.Count.None: { throw new Exception("Error: A Transition link to outgoing place shall not be null"); } default: throw new ArgumentOutOfRangeException(); } } ); }
/// <summary> /// Performs actions when save per-user and all-users targets occurs</summary> /// <param name="sender">Sender</param> /// <param name="e">Event args</param> protected void settingsService_Saving(object sender, EventArgs e) { string settingsPath = string.Empty; try { string perUserSettingsPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "SCE\\ATF\\TargetSettings.xml"); string allUsersSettingsPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "SCE\\ATF\\TargetSettings.xml"); var savingStages = new[] { new { SettingsPath = perUserSettingsPath, Scope = TargetScope.PerUser }, new { SettingsPath = allUsersSettingsPath, Scope = TargetScope.AllUsers }, }; foreach (var stage in savingStages) { settingsPath = stage.SettingsPath; string settingsDirectory = Path.GetDirectoryName(settingsPath); if (!Directory.Exists(settingsDirectory)) { Directory.CreateDirectory(settingsDirectory); } XmlElement targetsNode = null; var xmlDoc = new XmlDocument(); if (File.Exists(settingsPath)) { xmlDoc.Load(settingsPath); targetsNode = xmlDoc.SelectSingleNode("Targets") as XmlElement; } else { xmlDoc.AppendChild(xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "yes")); targetsNode = xmlDoc.CreateElement("Targets"); xmlDoc.AppendChild(targetsNode); } if (targetsNode == null) { return; } // remove all existing targets provided by this provider var targetsToRemove = new List <XmlNode>(); var tcpTargets = targetsNode.SelectSingleNode("TcpTargets"); if (tcpTargets != null) { foreach (XmlNode child in tcpTargets.ChildNodes) { var elem = child as XmlElement; if (elem != null) { var providerIdentifier = elem.GetAttribute("provider"); if (providerIdentifier == Id) { targetsToRemove.Add(child); } } } foreach (var target in targetsToRemove) { tcpTargets.RemoveChild(target); } } else { tcpTargets = xmlDoc.CreateElement("TcpTargets"); targetsNode.AppendChild(tcpTargets); } string results = SerializeTargets(stage.Scope); var tempRootNode = xmlDoc.CreateElement("TcpTargets"); tempRootNode.InnerXml = results; if (tempRootNode.FirstChild != null) { foreach (XmlNode child in tempRootNode.FirstChild.ChildNodes) { var target = child.CloneNode(false); tcpTargets.AppendChild(target); } } xmlDoc.Save(settingsPath); } } catch (Exception ex) { Outputs.Write(OutputMessageType.Error, settingsPath + ": "); Outputs.WriteLine(OutputMessageType.Error, ex.Message); } }
/// <summary> /// Add standard Neblio output /// </summary> /// <param name="amount"></param> /// <returns></returns> public async Task AddNeblioOutput(int amount = 10000) { Outputs.Add(new NeblioBuilderOutput(amount)); NewTransaction.Outputs.Add(new TxOut(new Money((long)amount), new Script())); await RefreshOutputSummary(); }
public Task RunProgram() { for (long instructionPointer = 0; instructionPointer < Addresses.Length;) { var instruction = Addresses[instructionPointer]; var opCode = (OpCode)(instruction % 100); long GetValue(long offset, InstructionMode instructionMode) { switch (instructionMode) { case InstructionMode.Position: return(Addresses[Addresses[instructionPointer + offset]]); case InstructionMode.Immediate: return(Addresses[instructionPointer + offset]); case InstructionMode.Relative: return(Addresses[Addresses[instructionPointer + offset] + RelativeBase]); default: throw new Exception($"Invalid Instruction mode {instructionMode}"); } } var firstInstructionMode = (InstructionMode)(instruction / 100 % 10); var secondInstructionMode = (InstructionMode)(instruction / 1000 % 10); var thirdInstructionMode = (InstructionMode)(instruction / 10000 % 10); void WriteToAddress(int offset, long valueToWrite, InstructionMode instructionMode = InstructionMode.Position) { switch (instructionMode) { case InstructionMode.Position: Addresses[Addresses[instructionPointer + offset]] = valueToWrite; break; case InstructionMode.Relative: Addresses[Addresses[instructionPointer + offset] + RelativeBase] = valueToWrite; break; default: throw new Exception($"Unknown Instruction mode for writing {instructionMode}"); } } long value; switch (opCode) { case OpCode.Add: value = GetValue(1, firstInstructionMode) + GetValue(2, secondInstructionMode); WriteToAddress(3, value, thirdInstructionMode); instructionPointer += 4; break; case OpCode.Multiply: value = GetValue(1, firstInstructionMode) * GetValue(2, secondInstructionMode); WriteToAddress(3, value, thirdInstructionMode); instructionPointer += 4; break; case OpCode.Input: long next; WaitingForInput = true; next = SupplyInputValue?.Invoke() ?? Inputs.Take(); WriteToAddress(1, next, firstInstructionMode); instructionPointer += 2; break; case OpCode.Output: var nextValue = GetValue(1, firstInstructionMode); Outputs.Add(nextValue); instructionPointer += 2; break; case OpCode.JumpIfTrue: instructionPointer = GetValue(1, firstInstructionMode) != 0 ? GetValue(2, secondInstructionMode) : instructionPointer + 3; break; case OpCode.JumpIfFalse: instructionPointer = GetValue(1, firstInstructionMode) == 0 ? GetValue(2, secondInstructionMode) : instructionPointer + 3; break; case OpCode.LessThan: value = GetValue(1, firstInstructionMode) < GetValue(2, secondInstructionMode) ? 1 : 0; WriteToAddress(3, value, thirdInstructionMode); instructionPointer += 4; break; case OpCode.Equals: value = GetValue(1, firstInstructionMode) == GetValue(2, secondInstructionMode) ? 1 : 0; WriteToAddress(3, value, thirdInstructionMode); instructionPointer += 4; break; case OpCode.AdjustRelativeBase: RelativeBase += GetValue(1, firstInstructionMode); instructionPointer += 2; break; case OpCode.Halt: return(Task.CompletedTask); default: throw new Exception($"Unknown Op Code {opCode}"); } } return(Task.CompletedTask); }
/// <summary> /// Get the return value from an aggregate function. /// </summary> /// <param name="index">Index represents result row number within the grouping, and is used for series functions that return multiple results from one aggregation.</param> /// <returns></returns> public object ReturnValue(int?index = 0) { if (ResultMethod != null) { var outputsCount = Outputs?.Length ?? 0; int indexAdjust; object[] parameters; //if the result method has an "index" as the first parameter, then add the index if (ResultMethod.GetParameters().Any() && ResultMethod.GetParameters()[0].Name == "index") { parameters = new object[outputsCount + 1]; parameters[0] = index; indexAdjust = 1; } else { parameters = new object[outputsCount]; indexAdjust = 0; } List <object> arrayValues = null; for (var i = 0; i < outputsCount; i++) { //FYI: this code will only accommodate for array being last parameter. if (Outputs != null && Outputs[i].IsArray) { if (arrayValues == null) { arrayValues = new List <object>(); } arrayValues.Add(null); } else { parameters[i + indexAdjust] = null; } } if (arrayValues != null) { parameters[outputsCount + indexAdjust] = arrayValues.Select(c => Convert.ChangeType(c, Type.GetType("System." + Outputs.Last().DataType))); } _returnValue = ResultMethod.Invoke(ObjectReference, parameters); var arrayNumber = 0; for (var i = 0; i < outputsCount; i++) { if (Outputs != null && Outputs[i].IsArray) { var array = (object[])parameters[i + indexAdjust]; try { Outputs[i].SetValue(arrayNumber >= array.Length ? DBNull.Value : array[arrayNumber]); } catch (Exception ex) { #if DEBUG throw new AggregateException($"The function {FunctionName} with the output array {Outputs[i].Name} with values {string.Join(",", array)} could not be converted. " + ex.Message, ex); #else throw new AggregateException($"The function {FunctionName} with the output array {Outputs[i].Name} could not be converted. " + ex.Message, ex); #endif } arrayNumber++; } else { try { Outputs[i].SetValue(parameters[i + indexAdjust]); } catch (Exception ex) { #if DEBUG throw new AggregateException($"The function {FunctionName} with the output parameter {Outputs[i].Name} with value {parameters[i + indexAdjust]} could not be converted. " + ex.Message, ex); #else throw new AggregateException($"The function {FunctionName} with the output parameter {Outputs[i].Name} could not be converted. " + ex.Message, ex); #endif } } } } return(_returnValue); }
private static void Run( string username, string password, IReadOnlyList<string> kompetenzen, string filter, LevelRange levelRange, Collection<Classification> classifications, Outputs output) { Console.WriteLine("started using"); Console.WriteLine($" filter = {filter}"); Console.WriteLine($" levels included = {levelRange.From}..{levelRange.To}"); Console.WriteLine($" classifications included = {string.Join(",", classifications)}"); Console.WriteLine($" output as {output}"); var youTrack = new YouTrack(); var issues = youTrack.GetIssues(username, password); Console.WriteLine($"{issues.Count} issues parsed"); var issueFilter = new IssueFilter(); var filteredIssues = issueFilter.FilterIssues(issues, levelRange, kompetenzen, filter, classifications); Console.WriteLine($"{filteredIssues.Count} issues left after filtering. Filtered out:"); foreach (var issue in issues.Except(filteredIssues)) { Console.WriteLine($" - {issue.Name}({issue.Level},{issue.Classification})"); } switch (output) { case Outputs.Tree: new TreeWriter().Write(filteredIssues); break; case Outputs.Radar: new RadarWriter().Write(filteredIssues); break; } Console.WriteLine("finished"); }
/// <summary> /// Override to compile a RDBMS Table /// </summary> protected virtual void DoColumn(IConfigSectionNode columnNode, RDBMSEntity table, StringBuilder sb, ref bool firstColumn, Outputs outputs) { var colComment = columnNode.AttrByName(SCRIPT_COMMENT_ATTR).Value; if (colComment.IsNotNullOrWhiteSpace()) sb.AppendLine(" -- {0}".Args( colComment ) ); var columnName = columnNode.Value; if (columnName.IsNullOrWhiteSpace()) { m_CompileErrors.Add(new SchemaCompilationException(columnNode.RootPath, "Table '{0}' missing column name.".Args(table.OriginalName))); return; } var column = new RDBMSEntity(table, columnNode, RDBMSEntityType.Column, columnName, columnNode.AttrByName(SHORT_NAME_ATTR).Value ?? columnName); TransformEntityName(column); var typeNode = columnNode.Navigate(TYPE_ATTR + "|$"+TYPE_ATTR); if (typeNode==null || typeNode.VerbatimValue.IsNullOrWhiteSpace()) { m_CompileErrors.Add(new SchemaCompilationException(columnNode.RootPath, "Column '{0}' missing {1} attribute.".Args(columnName, TYPE_ATTR))); return; } var columnType = typeNode.Value; var type = new RDBMSEntity(column, typeNode, RDBMSEntityType.Domain, columnType); TransformEntityName(type); var domain = CreateDomain("{0}.{1}::{2}".Args(table.OriginalName, column.OriginalName, type.OriginalName), type.OriginalName, typeNode); if (domain==null) { m_CompileErrors.Add(new SchemaCompilationException(columnNode.RootPath, "Domain could not be created: " +type.TransformedName )); return; } domain.TransformColumnName(this, column); if (!firstColumn) sb.AppendLine(","); #region Column Line { var cn = GetQuotedIdentifierName(RDBMSEntityType.Column, column.TransformedName); var tn = GetQuotedIdentifierName(RDBMSEntityType.Domain, domain.GetTypeName(this)); var required = (domain.GetColumnRequirement(this) ?? false) || columnNode.AttrByName(REQUIRED_ATTR).ValueAsBool(); var nn = TransformKeywordCase( GetColumnNullNotNullClause(column, required) ); var auto = domain.GetColumnAutoGeneratedScript(this, column, outputs); var dfltValue = columnNode.AttrByName(DEFAULT_ATTR).Value ?? domain.GetColumnDefaultScript(this, column, outputs); var dflt = dfltValue.IsNotNullOrWhiteSpace()? "{0} {1}".Args(TransformKeywordCase("default"), EscapeString(dfltValue)) : string.Empty; var chk = domain.GetColumnCheckScript(this, column, outputs); var cmntValue = columnNode.AttrByName(COMMENT_ATTR).Value; var cmnt = cmntValue.IsNotNullOrWhiteSpace()? "{0} {1}".Args(TransformKeywordCase("comment"), EscapeString(cmntValue)) : string.Empty; sb.Append( FormatColumnStatement(cn, tn, nn, auto, dflt, chk, cmnt) ); } #endregion firstColumn = false; foreach(var colSubNode in columnNode.Children) { if (colSubNode.IsSameName(PRIMARY_KEY_SECTION) || colSubNode.IsSameName(REFERENCE_SECTION)) { var keyType = colSubNode.IsSameName(PRIMARY_KEY_SECTION) ? RDBMSEntityType.PrimaryKey : RDBMSEntityType.Reference; var keyName = colSubNode.Value; if (keyName.IsNullOrWhiteSpace()) keyName = column.OriginalShortName; var key = new RDBMSEntity(column, colSubNode, keyType, keyName, colSubNode.AttrByName(SHORT_NAME_ATTR).Value); TransformEntityName(key); } else if (colSubNode.IsSameName(TYPE_ATTR)) { } //type may be used as section as well else m_CompileErrors.Add(new SchemaCompilationException(colSubNode.RootPath, "Unrecognized item inside '{0}.{1}' column, section '{2}'" .Args(table.OriginalName, columnName, colSubNode.Name))); } }
static void Main(string[] args) { DirectoryInfo d = new DirectoryInfo(Outputs.getAllFiles()); FileInfo[] Files = d.GetFiles("*.txt"); string output_path10 = @"C:\Users\maple\Documents\9° Semester\CS13309_Archivos_HTML\a10_matricula.txt"; string output; d = new DirectoryInfo(Outputs.getOutputFiles()); FileInfo stopListFile = d.GetFiles("stoplist.txt")[0]; string stopListAll = File.ReadAllText(stopListFile.FullName); stopListAll.Trim(); string[] stopList = stopListAll.Split('\n'); for (int i = 0; i < stopList.Length; i++) { stopList[i] = stopList[i].Replace("\r", ""); } var watch = System.Diagnostics.Stopwatch.StartNew(); int count = 0; foreach (FileInfo file in Files) { output = ""; var watchEach = System.Diagnostics.Stopwatch.StartNew(); string htmlContent = File.ReadAllText(file.FullName); htmlContent.Trim(); string[] eachWord = htmlContent.Split(' '); Dictionary <string, int> wordCount = new Dictionary <string, int>(); try { for (int i = 0; i < eachWord.Length; i++) { if (!string.IsNullOrEmpty(eachWord[i])) { if (!eachWord[i].Equals(" ")) { eachWord[i] = eachWord[i].ToLower(); eachWord[i] = eachWord[i].Replace(",", "") .Replace(".", "") .Replace("\r", "") .Replace("\t", "") .Replace("\n", "") .Replace("(", "") .Replace(")", ""); if (wordCount.ContainsKey(eachWord[i])) { wordCount[eachWord[i]] = wordCount[eachWord[i]] + 1; } else if (eachWord[i].Length > 1) { wordCount.Add(eachWord[i], 0); } } } } } catch (ArgumentNullException argExc) { Console.WriteLine(argExc.StackTrace); } catch (KeyNotFoundException keyNotFoundExc) { Console.WriteLine(keyNotFoundExc.StackTrace); } foreach (var key in wordCount.Keys.ToList()) { for (int i = 0; i < stopList.Length; i++) { wordCount.Remove(stopList[i]); } if (wordCount.ContainsKey(key)) { if (wordCount[key] < 5) { wordCount.Remove(key); } } } foreach (KeyValuePair <string, int> pair in wordCount) { string token = (string)pair.Key; float tokenWeight = (float)pair.Value; tokenWeight = (tokenWeight * 100) / wordCount.Count; output = token + " - " + tokenWeight + "\n"; Outputs.output_print(output_path10, output); Console.WriteLine(output); } output = file.Name + " finished in " + watchEach.Elapsed.TotalMilliseconds.ToString() + " ms"; Console.WriteLine(output); watchEach.Stop(); Outputs.output_print(output_path10, output); count++; } output = "\nFiles cleaned in\t" + watch.Elapsed.TotalMilliseconds.ToString() + " ms"; Console.WriteLine(output); watch.Stop(); Outputs.output_print(output_path10, output); Console.Read(); }
/// <summary> /// The default error reporting method that is assigned to the ErrorHandler field</summary> /// <param name="errorNum">The OpenGL error number that comes from glGetError()</param> private static void DefaultErrorHandler(int errorNum) { string errorText = GetErrorText(errorNum); Outputs.WriteLine(OutputMessageType.Error, "OpenGl error: " + errorText); }
public override void Run() { { string lotno = lotnoInput.Value?.ToString(); string skuno = skuInput.Value?.ToString(); string lotstatus = LotStatusInput.Value?.ToString(); string status = statusInput.Value?.ToString(); string start = null; string end = null; if (fromDate.Value != null && fromDate.Value.ToString() != "") { try { start = Convert.ToDateTime(fromDate.Value.ToString()).ToString("yyyy/MM/dd HH:mm:ss"); } catch (Exception ex) { throw new Exception("日期格式不正確!"); } } if (toDate.Value != null && toDate.Value.ToString() != "") { try { end = Convert.ToDateTime(toDate.Value.ToString()).ToString("yyyy/MM/dd HH:mm:ss"); } catch (Exception ex) { throw new Exception("日期格式不正確!"); } } string sql = $@" select lot_no,skuno,aql_type,lot_qty,reject_qty,sample_station,line,sample_qty,pass_qty,fail_qty, decode(closed_flag, 0, '待关闭', 1, '待抽检',2,'抽检完成') as closed,decode(lot_status_flag,0,'待抽檢',1,'PASS',2,'FAIL') as lotstatus, edit_time from r_lot_status where 1=1 "; StringBuilder condi = new StringBuilder(sql); if (!string.IsNullOrEmpty(lotno)) { condi.Append($@"and lot_no='{lotno.Replace("'", "''")}' "); } if (!string.IsNullOrEmpty(skuno)) { condi.Append($@"and skuno='{skuno.Replace("'", "''")}' "); } if (!string.IsNullOrEmpty(status) && !"ALL".Equals(status)) { string flag = "0"; switch (status.Trim()) { case "待抽检": flag = "0"; break; case "PASS": flag = "1"; break; case "FAIL": flag = "2"; break; default: break; } condi.Append($@"and lot_status_flag='{flag}' "); } if (!string.IsNullOrEmpty(lotstatus) && !"ALL".Equals(lotstatus)) { string closesflag = "0"; switch (lotstatus.Trim()) { case "待入批次": closesflag = "0"; break; case "待抽检": closesflag = "1"; break; case "抽检完成": closesflag = "2"; break; default: break; } condi.Append($@"and closed_flag='{closesflag}' "); } if (!string.IsNullOrEmpty(start)) { condi.Append($@"and edit_time >= to_date('{start}', 'yyyy/mm/dd HH24:mi:ss') "); } if (!string.IsNullOrEmpty(end)) { condi.Append($@"and edit_time <= to_date('{end}','yyyy/mm/dd HH24:mi:ss') "); } //sql += condi.ToString(); OleExec sfcdb = DBPools["SFCDB"].Borrow(); DataTable dt = sfcdb.RunSelect(condi.ToString()).Tables[0]; DataTable linkTable = new DataTable(); DataRow linkRow = null; if (sfcdb != null) { this.DBPools["SFCDB"].Return(sfcdb); } if (dt.Rows.Count > 0) { linkTable.Columns.Add("LOT_NO"); linkTable.Columns.Add("SKUNO"); linkTable.Columns.Add("AQL_TYPE"); linkTable.Columns.Add("LOT_QTY"); linkTable.Columns.Add("REJECT_QTY"); linkTable.Columns.Add("SAMPLE_STATION"); linkTable.Columns.Add("LINE"); linkTable.Columns.Add("SAMPLE_QTY"); linkTable.Columns.Add("PASS_QTY"); linkTable.Columns.Add("FAIL_QTY"); linkTable.Columns.Add("CLOSED"); linkTable.Columns.Add("LOTSTATUS"); linkTable.Columns.Add("EDIT_TIME"); for (int i = 0; i < dt.Rows.Count; i++) { linkRow = linkTable.NewRow(); linkRow["LOT_NO"] = "Link#/FunctionPage/Report/Report.html?ClassName=MESReport.BaseReport.LotNoDetailReport&RunFlag=1&LotNo=" + dt.Rows[i]["LOT_NO"].ToString(); linkRow["SKUNO"] = ""; linkRow["AQL_TYPE"] = ""; linkRow["LOT_QTY"] = "Link#/FunctionPage/Report/Report.html?ClassName=MESReport.BaseReport.OBAByLotReport&RunFlag=1&LotNo=" + dt.Rows[i]["LOT_NO"].ToString(); linkRow["REJECT_QTY"] = ""; linkRow["SAMPLE_STATION"] = ""; linkRow["LINE"] = ""; linkRow["SAMPLE_QTY"] = ""; linkRow["PASS_QTY"] = ""; linkRow["FAIL_QTY"] = ""; linkRow["CLOSED"] = ""; linkRow["LOTSTATUS"] = ""; linkRow["EDIT_TIME"] = ""; linkTable.Rows.Add(linkRow); } } ReportTable retTab = new ReportTable(); retTab.LoadData(dt, linkTable); retTab.Tittle = "OBA REPORT"; Outputs.Add(retTab); } //DateTime stime = Convert.ToDateTime(fromDate.Value); //DateTime etime = Convert.ToDateTime(toDate.Value); //string svalue = stime.ToString("yyyy/MM/dd HH:mm:ss"); //string evalue = etime.ToString("yyyy/MM/dd HH:mm:ss"); //OleExec SFCDB = DBPools["SFCDB"].Borrow(); //try //{ // string sqlOba = $@" SELECT* FROM R_LOT_STATUS WHERE EDIT_TIME BETWEEN TO_DATE('{svalue}', 'YYYY/MM/DD HH24:MI:SS') // AND TO_DATE('{evalue}', 'YYYY/MM/DD HH24:MI:SS')"; // DataSet res = SFCDB.RunSelect(sqlOba); // ReportTable retTab = new ReportTable(); // retTab.LoadData(res.Tables[0], null); // retTab.Tittle = "OBA"; // retTab.ColNames.RemoveAt(0);//不顯示ID列 add by fgg 2018.03.09 // Outputs.Add(retTab); // DBPools["SFCDB"].Return(SFCDB); //} //catch (Exception ee) //{ // DBPools["SFCDB"].Return(SFCDB); // throw ee; //} }
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) { writer.WriteStartObject(); if (DefaultLanguageCode != null) { writer.WritePropertyName("defaultLanguageCode"); writer.WriteStringValue(DefaultLanguageCode.Value.ToString()); } if (TextSplitMode != null) { writer.WritePropertyName("textSplitMode"); writer.WriteStringValue(TextSplitMode.Value.ToString()); } if (MaximumPageLength != null) { writer.WritePropertyName("maximumPageLength"); writer.WriteNumberValue(MaximumPageLength.Value); } writer.WritePropertyName("@odata.type"); writer.WriteStringValue(ODataType); if (Name != null) { writer.WritePropertyName("name"); writer.WriteStringValue(Name); } if (Description != null) { writer.WritePropertyName("description"); writer.WriteStringValue(Description); } if (Context != null) { writer.WritePropertyName("context"); writer.WriteStringValue(Context); } if (Inputs.Any()) { writer.WritePropertyName("inputs"); writer.WriteStartArray(); foreach (var item in Inputs) { writer.WriteObjectValue(item); } writer.WriteEndArray(); } else { writer.WriteNull("inputs"); } if (Outputs.Any()) { writer.WritePropertyName("outputs"); writer.WriteStartArray(); foreach (var item in Outputs) { writer.WriteObjectValue(item); } writer.WriteEndArray(); } else { writer.WriteNull("outputs"); } writer.WriteEndObject(); }
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) { writer.WriteStartObject(); writer.WritePropertyName("defaultToLanguageCode"); writer.WriteStringValue(DefaultToLanguageCode.ToString()); if (DefaultFromLanguageCode != null) { writer.WritePropertyName("defaultFromLanguageCode"); writer.WriteStringValue(DefaultFromLanguageCode.Value.ToString()); } if (SuggestedFrom != null) { writer.WritePropertyName("suggestedFrom"); writer.WriteStringValue(SuggestedFrom.Value.ToString()); } writer.WritePropertyName("@odata.type"); writer.WriteStringValue(ODataType); if (Name != null) { writer.WritePropertyName("name"); writer.WriteStringValue(Name); } if (Description != null) { writer.WritePropertyName("description"); writer.WriteStringValue(Description); } if (Context != null) { writer.WritePropertyName("context"); writer.WriteStringValue(Context); } if (Inputs.Any()) { writer.WritePropertyName("inputs"); writer.WriteStartArray(); foreach (var item in Inputs) { writer.WriteObjectValue(item); } writer.WriteEndArray(); } else { writer.WriteNull("inputs"); } if (Outputs.Any()) { writer.WritePropertyName("outputs"); writer.WriteStartArray(); foreach (var item in Outputs) { writer.WriteObjectValue(item); } writer.WriteEndArray(); } else { writer.WriteNull("outputs"); } writer.WriteEndObject(); }
/// <summary> /// Build the suggest index, using up to the specified /// amount of temporary RAM while building. Note that /// the weights for the suggestions are ignored. /// </summary> public virtual void Build(InputIterator iterator, double ramBufferSizeMB) { if (iterator.HasPayloads) { throw new System.ArgumentException("this suggester doesn't support payloads"); } if (iterator.HasContexts) { throw new System.ArgumentException("this suggester doesn't support contexts"); } string prefix = this.GetType().Name; var directory = OfflineSorter.DefaultTempDir(); // TODO: messy ... java7 has Files.createTempDirectory // ... but 4.x is java6: File tempIndexPath = null; Random random = new Random(); while (true) { tempIndexPath = new File(directory, prefix + ".index." + random.Next(int.MaxValue)); if (tempIndexPath.mkdir()) { break; } } Directory dir = FSDirectory.Open(tempIndexPath); IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_CURRENT, indexAnalyzer); iwc.OpenMode = IndexWriterConfig.OpenMode_e.CREATE; iwc.RAMBufferSizeMB = ramBufferSizeMB; IndexWriter writer = new IndexWriter(dir, iwc); var ft = new FieldType(TextField.TYPE_NOT_STORED); // TODO: if only we had IndexOptions.TERMS_ONLY... ft.IndexOptions = FieldInfo.IndexOptions.DOCS_AND_FREQS; ft.OmitNorms = true; ft.Freeze(); Document doc = new Document(); Field field = new Field("body", "", ft); doc.Add(field); totTokens = 0; IndexReader reader = null; bool success = false; count = 0; try { while (true) { BytesRef surfaceForm = iterator.Next(); if (surfaceForm == null) { break; } field.StringValue = surfaceForm.Utf8ToString(); writer.AddDocument(doc); count++; } reader = DirectoryReader.Open(writer, false); Terms terms = MultiFields.GetTerms(reader, "body"); if (terms == null) { throw new System.ArgumentException("need at least one suggestion"); } // Move all ngrams into an FST: TermsEnum termsEnum = terms.Iterator(null); Outputs <long?> outputs = PositiveIntOutputs.Singleton; Builder <long?> builder = new Builder <long?>(FST.INPUT_TYPE.BYTE1, outputs); IntsRef scratchInts = new IntsRef(); while (true) { BytesRef term = termsEnum.Next(); if (term == null) { break; } int ngramCount = CountGrams(term); if (ngramCount > grams) { throw new System.ArgumentException("tokens must not contain separator byte; got token=" + term + " but gramCount=" + ngramCount + ", which is greater than expected max ngram size=" + grams); } if (ngramCount == 1) { totTokens += termsEnum.TotalTermFreq(); } builder.Add(Lucene.Net.Util.Fst.Util.ToIntsRef(term, scratchInts), EncodeWeight(termsEnum.TotalTermFreq())); } fst = builder.Finish(); if (fst == null) { throw new System.ArgumentException("need at least one suggestion"); } //System.out.println("FST: " + fst.getNodeCount() + " nodes"); /* * PrintWriter pw = new PrintWriter("/x/tmp/out.dot"); * Util.toDot(fst, pw, true, true); * pw.close(); */ success = true; } finally { try { if (success) { IOUtils.Close(writer, reader); } else { IOUtils.CloseWhileHandlingException(writer, reader); } } finally { foreach (string file in dir.ListAll()) { File path = new File(tempIndexPath, file); if (path.Delete() == false) { throw new InvalidOperationException("failed to remove " + path); } } if (tempIndexPath.Delete() == false) { throw new InvalidOperationException("failed to remove " + tempIndexPath); } dir.Dispose(); } } }
/// <summary> /// Build the suggest index, using up to the specified /// amount of temporary RAM while building. Note that /// the weights for the suggestions are ignored. /// </summary> public virtual void Build(IInputEnumerator enumerator, double ramBufferSizeMB) { // LUCENENET: Added guard clause for null if (enumerator is null) { throw new ArgumentNullException(nameof(enumerator)); } if (enumerator.HasPayloads) { throw new ArgumentException("this suggester doesn't support payloads"); } if (enumerator.HasContexts) { throw new ArgumentException("this suggester doesn't support contexts"); } string prefix = this.GetType().Name; var directory = OfflineSorter.DefaultTempDir(); // LUCENENET specific - using GetRandomFileName() instead of picking a random int DirectoryInfo tempIndexPath; // LUCENENET: IDE0059: Remove unnecessary value assignment while (true) { tempIndexPath = new DirectoryInfo(Path.Combine(directory.FullName, prefix + ".index." + Path.GetFileNameWithoutExtension(Path.GetRandomFileName()))); tempIndexPath.Create(); if (System.IO.Directory.Exists(tempIndexPath.FullName)) { break; } } Directory dir = FSDirectory.Open(tempIndexPath); try { #pragma warning disable 612, 618 IndexWriterConfig iwc = new IndexWriterConfig(LuceneVersion.LUCENE_CURRENT, indexAnalyzer); #pragma warning restore 612, 618 iwc.SetOpenMode(OpenMode.CREATE); iwc.SetRAMBufferSizeMB(ramBufferSizeMB); IndexWriter writer = new IndexWriter(dir, iwc); var ft = new FieldType(TextField.TYPE_NOT_STORED); // TODO: if only we had IndexOptions.TERMS_ONLY... ft.IndexOptions = IndexOptions.DOCS_AND_FREQS; ft.OmitNorms = true; ft.Freeze(); Document doc = new Document(); Field field = new Field("body", "", ft); doc.Add(field); totTokens = 0; IndexReader reader = null; bool success = false; count = 0; try { while (enumerator.MoveNext()) { BytesRef surfaceForm = enumerator.Current; field.SetStringValue(surfaceForm.Utf8ToString()); writer.AddDocument(doc); count++; } reader = DirectoryReader.Open(writer, false); Terms terms = MultiFields.GetTerms(reader, "body"); if (terms is null) { throw new ArgumentException("need at least one suggestion"); } // Move all ngrams into an FST: TermsEnum termsEnum = terms.GetEnumerator(null); Outputs <long?> outputs = PositiveInt32Outputs.Singleton; Builder <long?> builder = new Builder <long?>(FST.INPUT_TYPE.BYTE1, outputs); Int32sRef scratchInts = new Int32sRef(); while (termsEnum.MoveNext()) { BytesRef term = termsEnum.Term; int ngramCount = CountGrams(term); if (ngramCount > grams) { throw new ArgumentException("tokens must not contain separator byte; got token=" + term + " but gramCount=" + ngramCount + ", which is greater than expected max ngram size=" + grams); } if (ngramCount == 1) { totTokens += termsEnum.TotalTermFreq; } builder.Add(Lucene.Net.Util.Fst.Util.ToInt32sRef(term, scratchInts), EncodeWeight(termsEnum.TotalTermFreq)); } fst = builder.Finish(); if (fst is null) { throw new ArgumentException("need at least one suggestion"); } //System.out.println("FST: " + fst.getNodeCount() + " nodes"); /* * PrintWriter pw = new PrintWriter("/x/tmp/out.dot"); * Util.toDot(fst, pw, true, true); * pw.close(); */ success = true; } finally { if (success) { IOUtils.Dispose(writer, reader); } else { IOUtils.DisposeWhileHandlingException(writer, reader); } } } finally { try { IOUtils.Dispose(dir); } finally { // LUCENENET specific - since we are removing the entire directory anyway, // it doesn't make sense to first do a loop in order remove the files. // Let the System.IO.Directory.Delete() method handle that. // We also need to dispose the Directory instance first before deleting from disk. try { System.IO.Directory.Delete(tempIndexPath.FullName, true); } catch (Exception e) { throw IllegalStateException.Create("failed to remove " + tempIndexPath, e); } } } }
public string GenerateHash(bool force = false) { if (string.IsNullOrEmpty(Hash) || force) { var inputsHash = Inputs == null ? string.Empty : HashHelper.Sha256(string.Join("", Inputs.Select(i => i.GenerateHash()))); var outputsHash = Outputs == null ? string.Empty : HashHelper.Sha256(string.Join("", Outputs.Select(i => i.GenerateHash()))); TransactionFee = 0; Hash = HashHelper.Sha256(inputsHash + HashHelper.Sha256(Data) + outputsHash + TransactionFee); } return(Hash); }
/// <summary> /// Returns true if TesTask instances are equal /// </summary> /// <param name="other">Instance of TesTask to be compared</param> /// <returns>Boolean</returns> public bool Equals(TesTask other) { if (other is null) { return(false); } if (ReferenceEquals(this, other)) { return(true); } return (( Id == other.Id || Id != null && Id.Equals(other.Id) ) && ( State == other.State || State.Equals(other.State) ) && ( Name == other.Name || Name != null && Name.Equals(other.Name) ) && ( Description == other.Description || Description != null && Description.Equals(other.Description) ) && ( Inputs == other.Inputs || Inputs != null && Inputs.SequenceEqual(other.Inputs) ) && ( Outputs == other.Outputs || Outputs != null && Outputs.SequenceEqual(other.Outputs) ) && ( Resources == other.Resources || Resources != null && Resources.Equals(other.Resources) ) && ( Executors == other.Executors || Executors != null && Executors.SequenceEqual(other.Executors) ) && ( Volumes == other.Volumes || Volumes != null && Volumes.SequenceEqual(other.Volumes) ) && ( Tags == other.Tags || Tags != null && Tags.SequenceEqual(other.Tags) ) && ( Logs == other.Logs || Logs != null && Logs.SequenceEqual(other.Logs) ) && ( CreationTime == other.CreationTime || CreationTime != null && CreationTime.Equals(other.CreationTime) )); }
/// <summary> /// Override to perform custom interpretation per particular compiler target /// </summary> protected abstract void BuildNodeOutput(IConfigSectionNode node, Outputs outputs);
/// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { var hashCode = 41; // Suitable nullity checks etc, of course :) if (Id != null) { hashCode = hashCode * 59 + Id.GetHashCode(); } hashCode = hashCode * 59 + State.GetHashCode(); if (Name != null) { hashCode = hashCode * 59 + Name.GetHashCode(); } if (Description != null) { hashCode = hashCode * 59 + Description.GetHashCode(); } if (Inputs != null) { hashCode = hashCode * 59 + Inputs.GetHashCode(); } if (Outputs != null) { hashCode = hashCode * 59 + Outputs.GetHashCode(); } if (Resources != null) { hashCode = hashCode * 59 + Resources.GetHashCode(); } if (Executors != null) { hashCode = hashCode * 59 + Executors.GetHashCode(); } if (Volumes != null) { hashCode = hashCode * 59 + Volumes.GetHashCode(); } if (Tags != null) { hashCode = hashCode * 59 + Tags.GetHashCode(); } if (Logs != null) { hashCode = hashCode * 59 + Logs.GetHashCode(); } if (CreationTime != null) { hashCode = hashCode * 59 + CreationTime.GetHashCode(); } return(hashCode); } }
/// <summary> /// Connects to the Perforce server and logs in, if there is not already a connection.</summary> /// <returns>Returns true if a connection was established and the log-in was successful and false otherwise.</returns> internal bool ValidateConnection(bool checkLogin) { if (m_connecting) { return(false); } lock (m_lock) { if (m_repository == null) { return(false); } try { if (m_repository.Connection.Status == ConnectionStatus.Disconnected) { m_repository.Connection.Connect(ConnectionOptions); // try to connect } if (m_repository.Connection.Status == ConnectionStatus.Disconnected) { return(false); } } catch (P4Exception ex) { switch (ex.ErrorLevel) { case ErrorSeverity.E_WARN: Outputs.WriteLine(OutputMessageType.Warning, ex.Message); break; case ErrorSeverity.E_FAILED: Outputs.WriteLine(OutputMessageType.Error, ex.Message); break; case ErrorSeverity.E_INFO: Outputs.WriteLine(OutputMessageType.Info, ex.Message); break; } if (ThrowExceptions) { throw; } } } bool result = true; if (checkLogin) //verifies that login -s does not have errors { m_connecting = true; bool checkLoginSucceeded; lock (m_lock) checkLoginSucceeded = CheckLogin(m_repository.Connection); if (!checkLoginSucceeded) { OnLoginCanceled(EventArgs.Empty); result = false; } } m_connecting = false; return(result); }
public ControlPointNode() { Name = "Control Points"; Outputs.Add(NodeOutput); }
public override void Run() { string skuno = skuInput.Value?.ToString(); string line = lineInput.Value?.ToString(); string eventpoint = eventInput.Value?.ToString(); string from = fromDate.Value?.ToString().Replace("/", "-"); string to = toDate.Value?.ToString().Replace("/", "-"); from = from.Substring(0, from.Length - 3); to = to.Substring(0, to.Length - 3); if (string.IsNullOrEmpty(skuno)) { ReportAlart alart = new ReportAlart("請輸入機種!"); Outputs.Add(alart); return; } try { DataTable dt = GetUphRateDetail(skuno, line, eventpoint, from, to); if (dt.Rows.Count == 0) { ReportAlart alart = new ReportAlart("輸入內容無信息!"); Outputs.Add(alart); return; } #region 時間點去重 重複的重 去重后的 List 為 timeList var tempList = new List <string>(); var timeList = new ArrayList(); for (int i = 0; i < dt.Rows.Count; i++) { tempList.Add(dt.Rows[i]["HOURPERIOD"].ToString()); } for (int i = 0; i < tempList.Count; i++) { if (!timeList.Contains(tempList[i])) { timeList.Add(tempList[i]); } } #endregion #region 構建需要顯示的 DataTable => showDt 把時間點作列名 DataTable showDt = new DataTable(); showDt.Columns.Add("機種"); showDt.Columns.Add("採集點"); showDt.Columns.Add("區分類"); showDt.Columns.Add("UPM*10"); for (int i = 0; i < timeList.Count; i++) { showDt.Columns.Add(timeList[i].ToString()); } #endregion #region 構建內容行 : 機種 | 工站 | 區分類 | UPM*10 | 時:分的值 List <string> qualifyRowList = MakeContentRow("良品數", dt, showDt); //查詢出的所有工站的良品數行的List集合 List <string> unQualifyRowList = MakeContentRow("不良數", dt, showDt); //查詢出的所有工站的不良品數行的List集合 List <string> dataList = new List <string>(); //將良品數行,不良數行,損失率行,良品率行拼在一起的List集合 for (int i = 0; i < qualifyRowList.Count; i++) { dataList.Add(qualifyRowList[i]); dataList.Add(unQualifyRowList[i]); string[] qualifyRowArray = qualifyRowList[i].Split(','); //良品數行的數組 string[] unQualifyRowArray = unQualifyRowList[i].Split(','); //不良數行的數組 string qualifyRateRow = string.Empty; //良品率行 string unQualifyRateRow = string.Empty; //損失率行 //分別拼接良品率行與損失率行字符串 qualifyRateRow += qualifyRowList[i].Split(',')[0] + "," + qualifyRowList[i].Split(',')[1] + ",良品率," + qualifyRowList[i].Split(',')[3]; unQualifyRateRow += qualifyRowList[i].Split(',')[0] + "," + qualifyRowList[i].Split(',')[1] + ",損失率," + qualifyRowList[i].Split(',')[3]; for (int j = 4; j < qualifyRowList[i].Split(',').Length; j++) { double upm10 = Convert.ToDouble(qualifyRowList[i].Split(',')[3]); int total = Convert.ToInt32(qualifyRowList[i].Split(',')[j]) + Convert.ToInt32(unQualifyRowList[i].Split(',')[j]); int good = Convert.ToInt32(qualifyRowList[i].Split(',')[j]); string qualifyRate = (total == 0 ? 0 : (double)good / total).ToString("0.00%"); string unQualifyRate = (upm10 == 0 ? 0 : (double)(upm10 - total) / upm10).ToString("0.00%"); qualifyRateRow += "," + qualifyRate; unQualifyRateRow += "," + unQualifyRate; } dataList.Add(unQualifyRateRow); //先將損失率行Add進List dataList.Add(qualifyRateRow); //再講良品率行Add進List } #endregion #region 根據機種路由工站順序重新排列dataList集合使之呈現最終報表的樣子 => showList //有些不是路由工站, 所以屏蔽這段 Edit By ZHB 2018年6月13日11:31:33 //DataTable eventDt = GetEventSeqNo(skuno); //List<string> showList = new List<string>(); //for (int i = 0; i < eventDt.Rows.Count; i++) //{ // for (int j = 0; j < dataList.Count; j++) // { // if (eventDt.Rows[i]["station_name"].ToString() == dataList[j].Split(',')[1]) // showList.Add(dataList[j]); // } //} #endregion #region 循環 showList 填充 showDt 再顯示出來 for (int i = 0; i < dataList.Count; i++) { DataRow dtRow = showDt.NewRow(); for (int j = 0; j < showDt.Columns.Count; j++) { dtRow[j] = dataList[i].Split(',')[j]; } showDt.Rows.Add(dtRow); } ReportTable retTab = new ReportTable(); retTab.LoadData(showDt, null); retTab.Tittle = "ZERO DEFECT UPH RATE REPORT"; Outputs.Add(retTab); #endregion } catch (Exception ex) { Outputs.Add(new ReportAlart(ex.Message)); } }
/// <summary> /// Applies a replacement on the results of the last Query</summary> /// <param name="replaceInfo">Replacement information</param> /// <returns>The list of objects on which we just performed a replacement</returns> public IEnumerable <object> Replace(object replaceInfo) { ITransactionContext currentTransaction = null; try { foreach (DomNodeQueryMatch match in m_results) { DomNode domNode = match.DomNode; // Set up undo/redo for the replacement operation ITransactionContext newTransaction = domNode != null?domNode.GetRoot().As <ITransactionContext>() : null; if (newTransaction != currentTransaction) { { if (currentTransaction != null) { currentTransaction.End(); } currentTransaction = newTransaction; if (currentTransaction != null) { currentTransaction.Begin("Replace".Localize()); } } } // Apply replacement to all matching items that were found on last search foreach (IQueryPredicate predicateInfo in match.PredicateMatchResults.Keys) { predicateInfo.Replace(match.PredicateMatchResults[predicateInfo], replaceInfo); } } } catch (InvalidTransactionException ex) { // cancel the replacement transaction in the undo/redo queue if (currentTransaction != null && currentTransaction.InTransaction) { currentTransaction.Cancel(); } if (ex.ReportError) { Outputs.WriteLine(OutputMessageType.Error, ex.Message); } } finally { // finish the replacement transaction for the undo/redo queue if (currentTransaction != null && currentTransaction.InTransaction) { currentTransaction.End(); } } ResultsChanged.Raise(this, EventArgs.Empty); return(m_results); }
protected override void BuildNodeOutput(IConfigSectionNode node, Outputs outputs) { if (node.IsSameName(TABLE_SECTION)) DoTable(node, outputs); else m_CompileErrors.Add(new SchemaCompilationException(node.RootPath, "Unrecognized item: " + node.Name)); }
public virtual IEnumerable <TType> OutputsTo <TType>() { return(Outputs.Select(p => p.GetInput(this.Node as IConnectableProvider)).OfType <TType>()); }
/// <summary> /// Override to outpur foreign keys /// </summary> protected virtual void DoForeignKeys(RDBMSEntity table, StringBuilder sb, ref bool firstItem, Outputs outputs) { var tableLevelKeys = table.Children.Where(c=>c.EntityType==RDBMSEntityType.Reference); var columnLevelKeys = table.Children.Where(c=>c.EntityType==RDBMSEntityType.Column) .SelectMany(col=>col.Children) .Where(c=>c.EntityType==RDBMSEntityType.Reference); var allKeys = tableLevelKeys.Concat(columnLevelKeys); foreach(var fke in allKeys) { var rt = ((IConfigSectionNode)fke.SourceNode).AttrByName(TABLE_SECTION).Value; var rc = ((IConfigSectionNode)fke.SourceNode).AttrByName(COLUMN_SECTION).Value; if (rt.IsNullOrWhiteSpace() || rc.IsNullOrWhiteSpace()) { m_CompileErrors.Add(new SchemaCompilationException(fke.SourceNode.RootPath, "Both table and column names are required for reference '{0}' table section '{1}'".Args(table.OriginalName, fke.SourceNode.Name))); continue; } var refTable = new RDBMSEntity(null, null, RDBMSEntityType.Table, rt); TransformEntityName(refTable); var refColumn = new RDBMSEntity(refTable, null, RDBMSEntityType.Column, rc); TransformEntityName(refColumn); var refTableWasAltreadyDeclared = m_All.Children.Any(t=>t.EntityType==RDBMSEntityType.Table && refTable.OriginalName.Equals(t.OriginalName, NameComparison)); var useAlterStatement = !refTableWasAltreadyDeclared || m_SeparateForeignKeys; var constraint = TransformKeywordCase(" constraint {0} foreign key ({1}) references {2}({3})") .Args( GetQuotedIdentifierName( RDBMSEntityType.Reference, fke.TransformedName ), GetQuotedIdentifierName( RDBMSEntityType.Column, fke.ParentEntity.TransformedName ), GetQuotedIdentifierName( RDBMSEntityType.Table, refTable.TransformedName ), GetQuotedIdentifierName( RDBMSEntityType.Column, refColumn.TransformedName ) ); if (useAlterStatement) { var ksb = outputs[RDBMSCompiler.FOREIGN_KEYS_OUTPUT]; ksb.AppendLine(GetStatementDelimiterScript(RDBMSEntityType.Reference, true)); ksb.AppendLine(TransformKeywordCase(" alter table {0} add {1}") .Args( GetQuotedIdentifierName( RDBMSEntityType.Table, table.TransformedName ), constraint ) ); ksb.AppendLine(GetStatementDelimiterScript(RDBMSEntityType.Reference, false)); } else { if (!firstItem) sb.AppendLine(","); sb.Append( constraint ); firstItem = false; } } }
public virtual TType OutputTo <TType>() { return(Outputs.Select(p => p.GetInput(this.Node as IConnectableProvider)).OfType <TType>().FirstOrDefault()); }
/// <summary> /// Override to compile a indexes per table /// </summary> protected virtual void DoTableIndexes(RDBMSEntity table, Outputs outputs) { var sb = m_SeparateIndexes ? outputs[RDBMSCompiler.INDEXES_OUTPUT] : outputs[RDBMSCompiler.TABLES_OUTPUT]; var indexes = table.Children.Where(c=>c.EntityType==RDBMSEntityType.Index); foreach(var idx in indexes) { var node = (IConfigSectionNode)idx.SourceNode; var unique = node.AttrByName(UNIQUE_ATTR).ValueAsBool(); var colNames = new List<string>(); foreach(var col in node.Children.Where(c=>c.IsSameName(COLUMN_SECTION))) { var cn = col.Value; var column = table.Children.FirstOrDefault(c=>c.EntityType==RDBMSEntityType.Column && c.OriginalName.Equals(cn, NameComparison)); if (column==null) { m_CompileErrors.Add(new SchemaCompilationException(table.SourceNode.RootPath, "Table '{0}' defines index '{1}' which references column by name '{2}' which does not exist" .Args(table.OriginalName, idx.OriginalName, cn))); return; } var colName = GetQuotedIdentifierName(RDBMSEntityType.Column, column.TransformedName); var colLen = col.AttrByName(LENGTH_ATTR).ValueAsInt(); if (colLen>0) colName += "({0})".Args(colLen); var colOrder = col.AttrByName(ORDER_ATTR).ValueAsEnum<RDBMSSortOrder>(); var ord = TransformSortOrder( colOrder ); if (ord.IsNotNullOrWhiteSpace()) colName = "{0} {1}".Args(colName, ord); colNames.Add( colName ); } var colNamesLine = string.Join(", ",colNames); var comment = node.AttrByName(COMMENT_ATTR).Value; var commentClause = comment.IsNullOrWhiteSpace()? string.Empty : TransformKeywordCase(" comment {0}").Args( EscapeString(comment) ); sb.AppendLine(GetStatementDelimiterScript(RDBMSEntityType.Index, true)); sb.Append(TransformKeywordCase(" create {0} index {1} on {2}({3}){4}") .Args( TransformKeywordCase( unique?"unique":string.Empty ), GetQuotedIdentifierName( RDBMSEntityType.Index, idx.TransformedName ), GetQuotedIdentifierName( RDBMSEntityType.Table, table.TransformedName ), colNamesLine, commentClause ) ); sb.AppendLine(GetStatementDelimiterScript(RDBMSEntityType.Index, false)); } }
public override void Run() { string strYear = ""; int IntWeek = 0; string strSkuno = ""; DateTime FromDate = DateTime.Now; string strFromDate = ""; DateTime ToDate = DateTime.Now; string strToDate = ""; if (Year.Value == null || Year.Value.ToString().Trim().Length <= 0) { strYear = DateTime.Now.Year.ToString(); Year.Value = strYear; } else { strYear = Year.Value.ToString(); try { if (Convert.ToDateTime(strYear + "/03/09 00:00:00").Year.ToString() != strYear) { throw new Exception("請填寫正確的Year"); } } catch { throw new Exception("請填寫正確的Year"); } } if (Week.Value == null || Week.Value.ToString().Trim().Length <= 0) { throw new Exception("Week 不能為空"); } else { try { IntWeek = Convert.ToInt32(Week.Value.ToString().Trim()); if (IntWeek <= 0) { throw new Exception("Week 必須是大於0數字"); } } catch { throw new Exception("Week 必須是數字"); } } if (SkuNo.Value == null || SkuNo.Value.ToString().Trim().Length <= 0) { throw new Exception("SkuNo 不能為空"); } else { strSkuno = SkuNo.Value.ToString().Trim(); if (strSkuno.ToUpper() == "ALL") { strSkuno = "select distinct(skuno) from c_sku"; } else { strSkuno = "'" + strSkuno + "'"; } } FromDate = ConverDate.GetWeekStartDate(strYear, IntWeek); strFromDate = FromDate.Year.ToString() + "-" + FromDate.Month.ToString() + "-" + FromDate.Day.ToString() + " "; strFromDate = strFromDate + FromDate.Hour.ToString() + ":" + FromDate.Minute.ToString() + ":" + FromDate.Second.ToString(); ToDate = FromDate.AddDays(6); strToDate = ToDate.Year.ToString() + "-" + ToDate.Month.ToString() + "-" + ToDate.Day.ToString() + " "; strToDate = strToDate + ToDate.Hour.ToString() + ":" + ToDate.Minute.ToString() + ":" + ToDate.Second.ToString(); string runSql = $@"select skuno, datestr, sum(totalfail) as totalfail, sum(duplicatefail) as duplicatefail from( select b.skuno, TO_CHAR(A.CREATE_TIME - 7.5 / 24, 'YYYY-MM-DD') as datestr, count(SN) as totalfail, (case when(count(Sn)) = 1 then 0 when(count(Sn)) > 1 then count(Sn) - 1 else 999 end ) as duplicatefail from r_repair_main a, r_wo_base b where a.workorderno = b.workorderno and b.skuno in({strSkuno}) and a.CREATE_TIME >= TO_DATE('{strFromDate}', 'YYYY-MM-DD HH24:MI:SS') and a.CREATE_TIME <= to_date('{strToDate}', 'YYYY-MM-DD HH24:MI:SS') group by b.skuno, TO_CHAR(A.CREATE_TIME - 7.5 / 24, 'YYYY-MM-DD'), sn ) group by skuno,datestr order by skuno, datestr"; RunSqls.Add(runSql); OleExec SFCDB = DBPools["SFCDB"].Borrow(); try { DataTable res = SFCDB.ExecuteDataTable(runSql, CommandType.Text); ReportTable retTab = new ReportTable(); retTab.LoadData(res, null); retTab.Tittle = "MultipleFailRate"; retTab.ColNames.RemoveAt(0); Outputs.Add(retTab); DBPools["SFCDB"].Return(SFCDB); } catch (Exception ex) { DBPools["SFCDB"].Return(SFCDB); throw ex; } }