コード例 #1
0
        public void Run(double[] input, int correct, bool testing)
        {
            //Forward
            Layers[0].Calculate(input, NumLayers == 1);
            for (int i = 1; i < Layers.Count; i++)
            {
                Layers[i].Calculate(Layers[i - 1].Values, i == Layers.Count - 1);
            }
            if (!testing)
            {
                //Backprop
                for (int i = NumLayers - 1; i >= 0; i--)
                {
                    bool     isoutput    = i == Layers.Count - 1;
                    iLayer   outputlayer = isoutput ? null : Layers[i + 1];
                    double[] inputvals   = i == 0 ? input : Layers[i - 1].Values;
                    Layers[i].Backprop(inputvals, outputlayer, isoutput, correct);
                }
            }
            //Report values
            Guess = -1; double certainty = -5; double error = 0;
            for (int i = 0; i < 10; i++)
            {
                if (Layers[Layers.Count - 1].Values[i] > certainty)
                {
                    Guess = i; certainty = Layers[Layers.Count - 1].Values[i];
                }
                error += ((i == correct ? 1d : 0d) - Layers[Layers.Count - 1].Values[i]) * ((i == correct ? 1d : 0d) - Layers[Layers.Count - 1].Values[i]);
            }
            error = Math.Sqrt(error);
            TrialNum++;

            PercCorrect = (PercCorrect * ((TrialNum) / (TrialNum + 1))) + ((Guess == correct) ? (1 / (TrialNum)) : 0d);
            Error       = (Error * ((TrialNum) / (TrialNum + 1))) + (error * (1 / (TrialNum)));
        }
コード例 #2
0
        private Dictionary <string, string> GetFieldValues(object sender)
        {
            iLayer layer      = (iLayer)sender;
            var    parameters = new Dictionary <string, string>(layer.ActionParameters);

            foreach (Fieldset fieldset in layer.Items.OfType <Fieldset>())
            {
                System.Console.WriteLine(fieldset.Header);

                foreach (Field field in fieldset.Fields)
                {
                    System.Console.WriteLine(field.Label);

                    if (field is SelectListField)
                    {
                        SelectListField listField = (SelectListField)field;
                        for (int i = 0; i < listField.Items.Count; i++)
                        {
                            System.Console.WriteLine((i + 1) + ".  " + listField.Items[i].Value);
                        }
                        var item = listField.Items[Convert.ToInt32(System.Console.ReadLine()) - 1];
                        parameters[listField.ID + ".Key"] = item.Key;
                        parameters[listField.ID]          = item.Value;
                    }
                    else
                    {
                        parameters[field.ID] = System.Console.ReadLine();
                    }
                }
            }

            return(parameters);
        }
コード例 #3
0
 public void PopToLayer(iLayer layer)
 {
     if (layer != null)
     {
         PopToView(layer.View);
     }
 }
コード例 #4
0
ファイル: WpfFactory.cs プロジェクト: chencai01/iFactr-WPF
        /// <summary>
        /// Outputs a layer to the WPF target.
        /// </summary>
        /// <param name="layer">The layer.</param>
        protected override bool OnOutputLayer(iLayer layer)
        {
            if (!_windowInited)
            {
                InitializeWindow();
            }

            if (layer == null)
            {
                return(false);
            }

            if (layer is LoginLayer)
            {
                new LoginControl(layer as LoginLayer).Show();
                return(true);
            }

            if (layer is Browser)
            {
                var uri = ((Browser)layer).Url;
                MainWindow.IsEnabled = true;
                IsBusy = false;
                const string imageScheme          = "image://";
                const string audioPlaybackScheme  = "audio://";
                const string videoPlaybackScheme  = "video://";
                const string voiceScheme          = "voicerecording://";
                const string videoRecordingScheme = "videorecording://";

                if (uri.StartsWith(imageScheme))
                {
                    new ImagePicker(layer.NavContext, HttpUtility.ParseQueryString(uri.Substring(imageScheme.Length)));
                    return(true);
                }
                else if (uri.StartsWith(audioPlaybackScheme))
                {
                    //AudioPlaybackExtensions.Launch(url);
                }
                else if (uri.StartsWith(voiceScheme))
                {
                    //AudioRecordingExtensions.Launch(url);
                }
                else if (uri.StartsWith(videoPlaybackScheme))
                {
                    //VideoPlaybackExtensions.Launch(url);
                }
                else if (uri.StartsWith(videoRecordingScheme))
                {
                    //VideoRecordingExtensions.Launch(url);
                }
                else if (uri.StartsWith("tel"))
                {
                    BrowserView.Launch(uri);
                    return(true);
                }
            }
            return(base.OnOutputLayer(layer));
        }
