Example #1
0
        private ElementCollection CreateElementGroup(string xPath, List<Element> list)
        {
            var names = new Dictionary<string, int>();
            foreach (var name in list.Select(el => el.Name))
            {
                if (names.ContainsKey(name))
                    names[name]++;
                else
                    names.Add(name, 1);
            }
            string mostRepeatedName = names.Keys.OrderBy(name => names[name]).First();

            int minX = list.Select(el => el.Location.X).Min();
            int minY = list.Select(el => el.Location.Y).Min();
            int maxX = list.Select(el => el.Location.X + el.Size.Width).Max();
            int maxY = list.Select(el => el.Location.Y + el.Size.Height).Max();

            var firstLocation = new Point(minX, minY);
            var combinedArea = new Size(maxX - minX, maxY - minY);
            return new ElementCollection()
            {
                Name = mostRepeatedName + "Group",
                LocatorType = "xpath",
                Locator = xPath,
                Location = firstLocation,
                Size = combinedArea
            };
        }
Example #2
0
        public WbImageData(
            List<WbVmUtils.PlotPoint<Color>> plotPoints,
            List<WbVmUtils.PlotRectangle<Color>> filledRects,
            List<WbVmUtils.PlotRectangle<Color>> openRects,
            List<WbVmUtils.PlotLine<Color>> plotLines, 
            double width, 
            double height)
        {
            Height = height;
            Width = width;
            PlotPoints = plotPoints;
            FilledRectangles = filledRects;
            OpenRectangles = openRects;
            PlotLines = plotLines;

            BoundingRect = RectExt.NegInfRect
                .BoundingRect(plotLines.Select(pl => pl.X1))
                .BoundingRect(plotLines.Select(pl => pl.X2))
                .BoundingRect(plotLines.Select(pl => pl.Y1))
                .BoundingRect(plotLines.Select(pl => pl.Y2))
                .BoundingRect(filledRects.Select(pl => pl.X))
                .BoundingRect(filledRects.Select(pl => pl.X + pl.Width))
                .BoundingRect(filledRects.Select(pl => pl.Y))
                .BoundingRect(filledRects.Select(pl => pl.Y + pl.Height))
                .BoundingRect(openRects.Select(pl => pl.X))
                .BoundingRect(openRects.Select(pl => pl.X + pl.Width))
                .BoundingRect(openRects.Select(pl => pl.Y))
                .BoundingRect(openRects.Select(pl => pl.Y + pl.Height))
                .BoundingRect(plotPoints.Select(pl => pl.X))
                .BoundingRect(plotPoints.Select(pl => pl.Y));
        }
Example #3
0
        private Delegate CreateActionDelegate(MethodInfo method)
        {
            List<ParameterExpression> parameters = new List<ParameterExpression>();
            foreach (ParameterInfo parameterInfo in method.GetParameters())
            {
                parameters.Add(Expression.Parameter(parameterInfo.ParameterType, parameterInfo.Name));
            }

            LambdaExpression lambda;

            if (method.IsStatic)
            {
                lambda = Expression.Lambda(
                    GetActionType(parameters.Select(p => p.Type).ToArray()),
                    Expression.Call(method, parameters.Cast<Expression>().ToArray()),
                    parameters.ToArray());
            }
            else
            {
                Type bindingType = method.DeclaringType;
                Expression<Func<object>> getInstanceExpression =
                    () => ScenarioContext.Current.GetBindingInstance(bindingType);

                lambda = Expression.Lambda(
                    GetActionType(parameters.Select(p => p.Type).ToArray()),
                    Expression.Call(
                        Expression.Convert(getInstanceExpression.Body, bindingType),
                        method,
                        parameters.Cast<Expression>().ToArray()),
                    parameters.ToArray());
            }


            return lambda.Compile();
        }
Example #4
0
        private List<DpsPerCharacter> FillEmptyDataPoints(List<DpsPerCharacter> list)
        {
            var allCharacters = list.Select(m => m.character).Distinct().OrderBy(m => m).ToList();
            var allIntervals = list.Select(m => m.interval).Distinct().OrderBy(m => m).ToList();

            // Fill in missing intervals
            var lastInterval = allIntervals.FirstOrDefault();
            foreach (var interval in allIntervals.OrderBy(m => m))
            {
                int diff = interval - lastInterval;
                if (diff > 1)
                {
                    for (int i = 1; i < diff; i++)
                    {
                        foreach (var character in allCharacters)
                        {
                            list.Add(new DpsPerCharacter { character = character, damage = 0, interval = lastInterval + i });
                        }
                    }
                }

                foreach (var character in allCharacters)
                {
                    if (list.Any(m => m.character == character && m.interval == interval) == false)
                    {
                        list.Add(new DpsPerCharacter { character = character, interval = interval, damage = 0 });
                    }
                }

                lastInterval = interval;
            }

            return list;
        }
