private static ValueTuple<SyntaxToken, SyntaxToken>? FixupOpenBrace(ValueTuple<SyntaxToken, SyntaxToken>? tokenRange)
        {
            if (!tokenRange.HasValue)
            {
                return tokenRange;
            }

            // with a auto brace completion which will do auto formatting when a user types "{", it is quite common that we will automatically put a space
            // between "{" and "}". but user might blindly type without knowing that " " has automatically inserted for him. and ends up have two spaces.
            // for those cases, whenever we see previous token of the range is "{", we expand the range to include preceeding "{"
            var currentToken = tokenRange.Value.Item1;
            var previousToken = currentToken.GetPreviousToken();

            while (currentToken.Kind() != SyntaxKind.CloseBraceToken && previousToken.Kind() == SyntaxKind.OpenBraceToken)
            {
                var pair = previousToken.Parent.GetBracePair();
                if (pair.Item2.Kind() == SyntaxKind.None || !AreTwoTokensOnSameLine(previousToken, pair.Item2))
                {
                    return ValueTuple.Create(currentToken, tokenRange.Value.Item2);
                }

                currentToken = previousToken;
                previousToken = currentToken.GetPreviousToken();
            }

            return ValueTuple.Create(currentToken, tokenRange.Value.Item2);
        }
Exemple #2
0
        void IViewTab.Fill(Protocol protocol, ViewerItem item)
        {
            ((IViewTab)this).Reset();

            m_strings = ParsingHelper.ExtractStrings(protocol, item);
            m_binaryDatas = ParsingHelper.ExtractBinaryDatas(protocol, item);
            int nStrings = m_strings.Length;
            int count = nStrings + m_binaryDatas.Length;

            if (count > 0)
            {
                ui_cbDatas.Items.Clear();

                for (int i = 0; i < count; i++)
                {
                    var obj = i >= nStrings ? m_binaryDatas[i - nStrings].Item1 : m_strings[i].Item1;
                    ui_cbDatas.Items.Add(ParsingHelper.GetContentName(obj, i));
                }

                ui_cbDatas.SelectedIndex = 0;

                if (count > 1)
                    ui_cbDatas.IsEnabled = true;

                //this.SelectData(0);
            }

            this.IsFilled = true;
        }
Exemple #3
0
 private static void LocalTupleImpl()
 {
     var t = new ValueTuple<int, int>(3, 5); // (x: 3, y: 5)
     var p = t.Item1 * t.Item2; // t.x * t.y
     var x = t.Item1;
     var y = t.Item2;
     Console.WriteLine($"{x} × {y} = {p}");
 }
        void IViewTab.Reset()
        {
            m_datas = null;
            ui_tbMain.Text = string.Empty;
            ui_cbDatas.IsEnabled = false;
            ui_cbDatas.Items.Clear();
            ui_cbDatas.Items.Add(Strings.View_NoBinaryData);
            ui_cbDatas.SelectedIndex = 0;
            ui_btnSave.IsEnabled = false;

            this.IsFilled = false;
        }
        private SyntaxNode GetNode(SyntaxNode root, ValueTuple<TextSpan, int, int> spanAndKindAndId)
        {
            var node = root.FindNode(spanAndKindAndId.Item1, getInnermostNodeForTie: true);
            if (spanAndKindAndId.Item2 == 0)
            {
                return node;
            }

            var nodeOfKind = node.FirstAncestorOrSelf<SyntaxNode>(n => n.RawKind == spanAndKindAndId.Item2);
            Assert.NotNull(nodeOfKind);
            return nodeOfKind;
        }
        void IViewTab.Reset()
        {
            m_images = null;
            ui_image.Source = null;
            ui_cbImages.IsEnabled = false;
            ui_cbImages.Items.Clear();
            ui_cbImages.Items.Add(Strings.View_NoImages);
            ui_cbImages.SelectedIndex = 0;
            ui_cbFormat.IsEnabled = false;
            ui_btnSave.IsEnabled = false;

            this.IsFilled = false;
        }
Exemple #7
0
        static void Main()
        {
            var tuple1 = (1, 2);
            Console.WriteLine(tuple1.Item1);
            Console.WriteLine(tuple1.Item2);

            var tuple2 = new ValueTuple<int, long>(1, 2);
            Console.WriteLine(tuple2.Item1);
            Console.WriteLine(tuple2.Item2);

            var tuple4 = (a: 1, b: 2);
            Console.WriteLine(tuple4.a);
            Console.WriteLine(tuple4.b);
        }