コード例 #5
0
        public void PopToLayer(iLayer layer)
        {
            var view = _views.FirstOrDefault(v => v.GetModel().Equals(layer));

            if (view != null)
            {
                PopToView(view);
            }
        }
コード例 #6
0
ファイル: DroidFactory.cs プロジェクト: Zebra/iFactr-Android
        /// <summary>
        /// Called when an <see cref="iLayer" /> instance is ready to be outputted.  Override this method in a subclass
        /// in order to handle layer types that cannot be handled by the available abstract objects.
        /// </summary>
        /// <param name="layer">The layer to be outputted.</param>
        /// <returns>
        ///   <c>true</c> if layer output was handled and the factory should not attempt to output it as a controller; otherwise <c>false</c>.
        /// </returns>
        protected override bool OnOutputLayer(iLayer layer)
        {
            var browser = layer as Core.Layers.Browser;

            if (browser == null || browser.Url.StartsWith("http") || browser.Url.StartsWith("data"))
            {
                return(false);
            }
            return(base.OnOutputLayer(layer) || HandleUrl(new Link(browser.Url), true, null));
        }
コード例 #7
0
ファイル: WpfFactory.cs プロジェクト: chencai01/iFactr-WPF
        protected override object OnGetCustomItem(ICustomItem item, iLayer layer, IListView view, object recycledCell)
        {
            var cell = GetNativeObject <FrameworkElement>(Converter.ConvertToCell(item, layer.LayerStyle, view, null), "item", true);

            if (CustomItemRequested != null)
            {
                return(CustomItemRequested(item, layer));
            }
            return(cell);
        }
コード例 #8
0
ファイル: DroidFactory.cs プロジェクト: Zebra/iFactr-Android
        protected override object OnGetCustomItem(ICustomItem item, iLayer layer, IListView view, object recycledCell)
        {
            if (CustomItemRequested == null)
            {
                return(base.OnGetCustomItem(item, layer, view, recycledCell));
            }
            var custom = recycledCell as CustomItemContainer;

            return(CustomItemRequested(item, custom?.CustomItem as View, layer));
        }
コード例 #9
0
 public void Clear(iLayer layer)
 {
     if (layer == null)
     {
         PopToRoot();
     }
     else
     {
         PopToLayer(layer);
     }
 }
コード例 #10
0
        protected override object OnGetCustomItem(ICustomItem item, iLayer layer, IListView view, object recycledCell)
        {
            var controller = GetNativeObject <UIViewController>(view, "view") as UITableViewController;
            var cell       = GetNativeObject <UITableViewCell>(Converter.ConvertToCell(item, layer.LayerStyle, view, null), "item");

            if (CustomItemRequested != null)
            {
                return(CustomItemRequested(item, cell, controller == null ? null : controller.TableView));
            }

            return(cell);
        }
コード例 #11
0
        protected override object OnGetCustomItem(ICustomItem item, iLayer layer, IListView view, object recycledCell)
        {
            var ci = GetCustomItem;

            if (ci != null)
            {
                return(ci(item, layer, view, recycledCell as Control));
            }
#pragma warning disable 618
            var cir = CustomItemRequested;
            return(cir == null ? null : cir(item, layer.LayerStyle));

#pragma warning restore 618
        }
コード例 #12
0
ファイル: TargetFactory.cs プロジェクト: Zebra/iFactr-Android
        /// <summary>
        /// Renders the specified <see cref="iLayer"/> instance on the screen.
        /// </summary>
        /// <param name="layer">A <see cref="iLayer"/> representing the Layer value.</param>
        /// <param name="navigatedUri">A <see cref="String"/> that represents the uri used to navigate to the layer.</param>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="layer"/> is <c>null</c>.</exception>
        public void OutputLayer(iLayer layer, string navigatedUri)
        {
            if (layer == null)
            {
                throw new ArgumentNullException("layer");
            }

            Thread.ExecuteOnMainThread(() =>
            {
                if (!OnOutputLayer(layer))
                {
                    OutputController(layer, layer.Name, navigatedUri);
                }
                else
                {
                    StopBlockingUserInput();
                }
            });
        }
コード例 #13
0
        /// <summary>
        /// Generates an <see cref="IMXView"/> instance that visually and functionally replicates the layer.
        /// </summary>
        /// <param name="layer">The layer from which the view will be generated.</param>
        /// <returns>The view that was generated.</returns>
        public static IMXView GetView(this iLayer layer)
        {
            if (layer is NavigationTabs)
            {
                return(GetTabView((NavigationTabs)layer));
            }

            if (layer is Browser)
            {
                return(GetBrowserView((Browser)layer));
            }

            if (layer is LoginLayer)
            {
                return(GetLoginView((LoginLayer)layer));
            }

            return(GetListView(layer));
        }
