/// <summary>
        /// Splits slash-separated strings into a submenu tree
        /// </summary>
        /// <param name="menu"></param>
        /// <param name="items"></param>
        private void AddMenuItems(ItemsControl menu, Tuple<KeyValuePair<int, string>, string[]>[] items)
        {
            foreach (var group in items.Where(x => x.Item2.Length > 1).GroupBy(x => x.Item2.First()))
            {
                var menuItem = new MenuItem { Command = null, CommandParameter = null, Header = group.Key };
                menu.Items.Add(menuItem);
                var subItems = group.Select(x => Tuple.Create(x.Item1, x.Item2.Skip(1).ToArray())).ToArray();
                AddMenuItems(menuItem, subItems);
            }

            foreach (var item in items.Where(x => x.Item2.Length == 1))
            {
                menu.Items.Add(new MenuItem { Command = SelectOptionCommand, CommandParameter = item.Item1, Header = item.Item2.Last() });
            }
        }
Example #2
0
        public PocoData(Type pocoType, string tableName, string keyspaceName, LookupKeyedCollection<string, PocoColumn> columns,
                        string[] partitionkeys, Tuple<string, SortOrder>[] clusteringKeys, bool caseSensitive, bool compact, bool allowFiltering)
        {
            if (pocoType == null) throw new ArgumentNullException("pocoType");
            if (tableName == null) throw new ArgumentNullException("tableName");
            if (columns == null) throw new ArgumentNullException("columns");
            if (partitionkeys == null) throw new ArgumentNullException("partitionkeys");
            if (clusteringKeys == null) throw new ArgumentNullException("clusteringKeys");
            PocoType = pocoType;
            TableName = tableName;
            Columns = columns;
            CaseSensitive = caseSensitive;
            CompactStorage = compact;
            AllowFiltering = allowFiltering;
            KeyspaceName = keyspaceName;
            _columnsByMemberName = columns.ToDictionary(c => c.MemberInfo.Name, c => c);
            PartitionKeys = partitionkeys.Where(columns.Contains).Select(key => columns[key]).ToList();
            ClusteringKeys = clusteringKeys.Where(c => columns.Contains(c.Item1)).Select(c => Tuple.Create(columns[c.Item1], c.Item2)).ToList();
            _primaryKeys = new HashSet<string>(PartitionKeys.Select(p => p.ColumnName).Concat(ClusteringKeys.Select(c => c.Item1.ColumnName)));

            MissingPrimaryKeyColumns = new List<string>();
            if (PartitionKeys.Count != partitionkeys.Length)
            {
                MissingPrimaryKeyColumns.AddRange(partitionkeys.Where(k => !columns.Contains(k)));
            }
            if (ClusteringKeys.Count != clusteringKeys.Length)
            {
                MissingPrimaryKeyColumns.AddRange(partitionkeys.Where(k => !columns.Contains(k)));
            }
        }
Example #3
0
 private static double[] DoPla(double[] w, Tuple<double[], double>[] classified)
 {
     var misclassified = classified.Where(t => GetY(w, t.Item1) != t.Item2).ToArray();
       //Console.WriteLine("{0} misclassified.", misclassified.Length);
       //Console.Write(".");
       if (misclassified.Length == 0)
     return w;
       else
     return DoPla(NextW(w, misclassified[R.Next(misclassified.Length)]), classified);
 }
