Esempio n. 1
0
    public static List<float> draw()
    {
        List<Vector2> points = new List<Vector2>();

        Vector2 place = Vector2.zero;

        for(int i = 0; i < 128/4; i++){
            points.Add(new Vector2(place.x,place.y));
            place.x+=5;
        }
        for(int i = 0; i < 128/4; i++){
            points.Add(new Vector2(place.x,place.y));
            place.y+=5;
        }
        for(int i = 0; i < 128/4; i++){
            points.Add(new Vector2(place.x,place.y));
            place.x-=5;
        }
        for(int i = 0; i < 128/4; i++){
            points.Add(new Vector2(place.x,place.y));
            place.y-=5;
        }

        Recognizer r = new Recognizer();
        return r.Vectorize(r.Resample(points,64));
    }
Esempio n. 2
0
        public SwipeDetection()
        {
            // Create the gesture recognizer.
            this.activeRecognizer = this.CreateRecognizer();

            InitializeNui();
        }
Esempio n. 3
0
        public KinectControl(double layoutHeight, double layoutWidth)
        {
            _layoutHeight = layoutHeight;
            _layoutWidth = layoutWidth;

            _kinect = KinectSensor.KinectSensors.FirstOrDefault();
            _kinect.SkeletonStream.TrackingMode = SkeletonTrackingMode.Seated;

            if (_kinect != null)
            {
                _kinect.Start();

                _kinect.ColorStream.Enable();
                _kinect.SkeletonStream.Enable(new TransformSmoothParameters
                {
                    Smoothing = 0.7f,
                    Correction = 0.1f,
                    Prediction = 0.1f,
                    JitterRadius = 0.05f,
                    MaxDeviationRadius = 0.05f
                });

                _activeRecognizer = CreateRecognizer();
                _kinect.SkeletonFrameReady += kinect_SkeletonFrameReady;
            }
        }
Esempio n. 4
0
        public KinectControl(HoverButton kinectButton, double layoutHeight, double layoutWidth, List<Button> buttons, TextBox debugBox = null)
        {
            _kinectButton = kinectButton;
            _layoutHeight = layoutHeight;
            _layoutWidth = layoutWidth;
            _buttons = buttons;
            _debugBox = debugBox;

            _kinect = KinectSensor.KinectSensors.FirstOrDefault();

            if (_kinect != null)
            {
                _kinect.Start();

                _kinect.ColorStream.Enable();
                _kinect.SkeletonStream.Enable(new TransformSmoothParameters
                    {
                        Smoothing = 0.7f,
                        Correction = 0.1f,
                        Prediction = 0.1f,
                        JitterRadius = 0.05f,
                        MaxDeviationRadius = 0.05f
                    });

                _kinect.SkeletonFrameReady += kinect_SkeletonFrameReady;
            }

            _activeRecognizer = CreateRecognizer();
            _kinectButton.Click += KinectButton_Click;
        }
        public MainWindow()
        {
            InitializeComponent();

            // Create the gesture recognizer.
            this.activeRecognizer = this.CreateRecognizer();
            kinectButton.Click += new RoutedEventHandler(kinectButton_Clicked);
        }
Esempio n. 6
0
 public static List<float> draw()
 {
     List<Vector2> vector = new List<Vector2>();
     for(int x=0; x <128*5; x+=5){
         vector.Add(new Vector2(x,0));
     }
     Recognizer r = new Recognizer();
     return r.Vectorize(r.Resample(vector,64));
 }
 public Recognizer CreateRecognizer()
 {
     var recognizer = new Recognizer();
     recognizer.SwipeRightDetected += (s, e) =>
     {
         Constants.isSwappingHand = true;
     };
     recognizer.SwipeLeftDetected += (s, e) =>
     {
         Constants.isSwappingHand = true;
     };
     return recognizer;
 }
Esempio n. 8
0
    public static List<float> draw()
    {
        List<Vector2> points = new List<Vector2>();

        float theta = 0;

        for(int i = 2; i <= 360; i +=2){
            theta = i * Mathf.Deg2Rad;
            points.Add(new Vector2(Mathf.Cos(theta)*10,Mathf.Sin(theta)*10));
        }

        Recognizer r = new Recognizer();
        return r.Vectorize(r.Resample(points,64));
    }
        /// <summary>
        ///     Process a line.
        /// </summary>
        /// <param name="start">The index of the start of the line</param>
        /// <param name="line">The line</param>
        private void ProcessLine(int start, string line)
        {
            if (ApplyPatterns)
            {
                // Save SelectionStart and SelectionLength because syntax highlighting will change
                int   savedSelectionStart  = SelectionStart;
                int   savedSelectionLength = SelectionLength;
                Color savedSelectionColor  = SelectionBackColor;

                SelectionStart  = start;
                SelectionLength = line.Length;
                SelectionColor  = Color.Black;
                SelectionFont   = RegularFont;

                Recognizer.Colorize(this, Instance, start, line);

                SelectionStart  = savedSelectionStart;
                SelectionLength = savedSelectionLength;
                SelectionColor  = savedSelectionColor;
            }
        }
Esempio n. 10
0
        private Recognizer CreateRecognizer()
        {
            // Instantiate a recognizer.
            var recognizer = new Recognizer();

            // Wire-up swipe right to manually advance picture.
            //recognizer.SwipeRightDetected += (s, e) =>
            //{
            //    _selected = _buttons.First();
            //    _selected.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent, _selected));
            //};

            // Wire-up swipe right to manually advance picture.
            //recognizer.SwipeLeftDetected += (s, e) =>
            //{
            //    _selected = _buttons[1];
            //    _selected.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent, _selected));
            //};

            return recognizer;
        }
        private void button3_Click(object sender, EventArgs e)
        {
            List <RadioInfo> radios = new List <RadioInfo>();

            string folderBase = Context.OutputDataDirectory;

            foreach (string folder in Directory.GetDirectories(folderBase))
            {
                string folderName = Path.GetFileName(folder);
                if (folderName != "Input")
                {
                    Recognizer reco = new Recognizer();
                    radios = reco.RecognizeFolder(folder);

                    ShapefileMaker shaper = new ShapefileMaker();
                    shaper.Create(radios, folderName, Context.Geo);
                }
            }
            Console.WriteLine("Listo");
            MessageBox.Show("Listo");
        }
        /// <summary>
        /// Converts 'for' loops with ParallelSchedule attributes into parallel for loops.
        /// </summary>
        /// <param name="ifs">The for loop to convert</param>
        /// <returns>The converted statement</returns>
        protected override IStatement ConvertFor(IForStatement ifs)
        {
            if (context.InputAttributes.Has <ConvergenceLoop>(ifs) || (ifs is IBrokenForStatement))
            {
                return(base.ConvertFor(ifs));
            }
            IVariableDeclaration       loopVar = Recognizer.LoopVariable(ifs);
            ParallelScheduleExpression pse     = context.InputAttributes.Get <ParallelScheduleExpression>(loopVar);

            if (pse != null)
            {
                return(ConvertForWithParallelSchedule(ifs, loopVar, pse));
            }
            DistributedScheduleExpression dse = context.InputAttributes.Get <DistributedScheduleExpression>(loopVar);

            if (dse != null)
            {
                return(ConvertForWithDistributedSchedule(ifs, loopVar, dse));
            }
            return(base.ConvertFor(ifs));
        }