コード例 #14
0
        protected override bool OnOutputLayer(iLayer layer)
        {
            var browser = layer as Browser;

            if (browser != null)
            {
                string url = browser.Url;
                if (url.StartsWith("image") ||
                    url.StartsWith("geoloc") ||
                    url.StartsWith("compass") ||
                    url.StartsWith("accel") ||
                    url.StartsWith("video") ||
                    url.StartsWith("audio") ||
                    url.StartsWith("voice"))
                {
                    //TODO: Launch integration
                    return(true);
                }
            }
            return(false);
        }
コード例 #15
0
        protected override bool OnOutputLayer(iLayer layer)
        {
            if (layer is LoginLayer)
            {
                ((LoginLayer)layer).Display();
                return(true);
            }

            if (layer is CameraScanLayer)
            {
                CameraScannerView.Scan(layer as CameraScanLayer);
                return(true);
            }

            if (layer is ScanLayer)
            {
                ScannerView.Scan((ScanLayer)layer);
                return(true);
            }

            return(HandleIntegration(layer as Browser) || base.OnOutputLayer(layer));
        }
コード例 #16
0
ファイル: iApp.cs プロジェクト: Zebra/iFactr-Android
        internal void LayerLoadCompleted(iLayer layer)
        {
            bool output = true;

            if (Device.Reflector.GetMethod(GetType(), "OnLayerLoading", typeof(iLayer)).DeclaringType != typeof(iApp))
            {
                output = false;
                OnLayerLoading(layer);
            }

            var handler = OnLayerLoadComplete;

            if (handler != null)
            {
                output = false;
                handler(layer);
            }

            if (output)
            {
                Factory.OutputLayer(layer);
            }
        }
コード例 #17
0
        /// <summary>
        /// Outputs a layer to the console platform.
        /// </summary>
        /// <param name="layer">The layer.</param>
        protected override bool OnOutputLayer(iLayer layer)
        {
            layer.NavContext.NavigatedUrl = LastAddress ?? string.Empty;
            page       = 0;
            searchTerm = string.Empty;

            if (navHistory.Contains(layer))
            {
                navHistory.Pop().Unload();
                while (navHistory.Count > 1 && navHistory.Peek() != layer)
                {
                    navHistory.Pop();
                }
            }
            else
            {
                navHistory.Push(layer);
            }

            DisplayLayer(layer);

            return(true);
        }
コード例 #18
0
ファイル: PoolingLayer.cs プロジェクト: qdm097/MNIST-CNN
 public void Backprop(double[] input, iLayer outputlayer, bool uselessbool, int uselessint)
 {
     //Calc errors
     if (outputlayer is FullyConnectedLayer)
     {
         var FCLOutput = outputlayer as FullyConnectedLayer;
         Errors = new double[Length];
         for (int k = 0; k < FCLOutput.Length; k++)
         {
             for (int j = 0; j < Length; j++)
             {
                 Errors[j] += FCLOutput.Weights[k, j] * Maths.TanhDerriv(outputlayer.ZVals[k]) * FCLOutput.Errors[k];
             }
         }
     }
     if (outputlayer is ConvolutionLayer)
     {
         var CLOutput = outputlayer as ConvolutionLayer;
         Errors = Maths.Convert(CLOutput.FullConvolve(CLOutput.Weights, Maths.Convert(CLOutput.Errors)));
     }
     if (outputlayer is PoolingLayer)
     {
         var PLOutput = outputlayer as PoolingLayer;
         int iterator = 0;
         Errors = new double[Length];
         for (int i = 0; i < Length; i++)
         {
             if (PLOutput.Mask[i] == 0)
             {
                 continue;
             }
             Errors[i] = PLOutput.Errors[iterator];
             iterator++;
         }
     }
     //There are no gradient with respect to a pooling layer
 }
コード例 #19
0
        protected void OutputForm(iLayer layer, Fieldset fieldset)
        {
            System.Console.WriteLine();

            Link link = layer.ActionButtons.FirstOrDefault(b => b.Action == iFactr.Core.Controls.Button.ActionType.Submit);

            if (link == null)
            {
                return;
            }
            link = (Link)link.Clone();

            layer.FieldValuesRequested -= GetFieldValues;
            layer.FieldValuesRequested += GetFieldValues;

            var parameters = layer.GetFieldValues();

            if (link.Parameters == null)
            {
                link.Parameters = parameters;
            }
            else
            {
                foreach (var key in parameters.Keys)
                {
                    link.Parameters[key] = parameters[key];
                }
            }

            if (link.RequestType == RequestType.ClearPaneHistory)
            {
                ClearHistory();
            }

            iApp.Navigate(link);
        }