Example #4
0
 private IValueProvider[] TrySelectDefault(Tuple<IValueProvider, IProbe>[] itemsWithHighestScore, int max)
 {
     var defaultValueProviders = itemsWithHighestScore.Where(x => x.Item2.ExplicitPositiveReferencesCount == 0 && x.Item2.ReferencesCount == 0).Select(x => x.Item1).ToArray();
     if (defaultValueProviders.Count() == 1)
     {
         return new[] { defaultValueProviders.Single()};
     }
     throw new ItemsWithConflictingHighestScoreException(itemsWithHighestScore, max);
 }
 private static string[] getLocationsOfObjectsThatBelongToCategory(Dictionary<string, Category> categoriesToTransfer, Tuple<string, List<Category>, List<MediaContent>>[] locationCategoriesTuplesWithMedia)
 {
     var resultLocations = locationCategoriesTuplesWithMedia.Where(tuple => tuple.Item2.Any(cat => categoriesToTransfer.ContainsKey(cat.ID)))
                                                 .SelectMany(tuple =>
                                                     {
                                                         List<string> joiningValues = new List<string>();
                                                         joiningValues.Add(tuple.Item1);
                                                         joiningValues.AddRange(tuple.Item3.Select(mc => mc.RelativeLocation));
                                                         return joiningValues.ToArray();
                                                     }).ToArray();
     return resultLocations;
 }
        private void ExecuteReloadConfig(Tuple<string, Action<bool>>[] items)
        {
            List<string> requestTypes;
            List<string> distinctRequestsTypes;

            DataSet configuration = null;
            bool systemConfigurationLoaded = false;

            requestTypes = items
                .Select(tuple => tuple.Item1)
                .ToList();

            distinctRequestsTypes = requestTypes
                .Distinct()
                .OrderBy(type => requestTypes.LastIndexOf(type))
                .ToList();

            foreach (string type in distinctRequestsTypes)
            {
                string typeInner = type;

                if (type == m_configurationType.ToString())
                {
                    DisplayStatusMessage("Loading system configuration...", UpdateType.Information);
                    configuration = GetConfigurationDataSet();

                    // Update data source on all adapters in all collections
                    if ((object)configuration != null)
                        PropagateDataSource(configuration);
                }
                else if (type == "Augmented")
                {
                    DisplayStatusMessage("Augmenting current system configuration...", UpdateType.Information);
                    configuration = AugmentConfigurationDataSet(DataSource);

                    // Update data source on all adapters in all collections
                    if ((object)configuration != null)
                        PropagateDataSource(configuration);
                }
                else if (type == "BinaryCache")
                {
                    DisplayStatusMessage("Loading binary cached configuration...", UpdateType.Information);
                    configuration = GetBinaryCachedConfigurationDataSet();

                    // Update data source on all adapters in all collections
                    if ((object)configuration != null)
                        PropagateDataSource(configuration);
                }
                else if (type == "XmlCache")
                {
                    DisplayStatusMessage("Loading XML cached configuration...", UpdateType.Information);
                    configuration = GetXMLCachedConfigurationDataSet();

                    // Update data source on all adapters in all collections
                    if ((object)configuration != null)
                        PropagateDataSource(configuration);
                }
                else if (type == "Startup")
                {
                    systemConfigurationLoaded = LoadStartupConfiguration();
                }
                else
                {
                    // No specific reload command was issued;
                    // load system configuration as normal
                    systemConfigurationLoaded = LoadSystemConfiguration();
                }

                foreach (Action<bool> callback in items.Where(tuple => tuple.Item1 == typeInner).Select(tuple => tuple.Item2))
                {
                    try
                    {
                        callback(systemConfigurationLoaded || (object)configuration != null);
                    }
                    catch (Exception ex)
                    {
                        DisplayStatusMessage("Failed to execute callback for ReloadConfig request of type {0}: {1}", UpdateType.Alarm, type, ex.Message);
                        LogException(ex);
                    }
                }

                // Spawn routing table calculation updates
                m_iaonSession.RecalculateRoutingTables();
            }
        }