Esempio n. 13
0
        public BatchModeRecognizer(
            Recognizer recognizer,
            List <IDataProcessor> inputDataProcessors,
            int skip,
            int utteranceId,
            int whichBatch,
            int totalBatches,
            Boolean usePooledBatchManager
            )
        {
            cm = null;

            this.skip                  = skip;
            this.utteranceId           = utteranceId;
            this.whichBatch            = whichBatch;
            this.totalBatches          = totalBatches;
            this.usePooledBatchManager = usePooledBatchManager;

            this.recognizer          = recognizer;
            this.inputDataProcessors = inputDataProcessors;
        }
 /// <summary>
 /// Attach DerivedVariable attributes to newly created variables
 /// </summary>
 /// <param name="iae"></param>
 /// <returns></returns>
 protected override IExpression ConvertAssign(IAssignExpression iae)
 {
     iae = (IAssignExpression)base.ConvertAssign(iae);
     if (iae.Expression is IMethodInvokeExpression imie)
     {
         IVariableDeclaration ivd = Recognizer.GetVariableDeclaration(iae.Target);
         if (ivd != null)
         {
             bool isDerived = context.InputAttributes.Has <DerivedVariable>(ivd);
             if (!isDerived)
             {
                 FactorManager.FactorInfo info = CodeRecognizer.GetFactorInfo(context, imie);
                 if (info.IsDeterministicFactor)
                 {
                     context.InputAttributes.Set(ivd, new DerivedVariable());
                 }
             }
         }
     }
     return(iae);
 }
Esempio n. 15
0
        public SpeechAligner(string amPath, string dictPath, string g2PPath)
        {
            var configuration = new Configuration();

            configuration.AcousticModelPath = amPath;
            configuration.DictionaryPath    = dictPath;

            _context = new Context(configuration);
            if (g2PPath != null)
            {
                _context.SetLocalProperty("dictionary->allowMissingWords", "true");
                _context.SetLocalProperty("dictionary->createMissingWords", "true");
                _context.SetLocalProperty("dictionary->g2pModelPath", g2PPath);
                _context.SetLocalProperty("dictionary->g2pMaxPron", "2");
            }
            _context.SetLocalProperty("lexTreeLinguist->languageModel", "dynamicTrigramModel");
            _recognizer    = (Recognizer)_context.GetInstance(typeof(Recognizer));
            _grammar       = (AlignerGrammar)_context.GetInstance(typeof(AlignerGrammar));
            _languageModel = (DynamicTrigramModel)_context.GetInstance(typeof(DynamicTrigramModel));
            Tokenizer      = new UsEnglishTokenizer();
        }