Example #5
0
 private static IEnumerable<string> GetUsedPaths(List<Customer> customers)
 {
     IEnumerable<string> usedPaths = customers.Select(cust => cust.PhotoPath);
     usedPaths = usedPaths.Concat(customers.Select(cust => cust.ProofOfIdPath));
     usedPaths = usedPaths.Concat(customers.Select(cust => cust.Address.ProofOfAddressPath));
     return usedPaths;
 }
        [Fact] // CodePlex 583
        public void RemoveDuplicateTphColumns_removes_multiple_batches_of_duplicate_columns_from_same_table()
        {
            var removed = new List<EdmMember>();
            var mockTableType = CreateMockType("Lancre");
            mockTableType.Setup(m => m.RemoveMember(It.IsAny<EdmMember>())).Callback<EdmMember>(removed.Add);

            var columns = CreateColumns(
                mockTableType,
                "Nanny", "Ogg", "Nanny", "Nanny", "Granny", "Magrat", "Weatherwax", "Weatherwax", "Magrat", "Garlik", "Tiffany", "Tiffany");

            var mappings = CreateMappings(
                columns,
                "Nanny1", "Ogg", "Nanny2", "Nanny2", "Granny", "Magrat1", "Weatherwax", "Weatherwax", "Magrat2", "Garlik", "Tiffany",
                "Tiffany");

            new TphColumnFixer(mappings).RemoveDuplicateTphColumns();

            Assert.Equal(5, removed.Count);
            Assert.Equal(2, removed.Select(m => m.Name).Count(n => n == "Nanny"));
            Assert.Equal(1, removed.Select(m => m.Name).Count(n => n == "Weatherwax"));
            Assert.Equal(1, removed.Select(m => m.Name).Count(n => n == "Magrat"));
            Assert.Equal(1, removed.Select(m => m.Name).Count(n => n == "Tiffany"));

            AssertDuplicatesRemoved(mappings, "Nanny");
            AssertDuplicatesRemoved(mappings, "Weatherwax");
            AssertDuplicatesRemoved(mappings, "Magrat");
            AssertDuplicatesRemoved(mappings, "Tiffany");
        }
 public static IEnumerable<RestrictionModel> Sanitize(this IEnumerable<RestrictionModel> input)
 {
     var patterns = new List<PatternRestrictionModel>();
     foreach (var item in input)
     {
         var pattern = item as PatternRestrictionModel;
         if (pattern != null)
             patterns.Add(pattern);
         else
             yield return item;
     }
     if (patterns.Count == 1)
     {
         yield return patterns[0];
     }
     else if (patterns.Count > 1)
     {
         var config = patterns.Select(x => x.Configuration).First();
         var pattern = string.Join("|", patterns.Select(x => string.Format("({0})", x.Value)));
         yield return new PatternRestrictionModel(config)
         {
             Value = pattern,
         };
     }
 }
        static void Main(string[] args)
        {
            var images = new List<ImageInfo>();

            var imageId = 0;
            foreach (var dir in new DirectoryInfo(@"..\..\Images").GetDirectories())
            {
                var groupId = int.Parse(dir.Name.Replace("s", string.Empty)) - 1;
                foreach (var imageFile in dir.GetFiles("*.pgm"))
                {
                    images.Add(new ImageInfo
                    {
                        Image = new Mat(imageFile.FullName, LoadMode.GrayScale),
                        ImageId = imageId++,
                        ImageGroupId = groupId
                    });
                }
            }

            var model = FaceRecognizer.CreateFisherFaceRecognizer();
            model.Train(images.Select(x => x.Image), images.Select(x => x.ImageGroupId));

            var rnd = new Random();
            var randomImageId = rnd.Next(0, images.Count - 1);
            var testSample = images[randomImageId];

            Console.WriteLine("Actual group: {0}", testSample.ImageGroupId);
            Cv2.ImShow("actual", testSample.Image);

            var predictedGroupId = model.Predict(testSample.Image);
            Console.WriteLine("Predicted group: {0}", predictedGroupId);

            Cv2.WaitKey(0);
        }
        public ActionResult Agitator(int Id)
        {
            var politicalViews = new List<KeyValuePair<string, int>>();
            var agitatorHouses = dataManager.AgitatorHouseRelations.GetAll().Where(ah => ah.AgitatorId == Id && ah.HouseId.HasValue).Select(wh => wh.HouseId.Value).ToList();

            var houses = dataManager.Houses.GetAll().Where(h => agitatorHouses.Contains(h.Id) && h.Latitude.HasValue && h.Longitude.HasValue).ToList();
            var persons = dataManager.Persons.GetAll().Where(p => houses.Select(x => x.Id).Contains(p.HouseId ?? 0)).ToList();
            var voters = dataManager.Voters.GetAll().Where(v => persons.Select(x => x.Id).Contains(v.PersonId ?? 0)).ToList();
            var voterPartyRelations = dataManager.VoterPartyRelations.GetAll().ToList();
            var parties = voterPartyRelations.Where(vp => voters.Select(x => x.Id).Contains(vp.VoterId ?? 0))
                .Select(x => dataManager.Parties.Get(x.PartyId ?? 0)).ToList();

            foreach (var house in houses)
            {
                var hPersons = persons.Where(x => x.HouseId == house.Id).ToList();
                var hVoters = voters.Where(x => hPersons.Select(x2 => x2.Id).Contains(x.PersonId ?? 0)).ToList();
                var hVoterPartyRelations = voterPartyRelations.Where(x => hVoters.Select(x2 => x2.Id).Contains(x.VoterId ?? 0)).ToList();
                var hParties = parties.Where(x => hVoterPartyRelations.Select(x2 => x2.PartyId).Contains(x.Id)).ToList();

                foreach (var hParty in hParties.GroupBy(x => x.Id).Select(x => x.First()))
                {
                    politicalViews.Add(new KeyValuePair<string, int>(hParty.Name, hVoterPartyRelations.Where(x => x.PartyId == hParty.Id).Count()));
                }
            }
            var chart = new Chart(width: 200, height: 200)
            .AddSeries(
                name: "Employee",
                xValue: politicalViews.Select(p => p.Key).ToArray(),
                yValues: politicalViews.Select(p => p.Value).ToArray(),
                chartType: "Pie");
            return File(chart.GetBytes(), "image/jpeg");
        }
        public static ISet<int> GetSchemaVersionsForSubscription(List<string> capabilities)
        {
            //The first two schema versions follow the old regex, and versions 3 on follow the new one.
            if (capabilities == null)
            {
                throw new ArgumentNullException("capabilities");
            }

            var matchesOld = capabilities.Select(s => ClustersContractCapabilityRegexOld.Match(s)).Where(match => match.Success).ToList();

            var schemaVersions = new HashSet<int>(matchesOld.Select(m => Int32.Parse(m.Groups[1].Value, CultureInfo.CurrentCulture)).ToList());

            var matchesNew = capabilities.Select(s => ClustersContractCapabilityRegex.Match(s)).Where(match => match.Success).ToList();
            if (matchesNew.Count != 0)
            {
                schemaVersions.UnionWith(
                    matchesNew.Select(m => Int32.Parse(m.Groups[1].Value, CultureInfo.CurrentCulture)));
            }

            if (schemaVersions == null || !schemaVersions.Any())
            {
                throw new NotSupportedException("This subscription is not enabled for the clusters contract.");
            }

            return schemaVersions;
        }
        public static bool Save(List<RoleFunctions> rolefunctions, OracleConnection conn)
        {
            try
            {
                bool saved = false;
                string query = "INSERT INTO SYSTEMROLEFUNCTIONS (ROLEID, FUNCTIONID) values(:roleid, :functionid)";
                using (var command = conn.CreateCommand())
                {
                    command.CommandText = query;
                    command.CommandType = CommandType.Text;
                    command.BindByName = true;
                    // In order to use ArrayBinding, the ArrayBindCount property
                    // of OracleCommand object must be set to the number of records to be inserted
                    command.ArrayBindCount = rolefunctions.Count;
                    command.Parameters.Add(":roleid", OracleDbType.Int32, rolefunctions.Select(rf => rf.RoleId).ToArray(), ParameterDirection.Input);
                    command.Parameters.Add(":functionid", OracleDbType.Int32, rolefunctions.Select(rf => rf.FunctionId).ToArray(), ParameterDirection.Input);

                    int result = command.ExecuteNonQuery();
                    if (result == rolefunctions.Count)
                        saved = true;

                    return saved;
                }
            }
            catch(Exception ex)
            {
                throw ex;
            }
        }
		public RefactorCombineTableForm(Microsoft.VisualStudio.Modeling.Store store, nHydrateDiagram diagram, nHydrateModel model, Entity entity1, Entity entity2)
			: this()
		{
			_store = store;
			_model = model;
			_diagram = diagram;
			_entity1 = entity1;
			_entity2 = entity2;

			lblEntity1.Text = entity1.Name;
			lblEntity2.Text = entity2.Name;

			var fieldList = new List<Field>();
			fieldList.AddRange(entity1.Fields);
			fieldList.AddRange(entity2.Fields);
			fieldList.Remove(x => entity2.PrimaryKeyFields.Contains(x));

			if (fieldList.Select(x => x.Name.ToLower()).Count() != fieldList.Select(x => x.Name.ToLower()).Distinct().Count())
			{
				cmdApply.Enabled = false;
				lblError.Text = "Duplicate field names are not allowed.";
				lblError.Visible = true;
			}

			fieldList.ForEach(x => lstField.Items.Add(x.Name));
		}