コード例 #20
0
ファイル: TargetFactory.cs プロジェクト: Zebra/iFactr-Android
 public void LoadLayer(iLayer navLayer, Dictionary <String, String> parameters)
 {
     LoadLayer(null, navLayer, null, parameters);
 }
コード例 #21
0
ファイル: iApp.cs プロジェクト: Zebra/iFactr-Android
 /// <summary>
 /// Called when an application layer begins loading.  This method is meant to be overridden in consuming applications
 /// for notification when a layer is loaded as an alternative to using events.
 /// </summary>
 /// <param name="layer">An <see cref="iLayer"/> representing the layer being loaded.</param>
 public virtual void OnLayerLoading(iLayer layer)
 {
 }
コード例 #22
0
        private void DisplayLayer(iLayer layer)
        {
            LastAddress = layer.NavContext.NavigatedUrl;
            ResetNavigationKeys();

            System.Console.Title = TheApp.Title;
            System.Console.Clear();

            if (!string.IsNullOrEmpty(layer.Title))
            {
                System.Console.WriteLine(layer.Title);
            }

            if (layer is NavigationTabs)
            {
                OutputTabs((NavigationTabs)layer);
            }
            else
            {
                foreach (var item in layer.Items)
                {
                    if (item is iBlock)
                    {
                        OutputBlock((iBlock)item);
                    }
                    else if (item is iPanel)
                    {
                        OutputPanel((iPanel)item);
                    }
                    else if (item is iList)
                    {
                        OutputList((iList)item);
                    }
                    else if (item is iMenu)
                    {
                        OutputMenu((iMenu)item);
                    }
                    else if (item is Fieldset)
                    {
                        OutputForm(layer, (Fieldset)item);
                    }
                }
                OutputActions(layer.ActionButtons);
            }

            if (layer.BackButton != null && layer.BackButton.Action != iFactr.Core.Controls.Button.ActionType.None)
            {
                layer.BackButton.Address = TheApp.NavigateOnLoad;
            }

            System.Console.WriteLine();
            System.Console.WriteLine("0. {0} ...", GetResourceString("Back") ?? "Back");
            System.Console.WriteLine();

            string input  = System.Console.ReadLine();
            Link   action = new Link(TheApp.NavigateOnLoad);

            try
            {
                int key = Convert.ToInt16(input);

                if (key == 0 && navHistory.Count > 1)
                {
                    navHistory.Pop().Unload();
                    var nextLayer = navHistory.Peek();
                    DisplayLayer(nextLayer);
                }
                action = navigationKeys[key];
            }
            catch
            {
                action = new Link(input == string.Empty ? TheApp.NavigateOnLoad : input);
            }

            if (action.Address != null && action.Address.StartsWith("##"))
            {
                if (action.Address == "##PREV##")
                {
                    page--;
                }
                else if (action.Address == "##NEXT##")
                {
                    page++;
                }
                else if (action.Address == "##SEARCH##")
                {
                    System.Console.Write("{0}: ", GetResourceString("SearchHint") ?? "Search");
                    input      = System.Console.ReadLine();
                    searchTerm = input;
                    page       = 0;
                }
                else if (action.Address == "##CLEAR##")
                {
                    searchTerm = string.Empty;
                    page       = 0;
                }
                DisplayLayer(layer);
                return;
            }

            if (!string.IsNullOrEmpty(action.ConfirmationText))
            {
                System.Console.Write(action.ConfirmationText + " (y/N) ");
                string confirm = System.Console.ReadLine();
                if (confirm.ToLower().Trim()[0] != 'y')
                {
                    DisplayLayer(layer);
                    return;
                }
            }

            System.Console.WriteLine();
            LastAddress = action.Address;

            if (action.RequestType == RequestType.ClearPaneHistory)
            {
                ClearHistory();
            }

            iApp.Navigate(action);
        }