Example #7
0
        private JsBlockStatement InitializeConstructor(INamedTypeSymbol type, string constructorName, Tuple<string, IParameterSymbol>[] parameters)
        {
            var block = new JsBlockStatement();
            block.Assign(GetFromPrototype(constructorName).Member(SpecialNames.TypeField), Js.Reference(SpecialNames.TypeInitializerTypeFunction));

            var parameterNames = parameters.Select(x => x.Item1);
            JsExpression[] arguments;
            if (!type.IsBuiltIn())
            {
                block.Assign(GetFromPrototype(constructorName).Member(SpecialNames.New), 
                    Js.Function().Body(Js.New(Js.Reference(SpecialNames.TypeInitializerTypeFunction), Js.This(), Js.Reference("arguments")).Return()));
            }
            else
            {
                arguments = parameters.Where(x => x.Item2 != null && x.Item2.IsBuiltIn()).Select(x => Js.Reference(x.Item1)).ToArray();
                block.Assign(GetFromPrototype(constructorName).Member(SpecialNames.New), 
                    Js.Function(parameterNames.Select(x => Js.Parameter(x)).ToArray())
                        .Body(Js.New(GetFromPrototype(constructorName).Member(SpecialNames.TypeField), Js.Array(arguments)).Return()));
            }

            return block;
        }
            /// <summary>
            /// This adds ioIndex to one of finalLinks
            /// </summary>
            /// <param name="closestBrainIndex">Index of the brain that is closest to the IO.  There is no extra burden for linking to this one</param>
            /// <param name="brainBrainBurdens">
            /// Item1=Index of other brain
            /// Item2=Link resistance (burden) between closestBrainIndex and this brain
            /// </param>
            private static void AddIOLink(BrainBurden[] finalLinks, int ioIndex, double ioSize, int closestBrainIndex, Tuple<int, double>[] brainBrainBurdens)
            {
                // Figure out the cost of adding the link to the various brains
                Tuple<int, double>[] burdens = new Tuple<int, double>[finalLinks.Length];

                for (int cntr = 0; cntr < finalLinks.Length; cntr++)
                {
                    int brainIndex = finalLinks[cntr].Index;        // this is likely always the same as cntr, but since that object has brainIndex as a property, I feel safer using it

                    // Adding to the closest brain has no exta cost.  Adding to any other brain has a cost based on the
                    // distance between the closest brain and that other brain
                    double linkCost = 0d;
                    if (brainIndex != closestBrainIndex)
                    {
                        //TODO: Link every brain to every other brain, then get rid of this if statement
                        var matchingBrain = brainBrainBurdens.FirstOrDefault(o => o.Item1 == brainIndex);
                        if (matchingBrain == null)
                        {
                            continue;
                        }

                        linkCost = matchingBrain.Item2;
                    }

                    // LinkCost + IOStorageCost
                    burdens[cntr] = Tuple.Create(cntr, linkCost + BrainBurden.CalculateBurden(finalLinks[cntr].IOSize + ioSize, finalLinks[cntr].Size));
                }

                int cheapestIndex = burdens.
                    Where(o => o != null).
                    OrderBy(o => o.Item2).First().Item1;

                finalLinks[cheapestIndex].AddIOLink(ioIndex);
            }
        private void btnPolyUnionTest4_Click(object sender, RoutedEventArgs e)
        {

            // The main problem is that lines are slicing through the entire polygon.  Need to detect that, also get rid of colinear points

            try
            {
                ClearAllVisuals();

                Point3D[][] initial3D = new Point3D[3][];

                initial3D[0] = new Point3D[] {
                    new Point3D(-16.1947246550931,-0.9149519332283,2.55976103387392),
                    new Point3D(-17.1107881600685,0.515445435128346,3.40133335668073),
                    new Point3D(-17.3596515210729,-0.829632679480615,4.42103762371103),
                    new Point3D(-17.3450427909807,-2.19357445878095,5.01957844043668),
                    new Point3D(-17.3283385073944,-2.17500700982897,4.98385833288751) };

                initial3D[1] = new Point3D[] {
                    new Point3D(-16.1947246550931,-0.914951933228302,2.55976103387392),
                    new Point3D(-17.3283385073944,-2.17500700982897,4.9838583328875),
                    new Point3D(-17.3450427909807,-2.19357445878095,5.01957844043668),
                    new Point3D(-17.341448388578,-2.52916527179157,5.16684630945675),
                    new Point3D(-15.3066235822732,-2.3016870563904,1.74387733292857) };

                initial3D[2] = new Point3D[] {
                    new Point3D(-17.3204018787836,-4.49416933689273,6.02915227870288),
                    new Point3D(-16.4203453178512,-4.5492595275131,4.58613381891047),
                    new Point3D(-14.928909934653,-2.89147215820253,1.39687808008519),
                    new Point3D(-15.3066235822732,-2.3016870563904,1.74387733292857),
                    new Point3D(-17.341448388578,-2.52916527179157,5.16684630945675) };

                // Create some random triangles
                Point[][] initialPolys = new Point[3][];

                initialPolys[0] = new Point[] {
                    new Point(-1.70753174254516,-10.6978382660948),
                    new Point(-0.726945738693094,-12.3201526746214),
                    new Point(-2.36588629353582,-12.7943243278674),
                    new Point(-3.85545055921974,-12.7943243278674),
                    new Point(-3.82425967044327,-12.7638803171038) };

                initialPolys[1] = new Point[] {
                    new Point(-1.70753174254517,-10.6978382660948),
                    new Point(-3.82425967044327,-12.7638803171038),
                    new Point(-3.85545055921974,-12.7943243278674),
                    new Point(-4.22195013459667,-12.7943243278674),
                    new Point(-2.65818579358351,-9.1250442852861) };

                initialPolys[2] = new Point[] {
                    new Point(-6.36793604229414,-12.7943243278674),
                    new Point(-5.84736974693176,-11.1743089731826),
                    new Point(-3.06250352298613,-8.45612745855601),
                    new Point(-2.65818579358351,-9.1250442852861),
                    new Point(-4.22195013459667,-12.7943243278674) };



                var feedsIntermediate = new Tuple<double, double, double, double>[]
                {
                    Tuple.Create(-1.70753174254516, -10.6978382660948, -0.726945738693094, -12.3201526746214),      //0
                    Tuple.Create(-0.726945738693094, -12.3201526746214, -2.36588629353582, -12.7943243278674),      //1
                    Tuple.Create(-2.36588629353582, -12.7943243278674, -3.85545055921974, -12.7943243278674),       //2
                    Tuple.Create(-3.85545055921974, -12.7943243278674, -3.82425967044327, -12.7638803171038),       //3
                    Tuple.Create(-3.82425967044327, -12.7638803171038, -1.70753174254516, -10.6978382660948),       //4
                    Tuple.Create(-1.70753174254517, -10.6978382660948, -3.82425967044327, -12.7638803171038),       //5
                    Tuple.Create(-3.82425967044327, -12.7638803171038, -3.85545055921974, -12.7943243278674),       //6
                    Tuple.Create(-3.85545055921974, -12.7943243278674, -4.22195013459667, -12.7943243278674),       //7
                    Tuple.Create(-4.22195013459667, -12.7943243278674, -2.65818579358351, -9.1250442852861),       //8
                    Tuple.Create(-2.65818579358351, -9.1250442852861, -1.70753174254517, -10.6978382660948),       //9
                    Tuple.Create(-6.36793604229414, -12.7943243278674, -5.84736974693176, -11.1743089731826),       //10
                    Tuple.Create(-5.84736974693176, -11.1743089731826, -3.06250352298613, -8.45612745855601),       //11
                    Tuple.Create(-3.06250352298613, -8.45612745855601, -2.65818579358351, -9.1250442852861),       //12
                    Tuple.Create(-2.65818579358351, -9.1250442852861, -4.22195013459667, -12.7943243278674),       //13
                    Tuple.Create(-4.22195013459667, -12.7943243278674, -6.36793604229414, -12.7943243278674)       //14
                }.Select(o => Tuple.Create(new Point(o.Item1, o.Item2), new Point(o.Item3, o.Item4))).ToArray();

                #region feeds intermediate dupes

                // Simplify duplication chains:
                //      Any point should only have one other match in the list
                //      If there is more than one match, the list should be able to be simplified

                List<Point> uniquePoints = new List<Point>();
                foreach (Point point in UtilityCore.Iterate(feedsIntermediate.Select(o => o.Item1), feedsIntermediate.Select(o => o.Item2)))
                {
                    if (!uniquePoints.Any(o => Math2D.IsNearValue(point, o)))
                    {
                        uniquePoints.Add(point);
                    }
                }

                var matchAttempt = uniquePoints
                    .Select(o => new { Point = o, Matches = feedsIntermediate.Where(p => Math2D.IsNearValue(o, p.Item1) || Math2D.IsNearValue(o, p.Item2)).ToArray() }).
                    OrderByDescending(o => o.Matches.Length).
                    ToArray();


                Tuple<Point, Point>[] feeds2 = feedsIntermediate.Select(o => o.Item1.X < o.Item2.X ? o : Tuple.Create(o.Item2, o.Item1)).ToArray();

                List<Tuple<Point, Point>> feeds3 = new List<Tuple<Point, Point>>();
                foreach (var feed in feeds2)
                {
                    if (!feeds3.Any(o => Math2D.IsNearValue(feed.Item1, o.Item1) && Math2D.IsNearValue(feed.Item2, o.Item2)))
                    {
                        feeds3.Add(feed);
                    }
                }


                var matchAttempt2 = uniquePoints
                    .Select(o => new { Point = o, Matches = feeds3.Where(p => Math2D.IsNearValue(o, p.Item1) || Math2D.IsNearValue(o, p.Item2)).ToArray() }).
                    OrderByDescending(o => o.Matches.Length).
                    ToArray();


                #endregion

                // This is what StitchSegments generates (should have just come up with one poly)
                Point[][] intermediate = new Point[1][];

                intermediate[0] = new Point[] {
                    new Point(-1.70753174254516,-10.6978382660948),     //0
                    new Point(-0.726945738693094,-12.3201526746214),        //1
                    new Point(-2.36588629353582,-12.7943243278674),     //2
                    new Point(-3.85545055921974,-12.7943243278674),     //3
                    new Point(-3.82425967044327,-12.7638803171038),     //4
                    new Point(-1.70753174254517,-10.6978382660948),     //5
                    new Point(-3.82425967044327,-12.7638803171038),     //6
                    new Point(-3.85545055921974,-12.7943243278674),     //7
                    new Point(-4.22195013459667,-12.7943243278674),     //8
                    new Point(-2.65818579358351,-9.1250442852861) };        //9

                //intermediate[1] = new Point[] {
                //    new Point(-6.36793604229414,-12.7943243278674),
                //    new Point(-5.84736974693176,-11.1743089731826),
                //    new Point(-3.06250352298613,-8.45612745855601),
                //    new Point(-2.65818579358351,-9.1250442852861),
                //    new Point(-4.22195013459667,-12.7943243278674) };

                #region intermediate distances

                List<Tuple<int, int, double, bool>> distances = new List<Tuple<int, int, double, bool>>();
                for (int outer = 0; outer < intermediate[0].Length - 1; outer++)
                {
                    for (int inner = outer + 1; inner < intermediate[0].Length; inner++)
                    {
                        double distance = (intermediate[0][outer] - intermediate[0][inner]).Length;

                        distances.Add(Tuple.Create(outer, inner, distance, Math1D.IsNearZero(distance)));
                    }
                }

                distances = distances.OrderBy(o => o.Item3).ToList();

                #endregion

                // Separate into islands
                Polygon2D[] finalPolys = null;
                try
                {
                    finalPolys = GetPolyUnion(initialPolys);
                }
                catch (Exception ex)
                {
                    //MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
                    finalPolys = new Polygon2D[0];
                }

                #region Draw

                Visual3D visual;

                // Lines
                foreach (Point[] polygon in initialPolys)
                {
                    visual = GetVisual_PolygonLines(polygon.Select(o => o.ToPoint3D(-2)).ToArray(), Colors.Gray, 1);
                    _debugVisuals.Add(visual);
                    _viewport.Children.Add(visual);
                }


                foreach (Point[] polygon in intermediate)
                {
                    visual = GetVisual_PolygonLines(polygon.Select(o => o.ToPoint3D(0)).ToArray(), Colors.Gray, 2);
                    _debugVisuals.Add(visual);
                    _viewport.Children.Add(visual);
                }


                for (int cntr = 0; cntr < intermediate[0].Length; cntr++)
                {
                    visual = GetVisual_Dot(intermediate[0][cntr].ToPoint3D(2), .02 + (cntr * .01), UtilityWPF.GetColorEGA(64, cntr));
                    _debugVisuals.Add(visual);
                    _viewport.Children.Add(visual);
                }


                //foreach (Point3D[] poly in initial3D)
                //{
                //    visual = GetPolygonLinesVisual(poly, Colors.Black, 1);
                //    _debugVisuals.Add(visual);
                //    _viewport.Children.Add(visual);
                //}


                foreach (Polygon2D polygon in finalPolys)
                {
                    visual = GetVisual_PolygonLines(polygon.Polygon.Select(o => o.ToPoint3D(2)).ToArray(), Colors.Black, 2);
                    _debugVisuals.Add(visual);
                    _viewport.Children.Add(visual);

                    foreach (Point[] hole in polygon.Holes)
                    {
                        visual = GetVisual_PolygonLines(hole.Select(o => o.ToPoint3D(2)).ToArray(), Colors.Red, 2);
                        _debugVisuals.Add(visual);
                        _viewport.Children.Add(visual);
                    }
                }

                // Polygons
                //foreach (Point[] polygon in finalPolys)       // can't do these, they are concave
                //foreach (Point[] polygon in initialPolys)
                for (int cntr = 0; cntr < initialPolys.Length; cntr++)
                {
                    Color color = UtilityWPF.GetColorEGA(10, cntr);
                    //Color color = Color.FromArgb(10, Convert.ToByte(StaticRandom.Next(256)), Convert.ToByte(StaticRandom.Next(256)), Convert.ToByte(StaticRandom.Next(256)));

                    visual = GetVisual_Polygon_Convex(initialPolys[cntr].Select(o => o.ToPoint3D()).ToArray(), color);
                    _debugVisuals.Add(visual);
                    _viewport.Children.Add(visual);
                }

                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
                private static List<Tuple<Point, Point>> StitchSegmentsSprtCleanup_TOOMUCH(Tuple<Point, Point>[] lineSegments)
                {
                    Tuple<Point, Point>[] cleaned = lineSegments.
                        Where(o => !Math2D.IsNearValue(o.Item1, o.Item2)).     // Remove single vertex matches
                        Select(o => o.Item1.X < o.Item2.X ? o : Tuple.Create(o.Item2, o.Item1)).     // Put the smaller x as item1
                        ToArray();

                    // Only return distinct segments
                    List<Tuple<Point, Point>> retVal = new List<Tuple<Point, Point>>();
                    foreach (var segment in cleaned)
                    {
                        if (!retVal.Any(o => Math2D.IsNearValue(segment.Item1, o.Item1) && Math2D.IsNearValue(segment.Item2, o.Item2)))
                        {
                            retVal.Add(segment);
                        }
                    }

                    // Exit Function
                    return retVal;
                }
                private static List<Tuple<Point, Point>> StitchSegmentsSprtCleanup_EXTENDCOLINEAR(Tuple<Point, Point>[] lineSegments)
                {
                    // Remove single vertex matches
                    var deduped = lineSegments.Where(o => !Math2D.IsNearValue(o.Item1, o.Item2)).ToList();



                    // Remove double T joints (happens when two polygons are butted up next to each other.  Need to get rid of that middle segment)



                    // Removing colinear should be optional, it's an expense that may not be desired
                    bool merged = false;
                    do
                    {
                        // Find segment pairs that are colienar, and convert to a single segment (but only if they have no other segments using the point
                        // to be deleted)






                    } while (merged);









                    return null;

                }
 private static List<Tuple<Point, Point>> StitchSegmentsSprtCleanup(Tuple<Point, Point>[] lineSegments)
 {
     // Remove single vertex matches
     return lineSegments.Where(o => !Math2D.IsNearValue(o.Item1, o.Item2)).ToList();
 }
            private static Point[] StitchSegments(Tuple<Point, Point>[] lineSegments)
            {
                // Need to remove single vertex matches, or the loop below will have problems
                var fixedSegments = lineSegments.Where(o => !Math2D.IsNearValue(o.Item1, o.Item2)).ToList();
                if (fixedSegments.Count == 0)
                {
                    return null;
                }

                List<Point> retVal = new List<Point>();

                // Stitch the segments together into a polygon
                retVal.Add(fixedSegments[0].Item1);
                Point currentPoint = fixedSegments[0].Item2;
                fixedSegments.RemoveAt(0);

                while (fixedSegments.Count > 0)
                {
                    var match = FindAndRemoveMatchingSegment(fixedSegments, currentPoint);
                    if (match == null)
                    {
                        //TODO: If this becomes an issue, make a method that builds fragments, then the final polygon will hop from fragment to fragment
                        //TODO: Or, use Math2D.GetConvexHull - make an overload that rotates the points into the xy plane
                        //throw new ApplicationException("The hull passed in has holes in it");
                        return null;
                    }

                    retVal.Add(match.Item1);
                    currentPoint = match.Item2;
                }

                if (!Math2D.IsNearValue(retVal[0], currentPoint))
                {
                    //throw new ApplicationException("The hull passed in has holes in it");
                    return null;
                }

                if (retVal.Count < 3)
                {
                    return null;
                }

                // Exit Function
                return retVal.ToArray();
            }
Example #14
0
        private void SetEntityState(EntityState newState, Tuple<IProperty, object>[] generatedValues)
        {
            // The entity state can be Modified even if some properties are not modified so always
            // set all properties to modified if the entity state is explicitly set to Modified.
            if (newState == EntityState.Modified)
            {
                _stateData.SetAllPropertiesModified(_entityType.Properties.Count(), isModified: true);

                // Assuming key properties are not modified
                foreach (var keyProperty in EntityType.GetKey().Properties)
                {
                    _stateData.SetPropertyModified(keyProperty.Index, isModified: false);
                }
            }
            else if (newState == EntityState.Unchanged)
            {
                _stateData.SetAllPropertiesModified(_entityType.Properties.Count(), isModified: false);
            }

            var oldState = _stateData.EntityState;
            if (oldState == newState)
            {
                return;
            }

            // An Added entity does not yet exist in the database. If it is then marked as deleted there is
            // nothing to delete because it was not yet inserted, so just make sure it doesn't get inserted.
            if (oldState == EntityState.Added
                && newState == EntityState.Deleted)
            {
                newState = EntityState.Unknown;
            }

            _configuration.Services.StateEntryNotifier.StateChanging(this, newState);

            if (newState == EntityState.Added)
            {
                foreach (var generatedValue in generatedValues.Where(v => v != null && v.Item2 != null))
                {
                    this[generatedValue.Item1] = generatedValue.Item2;
                }
            }
            else
            {
                Contract.Assert(generatedValues == null);
            }

            _stateData.EntityState = newState;

            if (oldState == EntityState.Unknown)
            {
                _configuration.StateManager.StartTracking(this);
            }
            else if (newState == EntityState.Unknown)
            {
                // TODO: Does changing to Unknown really mean stop tracking?
                _configuration.StateManager.StopTracking(this);
            }

            _configuration.Services.StateEntryNotifier.StateChanged(this, oldState);
        }
Example #15
0
		private IEnumerable<Tuple<IndexToWorkOn, IndexingBatch>> FilterIndexes(IList<IndexToWorkOn> indexesToWorkOn, JsonDocument[] jsonDocs)
		{
			var last = jsonDocs.Last();

			Debug.Assert(last.Etag != null);
			Debug.Assert(last.LastModified != null);

			var lastEtag = last.Etag.Value;
			var lastModified = last.LastModified.Value;

			var lastIndexedEtag = new ComparableByteArray(lastEtag.ToByteArray());

			var documentRetriever = new DocumentRetriever(null, context.ReadTriggers);

			var filteredDocs =
				BackgroundTaskExecuter.Instance.Apply(context, jsonDocs, doc =>
				{
					var filteredDoc = documentRetriever.ExecuteReadTriggers(doc, null, ReadOperation.Index);
					return filteredDoc == null ? new
					{
						Doc = doc,
						Json = (object)new FilteredDocument(doc)
					} : new
					{
						Doc = filteredDoc,
						Json = JsonToExpando.Convert(doc.ToJson())
					};
				});

			Log.Debug("After read triggers executed, {0} documents remained", filteredDocs.Count);

			var results = new Tuple<IndexToWorkOn, IndexingBatch>[indexesToWorkOn.Count];
			var actions = new Action<IStorageActionsAccessor>[indexesToWorkOn.Count];

			BackgroundTaskExecuter.Instance.ExecuteAll(context, indexesToWorkOn, (indexToWorkOn, i) =>
			{
				var indexLastInedexEtag = new ComparableByteArray(indexToWorkOn.LastIndexedEtag.ToByteArray());
				if (indexLastInedexEtag.CompareTo(lastIndexedEtag) >= 0)
					return;

				var indexName = indexToWorkOn.IndexName;
				var viewGenerator = context.IndexDefinitionStorage.GetViewGenerator(indexName);
				if (viewGenerator == null)
					return; // probably deleted

				var batch = new IndexingBatch();

				foreach (var item in filteredDocs)
				{
					if (FilterDocuments(item.Doc))
						continue;

					// did we already indexed this document in this index?
					var etag = item.Doc.Etag;
					if (etag == null)
						continue;

					if (indexLastInedexEtag.CompareTo(new ComparableByteArray(etag.Value.ToByteArray())) >= 0)
						continue;


					// is the Raven-Entity-Name a match for the things the index executes on?
					if (viewGenerator.ForEntityNames.Count != 0 &&
						viewGenerator.ForEntityNames.Contains(item.Doc.Metadata.Value<string>(Constants.RavenEntityName)) == false)
					{
						continue;
					}

					batch.Add(item.Doc, item.Json);

					if (batch.DateTime == null)
						batch.DateTime = item.Doc.LastModified;
					else
						batch.DateTime = batch.DateTime > item.Doc.LastModified
											? item.Doc.LastModified
											: batch.DateTime;
				}

				if (batch.Docs.Count == 0)
				{
					Log.Debug("All documents have been filtered for {0}, no indexing will be performed, updating to {1}, {2}", indexName,
						lastEtag, lastModified);
					// we use it this way to batch all the updates together
					actions[i] = accessor => accessor.Indexing.UpdateLastIndexed(indexName, lastEtag, lastModified);
					return;
				}
				if (Log.IsDebugEnabled)
				{
					Log.Debug("Going to index {0} documents in {1}: ({2})", batch.Ids.Count, indexToWorkOn, string.Join(", ", batch.Ids));
				}
				results[i] = Tuple.Create(indexToWorkOn, batch);

			});

			transactionalStorage.Batch(actionsAccessor =>
			{
				foreach (var action in actions)
				{
					if (action != null)
						action(actionsAccessor);
				}
			});

			return results.Where(x => x != null);
		}
Example #16
0
        private void ProcessSoulBags(Random rand, Tuple<Player, int>[] dat)
        {
            var items = new Dictionary<Player, HashSet<Item>>();
            foreach (var i in dat)
                items.Add(i.Item1, new HashSet<Item>());

            foreach (var i in SoulBag)
            {
                var eligiblePlayers = dat
                    .Where(_ => _.Item2 > i.Item1)
                    .OrderByDescending(_ => _.Item2)
                    .ToArray();

                var lootCount = i.Item2.BaseLootCount + i.Item2.PersonMultiplier*eligiblePlayers.Length;

                var loots = new List<Item>();
                for (var j = 0;
                    (j < lootCount || loots.Count < i.Item2.MinLootCount) &&
                    loots.Count < i.Item2.MaxLootCount;
                    j++)
                {
                    var loot = i.Item2.GetRandomLoot(rand);
                    if (loot != null) loots.Add(loot);
                }
                int idx = 0, q = -1;
                for (var j = 0; j < loots.Count;) //Give loots rounds
                {
                    if (items[eligiblePlayers[idx].Item1].Add(loots[j]) ||
                        idx == q)
                    {
                        j++;
                        q = -1;
                    }
                    else if (q == -1)
                        q = idx;

                    idx++;
                    if (idx == eligiblePlayers.Length) idx = 0;
                }
            }
            foreach (var i in items)
                if (i.Value.Count > 0)
                    ShowBags(rand, i.Value, i.Key);
        }
 private static void AssertReceivedTimes(Tuple<string, TimeSpan>[] changes, string id, int[] expectedReceivedSeconds)
 {
     var seconds = changes.Where(t => t.Item1 == id)
         .Select(t => (int)Math.Floor(t.Item2.TotalSeconds)).ToArray();
     seconds.ShouldAllBeEquivalentTo(expectedReceivedSeconds);
 }