Esempio n. 16
0
        internal static bool CouldOverlap(ExpressionWithBindings eb1, ExpressionWithBindings eb2)
        {
            var emptyBindings = (IEnumerable <IReadOnlyCollection <ConditionBinding> >) new[] { new ConditionBinding[0] };
            IEnumerable <IReadOnlyCollection <ConditionBinding> > bindings1 = (eb1.Bindings.Count > 0) ?
                                                                              eb1.Bindings : emptyBindings;
            IEnumerable <IReadOnlyCollection <ConditionBinding> > bindings2 = (eb2.Bindings.Count > 0) ?
                                                                              eb2.Bindings : emptyBindings;

            foreach (IReadOnlyCollection <ConditionBinding> binding1 in bindings1)
            {
                foreach (IReadOnlyCollection <ConditionBinding> binding2 in bindings2)
                {
                    // TODO: investigate whether we need to provide local var predicate.
                    if (Recognizer.MutatingFirstAffectsSecond(eb1.Expression, eb2.Expression, binding1, binding2, ivd => false))
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
        private async Task <DialogTurnResult> InitialStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var notificationOfIllnessDetails = (NotificationOfIllnessDetails)stepContext.Options;

            var promptMessage   = MessageFactory.Text(PromptMsgText, PromptMsgText, InputHints.ExpectingInput);
            var repromptMessage = MessageFactory.Text(RepromptMsgText, RepromptMsgText, InputHints.ExpectingInput);

            if (!Recognizer.TryGetDate(notificationOfIllnessDetails.Text, Culture.German, out DateTime sickUntilDate))
            {
                // We were not given any date at all so prompt the user.
                return(await stepContext.PromptAsync(nameof(DateTimePrompt),
                                                     new PromptOptions
                {
                    Prompt = promptMessage,
                    RetryPrompt = repromptMessage,
                }, cancellationToken));
            }

            notificationOfIllnessDetails.SickUntil = sickUntilDate;
            return(await stepContext.NextAsync(notificationOfIllnessDetails, cancellationToken));
        }
 protected bool IsPartitionedExpr(IExpression expr)
 {
     return(Recognizer.GetVariables(expr).Any(ivd =>
     {
         Containers c = context.InputAttributes.Get <Containers>(ivd);
         foreach (IStatement container in c.inputs)
         {
             if (container is IForStatement)
             {
                 IForStatement loop = (IForStatement)container;
                 IVariableDeclaration loopVar = Recognizer.LoopVariable(loop);
                 bool isPartitionedLoop = context.InputAttributes.Has <Partitioned>(loopVar);
                 if (isPartitionedLoop && loopVar.Equals(ivd))
                 {
                     return true;
                 }
             }
         }
         return false;
     }));
 }
Esempio n. 19
0
        public void CorrectFaceTest1()
        {
            Recognizer       _testReco;
            FaceImage        _testImage;
            LabelStorageMock _labelRepo = new LabelStorageMock(4);
            ImageStorageMock _imageRepo = new ImageStorageMock();

            _testReco = new Recognizer(_imageRepo, _labelRepo);

            Bitmap load_img = new Bitmap(Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.Parent.FullName + @"\Recognizer\TestSample\TestPerson1\e2105db7-8e4f-4cbe-b1d0-7b0c7274431c.bmp");

            _testImage = new FaceImage(load_img, _imageRepo.RepoPath + @"\DTO\haarcascade_frontalface_default.xml")
            {
                Id = new Identifier(0)
            }; // face detection there

            IIdentifier actual   = _testReco.GetIdentity(_testImage);
            var         expected = new Identifier(0);

            Assert.AreEqual(expected, actual);
        }
Esempio n. 20
0
        /// <summary>
        /// Converts an array indexed expression.
        /// </summary>
        /// <param name="iaie"></param>
        /// <returns></returns>
        protected override IExpression ConvertArrayIndexer(IArrayIndexerExpression iaie)
        {
            IExpression expr = base.ConvertArrayIndexer(iaie);

            // Check if this is the top level indexer
            if (Recognizer.IsBeingIndexed(context))
            {
                return(expr);
            }
            IExpression target;
            List <IList <IExpression> > indices = Recognizer.GetIndices(expr, out target);

            if (!(target is IVariableReferenceExpression))
            {
                return(expr);
            }
            IVariableDeclaration ivd = Recognizer.GetVariableDeclaration(target);

            if (ivd == null)
            {
                return(expr);
            }
            VariableToChannelInformation vtci = Context.InputAttributes.Get <VariableToChannelInformation>(ivd);

            if (vtci == null)
            {
                return(expr);
            }
            if (vtci.usageChannel == null)
            {
                return(expr);
            }
            bool isDef = Recognizer.IsBeingMutated(context, expr);

            if (isDef)
            {
                return(expr);
            }
            return(vtci.usageChannel.ReplaceWithUsesChannel(expr, Builder.LiteralExpr(vtci.shareAllUses ? 0 : vtci.useCount++)));
        }
Esempio n. 21
0
            public override SemanticContext EvalPrecedence <Symbol, ATNInterpreter>(Recognizer <Symbol, ATNInterpreter> parser, RuleContext parserCallStack)
            {
                bool differs = false;
                IList <SemanticContext> operands = new List <SemanticContext>();

                foreach (SemanticContext context in opnds)
                {
                    SemanticContext evaluated = context.EvalPrecedence(parser, parserCallStack);
                    differs |= (evaluated != context);
                    if (evaluated == None)
                    {
                        // The OR context is true if any element is true
                        return(None);
                    }
                    else
                    {
                        if (evaluated != null)
                        {
                            // Reduce the result by skipping false elements
                            operands.Add(evaluated);
                        }
                    }
                }
                if (!differs)
                {
                    return(this);
                }
                if (operands.Count == 0)
                {
                    // all elements were false, so the OR context is false
                    return(null);
                }
                SemanticContext result = operands[0];

                for (int i = 1; i < operands.Count; i++)
                {
                    result = SemanticContext.Or(result, operands[i]);
                }
                return(result);
            }
        public void TrainRecognizer()
        {
            var root = UsersRoot;

            if (!Directory.Exists(root))
            {
                return;
            }

            var images = Directory.EnumerateDirectories(root)
                         .OrderBy(p => p)
                         .SelectMany(person => Directory.EnumerateFiles(person, "*.jpg")
                                     .OrderBy(p => p)
                                     .Select(p => Mat.FromStream(File.OpenRead(p), LoadMode.AnyColor).CvtColor(ColorConversion.BgrToGray)))
                         .ToArray();

            var labels = Directory.EnumerateDirectories(root)
                         .OrderBy(p => p)
                         .SelectMany((person, i) => Directory.EnumerateFiles(person, "*.jpg")
                                     .OrderBy(p => p)
                                     .Select(_ => i + 1))
                         .ToArray();

            lock (IndicesToNames)
            {
                IndicesToNames = new[] { "Unknown" }.Concat(Directory.EnumerateDirectories(root)
                                                            .OrderBy(p => p)
                                                            .Select(Path.GetFileName))
                .ToArray();
            }


            Recognizer.Train(images, labels);

            // Implement to save and load trained recognizer
            // Recognizer.Save("filename.yml")
            // Recognizer.Load("filename.yml")

            isTrained = true;
        }
Esempio n. 23
0
        private async Task <bool> ValidatePizza(PromptValidatorContext <string> validatorContext, CancellationToken cancellationToken)
        {
            var value = validatorContext.Recognized.Value;

            if (value.Equals("personalizada", System.StringComparison.InvariantCultureIgnoreCase))
            {
                return(true);
            }
            var pizzaExists = _pizzaRepository.GetPizzas()
                              .Any(p => value.Contains(p.Name, System.StringComparison.InvariantCultureIgnoreCase));

            if (pizzaExists)
            {
                return(true);
            }

            var result = await Recognizer.RecognizeAsync <OrderPizza>(validatorContext.Context, cancellationToken);

            var intent = result.TopIntent();

            return(intent.intent == OrderPizza.Intent.GetMenu);
        }
Esempio n. 24
0
        protected static IExpression GetCommonPrefix(IExpression expr, IExpression expr2)
        {
            List <IExpression> prefixes1 = Recognizer.GetAllPrefixes(expr);
            List <IExpression> prefixes2 = Recognizer.GetAllPrefixes(expr2);

            if (!prefixes1[0].Equals(prefixes2[0]))
            {
                throw new Exception($"Expressions have no overlap: {expr}, {expr2}");
            }
            int count = System.Math.Min(prefixes1.Count, prefixes2.Count);

            for (int i = 1; i < count; i++)
            {
                IExpression prefix1 = prefixes1[i];
                IExpression prefix2 = prefixes2[i];
                if (!prefix1.Equals(prefix2))
                {
                    return(prefixes1[i - 1]);
                }
            }
            return(prefixes1[count - 1]);
        }
Esempio n. 25
0
        public TestControl(string name, string headerText, List <TestQuestion> questions, Action endTestAction)
        {
            InitializeComponent();
            tbHeader.Text = headerText;

            Name               = name;
            _questions         = questions;
            query              = new List <TestQuestion>(_questions);
            this.endTestAction = endTestAction;

            foreach (var rec in new Recognizers())
            {
                Debug.WriteLine(rec.Name);
                if (rec.Name.Contains("日本語"))
                {
                    jpnRecognizer = rec;
                }
            }

            currentQuestion = 0;
            RefreshQuestionText();
        }
        private void LoadGestureRecognizer(string basePath)
        {
            _recognizer = new Recognizer();

            _recognizer.LoadGesture(String.Format(basePath, "circle01.xml"));
            _recognizer.LoadGesture(String.Format(basePath, "circle02.xml"));
            _recognizer.LoadGesture(String.Format(basePath, "circle03.xml"));
            _recognizer.LoadGesture(String.Format(basePath, "check01.xml"));
            _recognizer.LoadGesture(String.Format(basePath, "check02.xml"));
            _recognizer.LoadGesture(String.Format(basePath, "check03.xml"));
            _recognizer.LoadGesture(String.Format(basePath, "pigtail01.xml"));
            _recognizer.LoadGesture(String.Format(basePath, "pigtail02.xml"));
            _recognizer.LoadGesture(String.Format(basePath, "pigtail03.xml"));
            _recognizer.LoadGesture(String.Format(basePath, "question_mark01.xml"));
            _recognizer.LoadGesture(String.Format(basePath, "question_mark02.xml"));
            _recognizer.LoadGesture(String.Format(basePath, "question_mark03.xml"));

            DollarRecognizerScoreThresholds[ShapeGestureEventArgs.Shapes.Circle]        = DefaultDollarRecognizerScoreThreshold;
            DollarRecognizerScoreThresholds[ShapeGestureEventArgs.Shapes.PigTail]       = DefaultDollarRecognizerScoreThreshold;
            DollarRecognizerScoreThresholds[ShapeGestureEventArgs.Shapes.Question_Mark] = DefaultDollarRecognizerScoreThreshold;
            DollarRecognizerScoreThresholds[ShapeGestureEventArgs.Shapes.Check]         = .9;
        }
Esempio n. 27
0
        static void Main(string[] args)
        {
            Recognizer rec = new Recognizer();

            Settings settings;

            using (StreamReader sr = new StreamReader("credentials.json"))
                settings = JsonConvert.DeserializeObject <Settings>(sr.ReadToEnd());

            BanchoApi api = new BanchoApi(settings.ClientId, settings.Secret);

            Console.WriteLine(api.ReloadToken());

            string[] dirFiles = Directory.GetFiles(@"./testImages/");

            foreach (string path in dirFiles)
            {
                Image img = rec.LoadFromFile(path);

                string[]          recedText = rec.RecognizeTopText(img).Split('\n');
                List <Beatmapset> bms       = api.Search(recedText.First(), WAV_Osu_NetApi.Bancho.QuerryParams.MapType.Any);

                foreach (string s in recedText)
                {
                    Console.WriteLine(s);
                }

                Beatmapset bm = bms?.First();

                if (bm is null)
                {
                    Console.WriteLine("No beatmap found");
                }
                else
                {
                    Console.WriteLine($"{bm.artist} - {bm.title}\n{bm.creator}");
                }
            }
        }
Esempio n. 28
0
        protected override IExpression ConvertMethodInvoke(IMethodInvokeExpression imie)
        {
            if (Recognizer.IsStaticGenericMethod(imie, new Func <PlaceHolder, PlaceHolder>(ArrayHelper.CopyStorage)))
            {
                return(imie);
            }
            IMethodInvokeExpression mie     = Builder.MethodInvkExpr();
            MessageFcnInfo          fcnInfo = GetMessageFcnInfo(context, imie);
            var  parameters = fcnInfo.Method.GetParameters();
            bool changed    = false;
            var  arguments  = imie.Arguments.Select((arg, i) =>
            {
                if ((fcnInfo != null) && (i == fcnInfo.ResultParameterIndex))
                {
                    // if argument is 'result' argument, do not convert
                    return(arg);
                }
                else
                {
                    formalTypeStack.Push(parameters[i].ParameterType);
                    var expr = ConvertExpression(arg);
                    formalTypeStack.Pop();
                    if (!ReferenceEquals(expr, arg))
                    {
                        changed = true;
                    }
                    return(expr);
                }
            });

            mie.Arguments.AddRange(arguments);
            mie.Method = (IMethodReferenceExpression)ConvertExpression(imie.Method);
            if (ReferenceEquals(mie.Method, imie.Method) && !changed)
            {
                return(imie);
            }
            context.InputAttributes.CopyObjectAttributesTo(imie, context.OutputAttributes, mie);
            return(mie);
        }
Esempio n. 29
0
        public string align()
        {
            if (PROP_PERFORM_SPOTTING)
            {
                phraseSpotterResult = new List <PhraseSpotterResult>();
                collectPhraseSpottingResult();
            }

            cm = new ConfigurationManager(config);
            AlignerSearchManager sm = (AlignerSearchManager)cm
                                      .lookup("searchManager");

            sm.setSpotterResult(phraseSpotterResult);
            optimize();
            setGlobalProperties();
            recognizer = (Recognizer)cm.lookup(PROP_RECOGNIZER);
            grammar    = (AlignerGrammar)cm.lookup(PROP_GRAMMAR);
            datasource = (AudioFileDataSource)cm.lookup(PROP_AUDIO_DATA_SOURCE);
            datasource.setAudioFile(new File(audioFile), null);
            allocate();
            return(start_align());
        }
Esempio n. 30
0
 protected override IStatement ConvertCondition(IConditionStatement ics)
 {
     ics = (IConditionStatement)base.ConvertCondition(ics);
     if (ics != null && ics.Then.Statements.Count == 1)
     {
         IStatement st = ics.Then.Statements[0];
         if (st is IForStatement)
         {
             IForStatement        ifs     = (IForStatement)st;
             IVariableDeclaration loopVar = Recognizer.LoopVariable(ifs);
             bool isSequential            = context.InputAttributes.Has <Sequential>(loopVar);
             if (isSequential)
             {
                 ics.Then = ifs.Body;
                 ifs.Body = Builder.BlockStmt();
                 ifs.Body.Statements.Add(ics);
                 return(ifs);
             }
         }
     }
     return(ics);
 }
Esempio n. 31
0
        protected override IStatement ConvertFor(IForStatement ifs)
        {
            var loopVar = Recognizer.LoopVariable(ifs);

            if (loopVarsToReverse.Contains(loopVar) && !(ifs is IBrokenForStatement))
            {
                // copied from CopyTransform.ConvertFor
                IForStatement fs = Builder.ForStmt();
                context.SetPrimaryOutput(fs);
                fs.Initializer = ConvertStatement(ifs.Initializer);
                fs.Condition   = ConvertExpression(ifs.Condition);
                fs.Increment   = ConvertStatement(ifs.Increment);
                fs.Body        = ConvertBlock(ifs.Body);
                context.InputAttributes.CopyObjectAttributesTo(ifs, context.OutputAttributes, fs);
                Recognizer.ReverseLoopDirection(fs);
                return(fs);
            }
            else
            {
                return(base.ConvertFor(ifs));
            }
        }
Esempio n. 32
0
        /// <summary>
        /// Create a wired-up recognizer for running the slideshow.
        /// </summary>
        /// <returns>The wired-up recognizer.</returns>
        private Recognizer CreateRecognizer()
        {
            // Instantiate a recognizer.
            var recognizer = new Recognizer();

            // Wire-up swipe right to manually advance picture.
            recognizer.SwipeRightDetected += (s, e) =>
            {
                if (isWatching)
                {
                    if (!gesturesInverted)
                    {
                        this.ShowNext();
                    }
                    else
                    {
                        this.ShowPrevious();
                    }
                }
            };

            // Wire-up swipe left to manually reverse picture.
            recognizer.SwipeLeftDetected += (s, e) =>
            {
                if (isWatching)
                {
                    if (!gesturesInverted)
                    {
                        this.ShowPrevious();
                    }
                    else
                    {
                        this.ShowNext();
                    }
                }
            };

            return(recognizer);
        }
Esempio n. 33
0
        private void CheckForDuplicateArguments(IMethodInvokeExpression mie)
        {
            Set <IExpression> args = new Set <IExpression>();

            for (int i = 0; i < mie.Arguments.Count; i++)
            {
                IExpression          arg = mie.Arguments[i];
                IVariableDeclaration ivd = Recognizer.GetVariableDeclaration(arg);
                if (ivd != null)
                {
                    VariableInformation vi = VariableInformation.GetVariableInformation(context, ivd);
                    if (vi.IsStochastic)
                    {
                        if (args.Contains(arg))
                        {
                            Error("Variable '" + vi.Name + "' appears twice in the same function call.  This will lead to inaccurate inference.  Try reformulating the model.");
                        }
                        args.Add(arg);
                    }
                }
            }
        }
Esempio n. 34
0
 private bool CanAddToContainer(IStatement container, int stmtIndex)
 {
     if (container is IBrokenForStatement)
     {
         return(false);
     }
     // convergence loops cannot be merged because they raise separate ProgressChanged events
     if (context.InputAttributes.Has <ConvergenceLoop>(container))
     {
         return(false);
     }
     if (loopMergingInfo != null && container is IForStatement && stmtIndex >= 0)
     {
         IForStatement        ifs           = (IForStatement)container;
         bool                 isForwardLoop = Recognizer.IsForwardLoop(ifs);
         Set <int>            stmts         = stmtsOfContainer[container];
         IVariableDeclaration loopVar       = Recognizer.LoopVariable(ifs);
         int conflict = loopMergingInfo.GetConflictingStmt(stmts, stmtIndex, loopVar, isForwardLoop);
         return(conflict == -1);
     }
     return(true);
 }
Esempio n. 35
0
        /// <summary>
        /// Constructs a universal recognizer that using the specified
        /// recognizers and caching enabled or disabled.
        /// </summary>
        /// <param name="wireRecognizer">the recognizer to use on wires</param>
        /// <param name="textRecognizer">the recognizer to use on text</param>
        /// <param name="gateRecognizer">the recognizer to use on gates</param>
        /// <exception cref="ArgumentException.ArgumentException">Thrown if
        /// the provided recognizers cannot recognize what they are intended
        /// to (e.g., if the wireRecognizer reports that it cannot recognize
        /// wires).</exception>
        public UniversalRecognizer(
            Recognizer wireRecognizer = null,
            Recognizer textRecognizer = null,
            Recognizer gateRecognizer = null)
        {
            if (wireRecognizer == null)
            {
                wireRecognizer = new WireRecognizer();
            }
            if (textRecognizer == null)
            {
                textRecognizer = new TextRecognizer();
            }
            if (gateRecognizer == null)
            {
#if AIR_OFF
                gateRecognizer = new ImageRecognizer();
#else
                gateRecognizer = AdaptiveImageRecognizer.LoadDefault();
#endif
            }

            if (!wireRecognizer.canRecognize("Wire"))
            {
                throw new ArgumentException("The provided wire recognizer '" + wireRecognizer + "' cannot recognize wires!");
            }
            if (!textRecognizer.canRecognize("Text"))
            {
                throw new ArgumentException("The provided text recognizer '" + textRecognizer + "' cannot recognize text!");
            }
            if (!gateRecognizer.canRecognize("Gate"))
            {
                throw new ArgumentException("The provided gate recognizer '" + gateRecognizer + "' cannot recognize gates!");
            }

            _wireRecognizer = wireRecognizer;
            _textRecognizer = textRecognizer;
            _gateRecognizer = gateRecognizer;
        }
Esempio n. 36
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            _recognizer = new Recognizer(_logger, _configuration);

            // Set up pipeline
            var pipeline = new BlockingCollection <Input>(boundedCapacity: 10);

            // Start the consumer
            var processingTask = ProcessQueuedFilesAsync(pipeline, cancellationToken);

            // Start producing data
            QueueImageFiles(_configuration.Value.ImagesPath, pipeline);

            // Signal producer completion
            pipeline.CompleteAdding();

            // Wait for pipeline to drain
            await processingTask;

            Console.WriteLine("Finished. Press any key to exit.");
            Console.ReadKey();
        }
Esempio n. 37
0
 private void RemoveMatchingSuffixes(IExpression expr1, IExpression expr2, List <IConditionStatement> condContext, out IExpression prefix1, out IExpression prefix2)
 {
     if (expr1 is IArrayIndexerExpression)
     {
         IArrayIndexerExpression iaie1 = (IArrayIndexerExpression)expr1;
         if (expr2 is IArrayIndexerExpression)
         {
             IArrayIndexerExpression iaie2 = (IArrayIndexerExpression)expr2;
             if (iaie1.Indices.Count == iaie2.Indices.Count)
             {
                 bool allIndicesAreEqual = true;
                 for (int i = 0; i < iaie1.Indices.Count; i++)
                 {
                     IExpression index1 = iaie1.Indices[i];
                     IExpression index2 = iaie2.Indices[i];
                     // indices only match if they are loop variables, because then we know that this is the only assignment for the whole array.
                     // literal indices, on the other hand, can appear in multiple assignments, e.g. array[0] = Copy(x0[0]), array[1] = Copy(x1[0]).
                     if (!(index1 is IVariableReferenceExpression) ||
                         !(index2 is IVariableReferenceExpression) ||
                         !index1.Equals(index2) ||
                         AnyConditionsDependOnLoopVariable(condContext, Recognizer.GetVariableDeclaration(index1)))
                     {
                         allIndicesAreEqual = false;
                     }
                 }
                 if (allIndicesAreEqual)
                 {
                     RemoveMatchingSuffixes(iaie1.Target, iaie2.Target, condContext, out prefix1, out prefix2);
                     if (prefix1.GetExpressionType().Equals(prefix2.GetExpressionType()))
                     {
                         return;
                     }
                 }
             }
         }
     }
     prefix1 = expr1;
     prefix2 = expr2;
 }
Esempio n. 38
0
        protected override IExpression ConvertAssign(IAssignExpression iae)
        {
            IParameterDeclaration ipd = null;
            IVariableDeclaration  ivd = Recognizer.GetVariableDeclaration(iae.Target);

            if (ivd == null)
            {
                ipd = Recognizer.GetParameterDeclaration(iae.Target);
                if (ipd == null)
                {
                    return(base.ConvertAssign(iae));
                }
            }
            IAssignExpression ae = (IAssignExpression)base.ConvertAssign(iae);

            if (ipd == null && !context.InputAttributes.Has <IsInferred>(ivd))
            {
                // assignment to a local variable
                if (ae.Expression is ILiteralExpression)
                {
                    bool isLoopInitializer = (Recognizer.GetAncestorIndexOfLoopBeingInitialized(context) != -1);
                    if (!isLoopInitializer)
                    {
                        Type valueType = ae.Expression.GetExpressionType();
                        if (Quoter.ShouldInlineType(valueType))
                        {
                            // inline all future occurrences of this variable with the rhs expression
                            conditionContext.Add(new ConditionBinding(ae.Target, ae.Expression));
                        }
                    }
                }
            }
            else
            {
                // assignment to a method parameter
            }
            return(ae);
        }
 /// <summary>
 /// Split expr into a target and extra indices, where target will be replicated and extra indices will be added later.
 /// </summary>
 /// <param name="loop">The loop we are replicating over</param>
 /// <param name="expr">Expression being replicated</param>
 /// <param name="indices">Modified to contain the extra indices</param>
 /// <param name="target">Prefix of expr to replicate</param>
 protected void AddUnreplicatedIndices(IForStatement loop, IExpression expr, List <IEnumerable <IExpression> > indices, out IExpression target)
 {
     if (expr is IArrayIndexerExpression)
     {
         IArrayIndexerExpression iaie = (IArrayIndexerExpression)expr;
         AddUnreplicatedIndices(loop, iaie.Target, indices, out target);
         if (indices.Count == 0)
         {
             // determine if iaie.Indices can be replicated
             bool canReplicate = true;
             foreach (IExpression index in iaie.Indices)
             {
                 if (NeedsContainer(loop, index))
                 {
                     canReplicate = false;
                     break;
                 }
             }
             IVariableDeclaration loopVar = Recognizer.LoopVariable(loop);
             bool isPartitioned           = context.InputAttributes.Has <Partitioned>(loopVar);
             if (isPartitioned && !AnyPartitionedExpr(iaie.Indices))
             {
                 canReplicate = false;
             }
             if (canReplicate)
             {
                 target = expr;
                 return;
             }
             // fall through
         }
         indices.Add(iaie.Indices);
     }
     else
     {
         target = expr;
     }
 }
Esempio n. 40
0
        public AdView()
        {
            this.InitializeComponent();

            // Create the gesture recognizer.
            this.activeRecognizer = this.CreateRecognizer();

            this.shuffleTimer = this.createTimer(slidshowLength, TimerTick);
            this.loadAfterTimer = this.createTimer(animationTime, LoadAdjacentAdsEvent);
            this.loadBeforeTimer = this.createTimer(slidshowLength-(animationTime*2), LoadAdjacentAdsEvent);

            orderedAds = AdChooser.chooseAd(FaceList.toList());
            AdView.currentAd = DatabaseManager.getAd(orderedAds[0]);
            this.Picture = LoadPicture(AdView.currentAd);
            this.changeProperty("Picture");

            allAds = DatabaseManager.getAllAds();

            oldIds = new List<int>();

            LoadAdjacentAds();
            CacheAds();
        }
Esempio n. 41
0
    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();

        if(GUILayout.Button("(Re)Draw Templates")){

            TemplateList t = this.target as TemplateList;

            List<Template> tl = new List<Template>();

            //Template algorithms go here

            //Line
            Template line = ScriptableObject.CreateInstance<Template>();
            line.name = LineT.name;
            line.vector = LineT.draw();
            tl.Add(line);

            //Square
            tl.Add(new Template(SquareT.name,SquareT.draw()));

            //Circle
            tl.Add(new Template(CircleT.name, CircleT.draw()));

            Recognizer r = new Recognizer();

            Match m1 = new Match(LineT.name, r.optimalCosineDistance(tl[0].vector,SquareT.draw() ));
            Match m2 = new Match(SquareT.name, r.optimalCosineDistance(tl[1].vector,SquareT.draw() ));
            Match m3 = new Match(CircleT.name, r.optimalCosineDistance(tl[2].vector,SquareT.draw() ));

            Debug.Log("Line: " +m1.score+" Square: "+m2.score+" Circle: " +m3.score);

            t.tl = tl;

        }
    }
        public MainWindow()
        {
            InitializeComponent();
            EventManager.RegisterClassHandler(typeof(Window), Window.KeyDownEvent, new KeyEventHandler(AppHotkeyKeyDown));
            //bagian kinect
            createTpose();
            this.actRecognizer = this.CreateRecognizer();
            KinectSensor.KinectSensors.StatusChanged += KinectSensors_StatusChanged;
            this.KinectDevice = KinectSensor.KinectSensors.FirstOrDefault(x => x.Status == KinectStatus.Connected);
            state = states.Welcome;

            //timer for instruction
            kinectDisable = false;
            instructionTimer = new DispatcherTimer();
            instructionTimer.Tick += new EventHandler(this.instrucTime);
            instructionTimer.Interval = new TimeSpan(0, 0, instructionSecond);

            //time for quiz waiting
            quizTimer = new DispatcherTimer();
            quizTimer.Tick += new EventHandler(this.quizTime);
            quizTimer.Interval = new TimeSpan(0, 0, quizSecond );
            //hide cursor
            this.Cursor = Cursors.None;
        }