Exemple #8
0
        public async Task<Solution> GetSolutionAsync(Checksum solutionChecksum, CancellationToken cancellationToken)
        {
            if (s_lastSolution.Item1 == solutionChecksum)
            {
                return s_lastSolution.Item2;
            }

            // create new solution
            var solution = await CreateSolutionAsync(solutionChecksum, cancellationToken).ConfigureAwait(false);

            // save it
            s_lastSolution = ValueTuple.Create(solutionChecksum, solution);

            return solution;
        }
        private INavigateToSearchResult ConvertResult(ValueTuple<DeclaredSymbolInfo, Document, IEnumerable<PatternMatch>> result)
        {
            var declaredSymbolInfo = result.Item1;
            var document = result.Item2;
            var matches = result.Item3;
            var matchKind = GetNavigateToMatchKind(matches);

            // A match is considered to be case sensitive if all its constituent pattern matches are
            // case sensitive. 
            var isCaseSensitive = matches.All(m => m.IsCaseSensitive);
            var kind = GetItemKind(declaredSymbolInfo);
            var navigableItem = NavigableItemFactory.GetItemFromDeclaredSymbolInfo(declaredSymbolInfo, document);

            return new SearchResult(document, declaredSymbolInfo, kind, matchKind, isCaseSensitive, navigableItem);
        }
Exemple #10
0
        public async Task<Solution> GetSolutionAsync(Checksum solutionChecksum, CancellationToken cancellationToken)
        {
            if (s_lastSolution.Item1 == solutionChecksum)
            {
                return s_lastSolution.Item2;
            }

            // make sure there is always only one that creates a new solution
            using (await s_gate.DisposableWaitAsync(cancellationToken).ConfigureAwait(false))
            {
                if (s_lastSolution.Item1 == solutionChecksum)
                {
                    return s_lastSolution.Item2;
                }

                var solution = await CreateSolutionAsync(solutionChecksum, cancellationToken).ConfigureAwait(false);
                s_lastSolution = ValueTuple.Create(solutionChecksum, solution);

                return solution;
            }
        }
        void IViewTab.Fill(Protocol protocol, ViewerItem item)
        {
            ((IViewTab)this).Reset();

            m_datas = ParsingHelper.ExtractBinaryDatas(protocol, item);
            int count = m_datas.Length;

            if (count > 0)
            {
                ui_cbDatas.Items.Clear();

                for (int i = 0; i < count; i++)
                    ui_cbDatas.Items.Add(ParsingHelper.GetContentName(m_datas[i].Item1, i));

                ui_cbDatas.SelectedIndex = 0;

                if (count > 1)
                    ui_cbDatas.IsEnabled = true;

                //this.SelectData(0);
            }

            this.IsFilled = true;
        }
Exemple #12
0
 public static ValueTuple <T1> VTuple <T1>(T1 item1) =>
 ValueTuple.Create(item1);
Exemple #13
0
 public static ValueTuple <T1, T2> VTuple <T1, T2>(T1 item1, T2 item2) =>
 ValueTuple.Create(item1, item2);
Exemple #14
0
 public static KeyValueLogMessage Create(int sessionId, int editSessionId, ValueTuple<ushort, ushort> rudeEdit, bool blocking)
 {
     return KeyValueLogMessage.Create(m => CreateEditSessionRudeEdit(m, sessionId, editSessionId, rudeEdit, blocking));
 }
Exemple #15
0
 public static ValueTuple <T1, T2, T3, T4, T5> VTuple <T1, T2, T3, T4, T5>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) =>
 ValueTuple.Create(item1, item2, item3, item4, item5);
Exemple #16
0
 public static ValueTuple <T1, T2, T3> VTuple <T1, T2, T3>(T1 item1, T2 item2, T3 item3) =>
 ValueTuple.Create(item1, item2, item3);
        /// <summary>
        /// Given a Symbol, creates the completion item for it.
        /// </summary>
        private CompletionItem CreateItem(
            ValueTuple<string, string> displayAndInsertionText,
            int position,
            List<ISymbol> symbols,
            AbstractSyntaxContext context,
            TextSpan textChangeSpan,
            Dictionary<ISymbol, List<ProjectId>> invalidProjectMap,
            List<ProjectId> totalProjects,
            bool preselect,
            CancellationToken cancellationToken)
        {
            Contract.ThrowIfNull(symbols);

            SupportedPlatformData supportedPlatformData = null;
            if (invalidProjectMap != null)
            {
                List<ProjectId> invalidProjects = null;
                foreach (var symbol in symbols)
                {
                    if (invalidProjectMap.TryGetValue(symbol, out invalidProjects))
                    {
                        break;
                    }
                }

                if (invalidProjects != null)
                {
                    supportedPlatformData = new SupportedPlatformData(invalidProjects, totalProjects, context.Workspace);
                }
            }

            return CreateItem(displayAndInsertionText, position, symbols, context, textChangeSpan, preselect, supportedPlatformData);
        }
        protected override CompletionItemRules GetCompletionItemRules(List <ISymbol> symbols, SyntaxContext context, bool preselect)
        {
            cachedRules.TryGetValue(ValueTuple.Create(context.IsInImportsDirective, preselect, context.IsPossibleTupleContext), out var rule);

            return(rule ?? CompletionItemRules.Default);
        }