Example #13
0
        public void Init(PluginInitContext context)
        {
            this.context = context;
            controlPanelItems = ControlPanelList.Create(48);
            iconFolder = Path.Combine(context.CurrentPluginMetadata.PluginDirectory, @"Images\ControlPanelIcons\");
            fileType = ".bmp";

            if (!Directory.Exists(iconFolder))
            {
                Directory.CreateDirectory(iconFolder);
            }

            foreach (ControlPanelItem item in controlPanelItems)
            {
                if (!File.Exists(iconFolder + item.GUID + fileType) && item.Icon != null)
                {
                    item.Icon.ToBitmap().Save(iconFolder + item.GUID + fileType);
                }
            }

            Task.Run(() =>
            {
                var characters = controlPanelItems.Select(i => i.LocalizedString)
                    .Concat(controlPanelItems.Select(i => i.InfoTip));

                Parallel.ForEach(characters, c =>
                {
                    if (!string.IsNullOrWhiteSpace(c) && Alphabet.ContainsChinese(c))
                    {
                        Alphabet.PinyinComination(c);
                    }
                });
            });
        }
Example #14
0
        public ILogFormat Create(Stream stream)
        {
            var savedPresets = Settings.Default.LexPresets ?? new XElement("Presets");

            var presets = new List<LexPreset>(
                from element in savedPresets.Elements("Preset")
                select new LexPreset {
                    Name = (string) element.Attribute("Name"),
                    CommonCode = (string) element.Attribute("CommonCode"),
                    SegmentCode = (string) element.Attribute("SegmentCode"),
                    RecordCode = (string) element.Attribute("RecordCode")
                });

            var selectView = new LexPresetsView();
            var viewModel = selectView.ViewModel;

            foreach (var preset in presets)
                viewModel.Presets.Add(preset);

            viewModel.SelectedPreset = viewModel.Presets.FirstOrDefault();

            viewModel.EditPreset = preset => {
                InvalidateCache(preset);
                ShowEditPresetDialog(selectView, stream, preset, presets.Select(x => x.Name));
            };

            viewModel.CreateNewPreset = () => {
                var preset = new LexPreset {
                    Name = "New Preset",
                    SegmentCode = "%%",
                    RecordCode = "%%"
                };

                return ShowEditPresetDialog(selectView, stream, preset, presets.Select(x => x.Name)) ? preset : null;
            };

            if (selectView.ShowDialog() != true)
                return null;

            Settings.Default.LexPresets =
                new XElement("Presets",
                    from preset in viewModel.Presets
                    select new XElement("Preset",
                        new XAttribute("Name", preset.Name),
                        new XAttribute("CommonCode", preset.CommonCode),
                        new XAttribute("SegmentCode", preset.SegmentCode),
                        new XAttribute("RecordCode", preset.RecordCode)));

            Settings.Default.Save();

            var selectedPreset = selectView.ViewModel.SelectedPreset;

            if (selectedPreset == null)
                return null;

            if (selectedPreset.Format != null)
                return selectedPreset.Format;

            return Compile(selectedPreset) ?? CompileManually(selectView, stream, selectedPreset);
        }
Example #15
0
        public static void ExecuteUserCommand(string command, Dictionary<string, string> userInputsArgs)
        {
            ChassisManagerLauncher launcher = new ChassisManagerLauncher();

            List<KeyValuePair<string, string>> methodParam = new List<KeyValuePair<string, string>>();

            foreach (KeyValuePair<string, string> parm in userInputsArgs)
            {
                if (parm.Key != command && parm.Key != string.Empty)
                {
                    methodParam.Add(new KeyValuePair<string, string>(CorrectParameterName(command,parm.Key) , parm.Value));
                }
            }

            try
            {
                launcher.GetType().InvokeMember(command, BindingFlags.InvokeMethod, null, launcher,
                    methodParam.Select(d => d.Value).ToArray(),
                    null, null, methodParam.Select(d => d.Key).ToArray());
            }
            catch (TargetInvocationException ex)
            {
                ex.InnerException.Data["OriginalStackTrace"] = ex.InnerException.StackTrace;
                throw ex.InnerException;
            }
        }
        public void SelectDisposableShouldWork()
        {
            var scheduler = new TestScheduler();
            var disposables = new List<BooleanDisposable>();
            var list = new CompositeDisposable();
            scheduler.CreateColdObservable(
                new Recorded<Notification<long>>(100, Notification.CreateOnNext(0L)),
                new Recorded<Notification<long>>(200, Notification.CreateOnNext(1L)),
                new Recorded<Notification<long>>(300, Notification.CreateOnNext(2L)),
                new Recorded<Notification<long>>(400, Notification.CreateOnNext(3L)),
                new Recorded<Notification<long>>(400, Notification.CreateOnCompleted<long>())
            )
            .SelectDisposable(list, i => {
                var d = new BooleanDisposable();
                disposables.Add(d);
                return d;
            }, (i, _) => i)
            .Subscribe()
            .DisposeWith(list);

            scheduler.AdvanceTo(300);

            disposables.Count.Should().Be(3);

            disposables.Select(d => d.IsDisposed).Should().NotContain(true);

            list.Dispose();

            disposables.Select(d => d.IsDisposed).Should().NotContain(false);

        }
        public override void Frame(double dt)
        {
            var enemies = Manager.GetEntitiesWithComponent<Enemy>().ToList();
            var bullets = Manager.GetEntitiesWithComponent<Bullet>().ToList();
            var collisions = new List<Tuple<Entity, Entity>>();

            foreach (var bullet in bullets)
            {
                foreach (var enemy in enemies)
                {
                    if (Collision(bullet.GetComponent<Position>(), enemy.GetComponent<Position>()))
                    {
                        collisions.Add(Tuple.Create(bullet, enemy));
                        break;
                    }
                }
            }

            var deadbullets = collisions.Select(x => x.Item1).Distinct();
            var deadEnemies = collisions.Select(x => x.Item2).Distinct();

            foreach (var deadBullet in deadbullets)
            {
                Manager.DestroyEntity(deadBullet);
            }

            foreach (var deadEnemy in deadEnemies)
            {
                Manager.DestroyEntity(deadEnemy);
            }
        }
Example #18
0
        private static void DumpPosts()
        {
            var path = Path.Combine(RawDataPath, "posts.xml");

            var sw = Stopwatch.StartNew();

            var buffer = new List<byte[]>(20000);
            int total = 0;
            foreach (var line in ReadLinesSequentially(path).Where(l => l.StartsWith("  <row ")))
            {
                total += 1;
                var post = PostParse(line);
                if (post == null)
                    continue;

                buffer.Add(post.ToBinary());

                if (buffer.Count == buffer.Capacity)
                {
                    _reader.WriteEventsInLargeBatch("", buffer.Select(x => (x)));
                    buffer.Clear();
                    var speed = total / sw.Elapsed.TotalSeconds;
                    Console.WriteLine("Posts:\r\n\t{0} per second\r\n\tAdded {1} posts", speed, total);
                }
            }
            _reader.WriteEventsInLargeBatch("s3:post", buffer.Select(x => (x)));
            Console.WriteLine("Posts import complete");
        }
Example #19
0
        public List<PostWrapped> Wrap(List<Guid> postIds, User currentUser = null)
        {
            var posts = new List<PostWrapped>();
            foreach (var postId in postIds)
            {
                var post = _postDao.GetPostById(postId);
                if (post != null)
                    posts.Add(new PostWrapped(post));
            }

            var authors = _membershipService.GetUsersByIds(posts.Select(x => x.Post.UserId).Distinct().ToList()).ToDictionary(x => x.Id, x => x);
            var subs = _subDao.GetSubsByIds(posts.Select(x => x.Post.SubId).Distinct().ToList()).ToDictionary(x => x.Id, x => x);

            var likes = currentUser != null ? _voteDao.GetVotesOnPostsByUser(currentUser.Id, postIds) : new Dictionary<Guid, VoteType>();

            foreach (var item in posts)
            {
                item.Author = authors.ContainsKey(item.Post.UserId) ? authors[item.Post.UserId] : null;
                item.Sub = subs.ContainsKey(item.Post.SubId) ? subs[item.Post.SubId] : null;
                if (currentUser != null)
                    item.CurrentUserVote = likes.ContainsKey(item.Post.Id) ? likes[item.Post.Id] : (VoteType?)null;
            }

            return posts;
        }
Example #20
0
        public void UpLoadJob()
        {
            List<int> successList = new List<int>();
            try
            {
                using (IDataReader dr = DataAccess.ExecuteReader("select * from jobMain where isUploaded=0"))
                {
                    int id = 0;
                    while (dr.Read())
                    {
                        String jobdate = dr["jobDate"].ToString();
                        Int32 userid = Int32.Parse(dr["UserID"].ToString());
                        string begintime = dr["BeginTime"] == DBNull.Value ? "" : dr["BeginTime"].ToString();
                        string endtime = dr["EndTime"] == DBNull.Value ? "" : dr["EndTime"].ToString();
                        string ipAddress = dr["ipAddress"] == DBNull.Value ? "" : dr["ipAddress"].ToString();
                        Int32 needcheckposition = dr["NeedCheckPosition"] == DBNull.Value ? 0 : Int32.Parse(dr["NeedCheckPosition"].ToString());
                        Int32 CheckPosition = dr["CheckPosition"] == DBNull.Value ? 0 : Int32.Parse(dr["CheckPosition"].ToString());
                        Int32 PassPosition = dr["PassPosition"] == DBNull.Value ? 0 : Int32.Parse(dr["PassPosition"].ToString());
                        id = Int32.Parse(dr["ID"].ToString());
                        String isfull = (dr["IsFull"] != DBNull.Value) ? dr["IsFull"].ToString() : "0";
                        string TrainCode = (dr["TrainCode"] == DBNull.Value) ? "" : dr["TrainCode"].ToString();
                        List<String> list = new List<string>();
                        using (IDataReader detaildr = DataAccess.ExecuteReader("select * from JobDetail where jobid=" + id.ToString()))
                        {

                            while (detaildr.Read())
                            {
                                list.Add(string.Format("{0}|{1}|{2}|{3}",
                                    detaildr["SpecsID"].ToString(),
                                    detaildr["CheckTime"].ToString(),
                                    detaildr["CheckDetailList"].ToString(),
                                    detaildr["BarCode"].ToString()));
                                if (detaildr["BarCode"] != DBNull.Value)
                                    TrainCode = detaildr["BarCode"].ToString().Trim();
                            }
                            detaildr.Close();
                        }
                        string childlist = string.Join("@", list.ToArray());
                        if (TrainCode.Length == AppHelper.BarCodeDim)
                            TrainCode = TrainCode.Substring(4, 3);
                        _Service.UploadJob(jobdate, userid, begintime, endtime, ipAddress, needcheckposition, CheckPosition, PassPosition, childlist, isfull == "1" ? true : false, TrainCode);
                        successList.Add(id);
                    }
                    dr.Close();
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (successList.Count > 0)
                {
                    DataAccess.ExecuteNonQuery(String.Format("Delete from jobmain where id in ({0})", String.Join(",", successList.Select(jid => jid.ToString()).ToArray())));
                    DataAccess.ExecuteNonQuery(String.Format("Delete from jobDetail where jobid in ({0})", String.Join(",", successList.Select(jid => jid.ToString()).ToArray())));
                }
            }
        }
		private async Task<AffineTransformationParameters> CalibrateAsync(CalibrationStyle style)
		{
			await _LoadTask.Task;

			double margin = 50;
			List<Tuple<Point, Point>> measurements = new List<Tuple<Point, Point>>();
			measurements.Add(new Tuple<Point, Point>(new Point(margin, margin), new Point())); //Top left
            if(style == CalibrationStyle.SevenPoint)
			    measurements.Add(new Tuple<Point, Point>(new Point(this.ActualWidth * .5, margin), new Point())); //Top center
			measurements.Add(new Tuple<Point, Point>(new Point(this.ActualWidth - margin, margin), new Point())); //Top right
			measurements.Add(new Tuple<Point, Point>(new Point(this.ActualWidth - margin, this.ActualHeight - margin), new Point())); //Bottom right
            if (style == CalibrationStyle.SevenPoint)
                measurements.Add(new Tuple<Point, Point>(new Point(this.ActualWidth * .5, this.ActualHeight - margin), new Point())); //Bottom center
			measurements.Add(new Tuple<Point, Point>(new Point(margin, this.ActualHeight - margin), new Point())); //Bottom left
            if (style == CalibrationStyle.CornersAndCenter || style == CalibrationStyle.SevenPoint)
                measurements.Add(new Tuple<Point, Point>(new Point(this.ActualWidth * .5, this.ActualHeight * .5), new Point())); //Center

			for (int i = 0; i < measurements.Count; i++)
			{
				progress.Value = i * 100d / measurements.Count;
				var p = measurements[i].Item1;
				CalibrationMarker.RenderTransform = new TranslateTransform() { X = p.X, Y = p.Y };
				var p1 = await GetRawTouchEventAsync();
				measurements[i] = new Tuple<Point, Point>(p, p1);
			}
			var lsa = new LeastSquaresAdjustment(measurements.Select(t => t.Item1), measurements.Select(t => t.Item2));
			
			return lsa.GetTransformation();
		}
Example #22
0
        private static List<Standing> GetStandings(List<Game> games)
        {
            var teams = games.Select(game => game.HomeTeam)
                .Concat(games.Select(game => game.AwayTeam))
                .Distinct();

            var standings = (from team in teams
                let teamGames = games.Where(game =>
                    (game.HomeTeam.Id == team.Id || game.AwayTeam.Id == team.Id) &&
                    game.IncludeInStandings
                ).ToList()
                let scores = teamGames.Select(Score.GetScore).ToList()
                select new Standing {
                    Team = team,
                    Wins = scores.Count(score => score.WinningTeamId == team.Id),
                    Losses = scores.Count(score => score.LosingTeamId == team.Id),
                    Ties = scores.Count(score => score.IsTie),
                    Forfeits = teamGames.Count(game => game.WasForfeited && game.ForfeitingTeamId == team.Id),
                    GamesPlayed = teamGames.Count,
                    GoalsFor = teamGames.Sum(game => {
                        var score = Score.GetScore(game);
                        return game.HomeTeam.Id == team.Id ? score.HomeTeamScore : score.AwayTeamScore;
                    }),
                    GoalsAgainst = teamGames.Sum(game => {
                        var score = Score.GetScore(game);
                        return game.HomeTeam.Id == team.Id ? score.AwayTeamScore : score.HomeTeamScore;
                    })
                }).ToList();

            return standings;
        }
Example #23
0
        protected AssociativeNode CreateOutputAST(
            AssociativeNode codeInputNode, List<AssociativeNode> inputAstNodes,
            List<Tuple<string, AssociativeNode>> additionalBindings)
        {
            var names =
                additionalBindings.Select(
                    x => AstFactory.BuildStringNode(x.Item1) as AssociativeNode).ToList();
            names.Add(AstFactory.BuildStringNode("IN"));

            var vals = additionalBindings.Select(x => x.Item2).ToList();
            vals.Add(AstFactory.BuildExprList(inputAstNodes));

            Func<string, IList, IList, object> backendMethod =
                IronPythonEvaluator.EvaluateIronPythonScript;

            return AstFactory.BuildAssignment(
                GetAstIdentifierForOutputIndex(0),
                AstFactory.BuildFunctionCall(
                    backendMethod,
                    new List<AssociativeNode>
                    {
                        codeInputNode,
                        AstFactory.BuildExprList(names),
                        AstFactory.BuildExprList(vals)
                    }));
        }
        private void onReceiveMessage(ZWaveContext context, ZWaveMessage message)
        {
            var response = message.Message;

            var foundNodes = new List<byte>();
            for (var i = 7; i < 35; i++)
            {
                for (var j = 0; j < 8; j++)
                {
                    if ((response[i] & (0x01 << j)) != 0)
                    {
                        var nodeId = (byte)((i - 7) * 8 + (j + 1));
                        if (nodeId != context.ControllerId)
                        {
                            foundNodes.Add(nodeId);
                        }
                    }
                }
            }

            if (foundNodes.Any())
            {
                context.DoParallelFor(foundNodes.Select(x => new LoadNodeProtocolInfo(x)).ToArray());
                context.DoParallelFor(foundNodes.Select(x => new LoadNodeCapabilities(x)).ToArray());
            }
        }
        public CollectionQuerySimplification(List<object> coll)
        {
            var x = coll.Select(element => element as object).Any(element => element != null);  // Noncompliant use OfType
            x = coll.Select((element) => ((element as object))).Any(element => (element != null) && CheckCondition(element) && true);  // Noncompliant use OfType
            var y = coll.Where(element => element is object).Select(element => element as object); // Noncompliant use OfType
            var y = coll.Where(element => element is object).Select(element => element as object[]);
            y = coll.Where(element => element is object).Select(element => (object)element); // Noncompliant use OfType
            x = coll.Where(element => element == null).Any();  // Noncompliant use Any([expression])
            var z = coll.Where(element => element == null).Count();  // Noncompliant use Count([expression])
            z = Enumerable.Count(coll.Where(element => element == null));  // Noncompliant
            z = Enumerable.Count(Enumerable.Where(coll, element => element == null));  // Noncompliant
            y = coll.Select(element => element as object);
            y = coll.ToList().Select(element => element as object); // Noncompliant
            y = coll
                .ToList()  // Noncompliant
                .ToArray() // Noncompliant
                .Select(element => element as object);

            var z = coll
                .Select(element => element as object)
                .ToList();

            var c = coll.Count(); //Noncompliant
            c = coll.OfType<object>().Count();

            x = Enumerable.Select(coll, element => element as object).Any(element => element != null); //Noncompliant
            x = Enumerable.Any(Enumerable.Select(coll, element => element as object), element => element != null); //Noncompliant
        }
        private Highcharts RenderChart()
        {
            Random rand = new Random();

            var transactionCounts = new List<VolumeModel>
            {
                new VolumeModel(){  Month="January", Volume=rand.Next(1001)},
                new VolumeModel(){  Month="February", Volume=rand.Next(1001)},
                new VolumeModel(){  Month="March", Volume=rand.Next(1001)},
                new VolumeModel(){  Month="April", Volume=rand.Next(1001)},
                new VolumeModel(){  Month="May", Volume=rand.Next(1001)},
                new VolumeModel(){  Month="June", Volume=rand.Next(1001)},
                new VolumeModel(){  Month="July", Volume=rand.Next(1001)},
                new VolumeModel(){  Month="August", Volume=rand.Next(1001)},
                new VolumeModel(){  Month="September", Volume=rand.Next(1001)},
                new VolumeModel(){  Month="October", Volume=rand.Next(1001)},
                new VolumeModel(){  Month="November", Volume=rand.Next(1001)},
                new VolumeModel(){  Month="December", Volume=rand.Next(1001)}
            };

            var xDataMonths = transactionCounts.Select(i => i.Month).ToArray();
            var yDataCounts = transactionCounts.Select(i => new object[] { i.Volume }).ToArray();

            var chart = new Highcharts("chart")

                        .InitChart(new Chart { DefaultSeriesType = ChartTypes.Line })

                        .SetTitle(new Title { Text = "Average Trading Volume per Day" })

                        .SetSubtitle(new Subtitle { Text = "Light-Sweet Crude Oil" })

                        .SetXAxis(new XAxis { Categories = xDataMonths })

                        .SetYAxis(new YAxis { Title = new YAxisTitle { Text = "Volume x 10,000" } })

                        .SetTooltip(new Tooltip
                        {
                            Enabled = true,
                            Formatter = @"function() { return '<b>'+ this.series.name +'</b><br/>'+ this.x +': '+ this.y; }"
                        })

                        .SetPlotOptions(new PlotOptions
                        {
                            Line = new PlotOptionsLine
                            {
                                DataLabels = new PlotOptionsLineDataLabels
                                {
                                    Enabled = true
                                },
                                EnableMouseTracking = false
                            }
                        })

                        .SetSeries(new[]
                        {
                            new Series {Name = "2015", Data = new Data(yDataCounts)}
                        });

            return chart;
        }
 public WatchSpecificMovies(List<Movie> moviesToWatch)
 {
     Require.NotNull(moviesToWatch, "moviesToWatch");
     Require.IsTrue(() => moviesToWatch.Count > 0, "At least one movie required");
     MoviesToWatch = moviesToWatch.Select(m => new MovieToWatch(m)).ToList();
     Description = "Watch all movies: " + string.Join(" ,", moviesToWatch.Select(m => m.Name));
 }
Example #28
0
        public static List<Manning> CreateHierarchicalTree(List<Manning> mannings)
        {
            Action<Manning> setChildren = null;

            setChildren = parent =>
            {
                parent.Children = mannings
                    .Where(childItem => childItem.ParentId == parent.Id)
                    .ToList();

                // Recursively call the SetChildren method for each child.
                if (setChildren != null)
                    parent.Children.ForEach(setChildren);
            };

            var ids = mannings.Select(x => x.Id).ToList();
            var parentIds = mannings.Select(x => x.ParentId).ToList();
            var roots = parentIds.Except(ids).ToList();

            // Initialize the hierarchical list to root level items
            var hierarchicalItems = mannings
                .Where(x => roots.Contains(x.ParentId))
                .ToList();

            // Call the SetChildren method to set the children on each root level item.
            hierarchicalItems.ForEach(setChildren);

            return hierarchicalItems;
        }
        protected override string GetSolution()
        {
            const double v = 3f / 7f;
            int maxD = 1000000;
            List<Tuple<int, int>> rpf = new List<Tuple<int, int>>();
            for (int d = 2; d < maxD; d++) {
                for (int n = 1; n < d; n++) {
                    if (Helper.GCD(d, n) == 1) {
                        rpf.Add(new Tuple<int, int>(n, d));
                        if (rpf.Count > 1000000) {
                            // Shrink list
                            var data = rpf.Select(x => new { Value = (double)x.Item1 / (double)x.Item2, Data = x }).OrderBy(x => x.Value).ToList();
                            var dataBefore = data.Where(x => x.Value <= v).ToList();
                            if (dataBefore.Count > 5) {
                                dataBefore = dataBefore.Skip(dataBefore.Count - 5).Take(5).ToList();
                            }
                            var dataAfter = data.Where(x => x.Value >= v).ToList();
                            if (dataAfter.Count > 5) {
                                dataAfter = dataAfter.Take(5).ToList();
                            }
                            data = dataBefore.Concat(dataAfter).Distinct().ToList();
                            System.Diagnostics.Debug.Print("Shrunk! D = " + d.ToString());
                            rpf = data.Select(x => x.Data).ToList();
                        }
                    }
                }
            }

            var sorted = rpf.Select(x => new { Value = (double)x.Item1 / (double)x.Item2, Data = x }).OrderBy(x => x.Value).ToList();
            var solution = sorted.Where(x => x.Value < v).Last();

            return solution.ToString();
        }
        /// <summary>
        /// The try save characteristics to database.
        /// </summary>
        /// <param name="characteristics">
        /// The characteristics.
        /// </param>
        public void TrySaveCharacteristicsToDatabase(List<Characteristic> characteristics)
        {
            if (characteristics.Count > 0)
            {
                try
                {
                    db.Characteristic.AddRange(characteristics);
                    db.SaveChanges();
                }
                catch (Exception exception)
                {
                    // todo: refactor and optimize all this
                    var characteristicsSequences = characteristics.Select(c => c.SequenceId).Distinct().ToArray();
                    var characteristicsTypes = characteristics.Select(c => c.CharacteristicTypeLinkId).Distinct().ToArray();
                    var characteristicsFilter = characteristics.Select(c => new { c.SequenceId, c.CharacteristicTypeLinkId }).ToArray();
                    var wasteCharacteristics = db.Characteristic.Where(c => characteristicsSequences.Contains(c.SequenceId) && characteristicsTypes.Contains(c.CharacteristicTypeLinkId))
                            .ToArray().Where(c => characteristicsFilter.Contains(new { c.SequenceId, c.CharacteristicTypeLinkId })).Select(c => new { c.SequenceId, c.CharacteristicTypeLinkId });
                    var wasteNewCharacteristics = characteristics.Where(c => wasteCharacteristics.Contains(new { c.SequenceId, c.CharacteristicTypeLinkId }));

                    db.Characteristic.RemoveRange(wasteNewCharacteristics);
                    try
                    {
                        db.SaveChanges();
                    }
                    catch (Exception anotherException)
                    {
                    }
                }
            }
        }