Esempio n. 43
0
        /// <summary>
        /// Create a wired-up recognizer for running the slideshow.
        /// </summary>
        /// <returns>The wired-up recognizer.</returns>
        private Recognizer CreateRecognizer()
        {
            // Instantiate a recognizer.
              var recognizer = new Recognizer();

              // Wire-up swipe right to manually advance picture.
              recognizer.SwipeRightDetected += (s, e) =>
              {
            if (e.Skeleton.TrackingId == nearestId)
              {
              Index++;

              // Setup corresponding picture if pictures are available.
              this.PreviousPicture = this.Picture;
              this.Picture = this.NextPicture;
              this.NextPicture = LoadPicture(Index + 1);

              // Notify world of change to Index and Picture.
              if (this.PropertyChanged != null)
            {
            this.PropertyChanged(this, new PropertyChangedEventArgs("PreviousPicture"));
            this.PropertyChanged(this, new PropertyChangedEventArgs("Picture"));
            this.PropertyChanged(this, new PropertyChangedEventArgs("NextPicture"));
            }

              var storyboard = Resources["LeftAnimate"] as Storyboard;
              if (storyboard != null)
            {
            storyboard.Begin();
            }

              HighlightSkeleton(e.Skeleton);
              }
              };

              // Wire-up swipe left to manually reverse picture.
              recognizer.SwipeLeftDetected += (s, e) =>
              {
            if (e.Skeleton.TrackingId == nearestId)
              {
              Index--;

              // Setup corresponding picture if pictures are available.
              this.NextPicture = this.Picture;
              this.Picture = this.PreviousPicture;
              this.PreviousPicture = LoadPicture(Index - 1);

              // Notify world of change to Index and Picture.
              if (this.PropertyChanged != null)
            {
            this.PropertyChanged(this, new PropertyChangedEventArgs("PreviousPicture"));
            this.PropertyChanged(this, new PropertyChangedEventArgs("Picture"));
            this.PropertyChanged(this, new PropertyChangedEventArgs("NextPicture"));
            }

              var storyboard = Resources["RightAnimate"] as Storyboard;
              if (storyboard != null)
            {
            storyboard.Begin();
            }

              HighlightSkeleton(e.Skeleton);
              }
              };

              return recognizer;
        }