Exemple #19
0
 private void RaiseEmptyDiagnosticUpdated(DocumentId documentId)
 {
     _service.RaiseDiagnosticsUpdated(new DiagnosticsUpdatedArgs(ValueTuple.Create(this, documentId), _workspace, null, documentId.ProjectId, documentId, ImmutableArray <DiagnosticData> .Empty));
 }
        private void AddAlignmentBlockOperationRelativeToFirstTokenOnBaseTokenLine(List <IndentBlockOperation> list, ValueTuple <SyntaxToken, SyntaxToken> bracePair)
        {
            var option = IndentBlockOption.RelativeToFirstTokenOnBaseTokenLine;

            SetAlignmentBlockOperation(list, bracePair.Item1, bracePair.Item1.GetNextToken(includeZeroWidth: true), bracePair.Item2, option);
        }
        public virtual void OnStart()
        {
            ((Task)this).OnStart();
            this._agent = this.Agent;
            this._agent.RuntimeMotivationInPhoto = this._agent.AgentData.StatsTable[5];
            this._prevStateType   = this._agent.StateType;
            this._agent.StateType = AIProject.Definitions.State.Type.Immobility;
            this._poseIDList      = ListPool <int> .Get();

            NavMeshAgent navMeshAgent = this._agent.NavMeshAgent;

            navMeshAgent.set_isStopped(true);
            this._prevPriority = navMeshAgent.get_avoidancePriority();
            navMeshAgent.set_avoidancePriority(Singleton <Resources> .Instance.AgentProfile.AvoidancePriorityStationary);
            this._player          = Singleton <Manager.Map> .Instance.Player;
            this._playerCameraCon = this._player.CameraControl;
            this._prevShotType    = this._playerCameraCon.ShotType;
            this._isFadeOut       = false;
            this._poseStateTable  = (ReadOnlyDictionary <int, ValueTuple <PoseKeyPair, bool> >)null;
            this._poseInfo        = new ValueTuple <PoseKeyPair, bool>(new PoseKeyPair(), false);
            Dictionary <int, ValueTuple <PoseKeyPair, bool> > source;

            if (Singleton <Resources> .Instance.Animation.AgentGravurePoseTable.TryGetValue(this._agent.ChaControl.fileParam.personality, out source) && !source.IsNullOrEmpty <int, ValueTuple <PoseKeyPair, bool> >())
            {
                this._poseStateTable = new ReadOnlyDictionary <int, ValueTuple <PoseKeyPair, bool> >((IDictionary <int, ValueTuple <PoseKeyPair, bool> >)source);
                this._poseIDList.AddRange((IEnumerable <int>) this._poseStateTable.get_Keys());
                this._lastPoseID = this._poseIDList[Random.Range(0, this._poseIDList.Count)];
                this._poseStateTable.TryGetValue(this._lastPoseID, ref this._poseInfo);
            }
            this._poseOutAnimAction = new Subject <Unit>();
            ObservableExtensions.Subscribe <Unit>(Observable.Take <Unit>(Observable.TakeUntilDestroy <Unit>((IObservable <M0>) this._poseOutAnimAction, (Component)this._agent), 1), (System.Action <M0>)(_ =>
            {
                this._isFadeOut = true;
                this.PlayOutAnimation(this._poseInfo);
                this._isWait = (Func <AgentActor, bool>)(actor => actor.Animation.PlayingOutAnimation);
            }));
            this._poseReplayAnimAction = new Subject <Unit>();
            ObservableExtensions.Subscribe <Unit>(Observable.TakeUntilDestroy <Unit>((IObservable <M0>) this._poseReplayAnimAction, (Component)this._agent), (System.Action <M0>)(_ =>
            {
                if (this._poseIDList.IsNullOrEmpty <int>())
                {
                    this._poseOutAnimAction.OnNext(Unit.get_Default());
                }
                else
                {
                    if (this._poseIDList.Count == 1)
                    {
                        this._agent.ClearItems();
                        this.PlayInAnimation(this._poseInfo);
                    }
                    else
                    {
                        List <int> toRelease = ListPool <int> .Get();
                        toRelease.AddRange((IEnumerable <int>) this._poseIDList);
                        toRelease.Remove(this._lastPoseID);
                        this._lastPoseID = toRelease[Random.Range(0, toRelease.Count)];
                        ListPool <int> .Release(toRelease);
                        this._poseStateTable.TryGetValue(this._lastPoseID, ref this._poseInfo);
                        this._agent.ClearItems();
                        this.PlayInAnimation(this._poseInfo);
                    }
                    this._isWait      = (Func <AgentActor, bool>)(actor => actor.Animation.PlayingInAnimation);
                    this._onEndAction = (Subject <Unit>)null;
                }
            }));
            this._poseLoopEndAnimAction = new Subject <Unit>();
            ObservableExtensions.Subscribe <Unit>(Observable.TakeUntilDestroy <Unit>((IObservable <M0>) this._poseLoopEndAnimAction, (Component)this._agent), (System.Action <M0>)(_ =>
            {
                this.PlayOutAnimation(this._poseInfo);
                this._isWait      = (Func <AgentActor, bool>)(actor => actor.Animation.PlayingOutAnimation);
                this._onEndAction = this._poseReplayAnimAction;
            }));
            this.PlayInAnimation(this._poseInfo);
            this._isWait      = (Func <AgentActor, bool>)(actor => actor.Animation.PlayingInAnimation);
            this._onEndAction = (Subject <Unit>)null;
        }