コード例 #23
0
        private static IListView GetListView(iLayer layer)
        {
            var view = new ListView <iLayer>(layer, layer.Layout == LayerLayout.Rounded ? ListViewStyle.Grouped : ListViewStyle.Default);

            var popover = layer as IPopoverLayer;

            view.PopoverPresentationStyle = popover != null && popover.IsFullscreen ||
                                            layer.PopoverPresentationStyle == PopoverPresentationStyle.FullScreen ?
                                            PopoverPresentationStyle.FullScreen : PopoverPresentationStyle.Normal;

            view.Activated   += ViewActivated;
            view.Deactivated += ViewDeactivated;

            view.Rendering += (o, e) =>
            {
                layer = view.GetModel() as iLayer;
                if (layer == null)
                {
                    return;
                }
                layer.FieldValuesRequested -= GetFieldValues;
                layer.FieldValuesRequested += GetFieldValues;

                view.StackID        = layer.Name ?? layer.GetType().FullName;
                view.Title          = layer.Title;
                view.TitleColor     = layer.LayerStyle.HeaderTextColor;
                view.HeaderColor    = layer.LayerStyle.HeaderColor;
                view.SeparatorColor = layer.LayerStyle.SeparatorColor;
                view.BackLink       = layer.BackButton;
                view.OutputPane     = layer.NavContext.OutputOnPane;
                ((IHistoryEntry)view).ShouldNavigate = layer.ShouldNavigateFrom;
                view.ColumnMode = (ColumnMode)layer.CompositeLayerLayout;

                if (layer.LayerStyle.LayerBackgroundImage != null)
                {
                    view.SetBackground(layer.LayerStyle.LayerBackgroundImage, ContentStretch.Fill);
                }
                else
                {
                    view.SetBackground(layer.LayerStyle.LayerBackgroundColor);
                }

                var searchList = layer.Items.OfType <SearchList>().FirstOrDefault();
                if (searchList != null)
                {
                    var searchBox = new SearchBox();
                    searchBox.SearchPerformed += (sender, args) =>
                    {
                        if (layer == null)
                        {
                            return;
                        }
                        for (int i = 0; i < layer.Items.Count; i++)
                        {
                            var list = layer.Items[i] as SearchList;
                            if (list == null)
                            {
                                continue;
                            }
                            list.PerformSearch(layer.NavContext.NavigatedUrl, args.SearchText);
                            view.Sections[i].ItemCount = list.Count;
                        }
                        view.ReloadSections();
                    };

                    searchBox.BorderColor = layer.LayerStyle.SectionHeaderColor;
                    searchBox.Placeholder = iApp.Factory.GetResourceString("SearchHint");
                    searchBox.Text        = searchList.SearchText;

                    view.SearchBox = searchBox;
                    if (searchList.AutoFocus)
                    {
                        searchBox.Focus();
                    }
                }

                if (layer.ActionButtons != null && layer.ActionButtons.Count > 0)
                {
                    var menu = new Menu();
                    if (menu != null)
                    {
                        menu.BackgroundColor = layer.LayerStyle.HeaderColor;
                        menu.ForegroundColor = layer.LayerStyle.HeaderTextColor;

                        foreach (var button in layer.ActionButtons)
                        {
                            var item = new MenuButton(button.Text);
                            if (item == null)
                            {
                                continue;
                            }
                            item.NavigationLink = button;
                            item.ImagePath      = button.Image == null ? null : button.Image.Location;

                            menu.Add(item);
                        }

                        view.Menu = menu;
                    }
                }
                else
                {
                    view.Menu = null;
                }

                int sectionIndex = 0;
                view.Sections.Clear();
                for (int i = 0; i < layer.Items.Count; i++)
                {
                    var item      = layer.Items[i];
                    var aggregate = iApp.Factory.Target == MobileTarget.Windows ? item as AggregateFieldset : null;
                    if (aggregate != null && aggregate.AggregateHeader == null && i > 0 && layer.Items[i - 1] is AggregateFieldset)
                    {
                        aggregate.SectionIndex = -1;
                        continue;
                    }

                    item.SectionIndex = sectionIndex++;
                    var section = new Section {
                        ItemCount = (item is IList && aggregate == null) ? ((IList)item).Count : 1,
                    };

                    if (aggregate != null && aggregate.AggregateHeader == null)
                    {
                        section.Header = null;
                    }
                    else if (item.Header == null)
                    {
                        section.Header = null;
                    }
                    else
                    {
                        if (section.Header == null)
                        {
                            section.Header = new SectionHeader();
                        }
                        section.Header.BackgroundColor = layer.LayerStyle.SectionHeaderColor;
                        section.Header.ForegroundColor = layer.LayerStyle.SectionHeaderTextColor;
                        section.Header.Text            = aggregate == null ? item.Header : aggregate.AggregateHeader;
                    }

                    if (item.Footer == null)
                    {
                        section.Footer = null;
                    }
                    else
                    {
                        if (section.Footer == null)
                        {
                            section.Footer = new SectionFooter();
                        }
                        section.Footer.BackgroundColor = layer.LayerStyle.SectionHeaderColor;
                        section.Footer.ForegroundColor = layer.LayerStyle.SectionHeaderTextColor;
                        section.Footer.Text            = item.Footer;
                    }

                    view.Sections.Add(section);
                }

                if (layer.FocusedItem != null)
                {
                    for (int i = 0; i < layer.Items.Count; i++)
                    {
                        var item = layer.Items[i];
                        if (item == layer.FocusedItem)
                        {
                            view.ScrollToCell(i, 0, false);
                            break;
                        }

                        var list = item as IList;
                        if (list != null)
                        {
                            int index = list.IndexOf(layer.FocusedItem);
                            if (index >= 0)
                            {
                                view.Metadata["NextField"] = list[index];
                                view.ScrollToCell(i, index, false);
                            }
                        }
                    }
                }
            };

            view.Submitting += (o, e) =>
            {
                e.Cancel = true;

                layer = view.GetModel() as iLayer;
                if (layer == null)
                {
                    return;
                }
                var values = layer.GetFieldValues();
                layer.Validate(values);

                if (layer.IsValid)
                {
                    foreach (var key in values.Keys)
                    {
                        e.DestinationLink.Parameters[key] = values[key];
                    }
                    iApp.Navigate(e.DestinationLink, view);
                }
                else
                {
                    view.Render();
                    new Alert(iApp.Factory.GetResourceString("ValidationFailure"), string.Empty, AlertButtons.OK).Show();
                }
            };

            ((IListView)view).ItemIdRequested = (section, index) =>
            {
                layer = view.Model;
                if (layer == null)
                {
                    return(0);
                }

                var item = iApp.Factory.Target == MobileTarget.Windows ?
                           layer.Items.SingleOrDefault(i => i.SectionIndex == section) : layer.Items.ElementAtOrDefault(section);

                if (item == null)
                {
                    return(0);
                }

                if (iApp.Factory.Target == MobileTarget.Windows && item is AggregateFieldset)
                {
                    return(item.SectionIndex);
                }

                var list = item as IList;
                if (list == null)
                {
                    return(item.GetType().Name.GetHashCode());
                }

                var obj       = list[index];
                var textField = obj as TextField;
                var hashCode  = (textField != null && textField.IsPassword) ? "PasswordField".GetHashCode() : obj.GetType().Name.GetHashCode();
                if (Device.Platform == MobilePlatform.Android && (obj is TextField || obj is SelectListField))
                {
                    hashCode = (hashCode + 1) * 31 + section.GetHashCode();
                    hashCode = hashCode * 31 + index.GetHashCode();
                }
                return(hashCode);
            };

            ((IListView)view).CellRequested = (section, index, recycledCell) =>
            {
                layer = view.Model;
                if (layer != null)
                {
                    var item = layer.Items.ElementAtOrDefault(section);

                    #region Aggregate Fieldsets
                    if (iApp.Factory.Target == MobileTarget.Windows)
                    {
                        AggregateFieldset aggregate = null;

                        try
                        {
                            item = layer.Items.SingleOrDefault(i => i.SectionIndex == section);
                        }
                        catch
                        {
                            int sectionIndex = 0;
                            for (int i = 0; i < layer.Items.Count; i++)
                            {
                                var li = layer.Items[i];
                                aggregate = li as AggregateFieldset;
                                if (aggregate != null && aggregate.AggregateHeader == null && i > 0 && layer.Items[i - 1] is AggregateFieldset)
                                {
                                    aggregate.SectionIndex = -1;
                                    continue;
                                }

                                li.SectionIndex = sectionIndex++;
                                if (li.SectionIndex == section)
                                {
                                    item = li;
                                }
                            }
                        }

                        aggregate = item as AggregateFieldset;
                        if (aggregate != null)
                        {
                            index = layer.Items.IndexOf(aggregate);
                            int count = 1;
                            for (int i = index + 1; i < layer.Items.Count; i++)
                            {
                                var fieldset = layer.Items[i] as AggregateFieldset;
                                if (fieldset == null || fieldset.AggregateHeader != null)
                                {
                                    break;
                                }
                                count++;
                            }

                            return(iApp.Factory.Converter.ConvertToCell(layer.Items.GetRange(index, count).Cast <AggregateFieldset>(), layer.LayerStyle, view, recycledCell));
                        }
                    }
                    #endregion

                    var list = item as IList;

                    object cell = null;
                    if (list == null)
                    {
                        cell = item;
                    }
                    else if (index >= 0 && index < list.Count)
                    {
                        cell = list[index];
                    }

                    if (cell is ICustomItem)
                    {
                        return(new CustomItemContainer(iApp.Factory.OnGetCustomItem((ICustomItem)cell, layer, view, recycledCell)));
                    }

                    return(cell == null ? null : iApp.Factory.Converter.ConvertToCell(cell, layer.LayerStyle, view, recycledCell));
                }

                return(null);
            };

            return(view);
        }