Esempio n. 44
0
 public KinectHelper()
 {
     try
     {
         if (KinectSensor.KinectSensors.Count > 0)
         {
             KinectSensor.KinectSensors.StatusChanged += KinectSensors_StatusChanged;
             this.sensor = KinectSensor.KinectSensors.FirstOrDefault(x => x.Status == KinectStatus.Connected);
             if (this.sensor != null)
             {
                 Initialize();
             }
             else
             {
                 KinectConnectionState = "Disconnected";
             }
         }
         else
         {
             KinectConnectionState = "Disconnected";
         }
         activeRecognizer = CreateRecognizer();
     }
     catch (Exception)
     {
         throw;
     }
 }
Esempio n. 45
0
        public void RegisterGestures(List<GestureType> gestureList)
        {
            if (gestureList.Contains(GestureType.JoinedHands) || gestureList.Contains(GestureType.LeftHandHalfLift) ||
                gestureList.Contains(GestureType.Pull) || gestureList.Contains(GestureType.Push) ||
                gestureList.Contains(GestureType.ZoomIn) || gestureList.Contains(GestureType.ZoomOut))
            {
                gestureController = new GestureController();
                gestureController.GestureRecognized += OnGestureRecognized;
                if (gestureList.Contains(GestureType.JoinedHands))
                {
                    IRelativeGestureSegment[] joinedhandsSegments = new IRelativeGestureSegment[15];
                    JoinedHandsSegment1 joinedhandsSegment = new JoinedHandsSegment1();
                    for (int i = 0; i < 15; i++)
                    {
                        // gestureType consists of the same thing 10 times
                        joinedhandsSegments[i] = joinedhandsSegment;
                    }
                    gestureController.AddGesture("JoinedHands", joinedhandsSegments);
                }
                if (gestureList.Contains(GestureType.LeftHandHalfLift))
                {
                    IRelativeGestureSegment[] menuSegments = new IRelativeGestureSegment[15];
                    MenuSegment1 menuSegment = new MenuSegment1();
                    for (int i = 0; i < 15; i++)
                    {
                        // gestureType consists of the same thing 20 times
                        menuSegments[i] = menuSegment;
                    }
                    gestureController.AddGesture("Menu", menuSegments);
                }
                if (gestureList.Contains(GestureType.Pull))
                {
                    IRelativeGestureSegment[] pullLeftSegment = new IRelativeGestureSegment[2];
                    pullLeftSegment[0] = new PullAndPush6();
                    pullLeftSegment[1] = new PullAndPush7();
                    gestureController.AddGesture("PullLeft", pullLeftSegment);

                    IRelativeGestureSegment[] pullSegment = new IRelativeGestureSegment[2];
                    pullSegment[0] = new PullAndPush3();
                    pullSegment[1] = new PullAndPush4();
                    gestureController.AddGesture("Pull", pullSegment);
                }
                if (gestureList.Contains(GestureType.Push))
                {
                    IRelativeGestureSegment[] pushLeftSegment = new IRelativeGestureSegment[2];
                    pushLeftSegment[0] = new PullAndPush8();
                    pushLeftSegment[1] = new PullAndPush6();
                    gestureController.AddGesture("PushLeft", pushLeftSegment);

                    IRelativeGestureSegment[] pushSegment = new IRelativeGestureSegment[2];
                    pushSegment[0] = new PullAndPush5();
                    pushSegment[1] = new PullAndPush3();
                    gestureController.AddGesture("Push", pushSegment);
                }
                if (gestureList.Contains(GestureType.ZoomIn))
                {
                    IRelativeGestureSegment[] zoomInSegments = new IRelativeGestureSegment[3];
                    zoomInSegments[0] = new ZoomSegment1();
                    zoomInSegments[1] = new ZoomSegment2();
                    zoomInSegments[2] = new ZoomSegment3();
                    gestureController.AddGesture("ZoomIn", zoomInSegments);
                }
                if (gestureList.Contains(GestureType.ZoomOut))
                {
                    IRelativeGestureSegment[] zoomOutSegments = new IRelativeGestureSegment[3];
                    zoomOutSegments[0] = new ZoomSegment3();
                    zoomOutSegments[1] = new ZoomSegment2();
                    zoomOutSegments[2] = new ZoomSegment1();
                    gestureController.AddGesture("ZoomOut", zoomOutSegments);
                }
            }

            if (gestureList.Contains(GestureType.SwipLeft)||gestureList.Contains(GestureType.SwipRight))
            {
               activeRecognizer  = new Recognizer();
                if (gestureList.Contains(GestureType.SwipLeft))
                {
                    activeRecognizer.SwipeLeftDetected += (s, e) =>
                    {
                        if (e.Skeleton.TrackingId == NearestId)
                        {
                            GestureDetected(this,GestureType.SwipLeft);
                        }
                    };
                }
                if (gestureList.Contains(GestureType.SwipRight))
                {
                    activeRecognizer.SwipeRightDetected += (s, e) =>
                    {
                        if (e.Skeleton.TrackingId == NearestId)
                        {
                            GestureDetected(this,GestureType.SwipRight);
                        }
                    };
                }
            }
        }