Exemple #22
0
 static internal int[] AdjustPadToPool(this Tensor tensor, ValueTuple <int, int> pool, int[] stride, int[] pad)
 {
     return(AdjustPadToPool(tensor.shape, pool, stride, pad));
 }
        private static ValueTuple <SyntaxToken, SyntaxToken>?FindAppropriateRangeForCloseBrace(SyntaxToken endToken)
        {
            // don't do anything if there is no proper parent
            var parent = endToken.Parent;

            if (parent == null || parent.Kind() == SyntaxKind.SkippedTokensTrivia)
            {
                return(null);
            }

            // cases such as namespace, type, enum, method almost any top level elements
            if (parent is MemberDeclarationSyntax ||
                parent is SwitchStatementSyntax)
            {
                return(ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken()), parent.GetLastToken()));
            }

            // property decl body or initializer
            if (parent is AccessorListSyntax)
            {
                // include property decl
                var containerOfList = parent.Parent;
                if (containerOfList == null)
                {
                    return(ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken()), parent.GetLastToken()));
                }

                return(ValueTuple.Create(containerOfList.GetFirstToken(), containerOfList.GetLastToken()));
            }

            if (parent is AnonymousObjectCreationExpressionSyntax)
            {
                return(ValueTuple.Create(parent.GetFirstToken(), parent.GetLastToken()));
            }

            if (parent is InitializerExpressionSyntax)
            {
                var parentOfParent = parent.Parent;
                if (parentOfParent == null)
                {
                    return(ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken()), parent.GetLastToken()));
                }

                // double initializer case such as
                // { { }
                var doubleInitializer = parentOfParent as InitializerExpressionSyntax;
                if (doubleInitializer != null)
                {
                    // if parent block has a missing brace, and current block is on same line, then
                    // don't try to indent inner block.
                    var firstTokenOfInnerBlock = parent.GetFirstToken();
                    var lastTokenOfInnerBlock  = parent.GetLastToken();

                    var twoTokensOnSameLine = AreTwoTokensOnSameLine(firstTokenOfInnerBlock, lastTokenOfInnerBlock);
                    if (twoTokensOnSameLine)
                    {
                        return(ValueTuple.Create(firstTokenOfInnerBlock, lastTokenOfInnerBlock));
                    }
                }

                // include owner of the initializer node such as creation node
                return(ValueTuple.Create(parentOfParent.GetFirstToken(), parentOfParent.GetLastToken()));
            }

            if (parent is BlockSyntax)
            {
                var containerOfBlock = GetTopContainingNode(parent);
                if (containerOfBlock == null)
                {
                    return(ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken()), parent.GetLastToken()));
                }

                // things like method, constructor, etc and special cases
                if (containerOfBlock is MemberDeclarationSyntax ||
                    IsSpecialContainingNode(containerOfBlock))
                {
                    return(ValueTuple.Create(GetAppropriatePreviousToken(containerOfBlock.GetFirstToken()), containerOfBlock.GetLastToken()));
                }

                // double block case on single line case
                // { { }
                if (containerOfBlock is BlockSyntax)
                {
                    // if parent block has a missing brace, and current block is on same line, then
                    // don't try to indent inner block.
                    var firstTokenOfInnerBlock = parent.GetFirstToken();
                    var lastTokenOfInnerBlock  = parent.GetLastToken();

                    var twoTokensOnSameLine = AreTwoTokensOnSameLine(firstTokenOfInnerBlock, lastTokenOfInnerBlock);
                    if (twoTokensOnSameLine)
                    {
                        return(ValueTuple.Create(firstTokenOfInnerBlock, lastTokenOfInnerBlock));
                    }
                }

                // okay, for block, indent regardless whether it is first one on the line
                return(ValueTuple.Create(GetPreviousTokenIfNotFirstTokenInTree(parent.GetFirstToken()), parent.GetLastToken()));
            }

            // don't do anything
            return(null);
        }
 public static void Add <S, A>(this DeltaFunction <S, A> deltaFunction, ValueTuple <S, A, S> tuple)
 {
     deltaFunction.Define(tuple.Item1, tuple.Item2, tuple.Item3);
 }