コード例 #24
0
ファイル: TargetFactory.cs プロジェクト: Zebra/iFactr-Android
 /// <summary>
 /// Called when an <see cref="ICustomItem"/> instance is ready to be rendered and a native object is needed for insertion into the view.
 /// </summary>
 /// <param name="item">The item that is ready to be rendered.</param>
 /// <param name="layer">The layer instance associated with the item, or <c>null</c> if the item is not associated with a layer.</param>
 /// <param name="view">The view that will contain the item.</param>
 /// <param name="recycledCell">An already instantiated cell that is ready for reuse, or <c>null</c> if no cell has been recycled.</param>
 /// <returns>The object that will be inserted into the view.</returns>
 protected internal virtual object OnGetCustomItem(ICustomItem item, iLayer layer, IListView view, object recycledCell)
 {
     return(Converter.ConvertToCell(item, layer.LayerStyle, view, recycledCell as ICell));
 }
コード例 #25
0
ファイル: TargetFactory.cs プロジェクト: Zebra/iFactr-Android
        /// <summary>
        /// Called when an <see cref="iLayer"/> instance is ready to be outputted.  Override this method in a subclass
        /// in order to handle layer types that cannot be handled by the available abstract objects.
        /// </summary>
        /// <param name="layer">The layer to be outputted.</param>
        /// <returns><c>true</c> if layer output was handled and the factory should not attempt to output it as a controller; otherwise <c>false</c>.</returns>
        protected virtual bool OnOutputLayer(iLayer layer)
        {
            var browser = layer as Browser;

            if (browser != null && browser.Url != null)
            {
                int index = browser.Url.IndexOf(':');
                if (index < 0)
                {
                    return(false);
                }

                switch (browser.Url.Substring(0, index))
                {
                case "accel":
                    var    parameters = HttpUtility.ParseQueryString(browser.Url.Substring(browser.Url.IndexOf('?')));
                    string callback   = parameters == null ? null : parameters.GetValueOrDefault("callback");
                    if (callback == null)
                    {
                        throw new ArgumentException("Accelerometer requires a callback URI.");
                    }

                    var accel = new Accelerometer();
                    accel.ValuesUpdated += (o, e) =>
                    {
                        lock (accel)
                        {
                            if (accel.IsActive)
                            {
                                accel.Stop();
                                iApp.Navigate(callback, new Dictionary <string, string>()
                                {
                                    { "X", e.Data.X.ToString() },
                                    { "Y", e.Data.Y.ToString() },
                                    { "Z", e.Data.Z.ToString() },
                                });
                            }
                        }
                    };

                    accel.Start();
                    return(true);

                case "compass":
                    parameters = HttpUtility.ParseQueryString(browser.Url.Substring(browser.Url.IndexOf('?')));
                    callback   = parameters == null ? null : parameters.GetValueOrDefault("callback");
                    if (callback == null)
                    {
                        throw new ArgumentException("Compass requires a callback URI.");
                    }

                    var compass = new Compass();
                    compass.HeadingUpdated += (o, e) =>
                    {
                        lock (compass)
                        {
                            if (compass.IsActive)
                            {
                                compass.Stop();
                                iApp.Navigate(callback, new Dictionary <string, string>()
                                {
                                    { "Bearing", e.Data.TrueHeading.ToString() },
                                });
                            }
                        }
                    };

                    compass.Start();
                    return(true);

                case "geoloc":
                    parameters = HttpUtility.ParseQueryString(browser.Url.Substring(browser.Url.IndexOf('?')));
                    callback   = parameters == null ? null : parameters.GetValueOrDefault("callback");
                    if (callback == null)
                    {
                        throw new ArgumentException("Geolocation requires a callback URI.");
                    }

                    var geoloc = new GeoLocation();
                    geoloc.LocationUpdated += (o, e) =>
                    {
                        lock (geoloc)
                        {
                            if (geoloc.IsActive)
                            {
                                geoloc.Stop();
                                iApp.Navigate(callback, new Dictionary <string, string>()
                                {
                                    { "Lat", e.Data.Latitude.ToString() },
                                    { "Lon", e.Data.Longitude.ToString() }
                                });
                            }
                        }
                    };

                    geoloc.Start();
                    return(true);
                }
            }
            return(false);
        }