Esempio n. 46
0
        /// <summary>
        /// Create a wired-up recognizer for running the slideshow.
        /// </summary>
        /// <returns>The wired-up recognizer.</returns>
        private Recognizer CreateRecognizer()
        {
            // Instantiate a recognizer.
            var recognizer = new Recognizer();

            // Wire-up swipe right gesture
            recognizer.SwipeRightDetected += (s, e) => {
                if (e.Skeleton.TrackingId == nearestId) {
                    ShowNextPicture(Animation.Right);
                    HighlightSkeleton(e.Skeleton);
                }
            };

            // Wire-up swipe left gesture
            recognizer.SwipeLeftDetected += (s, e) => {
                if (e.Skeleton.TrackingId == nearestId) {
                    ShowNextPicture(Animation.Left);
                    HighlightSkeleton(e.Skeleton);
                }
            };

            return recognizer;
        }
Esempio n. 47
0
        private Recognizer CreateRecognizer()
        {
            // Instantiate a recognizer.
            var recognizer = new Recognizer();

            // Wire-up swipe right to manually advance picture.
            recognizer.SwipeRightDetected += (s, e) =>
            {
                swept = "R";

            };

            // Wire-up swipe left to manually reverse picture.
            recognizer.SwipeLeftDetected += (s, e) =>
            {
                swept = "L";
            };

            return recognizer;
        }