Exemple #25
0
        static void Main(string[] args)
        {
            Console.WriteLine("Seq2seq Test");

            int seed;

            using (var rng = new RNGCryptoServiceProvider())
            {
                var buffer = new byte[sizeof(int)];

                rng.GetBytes(buffer);
                seed = BitConverter.ToInt32(buffer, 0);
            }

            RandomProvider.SetSeed(seed);

            var dataList = new List <ValueTuple <int, string, double[]> >();

            using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("LangModel.Wikipedia.zip"))
                using (var zipArchive = new ZipArchive(stream))
                {
                    foreach (var zipArchiveEntry in from zipArchiveEntry in zipArchive.Entries where zipArchiveEntry.FullName.EndsWith(".tsv", StringComparison.OrdinalIgnoreCase) select zipArchiveEntry)
                    {
                        using (var s = zipArchiveEntry.Open())
                            using (var sr = new StreamReader(s, Encoding.UTF8))
                            {
                                var    tabSeparator    = new char[] { '\t' };
                                var    spaceSeparator  = new char[] { ' ' };
                                var    isVectorStarted = false;
                                int    tokenIndex      = -1;
                                string tokenName       = null;
                                var    weightList      = new List <double>();
                                var    line            = sr.ReadLine();

                                while (line != null)
                                {
                                    if (isVectorStarted)
                                    {
                                        if (line.EndsWith(']'))
                                        {
                                            foreach (var weight in line.Substring(0, line.Length - 1).Split(spaceSeparator))
                                            {
                                                if (weight.Length > 0)
                                                {
                                                    weightList.Add(Double.Parse(weight));
                                                }
                                            }

                                            dataList.Add(ValueTuple.Create <int, string, double[]>(tokenIndex, tokenName, weightList.ToArray()));
                                            weightList.Clear();

                                            isVectorStarted = false;
                                        }
                                        else
                                        {
                                            foreach (var weight in line.Split(spaceSeparator))
                                            {
                                                if (weight.Length > 0)
                                                {
                                                    weightList.Add(Double.Parse(weight));
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        var columns = line.Split(tabSeparator);

                                        tokenIndex = Int32.Parse(columns[0]);
                                        tokenName  = columns[1];

                                        foreach (var weight in columns[2].Substring(1, columns[2].Length - 1).Split(spaceSeparator))
                                        {
                                            if (weight.Length > 0)
                                            {
                                                weightList.Add(Double.Parse(weight));
                                            }
                                        }

                                        isVectorStarted = true;
                                    }

                                    line = sr.ReadLine();
                                }
                            }
                    }
                }

            var wordData = new ValueTuple <string, double[]> [dataList.Count];
            var weights  = new double[wordData.Length * dataList[0].Item3.Length];

            dataList.ForEach(x =>
            {
                wordData[x.Item1] = ValueTuple.Create <string, double[]>(x.Item2, x.Item3);

                for (int i = 0, offset = x.Item1 * x.Item3.Length; i < x.Item3.Length; i++)
                {
                    weights[offset + i] = x.Item3[i];
                }
            });

            var trainingDataList = new List <ValueTuple <double[], double[]> >();
            int epochs           = 100;
            int iterations       = 1;
            var model            = new Model(new Seq2seq(100, 100, 100, 256));

            model.MaxGradient = 5.0;
            model.Stepped    += (sender, args) =>
            {
                if (iterations % 10 == 0)
                {
                    Console.WriteLine("Epoch {0}/{1}", iterations, epochs);
                }

                iterations++;
            };

            Console.WriteLine("Training...");

            var stopwatch = Stopwatch.StartNew();

            model.Fit(trainingDataList, epochs, 10, new SGD(), new SoftmaxCrossEntropy());

            stopwatch.Stop();

            Console.WriteLine("Done ({0}).", stopwatch.Elapsed.ToString());
        }
Exemple #26
0
        private TextSpan GetTextSpan(ValueTuple<SyntaxToken, SyntaxToken> pair)
        {
            if (pair.Item1.RawKind == 0)
            {
                return TextSpan.FromBounds(_node.FullSpan.Start, pair.Item2.SpanStart);
            }

            if (pair.Item2.RawKind == 0)
            {
                return TextSpan.FromBounds(pair.Item1.Span.End, _node.FullSpan.End);
            }

            return TextSpan.FromBounds(pair.Item1.Span.End, pair.Item2.SpanStart);
        }
Exemple #27
0
        /// <summary>
        /// Receiver for the combined VAD signal and audio data.
        /// </summary>
        /// <param name="data">A message containing the combined VAD signal and audio data.</param>
        /// <param name="e">The message envelope.</param>
        /// <returns>The <see cref="Task"/> representing the asynchronous operation.</returns>
        protected override async Task ReceiveAsync(ValueTuple <AudioBuffer, bool> data, Envelope e)
        {
            byte[] audioData = data.Item1.Data;
            bool   hasSpeech = data.Item2;

            var previousAudioOriginatingTime = this.lastAudioOriginatingTime;

            this.lastAudioOriginatingTime = e.OriginatingTime;

            // Throw if a fatal error has occurred in the OnConversationError event handler
            if (this.fatalError)
            {
                if (this.conversationError != null)
                {
                    var error = this.conversationError;
                    this.conversationError = null;
                    throw error;
                }

                // Stop processing until the pipeline terminates
                return;
            }

            if (hasSpeech)
            {
                this.lastAudioContainingSpeechTime = e.OriginatingTime;
            }

            if (hasSpeech || this.lastAudioContainedSpeech)
            {
                // Send the audio data to the cloud
                await this.speechRecognitionClient.SendAudioAsync(audioData, this.cancellationTokenSource.Token);

                // Add audio to the current utterance queue so we can reconstruct it in the recognition result later
                this.currentQueue.Enqueue(data.DeepClone(this.In.Recycler));
            }

            // If this is the last audio packet containing speech
            if (!hasSpeech && this.lastAudioContainedSpeech)
            {
                this.lastVADSpeechEndTime      = this.lastAudioContainingSpeechTime;
                this.lastVADSpeechTimeInterval = new TimeInterval(this.lastVADSpeechStartTime, this.lastVADSpeechEndTime);

                // Allocate a buffer large enough to hold the buffered audio
                BufferWriter bw = new BufferWriter(this.currentQueue.Sum(b => b.Item1.Length));

                // Get the audio associated with the recognized text from the current queue.
                ValueTuple <AudioBuffer, bool> buffer;
                while (this.currentQueue.TryDequeue(out buffer))
                {
                    bw.Write(buffer.Item1.Data);

                    // We are done with this buffer so enqueue it for recycling
                    this.In.Recycle(buffer);
                }

                // Save the buffered audio
                this.lastAudioBuffer = bw.Buffer;

                // Call EndAudio to signal that this is the last packet
                await this.speechRecognitionClient.SendEndAudioAsync(this.cancellationTokenSource.Token);
            }
            else if (hasSpeech && !this.lastAudioContainedSpeech)
            {
                // If this is the first audio packet containing speech, mark the time of the previous audio packet
                // as the start of the actual speech
                this.lastVADSpeechStartTime = previousAudioOriginatingTime;

                // Also post a null partial recognition result
                this.lastPartialResult = string.Empty;
                this.PostWithOriginatingTimeConsistencyCheck(this.PartialRecognitionResults, this.BuildPartialSpeechRecognitionResult(this.lastPartialResult), e.OriginatingTime);
            }

            // Remember last audio state.
            this.lastAudioContainedSpeech = hasSpeech;
        }
Exemple #28
0
 public void WriteTimesAndGcs(IEnumerable <ValueTuple <int, int> > trials) => WriteTimesAndGcs(trials.Select(t => ValueTuple.Create(t.Item1, (int?)t.Item2)));
Exemple #29
0
 private static ulong ProjectId(ValueTuple <QuicWorker, QuicActivityData> data)
 {
     return(data.Item1.Id);
 }
Exemple #30
0
    /*
     * Small diagram for reference :)
     *       |      |  /|
     *       |      | / |P1
     *       |      |/  |
     *       |    I1|   |
     *       |     /|   |
     *      y|    / |   |
     *       | P0/__|___|P2
     *       |      |I2
     *       |      |
     *       |___________________
     */

    public bool TrianglePlaneIntersect(List <Vector3> vertices, List <Vector2> uvs, List <int> triangles, int startIdx, ref Plane plane, TempMesh posMesh, TempMesh negMesh, Vector3[] intersectVectors)
    {
        int i;

        // Store triangle, vertex and uv from indices
        for (i = 0; i < 3; ++i)
        {
            t[i] = triangles[startIdx + i];
            v[i] = vertices[t[i]];
            u[i] = uvs[t[i]];
        }

        // Store wether the vertex is on positive mesh
        posMesh.ContainsKeys(triangles, startIdx, positive);

        // If they're all on the same side, don't do intersection
        if (positive[0] == positive[1] && positive[1] == positive[2])
        {
            // All points are on the same side. No intersection
            // Add them to either positive or negative mesh
            (positive[0] ? posMesh : negMesh).AddOgTriangle(t);
            return(false);
        }

        // Find lonely point
        int lonelyPoint = 0;

        if (positive[0] != positive[1])
        {
            lonelyPoint = positive[0] != positive[2] ? 0 : 1;
        }
        else
        {
            lonelyPoint = 2;
        }

        // Set previous point in relation to front face order
        int prevPoint = lonelyPoint - 1;

        if (prevPoint == -1)
        {
            prevPoint = 2;
        }
        // Set next point in relation to front face order
        int nextPoint = lonelyPoint + 1;

        if (nextPoint == 3)
        {
            nextPoint = 0;
        }

        // Get the 2 intersection points
        ValueTuple <Vector3, Vector2> newPointPrev = Intersect(plane, v[lonelyPoint], v[prevPoint], u[lonelyPoint], u[prevPoint]);
        ValueTuple <Vector3, Vector2> newPointNext = Intersect(plane, v[lonelyPoint], v[nextPoint], u[lonelyPoint], u[nextPoint]);

        //Set the new triangles and store them in respective tempmeshes
        (positive[lonelyPoint] ? posMesh : negMesh).AddSlicedTriangle(t[lonelyPoint], newPointNext.Item1, newPointPrev.Item1, newPointNext.Item2, newPointPrev.Item2);

        (positive[prevPoint] ? posMesh : negMesh).AddSlicedTriangle(t[prevPoint], newPointPrev.Item1, newPointPrev.Item2, t[nextPoint]);

        (positive[prevPoint] ? posMesh : negMesh).AddSlicedTriangle(t[nextPoint], newPointPrev.Item1, newPointNext.Item1, newPointPrev.Item2, newPointNext.Item2);

        // We return the edge that will be in the correct orientation for the positive side mesh
        if (positive[lonelyPoint])
        {
            intersectVectors[0] = newPointPrev.Item1;
            intersectVectors[1] = newPointNext.Item1;
        }
        else
        {
            intersectVectors[0] = newPointNext.Item1;
            intersectVectors[1] = newPointPrev.Item1;
        }
        return(true);
    }
Exemple #31
0
 private static ushort ProjectCPU(ValueTuple <QuicWorker, QuicActivityData> data)
 {
     return(data.Item2.Processor);
 }
 private bool ShouldUseSemanticPart(ValueTuple<SymbolDisplayPart, TextSpan> partAndSpan)
 {
     // Don't take 'text' from the semantic parts.  We'll get those for the 
     // spaces between the actual interesting semantic spans, and we don't 
     // want them to override actual good syntax spans.
     return partAndSpan.Item1.Kind != SymbolDisplayPartKind.Text;
 }
Exemple #33
0
 private static uint ProjectThreadId(ValueTuple <QuicWorker, QuicActivityData> data)
 {
     return(data.Item1.ThreadId);
 }
Exemple #34
0
 public static ValueTuple <T1, T2, T3, T4> VTuple <T1, T2, T3, T4>(T1 item1, T2 item2, T3 item3, T4 item4) =>
 ValueTuple.Create(item1, item2, item3, item4);
Exemple #35
0
 public static ValueTuple <T1, T2, T3, T4, T5, T6, T7> VTuple <T1, T2, T3, T4, T5, T6, T7>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7) =>
 ValueTuple.Create(item1, item2, item3, item4, item5, item6, item7);
 public PropertyAggregatorUpdate(PropertyAggregatorConfig config, ValueTuple values)
 {
     _config = config;
     _values = values;
 }
Exemple #37
0
 public void WriteMillis(IEnumerable <int> millis) => WriteTimesAndGcs(millis.Select(m => ValueTuple.Create(m, new int?())));
 private void AddAlignmentBlockOperationRelativeToFirstTokenOnBaseTokenLine(List<IndentBlockOperation> list, ValueTuple<SyntaxToken, SyntaxToken> bracePair)
 {
     var option = IndentBlockOption.RelativeToFirstTokenOnBaseTokenLine;
     SetAlignmentBlockOperation(list, bracePair.Item1, bracePair.Item1.GetNextToken(includeZeroWidth: true), bracePair.Item2, option);
 }
Exemple #39
0
 private static TimestampDelta ProjectDuration(ValueTuple <QuicWorker, QuicActivityData> data)
 {
     return(data.Item2.Duration);
 }
Exemple #40
0
        private static void CreateEditSessionRudeEdit(Dictionary<string, object> map, int sessionId, int editSessionId, ValueTuple<ushort, ushort> rudeEdit, bool blocking)
        {
            map[SessionId] = sessionId;
            map[EditSessionId] = editSessionId;

            map[RudeEditKind] = rudeEdit.Item1;
            map[RudeEditSyntaxKind] = rudeEdit.Item2;
            map[RudeEditBlocking] = blocking;
        }
Exemple #41
0
 public void Serialize(ref byte[] buffer, ref int offset, ValueTuple <T1> value)
 {
     _item1Formatter.Serialize(ref buffer, ref offset, value.Item1);
 }
Exemple #42
0
 public static ValueTuple VTuple() =>
 ValueTuple.Create();
 public EdgeNonWeighted(ValueTuple <V, V> value)
 {
     (From, To) = value;
 }
Exemple #44
0
        private SyntaxTriviaList GetLeadingTriviaAtBeginningOfTree(
            ValueTuple<SyntaxToken, SyntaxToken> pair,
            TriviaData triviaData,
            CancellationToken cancellationToken)
        {
            var csharpTriviaData = triviaData as TriviaDataWithList;
            if (csharpTriviaData != null)
            {
                return SyntaxFactory.TriviaList(csharpTriviaData.GetTriviaList(cancellationToken));
            }

            // whitespace trivia case such as spaces/tabs/new lines
            // these will always have single text changes
            var text = triviaData.GetTextChanges(GetTextSpan(pair)).Single().NewText;
            return SyntaxFactory.ParseLeadingTrivia(text);
        }
 public bool Equals(ValueTuple <string, string> x, ValueTuple <string, string> y)
 {
     return(StringComparer.OrdinalIgnoreCase.Equals(x.Item1, y.Item1) && StringComparer.OrdinalIgnoreCase.Equals(x.Item2, y.Item2));
 }
 protected virtual CompletionItem CreateItem(ValueTuple<string, string> displayAndInsertionText, int position, List<ISymbol> symbols, AbstractSyntaxContext context, TextSpan textChangeSpan, bool preselect, SupportedPlatformData supportedPlatformData)
 {
     return new SymbolCompletionItem(
         this,
         displayAndInsertionText.Item1,
         displayAndInsertionText.Item2,
         GetFilterText(symbols[0], displayAndInsertionText.Item1, context),
         textChangeSpan,
         position,
         symbols,
         context,
         supportedPlatforms: supportedPlatformData,
         preselect: preselect);
 }
 public int GetHashCode(ValueTuple <string, string> obj)
 {
     return(HashCode.Combine(obj.Item1.GetHashCode(StringComparison.OrdinalIgnoreCase), obj.Item2.GetHashCode(StringComparison.OrdinalIgnoreCase)));
 }
Exemple #48
0
        private static double ProjectPercentWeight(ValueTuple <QuicWorker, QuicActivityData> data)
        {
            TimestampDelta TimeNs = data.Item1.FinalTimeStamp - data.Item1.InitialTimeStamp;

            return(100.0 * data.Item2.Duration.ToNanoseconds / TimeNs.ToNanoseconds);
        }
Exemple #49
0
        // Drop: __hash__

        // Drop: __eq__

        internal string __Str__()
        {
            return("%s(%d)".PyFormat(ValueTuple.Create(this.DeviceType, this.DeviceId)));
        }
 private bool TouchDocumentActionForDocument(ValueTuple<ProjectState, CompilationTranslationAction> tuple, DocumentId id)
 {
     var touchDocumentAction = tuple.Item2 as CompilationTranslationAction.TouchDocumentAction;
     return touchDocumentAction != null && touchDocumentAction.DocumentId == id;
 }
Exemple #51
0
 private static Timestamp ProjectTime(ValueTuple <QuicWorker, QuicActivityData> data)
 {
     return(data.Item2.TimeStamp);
 }