コード例 #26
0
ファイル: TargetFactory.cs プロジェクト: Zebra/iFactr-Android
 /// <summary>
 /// Renders the specified <see cref="iLayer"/> instance on the screen.
 /// </summary>
 /// <param name="layer">A <see cref="iLayer"/> representing the Layer value.</param>
 /// <exception cref="ArgumentNullException">Thrown when the <paramref name="layer"/> is <c>null</c>.</exception>
 public void OutputLayer(iLayer layer)
 {
     OutputLayer(layer, LastNavigationUrl);
 }
コード例 #27
0
 /// <summary>
 /// Backpropegation of error and calcluation of gradients
 /// </summary>
 /// <param name="input">Previous layer's values</param>
 /// <param name="isoutput">Whether the layer is the output layer</param>
 public void Backprop(double[] input, iLayer outputlayer, bool isoutput, int correct)
 {
     //Calculate error
     if (isoutput)
     {
         Errors = new double[Length];
         for (int i = 0; i < Length; i++)
         {
             Errors[i] = 2d * (Values[i] - (i == correct ? 1d : 0d));
         }
     }
     else
     {
         if (outputlayer is FullyConnectedLayer)
         {
             var FCLOutput = outputlayer as FullyConnectedLayer;
             Errors = new double[Length];
             for (int k = 0; k < FCLOutput.Length; k++)
             {
                 for (int j = 0; j < Length; j++)
                 {
                     Errors[j] += FCLOutput.Weights[k, j] * Maths.TanhDerriv(outputlayer.ZVals[k]) * FCLOutput.Errors[k];
                 }
             }
         }
         if (outputlayer is ConvolutionLayer)
         {
             var CLOutput = outputlayer as ConvolutionLayer;
             Errors = Maths.Convert(CLOutput.FullConvolve(CLOutput.Weights, Maths.Convert(CLOutput.Errors)));
         }
         if (outputlayer is PoolingLayer)
         {
             var PLOutput = outputlayer as PoolingLayer;
             int iterator = 0;
             Errors = new double[Length];
             for (int i = 0; i < Length; i++)
             {
                 if (PLOutput.Mask[i] == 0)
                 {
                     continue;
                 }
                 Errors[i] = PLOutput.Errors[iterator];
                 iterator++;
             }
         }
     }
     //Calculate gradients
     for (int i = 0; i < Length; i++)
     {
         for (int ii = 0; ii < InputLength; ii++)
         {
             //Weight gradients
             WeightGradient[i, ii] = -1 * input[ii] * Maths.TanhDerriv(ZVals[i]) * Errors[i];
             if (NN.UseMomentum)
             {
                 if (NN.UseNesterov)
                 {
                     //Nesterov momentum formula
                     WeightGradient[i, ii] = ((1 + NN.Momentum) * (NN.LearningRate * WeightGradient[i, ii]))
                                             + (NN.Momentum * NN.Momentum * WMomentum[i, ii]);
                 }
                 else
                 {
                     //Standard momentum formula
                     WeightGradient[i, ii] = (WMomentum[i, ii] * NN.Momentum) + (NN.LearningRate * WeightGradient[i, ii]);
                 }
                 //Momentum is the previous iteration's gradient
                 WMomentum[i, ii] = WeightGradient[i, ii];
             }
         }
         if (isoutput)
         {
             continue;
         }
         //Bias gradients
         BiasGradient[i] = -1 * Maths.TanhDerriv(ZVals[i]) * Errors[i];
         if (NN.UseMomentum)
         {
             if (NN.UseNesterov)
             {
                 BiasGradient[i] = ((1 + NN.Momentum) * (NN.LearningRate * BiasGradient[i]))
                                   + (NN.Momentum * NN.Momentum * BMomentum[i]);
             }
             else
             {
                 BiasGradient[i] = (BMomentum[i] * NN.Momentum) + (NN.LearningRate * BiasGradient[i]);
             }
             //Momentum is the previous iteration's gradient
             BMomentum[i] = BiasGradient[i];
         }
     }
 }
コード例 #28
0
        public void PopToLayer(iLayer layer)
        {
            var display = ViewControllers.OfType <IMXView>().First(vc => layer.Equals(vc.GetModel()));

            PopToViewController(display as UIViewController, true);
        }
コード例 #29
0
 public virtual void Clear(iLayer layer)
 {
     PopToRoot();
 }
コード例 #30
0
ファイル: TargetFactory.cs プロジェクト: Zebra/iFactr-Android
 /// <summary>
 /// Loads the specified layer with the specified parameters.
 /// </summary>
 /// <param name="fromView">The <see cref="IMXView"/> instance from which the navigation was initiated.</param>
 /// <param name="navLayer">The <see cref="iLayer"/> instance to load.</param>
 /// <param name="navigatedUri">A <see cref="String"/> that represents the uri used to navigate to the layer.</param>
 /// <param name="parameters">A <see cref="Dictionary&lt;TKey, TValue&gt;"/> representing the parameters to pass to the layer's Load method.</param>
 internal virtual void LoadLayer(IMXView fromView, iLayer navLayer, string navigatedUri, Dictionary <String, String> parameters)
 {
     TryLoadController(this, fromView, navLayer, navigatedUri, parameters);
 }