Esempio n. 48
0
        public void onError(Recognizer recognizer, SpeechError error)
        {
            Logger.info(this, "onError()");

            // for debugging purpose: logging the speechkit session id
            Logger.info(this, "session id: [" + _speechKit.getSessionId() + "]");

            if (recognizer != _recognizer)
            {
                return;
            }
            hidePopup();
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                MessageBox.Show(error.getErrorDetail());
            });
            _recognizer.cancel();
            _recognizer = null;
        }
Esempio n. 49
0
        public void onResults(Recognizer recognizer, Recognition results)
        {
            Logger.info(this, "onResults()");

            // for debugging purpose: logging the speechkit session id
            Logger.info(this, "session id: [" + _speechKit.getSessionId() + "]");

            hidePopup();
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                block.Text = results.getResult(0).getText();
            });
            _recognizer.cancel();
            _recognizer = null;
        }
Esempio n. 50
0
 public void onRecordingBegin(Recognizer recognizer)
 {
     Logger.info(this, "onRecordingBegin()");
     showPopup("Listening");
 }
Esempio n. 51
0
        public KinectHelper()
        {
            try
            {
                //Get the callibration data
                CalibrationConfiguration config = RippleDictionary.Dictionary.GetFloorConfigurations(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location));
                frontDistance = config.FrontDistance;
                backDistance = config.BackDistance;
                leftDistance = config.LeftDistance;
                rightDistance = config.RightDistance;


                //Get the floor tile data
                tileCount = FloorWindow.floorData.Tiles.Count;

                tileOriginX = new double[tileCount];
                tileOriginY = new double[tileCount];

                tileWidth = new double[tileCount];
                tileHeight = new double[tileCount];

                floorWidth = new double[tileCount];
                floorHeight = new double[tileCount];

                leftTileBoundary = new double[tileCount];
                topTileBoundary = new double[tileCount];

                rightTileBoundary = new double[tileCount];
                bottomTileBoundary = new double[tileCount];

                for (int i = 0; i < tileCount; i++)
                {
                    // Origin at top left (towards the side of the video)
                    tileOriginX[i] = FloorWindow.floorData.Tiles["Tile" + i].Coordinate.X;
                    tileOriginY[i] = FloorWindow.floorData.Tiles["Tile" + i].Coordinate.Y;

                    tileWidth[i] = FloorWindow.floorData.Tiles["Tile" + i].Style.Width;
                    tileHeight[i] = FloorWindow.floorData.Tiles["Tile" + i].Style.Height;

                    floorWidth[i] = rightDistance - leftDistance;
                    floorHeight[i] = backDistance - frontDistance;

                    leftTileBoundary[i] = leftDistance + tileOriginX[i] * floorWidth[i];
                    topTileBoundary[i] = frontDistance + tileOriginY[i] * floorHeight[i];

                    rightTileBoundary[i] = leftDistance + tileOriginX[i] * floorWidth[i] + tileWidth[i] * floorWidth[i];
                    bottomTileBoundary[i] = frontDistance + tileOriginY[i] * floorHeight[i] + tileHeight[i] * floorHeight[i];
                }


                if (KinectSensor.KinectSensors.Count > 0)
                {
                    KinectSensor.KinectSensors.StatusChanged += KinectSensors_StatusChanged;
                    this.sensor = KinectSensor.KinectSensors.FirstOrDefault(x => x.Status == KinectStatus.Connected);
                    if (this.sensor != null)
                    {
                        Initialize();
                    }
                    else
                    {
                        KinectConnectionState = "Disconnected";
                    }
                }
                else
                {
                    KinectConnectionState = "Disconnected";
                }
                activeRecognizer = CreateRecognizer();
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        /// Create a wired-up recognizer for running the slideshow.
        /// </summary>
        /// <returns>The wired-up recognizer.</returns>
        private Recognizer CreateRecognizer()
        {
            // Instantiate a recognizer.
            var recognizer = new Recognizer();

            // Wire-up swipe right to manually advance picture.
            recognizer.SwipeRightDetected += (s, e) =>
            {
                _slideManager.MoveToNextSlide();
            };

            // Wire-up swipe left to manually reverse picture.
            recognizer.SwipeLeftDetected += (s, e) =>
            {
                _slideManager.MoveToPrevSlide();
            };

            return recognizer;
        }
Esempio n. 53
0
 private void dictationStart(string type)
 {
     Logger.info(this, "dictationStart() type: " + type);
     Thread thread = new Thread(() =>
     {
         _recognizer = _speechKit.createRecognizer(type, RecognizerEndOfSpeechDetection.Long, _oemconfig.defaultLanguage(), this, _handler);
         _recognizer.start();
         showPopup("Please wait");
     });
     thread.Start();
 }
Esempio n. 54
0
        public MainWindow()
        {
            this.PreviousPicture = this.LoadPicture(this.Index - 1);
              this.Picture = this.LoadPicture(this.Index);
              this.NextPicture = this.LoadPicture(this.Index + 1);

              InitializeComponent();

              // Create the gesture recognizer.
              this.activeRecognizer = this.CreateRecognizer();

              // Wire-up window loaded event.
              Loaded += this.OnMainWindowLoaded;
        }
Esempio n. 55
0
        public Slideshow(MainWindow mainWindow)
        {
            this.main = mainWindow;

            // Create the gesture recognizer.
            this.activeRecognizer = this.CreateRecognizer();

            this.timer = this.createTimer(5, TimerTick);

            //main.PreviousPicture = this.LoadPicture(this.Index - 1);
            MainWindow.currentAd = (adChooser.getRandomAd());
            MainWindow.Picture = this.LoadPicture(MainWindow.currentAd);
            MainWindow.rightAd = adChooser.getRandomAd();
            MainWindow.RightPicture = this.LoadPicture(MainWindow.rightAd);
        }
Esempio n. 56
0
 public void onRecordingDone(Recognizer recognizer)
 {
     Logger.info(this, "onRecordingDone()");
     _recognizer.stopRecording();
     showPopup("Processing Dictation");
 }
Esempio n. 57
0
        /// <summary>
        /// Create a wired-up recognizer for running the slideshow.
        /// </summary>
        /// <returns>The wired-up recognizer.</returns>
        private Recognizer CreateRecognizer()
        {
            // Instantiate a recognizer.
            var recognizer = new Recognizer();
            // Wire-up swipe right to manually advance picture.
            recognizer.SwipeRightDetected += (s, e) =>
            {
                KinectSwipeDetected = GestureTypes.RightSwipe;
            };

            // Wire-up swipe left to manually reverse picture.
            recognizer.SwipeLeftDetected += (s, e) =>
            {
                KinectSwipeDetected = GestureTypes.LeftSwipe;
            };

            return recognizer;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="MainWindow" /> class.
        /// </summary>
        public MainWindow()
        {
            this.Index = 0;
            this.PreviousPicture = this.LoadPicture(this.Index - 1);
            this.Picture = this.LoadPicture(this.Index);
            this.NextPicture = this.LoadPicture(this.Index + 1);
            this.backgroundPic = this.LoadBackgroundPicture(this.backIndex);

            InitializeComponent();

            //For displaying a folders images after some seconds
            t = new System.Windows.Threading.DispatcherTimer();
            t2 = new System.Windows.Threading.DispatcherTimer();
            t3 = new System.Windows.Threading.DispatcherTimer();
            t4 = new System.Windows.Threading.DispatcherTimer();
            t5 = new System.Windows.Threading.DispatcherTimer();
            t6 = new System.Windows.Threading.DispatcherTimer();
            t.Tick += new EventHandler(t_Tick);
            t2.Tick += new EventHandler(t2_tick);
            t3.Tick += new EventHandler(t3_tick);
            t4.Tick += new EventHandler(t4_tick);
            t5.Tick += new EventHandler(t5_tick);
            t6.Tick += new EventHandler(t6_tick);

            //Load custom cursor from resource
            newCursor = new Cursor(new System.IO.MemoryStream(PictureViewer.Resource1.bigArrow));
            window.Cursor = newCursor;

            #region Get the names of folders in the Images Direcotry (Future Use)
            /*
            //Getting folder names in a directory
            string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            string final = path + "\\Images";
            foreach (string dir in Directory.GetDirectories(@final, "*"))
            {
                int i = 2;
                string[] directories = dir.Split(System.IO.Path.DirectorySeparatorChar);
                //newBox.Items.Insert(i, directories[directories.Length-1]);
                i++;
            }
             * */
            #endregion

            //Set the height and width of the Display window
            window.Height = SystemParameters.MaximizedPrimaryScreenHeight;
            window.Width = SystemParameters.MaximizedPrimaryScreenWidth;

            //Create a transform group for Scaling and translating
            TransformGroup group = new TransformGroup();
            ScaleTransform xform = new ScaleTransform();
            group.Children.Add(xform);
            TranslateTransform tt = new TranslateTransform();
            group.Children.Add(tt);
            current.RenderTransform = group;

            // Create the gesture recognizer.
            this.activeRecognizer = this.CreateRecognizer();

            // Wire-up window loaded event.
            Loaded += this.OnMainWindowLoaded;

            //Wire-up window unloaded event
            Unloaded += this.OnMainWindowUnLoaded;
        }
Esempio n. 59
0
        /// <summary>
        /// Create a wired-up recognizer for running the slideshow.
        /// </summary>
        /// <returns>The wired-up recognizer.</returns>
        private Recognizer CreateRecognizer()
        {
            // Instantiate a recognizer.
            var recognizer = new Recognizer();

               // Wire-up swipe right to manually advance picture.
            recognizer.SwipeRightDetected += (s, e) =>
              {
                  //System.Diagnostics.Debug.WriteLine("Right swipe detected");

                  if (e.Skeleton.TrackingId == nearestId)
                  {
                      Index++;

                      // Setup corresponding picture if pictures are available.
                      this.NextPicture = p.getNextSlide().getImage();
                      this.PreviousPicture = this.Picture;
                      this.Picture = this.NextPicture;
                      p.moveToNextSlide();
                      GetVideo(p.getCurrentSlide());

                      RefreshRelated();

                      // Notify world of change to Index and Picture.
                      if (this.PropertyChanged != null)
                      {
                          this.PropertyChanged(this, new PropertyChangedEventArgs("PreviousPicture"));
                          this.PropertyChanged(this, new PropertyChangedEventArgs("Picture"));
                          this.PropertyChanged(this, new PropertyChangedEventArgs("NextPicture"));
                      }

                      var storyboard = Resources["LeftAnimate"] as Storyboard;
                      if (storyboard != null)
                      {
                          storyboard.Begin();
                      }

                     // HighlightSkeleton(e.Skeleton);
                  }
              };

              // Wire-up swipe left to manually reverse picture.
              recognizer.SwipeLeftDetected += (s, e) =>
              {

                  //System.Diagnostics.Debug.WriteLine("Left swipe detected");

                  if (e.Skeleton.TrackingId == nearestId)
                  {
                      Index--;

                      // Setup corresponding picture if pictures are available.
                      this.NextPicture = this.Picture;
                      this.Picture = this.PreviousPicture;
                      p.moveToPreviousSlide();
                      this.PreviousPicture = p.getPreviousSlide().getImage();
                      GetVideo(p.getCurrentSlide());

                      RefreshRelated();

                      // Notify world of change to Index and Picture.
                      if (this.PropertyChanged != null)
                      {
                          this.PropertyChanged(this, new PropertyChangedEventArgs("PreviousPicture"));
                          this.PropertyChanged(this, new PropertyChangedEventArgs("Picture"));
                          this.PropertyChanged(this, new PropertyChangedEventArgs("NextPicture"));
                      }

                      var storyboard = Resources["RightAnimate"] as Storyboard;
                      if (storyboard != null)
                      {
                          storyboard.Begin();
                      }

                     // HighlightSkeleton(e.Skeleton);
                  }
              };

                return recognizer;
        }
Esempio n. 60
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MainWindow" /> class.
        /// </summary>
        public MainWindow()
        {
            InitializePresentation();
            picturePaths = CreatePicturePaths();
            videoPlaying = false;
            this.PreviousPicture = p.getPreviousSlide().getImage();
            this.Picture = p.getCurrentSlide().getImage();
            this.NextPicture = p.getNextSlide().getImage();
            this.ParentPicture = null;

            InitializeComponent();

            // Create the gesture recognizer.
            this.activeRecognizer = this.CreateRecognizer();
            recognitionEngine = new GestureRecognitionEngine();
            recognitionEngine.GestureRecognized += new EventHandler<GestureEventArgs>(recognitionEngine_GestureRecognized);

            // Wire-up window loaded event.
            Loaded += this.OnMainWindowLoaded;

            GetVideo(p.getCurrentSlide());
        }