/// <summary> /// Creates a new Contest with predetermined teams. /// </summary> /// <param name="id">Numeric indentifier for the contest.</param> /// <param name="name">Contest Name.<param> /// <param name="description">Contest Description.</param> /// <param name="points">Points to be distributed to the winner(s).</param> /// <param name="mode">Contest mode for determining termination.</param> /// <param name="type">Contest type (group or individual)</param> /// <param name="start">Time to start the contest.</param> /// <param name="end">End Conditions to be observed.</param> /// <param name="statistic">Statistic on which the Contest is based.</param> /// <param name="teams">Teams participating in the Contest.</param> protected Contest(int id, string name, string description, int points, ContestEndMode mode, ContestType type, DateTime start, EndCondition end, Statistic statistic, List<Team> teams) : this(name, description, points, mode, type, start, end, statistic) { this.Teams = teams; }
public Statistic FindByUserId(int userID) { var myStats = (from stats in _context.Statistics where stats.UserID == userID select stats).ToList(); var singleStat= myStats.GroupBy(x => x.UserID) .Select(y => new { UserId = y.Key, Wins = y.Sum(i => i.Wins), GamesPlayed = y.Sum(i => i.GamesPlayed) }).FirstOrDefault(); var newStats = new Statistic(); if (singleStat == null) { newStats.Wins = 0; newStats.GamesPlayed = 0; newStats.UserID = 0; } else { newStats.Wins = singleStat.Wins; newStats.GamesPlayed = singleStat.GamesPlayed; newStats.UserID = singleStat.UserId; } return newStats; }
/// <summary> /// Saves a user statistic as a new entry in the DB. /// </summary> /// <param name="userId">User to create stat for.</param> /// <param name="statType">Statistic type to create.</param> /// <param name="val">Value of the statistic.</param> /// <returns>ID of the created statistic on success, 0 on failure.</returns> public static int CreateNewStatisticForUser(int userId, Statistic statType, float val) { try { int id; using (SqlConnection connection = ConnectionManager.GetConnection()) { var data = new ActivEarthDataProvidersDataContext(connection); var statisticData = new UserStatisticDataProvider { user_id = userId, value = val, statistic_type = (byte)statType }; data.UserStatisticDataProviders.InsertOnSubmit(statisticData); data.SubmitChanges(); id = statisticData.id; } return id; } catch (Exception) { return 0; } }
public void Set(Statistic s, StatisticHolder origin, CarryType t) { statistic = s; type = t; originalStat = origin; originalStat.AddSavable(this); GameState.IsCarrying = true; }
/* public float LongestHit() { //Calculate } */ /* public float ResetLongestHit() { //Calculate } */ /* public float IndividualScoring() { //Calculate } */ /* public float TeamScoring() { //Calculate } */ public override void GenerateStats() { Debug.Log("Starting to generate statistics"); stats = new Statistic[4]; stats[0] = new Statistic("KILLS", kills); stats[1] = new Statistic("DEATHS", deaths); stats[2] = new Statistic("K/D", KillDeathRatio(), Statistic.Format.ratio); stats[3] = new Statistic("BATTING AVERAGE", BattingAverage, Statistic.Format.ratio); }
/* public float IndividualScoring() { //Calculate } */ /* public float TeamScoring() { //Calculate } */ public override void GenerateStats() { Debug.Log("Starting to generate statistics"); stats = new Statistic[4]; stats[0] = new Statistic("KILLS", kills); stats[1] = new Statistic("DEATHS", deaths); stats[2] = new Statistic("K/D", KillDeathRatio(), Statistic.Format.ratio); stats[3] = new Statistic("GOALS", succesfulGoals, Statistic.Format.none); }
public Item(int ID) { id = Static.items[ID].id; name = Static.items[ID].name; damage = Static.items[ID].damage; attackSpeed = Static.items[ID].attackSpeed; moveSpeed = Static.items[ID].moveSpeed; cost = Static.items [ID].cost; }
public TagCloud GenerateCloud(Statistic wordsStatistics, Func<string, Font, Size> measureString) { _minWeight = wordsStatistics.MinWeight; _maxWeight = wordsStatistics.MaxWeight; _measureString = measureString; var words = PlaceWords((wordsStatistics.WordsStatistics)); return new TagCloud(ImageWidth, ImageHeight, words); }
public void AddElement(string key, Statistic value) { XElement element = new XElement("Statistic"); element.SetAttributeValue(valueName, value.Value); element.SetAttributeValue(minValueName, value.MinValue); element.SetAttributeValue(maxValueName, value.MaxValue); base.AddElement(key, element.ToString()); }
/// <summary> /// Retrieves the reward for a particular badge. /// </summary> /// <param name="stat">Statistic for which the badge is awarded.</param> /// <param name="badgeLevel">Desired level of the badge.</param> /// <returns>Reward for the given badge.</returns> public static float GetBadgeReward(Statistic stat, int badgeLevel) { using (SqlConnection connection = ConnectionManager.GetConnection()) { var data = new ActivEarthDataProvidersDataContext(connection); return (from c in data.BadgeConstantsDataProviders where c.statistic == (byte)stat && c.level == badgeLevel select (float)c.reward).FirstOrDefault(); } }
/// <summary> /// Retrieves the statistic requirements for all levels of a particular badge. /// </summary> /// <param name="stat">Statistic for which the badge is awarded.</param> /// <returns>Statistic requirement for the given badge.</returns> public static float[] GetBadgeRequirementArray(Statistic stat) { using (SqlConnection connection = ConnectionManager.GetConnection()) { var data = new ActivEarthDataProvidersDataContext(connection); return (from c in data.BadgeConstantsDataProviders where c.statistic == (byte)stat select (float)c.requirement).ToArray(); } }
/// <summary> /// Retrieves the image path for a particular badge. /// </summary> /// <param name="stat">Statistic for which the badge is awarded.</param> /// <param name="badgeLevel">Desired level of the badge.</param> /// <returns>Reward for the given badge.</returns> public static string GetBadgeImagePath(Statistic stat, int badgeLevel) { using (SqlConnection connection = ConnectionManager.GetConnection()) { var data = new ActivEarthDataProvidersDataContext(connection); return (from c in data.BadgeConstantsDataProviders where c.statistic == (byte)stat && c.level == badgeLevel select c.image_path).FirstOrDefault(); } }
/// <summary> /// Creates a new Challenge and adds it to the collection. /// </summary> /// <param name="name">Challenge Name.</param> /// <param name="description">Challenge Description.</param> /// <param name="points">Points to be awarded upon completion of the Challenge.</param> /// <param name="start">Time at which the challenge should begin.</param> /// <param name="durationInDays">Number of days that the challenge should be active.</param> /// <param name="persistent">True if the Challenge is persistent, false otherwise.</param> /// <param name="statistic">Statistic on which the Challenge is based.</param> /// <param name="requirement">Statistic value required to complete the challenge.</param> /// <returns></returns> public static int CreateChallenge(string name, string description, int points, bool persistent, DateTime start, int durationInDays, Statistic statistic, float requirement) { Challenge newChallenge = new Challenge(name, description, points, persistent, start, durationInDays, statistic, requirement); int id = ChallengeDAO.CreateNewChallenge(newChallenge); return id; }
/* public float LongestPutt() { //Calculate } */ /* public float ResetLongestPutt() { //Calculate } */ /* public float ShortestPutt() { //Calculate } */ /* public float ResetShortestPutt() { //Calculate } */ /* public float IndividualScoring() { //Calculate } */ /* public float TeamScoring() { //Calculate } */ public override void GenerateStats() { Debug.Log("Starting to generate statistics"); stats = new Statistic[5]; stats[0] = new Statistic("KILLS", kills); stats[1] = new Statistic("DEATHS", deaths); stats[2] = new Statistic("K/D", KillDeathRatio(), Statistic.Format.ratio); stats[3] = new Statistic("SANK PUTTS", PuttsMade, Statistic.Format.none); stats[4] = new Statistic("ACCURACY", CalculateAccuracy(),Statistic.Format.percentage); }
public Item(){ name = "unknown"; id = -1; damage = new Statistic (0, 0, 0, 0); attackSpeed = new Statistic (0, 0, 0, 0); moveSpeed = new Statistic (0, 0, 0, 0); cost = 0; roomTypes = new List<int>(); iconFile = "unknown.png"; }
public Item(int ID, string Name, Statistic Damage, Statistic AttackSpeed, Statistic MoveSpeed, int Cost, List<int> RoomTypes, string IconFile) { id = ID; name = Name; damage = Damage; attackSpeed = AttackSpeed; moveSpeed = MoveSpeed; roomTypes = RoomTypes; cost = Cost; iconFile = IconFile; }
/// <summary> /// Creates a new badge belonging to a user, based on a specific statistic. /// </summary> /// <param name="user">User to whom the Badge is bound.</param> /// <param name="statistic">Statistic to which the Badge is bound.</param> public Badge(int userId, Statistic statistic, float[] levelValues, int[] levelPoints, string[] imagePaths) { this.Level = BadgeLevels.None; this.Progress = 0; this.UserID = userId; this.StatisticBinding = statistic; this.LevelRequirements = levelValues; this.LevelRewards = levelPoints; }
// Use this for initialization void Start() { ObjectDictionaries.LoadedSaveFile.AddSavable(this); statistic = ObjectDictionaries.LoadedSaveFile.Statistics.GetElement(statisticName); if (statistic == null) { Debug.Log("Making new Statistic for '" + statisticName + "'"); statistic = new Statistic(defaultStatisticValues.value, defaultStatisticValues.minValue, defaultStatisticValues.maxValue); ObjectDictionaries.LoadedSaveFile.Statistics.AddElement(statisticName, statistic); } gameObject.name = statisticName; }
public PlayerStatistics(string _player) { player = _player; score = new Statistic<int>(); death = new Statistic<int>(); death.postChanged += (Statistic<int> statistic) => { ++Game.Statistic ().total.death.val; }; Reset (); }
/// <summary> /// Retrieves the statistic requirement for a particular badge. /// </summary> /// <param name="stat">Statistic for which the badge is awarded.</param> /// <param name="badgeLevel">Desired level of the badge.</param> /// <returns>Statistic requirement for the given badge.</returns> public static float GetBadgeRequirement(Statistic stat, int badgeLevel) { using (SqlConnection connection = ConnectionManager.GetConnection()) { var data = new ActivEarthDataProvidersDataContext(connection); float foundEntry = (from c in data.BadgeConstantsDataProviders where c.statistic == (byte)stat && c.level == badgeLevel select (float)c.requirement).FirstOrDefault(); return (foundEntry >= 0 ? (float)foundEntry : float.PositiveInfinity); } }
void Start() { invulnerabilityTime = 1.5f; if (NewGameOrLoad.LoadName == null) { moveSpeed = new Statistic(350f); attackSpeed = new Statistic(4f); damage = new Statistic(7.5f); //shootType = 0; //shootAmount = 1; } }
public StatisticData(Statistic statistic) { this.Name = statistic.Name; this.Count = statistic.Count.GetValueOrDefault(); this.Min = statistic.Min.GetValueOrDefault(); this.Max = statistic.Max.GetValueOrDefault(); this.Range = statistic.Range.GetValueOrDefault(); this.Mean = statistic.Mean.GetValueOrDefault(); this.Median = statistic.Median.GetValueOrDefault(); this.StandardDeviation = statistic.StandardDeviation.GetValueOrDefault(); this.ConfidenceInterval = statistic.ConfidenceInterval; }
protected void BindData(Guid productId) { using (ProductProvider provider = new ProductProvider()) { if (Guid.Empty.Equals(productId)) return; Statistic stat = new Statistic(); divSummaryWeight = weightOfProduct(provider, productId, 1, ref stat).ToString(); divProductName = productName(productId); divIgnore = stat.ingoreProducts.ToString(); } }
/// <summary> /// Retrieves the name for a particular statistic. /// </summary> /// <param name="stat">Statistic to query.</param> /// <returns>Name to be used for the statistic.</returns> public static string GetStatisticName(Statistic stat) { using (SqlConnection connection = ConnectionManager.GetConnection()) { var data = new ActivEarthDataProvidersDataContext(connection); string toReturn = (from c in data.StatisticConstantsDataProviders where c.statistic_id == (byte)stat select c.name).FirstOrDefault(); return (toReturn != null ? toReturn.Trim() : String.Empty); } }
/// <summary> /// Calculates the user's change in the relevant statistic /// since the beginning of the contest; their 'score' for /// the contest. /// </summary> /// <returns></returns> public float CalculateScore(Statistic statistic) { if (this.Initialized) { return (this.User.GetStatistic(statistic) - this.InitialScore); } else { throw new Exception(String.Format("User's Score ({0} {1}) was never Initialized", this.User.FirstName, this.User.LastName)); } }
public Image DrawTagCloudImage(Statistic statistic, ITagCloudGenerator tagCloudGenerator) { var image = new Bitmap(tagCloudGenerator.ImageWidth, tagCloudGenerator.ImageHeight); var graphics = Graphics.FromImage(image); var cloud = tagCloudGenerator.GenerateCloud(statistic, (s, f) => graphics.MeasureString(s, f).ToSize()); graphics.SmoothingMode = SmoothingMode.HighQuality; foreach (var wordRectangle in cloud.Elements) { //graphics.DrawRectangle(new Pen(Color.Black), wordRectangle.Border); graphics.DrawString(wordRectangle.Text, wordRectangle.Font, new SolidBrush(wordRectangle.Color), wordRectangle.Location.Location); } return image; }
public void InsertStatisticErrorTest() { List<string> errors = new List<string>(); BLStatistic.InsertStatistic(null, ref errors); Assert.AreEqual(1, errors.Count); errors = new List<string>(); Statistic statistic = new Statistic(); BLStatistic.InsertStatistic(statistic, ref errors); Assert.AreEqual(1, errors.Count); }
/// <summary> /// Creates a new Challenge. /// </summary> /// <param name="id">Identifier for the challenge.</param> /// <param name="name">Challenge Name.</param> /// <param name="description">Challenge Description.</param> /// <param name="points">Points to be awarded upon completion of the Challenge.</param> /// <param name="persistent">True if the Challenge is persistent, false otherwise.</param> /// <param name="startTime">Time at which the challenge begins.</param> /// <param name="durationInDays">Number of days for which the challenge is active.</param> /// <param name="statistic">Statistic to which the Challenge is bound.</param> /// <param name="requirement">Statistic value required to complete the challenge.</param> public Challenge(string name, string description, int points, bool persistent, DateTime startTime, int durationInDays, Statistic statistic, float requirement) { this.Name = name; this.Description = description; this.Points = points; this.IsPersistent = persistent; this.Duration = new TimeSpan(durationInDays, 0, 0, 0); this.EndTime = startTime.AddDays(durationInDays); this.StatisticBinding = statistic; this.Requirement = requirement; this.IsActive = true; }
/// <summary> /// Updates the badge to reflect a change in statistics. /// </summary> /// <param name="userId">User to update.</param> /// <param name="statistic">Statistic tracked by the badge to be updated.</param> public static int UpdateBadge(int userId, Statistic statistic) { int pointsEarned = 0; Badge badge = BadgeDAO.GetBadgeFromUserIdAndStatistic(userId, statistic); if (badge != null) { int oldLevel = badge.Level; int newLevel = oldLevel; UserStatistic userStat = UserStatisticDAO.GetStatisticFromUserIdAndStatType(userId, statistic); if (userStat == null) { UserStatisticDAO.CreateNewStatisticForUser(userId, statistic, 0); userStat = UserStatisticDAO.GetStatisticFromUserIdAndStatType(userId, statistic); if (userStat == null) { return 0; } } float stat = userStat.Value; while ((newLevel < BadgeLevels.Max) && (stat >= badge.LevelRequirements[(int)newLevel + 1])) { newLevel++; } for (int i = oldLevel + 1; i <= newLevel; i++) { pointsEarned += badge.LevelRewards[i]; } badge.Level = newLevel; if (badge.Level == BadgeLevels.Max) { badge.Progress = 100; } else { badge.Progress = (int)(100 * (stat - badge.LevelRequirements[newLevel]) / (badge.LevelRequirements[newLevel + 1] - badge.LevelRequirements[newLevel])); } BadgeDAO.UpdateBadge(badge); } return pointsEarned; }
public new Statistic GetElement(string key) { Statistic toReturn ; string val = base.GetElement(key); if (val == null) return null; XElement element = XElement.Parse(val); toReturn = new Statistic( float.Parse(element.Attribute(valueName).Value), float.Parse(element.Attribute(minValueName).Value), float.Parse(element.Attribute(maxValueName).Value) ); return toReturn; }
internal static void MakeLocalHistoryTrend() { var dirWithResults = AllureLifecycle.Instance.GetDirectoryWithResults(AllureLifecycle.Instance.Config.Allure.Directory); var historyDir = Path.Combine(dirWithResults, AllureConstants.HistoryDirName); if (AllureLifecycle.Instance.Config.Allure.AllowLocalHistoryTrend) { var newPreviousResult = new Statistic(); var previousFilesWithTests = Directory.GetFiles(dirWithResults, "*-test-run1*"); if (previousFilesWithTests.Length == 0) { return; } foreach (var filePath in previousFilesWithTests) { using (var reader = File.OpenText(filePath)) { var statusOfTest = JsonConvert.DeserializeObject <StatusTests>(reader.ReadToEnd()); switch (statusOfTest.StatusEnum) { case Status.none: newPreviousResult.Unknown++; break; case Status.failed: newPreviousResult.Failed++; break; case Status.broken: newPreviousResult.Broken++; break; case Status.passed: newPreviousResult.Passed++; break; case Status.skipped: newPreviousResult.Skipped++; break; } } } LinkedList <HistoryTrend> historyTrend; var pathHistoryTrend = Path.Combine(historyDir, AllureConstants.HistoryTrendFileName); long buildOrder = 1; if (File.Exists(pathHistoryTrend)) { using (var reader = new StreamReader(pathHistoryTrend)) { var str = reader.ReadToEnd(); historyTrend = new LinkedList <HistoryTrend>(HistoryTrend.FromJson(str).ToList()); buildOrder = historyTrend.First().BuildOrder + 1; } } else { if (!Directory.Exists(historyDir)) { Directory.CreateDirectory(historyDir); } historyTrend = new LinkedList <HistoryTrend>(); } historyTrend.AddFirst(new HistoryTrend { BuildOrder = buildOrder }); historyTrend.First().Statistic = newPreviousResult; var serialized = JsonConvert.SerializeObject(historyTrend, Formatting.Indented); using (var reader = new StreamWriter(pathHistoryTrend, false)) { reader.WriteLine(serialized); } } else { if (Directory.Exists(historyDir)) { try { Directory.Delete(historyDir, true); } catch (UnauthorizedAccessException) { // nothing } } } }
public StatModifier(Statistic stat, float mod, bool isMultiplier) { modifiedStat = stat; modifier = mod; this.isMultiplier = isMultiplier; }
protected virtual string GetStatisticText(int position) { return(Statistic.GetStatValueText(position, Competitor, DisplayType)); }
/// <summary> /// 初始化unit场景显示游戏对象 /// </summary> private void Initialize() { if (this.destroyed || this.willRemoved) //待销毁或移除,无法初始化 { return; } if (this.ins == null && this.pre != null) { //实例化gameObject if (!this.isStatic) //动态unit直接instantiate { this.ins = (DelegateProxy.Instantiate(this.pre) as GameObject); } else //静态unit,根据数据信息解析相关属性来构建 { this.ins = (this.unitParser.Instantiate(this.pre) as GameObject); } if (!GameScene.isPlaying) { this.type = UnitType.GetType(this.ins.layer); //根据layer获取unit的类型 } if (!this.isStatic && this.needSampleHeight) //非静态物体,计算unit位置点的地面高度给位置坐标y值,保证站立在地面上 { this.position.y = this.scene.SampleHeight(this.position, true); } this.ins.transform.position = this.position; //设定位置 if (this.components != null) //挂载component,问题components从哪儿获取?????// { int count = this.components.Count; for (int i = 0; i < count; i++) { this.ins.AddComponent(this.components[i]); } } if (this.isStatic) { this.ins.transform.rotation = this.rotation; this.ins.transform.localScale = this.localScale; if (LightmapSettings.lightmaps.Length > 0) //光照贴图属性赋值 { int count = this.lightmapPrototypes.Count; for (int j = 0; j < count; j++) { LightmapPrototype lightmapPrototype = this.lightmapPrototypes[j]; Renderer renderer = null; if (lightmapPrototype.rendererChildIndex == -1) { renderer = this.ins.renderer; } else if (lightmapPrototype.rendererChildIndex < this.ins.transform.childCount) { renderer = this.ins.transform.GetChild(lightmapPrototype.rendererChildIndex).renderer; } if (renderer != null) { renderer.lightmapIndex = lightmapPrototype.lightmapIndex; renderer.lightmapTilingOffset = lightmapPrototype.lightmapTilingOffset; } } } //收集所有Render列表 List <Renderer> list = new List <Renderer>(); if (this.ins.renderer != null) { list.Add(this.ins.renderer); } for (int k = 0; k < this.ins.transform.childCount; k++) { Renderer renderer2 = this.ins.transform.GetChild(k).renderer; if (renderer2 != null) { list.Add(renderer2); } } if (GameScene.isPlaying) //场景开始运行 { for (int l = 0; l < list.Count; l++) { for (int m = 0; m < list[l].materials.Length; m++) { Material material = list[l].materials[m]; if (material != null) { if (list[l].gameObject.layer == GameLayer.Layer_Ground) //实时场景运行时,只有地面接受阴影 { list[l].receiveShadows = true; } else { list[l].receiveShadows = false; } this.shaderName = material.shader.name; if (!this.scene.terrainConfig.enablePointLight) //根据是否启用点光源,使用不同的材质shader { if (this.shaderName == GameObjectUnit.diffuseShaderName || this.shaderName == GameObjectUnit.snailDiffusePointShaderName) { material.shader = GameObjectUnit.snailDiffuseShader; } if (this.shaderName == GameObjectUnit.diffuseCutoutShaderName || this.shaderName == GameObjectUnit.snailDiffusePointCutoutShaderName) { material.shader = GameObjectUnit.snailDiffuseCutoutShader; } } else { if (this.shaderName == GameObjectUnit.diffuseShaderName || this.shaderName == GameObjectUnit.snailDiffuseShaderName) { material.shader = GameObjectUnit.snailDiffusePointShader; } if (this.shaderName == GameObjectUnit.diffuseCutoutShaderName || this.shaderName == GameObjectUnit.snailDiffuseCutoutShaderName) { material.shader = GameObjectUnit.snailDiffusePointCutoutShader; } } } } } } else { //场景没有运行时,需要开启接受阴影和产生阴影,便于bake光照贴图 for (int n = 0; n < list.Count; n++) { list[n].receiveShadows = true; list[n].castShadows = true; for (int num = 0; num < list[n].sharedMaterials.Length; num++) { Material material2 = list[n].sharedMaterials[num]; if (this.scene.statisticMode) { Statistic.Push(material2, AssetType.Material); } if (material2 != null) { this.shaderName = material2.shader.name; if (this.shaderName == GameObjectUnit.snailDiffuseShaderName || this.shaderName == GameObjectUnit.snailDiffusePointShaderName) { material2.shader = GameObjectUnit.diffuseShader; } if (this.shaderName == GameObjectUnit.snailDiffuseCutoutShaderName || this.shaderName == GameObjectUnit.snailDiffusePointCutoutShaderName) { material2.shader = GameObjectUnit.diffuseCutoutShader; } } } } } } else if (this.createInsListener != null) { try { this.createInsListener(); //动态unit调用创建对象回调 } catch (Exception ex) { LogSystem.LogError(new object[] { "监听创建单位函数中出错!" + ex.ToString() }); } } this.Renamme(); if (!GameScene.isPlaying) //场景没有开始运行 { this.CollectMaterials(); this.AddMeshRenderColliders(); if (this.cullingFactor <= 0.01f) { this.cullingFactor = this.scene.terrainConfig.defautCullingFactor; } if (this.isStatic) //如果是静态unit,计算更新影响的阻塞tile列表 { this.ComputeTiles(); } } } else { this.lostAsset = true; if (GameScene.isEditor) { this.ins = GameObject.CreatePrimitive(PrimitiveType.Cube); this.ins.transform.position = this.position; this.ins.transform.rotation = this.rotation; this.ins.transform.localScale = new Vector3(2f, 2f, 2f); string[] array = this.prePath.Split(new char[] { '/' }); if (this.lightmapPrototypes.Count > 0 && this.ins.renderer != null) { this.ins.name = string.Concat(new object[] { array[array.Length - 1], ":LM{", this.lightmapPrototypes[0].scale, "} : Unit_", this.createID }); } else { this.ins.name = array[array.Length - 1] + ":Unit_" + this.createID; } } } this.PlayBornEffect(); //初始化完成,开始播放出生效果 }
public Task <Statistic> Update(int pkId, Statistic item) { return(Update <Statistic>(pkId, item)); }
public void CreateSectionFromPolylineCommand() { #if !DEBUG Statistic.SendCommandStarting("mpSectionFromPolyline", ModPlusConnector.Instance.AvailProductExternalVersion); #endif try { // Выберите полилинию: var peo = new PromptEntityOptions($"\n{Language.GetItem("msg6")}") { AllowNone = false, AllowObjectOnLockedLayer = true }; peo.SetRejectMessage($"\n{Language.GetItem("wrong")}"); peo.AddAllowedClass(typeof(Polyline), true); var per = AcadUtils.Editor.GetEntity(peo); if (per.Status != PromptStatus.OK) { return; } /* Регистрация ЕСКД приложения должна запускаться при запуске * функции, т.к. регистрация происходит в текущем документе * При инициализации плагина регистрации нет! */ ExtendedDataUtils.AddRegAppTableRecord(Section.GetDescriptor()); var style = StyleManager.GetCurrentStyle(typeof(Section)); var sectionLastLetterValue = string.Empty; var sectionLastIntegerValue = string.Empty; FindLastSectionValues(ref sectionLastLetterValue, ref sectionLastIntegerValue); var section = new Section(sectionLastIntegerValue, sectionLastLetterValue); MainFunction.CreateBlock(section); section.ApplyStyle(style, true); var plineId = per.ObjectId; using (AcadUtils.Document.LockDocument(DocumentLockMode.ProtectedAutoWrite, null, null, true)) { using (var tr = AcadUtils.Document.TransactionManager.StartOpenCloseTransaction()) { var dbObj = tr.GetObject(plineId, OpenMode.ForRead); if (dbObj is Polyline pline) { for (int i = 0; i < pline.NumberOfVertices; i++) { if (i == 0) { section.InsertionPoint = pline.GetPoint3dAt(i); } else if (i == pline.NumberOfVertices - 1) { section.EndPoint = pline.GetPoint3dAt(i); } else { section.MiddlePoints.Add(pline.GetPoint3dAt(i)); } } section.UpdateEntities(); section.BlockRecord.UpdateAnonymousBlocks(); var ent = (BlockReference)tr.GetObject(section.BlockId, OpenMode.ForWrite, true, true); ent.Position = pline.GetPoint3dAt(0); ent.XData = section.GetDataForXData(); } tr.Commit(); } AcadUtils.Document.TransactionManager.QueueForGraphicsFlush(); AcadUtils.Document.TransactionManager.FlushGraphics(); // "Удалить исходную полилинию?" if (MessageBox.ShowYesNo(Language.GetItem("msg7"), MessageBoxIcon.Question)) { using (var tr = AcadUtils.Document.TransactionManager.StartTransaction()) { var dbObj = tr.GetObject(plineId, OpenMode.ForWrite, true, true); dbObj.Erase(true); tr.Commit(); } } } } catch (System.Exception exception) { ExceptionBox.Show(exception); } }
public static void Main(string[] args) { // Setup configuration to either read from the appsettings.json file (if present) or environment variables. var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables(); _configuration = builder.Build(); var arguments = ParseArguments(); var cosmosDbConnectionString = new CosmosDbConnectionString(arguments.CosmosDbConnectionString); // Set an optional timeout for the generator. var cancellationSource = arguments.MillisecondsToRun == 0 ? new CancellationTokenSource() : new CancellationTokenSource(arguments.MillisecondsToRun); var cancellationToken = cancellationSource.Token; var statistics = new Statistic[0]; // Set the Cosmos DB connection policy. var connectionPolicy = new ConnectionPolicy { ConnectionMode = ConnectionMode.Direct, ConnectionProtocol = Protocol.Tcp, UseMultipleWriteLocations = true }; var numberOfMillisecondsToLead = arguments.MillisecondsToLead; var taskWaitTime = 0; if (numberOfMillisecondsToLead > 0) { taskWaitTime = numberOfMillisecondsToLead; } var progress = new Progress <Progress>(); progress.ProgressChanged += (sender, progressArgs) => { foreach (var message in progressArgs.Messages) { WriteLineInColor(message.Message, message.Color.ToConsoleColor()); } statistics = progressArgs.Statistics; }; WriteLineInColor("Vehicle Telemetry Generator", ConsoleColor.White); Console.WriteLine("======"); WriteLineInColor("Press Ctrl+C or Ctrl+Break to cancel.", ConsoleColor.Cyan); Console.WriteLine("Statistics for generated vehicle telemetry data will be updated for every 500 sent"); Console.WriteLine(string.Empty); ThreadPool.SetMinThreads(100, 100); // Handle Control+C or Control+Break. Console.CancelKeyPress += (o, e) => { WriteLineInColor("Stopped generator. No more events are being sent.", ConsoleColor.Yellow); cancellationSource.Cancel(); // Allow the main thread to continue and exit... WaitHandle.Set(); OutputStatistics(statistics); }; // Initialize the telemetry generator: TelemetryGenerator.Init(); // Instantiate Cosmos DB client and start sending messages: using (_cosmosDbClient = new DocumentClient(cosmosDbConnectionString.ServiceEndpoint, cosmosDbConnectionString.AuthKey, connectionPolicy)) { InitializeCosmosDb().Wait(); // Find and output the collection details, including # of RU/s. var dataCollection = GetCollectionIfExists(DatabaseName, CollectionName); var offer = (OfferV2)_cosmosDbClient.CreateOfferQuery().Where(o => o.ResourceLink == dataCollection.SelfLink).AsEnumerable().FirstOrDefault(); if (offer != null) { var currentCollectionThroughput = offer.Content.OfferThroughput; WriteLineInColor($"Found collection `{CollectionName}` with {currentCollectionThroughput} RU/s ({currentCollectionThroughput} reads/second; {currentCollectionThroughput / 5} writes/second @ 1KB doc size)", ConsoleColor.Green); var estimatedCostPerMonth = 0.06 * offer.Content.OfferThroughput; var estimatedCostPerHour = estimatedCostPerMonth / (24 * 30); WriteLineInColor($"The collection will cost an estimated ${estimatedCostPerHour:0.00} per hour (${estimatedCostPerMonth:0.00} per month (per write region))", ConsoleColor.Green); } // Start sending data to Cosmos DB. SendData(100, taskWaitTime, cancellationToken, progress).Wait(); } cancellationSource.Cancel(); Console.WriteLine(); WriteLineInColor("Done sending generated vehicle telemetry data", ConsoleColor.Cyan); Console.WriteLine(); Console.WriteLine(); OutputStatistics(statistics); // Keep the console open. Console.ReadLine(); WaitHandle.WaitOne(); }
/// <summary> /// 格式化xml配置 /// </summary> /// <param name="persons"></param> /// <returns></returns> public static List <StatisticItem> GetStatisticItems(List <Person> persons, List <Skill> skills) { List <StatisticItem> list = new List <StatisticItem>(); IEnumerable <XElement> childList = from el in doc.Elements("Statistic") select el; int i = 0; foreach (XElement cl in childList) { i++; var info = new Statistic(); if (cl.Attribute("CacheKey") != null) { info.CacheKey = cl.Attribute("CacheKey").Value; } if (cl.Attribute("StatisticType") != null) { info.StatisticType = cl.Attribute("StatisticType").Value; } if (cl.Attribute("ObjectType") != null) { info.ObjectType = int.Parse(cl.Attribute("ObjectType").Value); } if (cl.Attribute("Uri") != null) { info.Uri = cl.Attribute("Uri").Value; } if (cl.Attribute("BaseReferenceId") != null) { info.BaseReferenceId = int.Parse(cl.Attribute("BaseReferenceId").Value); } info.Index = i; info.ClientName = "SDI2-" + info.Uri; if (info.CacheKey.StartsWith("skill/")) { var switchname = info.CacheKey.Substring("skill/".Length); var skillquery = skills.Where(x => x.SwitchName == switchname).ToList(); foreach (var skill in skillquery) { var item = new StatisticItem() { ObjectId = skill.Number + "@" + skill.SwitchName, DBID = skill.DBID, TypeID = 1 }; item.ReferenceId = item.DBID + info.BaseReferenceId; item.Statistic = info; list.Add(item); } } else if (info.CacheKey.StartsWith("agent/")) { if (persons != null) { foreach (var person in persons) { var item = new StatisticItem() { ObjectId = person.EmployeeID, DBID = person.DBID, TypeID = 2 }; item.ReferenceId = item.DBID + info.BaseReferenceId; item.Statistic = info; list.Add(item); } } } } return(list); }
/// <summary> /// Добавление модели /// </summary> public void AddModel(Vector[] vectors, string name) { Vector[] components = new Vector[vectors[0].N]; SModel sMode = new SModel(); sMode.NameClass = name; for (int i = 0; i < components.Length; i++) { components[i] = new Vector(vectors.Length); for (int j = 0; j < vectors.Length; j++) { components[i].Vecktor[j] = vectors[j].Vecktor[i]; } sMode.Add(new SModelComponent(Statistic.ExpectedValue(components[i]), Statistic.Sco(components[i]))); } models.Add(sMode); }
//function to remove from operation list when checkbox is unchecked private void OperationUnchecked(object sender, RoutedEventArgs e) { CheckBox uncheck = sender as CheckBox; Statistic.removeOperationID(uncheck.Name.ToString()); }
//function to add to operation list when checkbox is checked private void OperationChecked(object sender, RoutedEventArgs e) { CheckBox check = sender as CheckBox; Statistic.setOperationID(check.Name.ToString()); }
public void LoadFromFile() { if (!Directory.Exists(logPath_)) { return; } // 总流量统计文件 /// /// 文件结构 /// LastUpdate [date] [time] /// UP [readable string] [amount] /// DOWN [readable string] [amount] /// 每行每个数据空格分隔 try { var overallPath = Path.Combine(logPath_, Global.StatisticLogOverall); if (File.Exists(overallPath)) { using (var overallReader = new StreamReader(overallPath)) { while (!overallReader.EndOfStream) { var line = overallReader.ReadLine(); if (line.StartsWith("LastUpdate")) { } else if (line.StartsWith("UP")) { var datas = line.Split(' '); if (datas.Length < 3) { return; } TotalUp = ulong.Parse(datas[2]); } else if (line.StartsWith("DOWN")) { var datas = line.Split(' '); if (datas.Length < 3) { return; } TotalDown = ulong.Parse(datas[2]); } else if (line.StartsWith("*")) { var datas = line.Split(' '); if (datas.Length < 8) { return; } var name = datas[1]; var address = datas[2]; var port = int.Parse(datas[3]); var path = datas[4]; var host = datas[5]; var totalUp = ulong.Parse(datas[6]); var totalDown = ulong.Parse(datas[7]); var temp = new ServerStatistics(name, address, port, path, host, 0, 0, 0, 0); var index = Statistic.FindIndex(item => Utils.IsIdenticalServer(item, temp)); if (index != -1) { Statistic[index].totalUp = totalUp; Statistic[index].totalDown = totalDown; } else { var s = new Mode.ServerStatistics(name, address, port, path, host, totalUp, totalDown, 0, 0); Statistic.Add(s); } } } } } } catch (Exception ex) { Utils.SaveLog(ex.Message, ex); } try { // 当天流量记录文件 var dailyPath = Path.Combine(logPath_, $"{DateTime.Now.ToString("yyyy-MM-dd")}.txt"); if (File.Exists(dailyPath)) { using (var dailyReader = new StreamReader(dailyPath)) { while (!dailyReader.EndOfStream) { var line = dailyReader.ReadLine(); if (line.StartsWith("LastUpdate")) { } else if (line.StartsWith("*")) { var datas = line.Split(' '); if (datas.Length < 8) { return; } var name = datas[1]; var address = datas[2]; var port = int.Parse(datas[3]); var path = datas[4]; var host = datas[5]; var todayUp = ulong.Parse(datas[6]); var todayDown = ulong.Parse(datas[7]); var temp = new ServerStatistics(name, address, port, path, host, 0, 0, 0, 0); var index = Statistic.FindIndex(item => Utils.IsIdenticalServer(item, temp)); if (index != -1) { Statistic[index].todayUp = todayUp; Statistic[index].todayDown = todayDown; } else { var s = new Mode.ServerStatistics(name, address, port, path, host, 0, 0, todayUp, todayDown); Statistic.Add(s); } } } } } } catch (Exception ex) { Utils.SaveLog(ex.Message, ex); } }
public void Run() { while (!exitFlag_) { try { if (enabled_ && channel_.State == ChannelState.Ready) { QueryStatsResponse res = null; try { res = client_.QueryStats(new QueryStatsRequest() { Pattern = "", Reset = true }); } catch (Exception ex) { Utils.SaveLog(ex.Message, ex); } if (res != null) { var addr = config_.address(); var port = config_.port(); var path = config_.path(); var cur = Statistic.FindIndex(item => item.address == addr && item.port == port && item.path == path); ulong up = 0, down = 0; //TODO: parse output ParseOutput(res.Stat, out up, out down); Up = up; Down = down; TotalUp += up; TotalDown += down; if (cur != -1) { Statistic[cur].todayUp += up; Statistic[cur].todayDown += down; Statistic[cur].totalUp += up; Statistic[cur].totalDown += down; } if (UpdateUI) { updateFunc_(TotalUp, TotalDown, Up, Down, Statistic); } } } Thread.Sleep(config_.statisticsFreshRate); channel_.ConnectAsync(); } catch (Exception ex) { Utils.SaveLog(ex.Message, ex); } } }
protected override void OnModelCreating(ModelBuilder modelBuilder) { var user = new User { Id = 2, FirstName = "Ivan", SecondName = "Bad", Birthday = DateTime.Now, Email = "*****@*****.**", Password = "******", Role = "user" }; var admin = new User { Id = 1, FirstName = "Admin", SecondName = "admin", Birthday = DateTime.Now, Email = "*****@*****.**", Password = "******", Role = "admin" }; modelBuilder.Entity <User>().HasData(user); modelBuilder.Entity <User>().HasData(admin); var beeGarder = new BeeGarden { Id = 1, Name = "Bee Garden 1", Description = "Description Bee Garden 1", UserId = user.Id }; modelBuilder.Entity <BeeGarden>().HasData(beeGarder); var beehive = new Beehive { Id = 1, Name = "Beehive 1", Description = "Description Beehives 1", NumberOfTheFrames = 10, Type = "Dadan", RecommendedTemperature = 20, RecommendedHumidity = 60, YearOfTheQueenBee = 2020, BeeGardenId = beeGarder.Id }; modelBuilder.Entity <Beehive>().HasData(beehive); var beehive2 = new Beehive { Id = 2, Name = "Beehive 2", Description = "Description Beehives 2", NumberOfTheFrames = 12, Type = "Dadan", RecommendedTemperature = 25, RecommendedHumidity = 40, YearOfTheQueenBee = 2019, BeeGardenId = beeGarder.Id }; modelBuilder.Entity <Beehive>().HasData(beehive2); var statistics = new Statistic { Id = 1, DateTime = DateTime.Now, Temperature = 21.3, Humidity = 50, Weight = 85.7, Location = "49.82236707355737, 34.532303261131425", BeehiveId = beehive.Id }; modelBuilder.Entity <Statistic>().HasData(statistics); var statistics2 = new Statistic { Id = 2, DateTime = DateTime.Now, Temperature = 22.3, Humidity = 55, Weight = 80.7, Location = "48.82236707355737, 33.532303261131425", BeehiveId = beehive.Id }; modelBuilder.Entity <Statistic>().HasData(statistics2); var statistics3 = new Statistic { Id = 3, DateTime = DateTime.Now, Temperature = 30.3, Humidity = 70, Weight = 70.7, Location = "45.82236707355737, 31.532303261131425", BeehiveId = beehive.Id }; modelBuilder.Entity <Statistic>().HasData(statistics3); base.OnModelCreating(modelBuilder); }
public static void Tessellate(float minAngle, float maxAngle, float meshAreaFactor, float largestTriangleAreaFactor, int smoothIterations, IList <Vector2> vertices, IList <Edge> edges, IList <int> indices) { if (vertices.Count < 3) { return; } largestTriangleAreaFactor = Mathf.Clamp01(largestTriangleAreaFactor); var polygon = new Polygon(vertices.Count); for (int i = 0; i < vertices.Count; ++i) { Vector2 position = vertices[i]; polygon.Add(new Vertex(position.x, position.y, 1)); } for (int i = 0; i < edges.Count; ++i) { Edge edge = edges[i]; polygon.Add(new Segment(polygon.Points[edge.index1], polygon.Points[edge.index2])); } var mesh = polygon.Triangulate(); var statistic = new Statistic(); statistic.Update((UnityEngine.Experimental.U2D.TriangleNet.Mesh)mesh, 1); if (statistic.LargestArea < 0.01f) { throw new System.Exception("Invalid Mesh: Largest triangle area too small"); } var maxAreaToApply = (double)Mathf.Max((float)statistic.LargestArea * largestTriangleAreaFactor, (float)(statistic.MeshArea * meshAreaFactor)); var qualityOptions = new QualityOptions() { SteinerPoints = 0 }; if (maxAreaToApply > 0f) { qualityOptions.MaximumArea = maxAreaToApply; } qualityOptions.MinimumAngle = minAngle; qualityOptions.MaximumAngle = maxAngle; mesh.Refine(qualityOptions, false); mesh.Renumber(); if (smoothIterations > 0) { try { var smoother = new SimpleSmoother(); smoother.Smooth(mesh, smoothIterations); } catch (System.Exception) { Debug.Log(TextContent.smoothMeshError); } } vertices.Clear(); edges.Clear(); indices.Clear(); foreach (Vertex vertex in mesh.Vertices) { vertices.Add(new Vector2((float)vertex.X, (float)vertex.Y)); } foreach (ISegment segment in mesh.Segments) { edges.Add(new Edge(segment.P0, segment.P1)); } foreach (ITriangle triangle in mesh.Triangles) { int id0 = triangle.GetVertexID(0); int id1 = triangle.GetVertexID(1); int id2 = triangle.GetVertexID(2); if (id0 < 0 || id1 < 0 || id2 < 0 || id0 >= vertices.Count || id1 >= vertices.Count || id2 >= vertices.Count) { continue; } indices.Add(id0); indices.Add(id2); indices.Add(id1); } }
/// <summary> /// Gets the statistic per scenario for the specified unit. /// </summary> /// <param name="unit">A unit.</param> /// <param name="statistic">The statistic to use.</param> /// <returns> /// The statistic per scenario for the specified unit. /// </returns> public static IEnumerable <KeyValuePair <string, double> > GetPerScenario(Unit unit, Statistic statistic) { if (statistic == Statistic.KillRatio) { return(GetKillRatio(GetPerScenario(unit, Statistic.Kills), GetPerScenario(unit, Statistic.Losses))); } Func <Report, double> function = ReportFunctions[statistic]; return (unit.Reports.SelectByPrevious( first => new KeyValuePair <string, double>(first.ScenarioName, function(first)), (previous, current) => new KeyValuePair <string, double>(current.ScenarioName, (function(current) - function(previous))))); }
protected virtual void OnStatistic(StatisticStructure e) { Statistic?.Invoke(this, e); }
/// <summary> /// Gets the statistic progression for the specified unit. /// </summary> /// <param name="unit">A unit.</param> /// <param name="statistic">The statistic to use.</param> /// <returns> /// The statistic progression for the specified unit. /// </returns> public static IEnumerable <KeyValuePair <string, double> > GetProgression(Unit unit, Statistic statistic) { if (statistic == Statistic.KillRatio) { return(GetKillRatio(GetProgression(unit, Statistic.Kills), GetProgression(unit, Statistic.Losses))); } return (unit.Reports.Select( report => new KeyValuePair <string, double>(report.ScenarioName, ReportFunctions[statistic](report)))); }
public BeatmapPicker() { RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; Children = new Drawable[] { new FillFlowContainer { AutoSizeAxes = Axes.Y, RelativeSizeAxes = Axes.X, Direction = FillDirection.Vertical, Children = new Drawable[] { difficulties = new DifficultiesContainer { AutoSizeAxes = Axes.Both, Margin = new MarginPadding { Left = -(tile_icon_padding + tile_spacing / 2) }, OnLostHover = () => { showBeatmap(Beatmap.Value); starRating.FadeOut(100); }, }, new FillFlowContainer { AutoSizeAxes = Axes.Both, Margin = new MarginPadding { Top = 10 }, Spacing = new Vector2(5f), Children = new[] { version = new OsuSpriteText { Anchor = Anchor.BottomLeft, Origin = Anchor.BottomLeft, TextSize = 20, Font = @"Exo2.0-Bold", }, starRating = new OsuSpriteText { Anchor = Anchor.BottomLeft, Origin = Anchor.BottomLeft, TextSize = 13, Font = @"Exo2.0-Bold", Text = "Star Difficulty", Alpha = 0, Margin = new MarginPadding { Bottom = 1 }, }, }, }, new FillFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Spacing = new Vector2(10f), Margin = new MarginPadding { Top = 5 }, Children = new[] { plays = new Statistic(FontAwesome.fa_play_circle), favourites = new Statistic(FontAwesome.fa_heart), }, }, }, }, }; Beatmap.ValueChanged += b => { showBeatmap(b); updateDifficultyButtons(); }; }
/// <summary> /// Gets the total statistic per scenario. /// </summary> /// <param name="units">The units.</param> /// <param name="scenarioReports">The scenario reports.</param> /// <param name="statistic">The statistic.</param> /// <returns>The total statistic per scenario.</returns> public static IEnumerable <KeyValuePair <string, double> > GetTotalPerScenario(IEnumerable <UnitDecorator> units, IList <ScenarioReportDecorator> scenarioReports, Statistic statistic) { if (statistic == Statistic.KillRatio) { List <UnitDecorator> unitsList = units.ToList(); return(GetKillRatio(GetTotalPerScenario(unitsList, scenarioReports, Statistic.Kills), GetTotalPerScenario(unitsList, scenarioReports, Statistic.Losses))); } return (units.SelectMany(unit => GetPerScenario(unit, statistic)) .GroupBy(pair => pair.Key) .OrderBy( grouping => scenarioReports.IndexOf( scenarioReports.FirstOrDefault(report => report.ScenarioName == grouping.First().Key))) .Select( grouping => new KeyValuePair <string, double>(grouping.First().Key, grouping.Sum(pair => pair.Value)))); }
public void AddModifier(string statName, float modValue, StatModType type) { Statistic stat = character.GetStat(statName); stat.AddModifier(this, modValue, type); }
/// <summary> /// Gets the total statistic progression per scenario. /// </summary> /// <param name="units">The units.</param> /// <param name="scenarioReports">The scenario reports.</param> /// <param name="statistic">The statistic.</param> /// <returns></returns> /// <value> /// The total statistic progression per scenario. /// </value> public static IEnumerable <KeyValuePair <string, double> > GetTotalProgression(IEnumerable <UnitDecorator> units, IList <ScenarioReportDecorator> scenarioReports, Statistic statistic) { if (statistic == Statistic.KillRatio) { List <UnitDecorator> unitsList = units.ToList(); return(GetKillRatio(GetTotalProgression(unitsList, scenarioReports, Statistic.Kills), GetTotalProgression(unitsList, scenarioReports, Statistic.Losses))); } return (scenarioReports.Select( (scenarioReport, index) => new KeyValuePair <string, double>(scenarioReport.ScenarioName, HierarchyHelper.GetUnitReportIndices(units, scenarioReports) .Select( reports => reports.LastOrDefault(pair => pair.Key <= index) .Value) .Where(report => report != null) .Sum(report => ReportFunctions[statistic](report))))); }
public Statistic Delete(Statistic p) { return(_context.Statistics.Remove(p).Entity); }
/// <summary> /// Gets the average statistic per unit type. /// </summary> /// <param name="units">The units.</param> /// <param name="statistic">The statistic.</param> /// <returns></returns> /// <value> /// The average statistic per unit type. /// </value> public static IEnumerable <KeyValuePair <string, double> > GetAveragePerUnitType(IEnumerable <UnitDecorator> units, Statistic statistic) { if (statistic == Statistic.KillRatio) { List <UnitDecorator> unitsList = units.ToList(); return(GetKillRatio(GetAveragePerUnitType(unitsList, Statistic.Kills), GetAveragePerUnitType(unitsList, Statistic.Losses))); } return (units.OrderBy(unit => unit.Type.Value) .GroupBy(unit => unit.Type.Value) .Select( grouping => new KeyValuePair <string, double>(grouping.First().Type.Key, Math.Round( grouping.Average(unit => UnitFunctions[statistic](unit))))) .Reverse()); }
public Task <Statistic> Add(Statistic item) { return(Add <Statistic>(item)); }
public BaseUIData(IUExport[] exports, int baseIndex) : this() { if (exports[baseIndex].GetExport <TextProperty>("DisplayName") is TextProperty displayName) { DisplayName = Text.GetTextPropertyBase(displayName) ?? ""; } if (exports[baseIndex].GetExport <TextProperty>("Description") is TextProperty description) { Description = Text.GetTextPropertyBase(description) ?? ""; if (Description.Equals(DisplayName)) { Description = string.Empty; } if (!string.IsNullOrEmpty(Description)) { Height += (int)descriptionPaint.TextSize * Helper.SplitLines(Description, descriptionPaint, Width - Margin).Count; Height += (int)descriptionPaint.TextSize; } } if (exports[baseIndex].GetExport <ObjectProperty>("StoreFeaturedImage", "FullRender", "VerticalPromoImage", "LargeIcon", "DisplayIcon2", "DisplayIcon") is ObjectProperty icon) { SKBitmap raw = Utils.GetObjectTexture(icon); if (raw != null) { float coef = (float)Width / (float)raw.Width; int sizeX = (int)(raw.Width * coef); int sizeY = (int)(raw.Height * coef); Height += sizeY; IconImage = raw.Resize(sizeX, sizeY); } } if (exports[baseIndex].GetExport <MapProperty>("Abilities") is MapProperty abilities) { AdditionalWidth = 768; foreach (var(_, value) in abilities.Value) { if (value is ObjectProperty o && o.Value.Resource == null && o.Value.Index > 0) { Statistic s = new Statistic(); if (exports[o.Value.Index - 1].GetExport <TextProperty>("DisplayName") is TextProperty aDisplayName) { s.DisplayName = Text.GetTextPropertyBase(aDisplayName) ?? ""; } if (exports[o.Value.Index - 1].GetExport <TextProperty>("Description") is TextProperty aDescription) { s.Description = Text.GetTextPropertyBase(aDescription) ?? ""; if (!string.IsNullOrEmpty(Description)) { s.Height += (int)descriptionPaint.TextSize * Helper.SplitLines(s.Description, descriptionPaint, Width - Margin).Count; s.Height += (int)descriptionPaint.TextSize * 3; } } if (exports[o.Value.Index - 1].GetExport <ObjectProperty>("DisplayIcon") is ObjectProperty displayIcon) { SKBitmap raw = Utils.GetObjectTexture(displayIcon); if (raw != null) { s.Icon = raw.Resize(128, 128); } } Abilities.Add(s); } } } }
public PersonStatistics(string sessionId, int numberOfSamplesToTake, int ageQuants, int?ageQuantLevel) : base(sessionId, numberOfSamplesToTake, ageQuants, ageQuantLevel) { RelationshipStatistics = new RelationshipStatistics(numberOfSamplesToTake); SivilstatusStatistics = new SivilstatusStatistics(numberOfSamplesToTake); NameStatistics = ageQuantLevel.HasValue ? null : new NameStatistics(numberOfSamplesToTake); RegstatusStatistics = new RegstatusStatistics(numberOfSamplesToTake); AdressStatistics = ageQuantLevel.HasValue ? null : new AdressStatistics(numberOfSamplesToTake); RegStatus_Vs_PostalType = new DependentDiscreteStatistic(numberOfSamplesToTake, "RegStatus_Vs_PostalType", (p, a) => new Tuple <double?, double?>(p.RegStatus, AdressStatistics.GetCurrent(p.Addresses)?.PostalType)); CustomModels.Add("RelationshipStatistics", RelationshipStatistics); CustomModels.Add("SivilstatusStatistics", SivilstatusStatistics); CustomModels.Add("NameStatistics", NameStatistics); CustomModels.Add("RegstatusStatistics", RegstatusStatistics); CustomModels.Add("AdressStatistics", AdressStatistics); CustomModels.Add("RegStatus_Vs_PostalType", RegStatus_Vs_PostalType); Kjonn = new DiscreteStatistic(numberOfSamplesToTake, "Kjonn", CorrelationFactory, (p, a) => { if (NinModel.IsValidNin(p.NIN) && !CommonFunctions.HasDnummer(p.NIN)) { return(CommonFunctions.GetKjonn(p.NIN).Value); } return(Statistic.DontUpdateWhenThisValue); }); HasDnummer_Kjonn = new DiscreteStatistic(numberOfSamplesToTake, "HasDnummer_Kjonn", CorrelationFactory, (p, a) => { if (NinModel.IsValidNin(p.NIN) && CommonFunctions.HasDnummer(p.NIN)) { return(CommonFunctions.GetKjonn(p.NIN).Value); } return(Statistic.DontUpdateWhenThisValue); }); HasDnummer = new BooleanStatistic(numberOfSamplesToTake, PersonStatisticKeys.HasDnummer, CorrelationFactory, (p, a) => { if (NinModel.IsValidNin(p.NIN)) { return(CommonFunctions.HasDnummer(p.NIN) ? 1 : 0); } return(Statistic.DontUpdateWhenThisValue); }); Age = new Statistic(numberOfSamplesToTake, PersonStatisticKeys.Age, CorrelationFactory, (p, a) => p.DateOfBirth.HasValue? CommonFunctions.GetAge(p.DateOfBirth.Value).GetValue() : null); IsDead = new BooleanStatistic(numberOfSamplesToTake, PersonStatisticKeys.IsDead, CorrelationFactory, (p, a) => IsPersonDead(p)); IsUkjent = new BooleanStatistic(numberOfSamplesToTake, PersonStatisticKeys.IsUkjent, CorrelationFactory, (p, a) => HasUkjentRegCode(p)); //-1000 IsBosatt = new BooleanStatistic(numberOfSamplesToTake, PersonStatisticKeys.IsBosatt, CorrelationFactory, (p, a) => HasRegcode(p, 1)); //1 IsUtflyttet = new BooleanStatistic(numberOfSamplesToTake, PersonStatisticKeys.IsUtflyttet, CorrelationFactory, (p, a) => HasRegcode(p, 2)); //2 IsUtvandret = new BooleanStatistic(numberOfSamplesToTake, PersonStatisticKeys.IsUtvandret, CorrelationFactory, (p, a) => HasRegcode(p, 3)); //3 IsForsvunnet = new BooleanStatistic(numberOfSamplesToTake, PersonStatisticKeys.IsForsvunnet, CorrelationFactory, (p, a) => HasRegcode(p, 4)); //4 IsUtgaatFodselsnummer = new BooleanStatistic(numberOfSamplesToTake, PersonStatisticKeys.IsUtgaatFodselsnummer, CorrelationFactory, (p, a) => HasRegcode(p, 6)); //6 IsFodselsregistrert = new BooleanStatistic(numberOfSamplesToTake, PersonStatisticKeys.IsFodselsregistrert, CorrelationFactory, (p, a) => HasRegcode(p, 7)); //7 IsAnnullertTilgang = new BooleanStatistic(numberOfSamplesToTake, PersonStatisticKeys.IsAnnullertTilgang, CorrelationFactory, (p, a) => HasRegcode(p, 8)); //8 IsUregistrertTilgang = new BooleanStatistic(numberOfSamplesToTake, PersonStatisticKeys.IsUregistrertTilgang, CorrelationFactory, (p, a) => HasRegcode(p, 9)); //9 HasFirstname = new BooleanStatistic(numberOfSamplesToTake, PersonStatisticKeys.HasFirstname, CorrelationFactory, (p, a) => string.IsNullOrEmpty(p.GivenName) || string.IsNullOrWhiteSpace(p.GivenName) ? 0 : 1); HasLastname = new BooleanStatistic(numberOfSamplesToTake, PersonStatisticKeys.HasLastname, CorrelationFactory, (p, a) => string.IsNullOrEmpty(p.Sn) || string.IsNullOrWhiteSpace(p.Sn) ? 0 : 1); HasFather = new BooleanStatistic(numberOfSamplesToTake, PersonStatisticKeys.HasFather, CorrelationFactory, (p, a) => String.IsNullOrEmpty(p.FathersNIN) ? 0 : 1); HasMother = new BooleanStatistic(numberOfSamplesToTake, PersonStatisticKeys.HasMother, CorrelationFactory, (p, a) => String.IsNullOrEmpty(p.MothersNIN) ? 0 : 1); HasSpouse = new BooleanStatistic(numberOfSamplesToTake, PersonStatisticKeys.HasSpouse, CorrelationFactory, (p, a) => String.IsNullOrEmpty(p.SpouseNIN) ? 0 : 1); Citizenship_And_CitizenshipCode = new DiscreteStringStatistics(numberOfSamplesToTake, ageQuantLevel, PersonStatisticKeys.Citizenship_And_CitizenshipCode, CorrelationFactory, (p, a) => (string.IsNullOrEmpty(p.Citizenship) ? "null" : p.Citizenship) + "_" + (string.IsNullOrEmpty(p.CitizenshipCode) ? "null" : p.CitizenshipCode)); HasCitizenship = new BooleanStatistic(numberOfSamplesToTake, PersonStatisticKeys.HasCitizenship, CorrelationFactory, (p, a) => string.IsNullOrEmpty(p.Citizenship) ? 0 : 1); Custody = new DiscreteStringStatistics(numberOfSamplesToTake, ageQuantLevel, PersonStatisticKeys.Custody, CorrelationFactory, (p, a) => p.Custody); HasCustody = new BooleanStatistic(numberOfSamplesToTake, PersonStatisticKeys.HasCustody, CorrelationFactory, (p, a) => string.IsNullOrEmpty(p.Custody) ? 0 : 1); WithoutLegalCapacity = new DiscreteStringStatistics(numberOfSamplesToTake, ageQuantLevel, PersonStatisticKeys.WithoutLegalCapacity, CorrelationFactory, (p, a) => p.WithoutLegalCapacity); HasWithoutLegalCapacity = new BooleanStatistic(numberOfSamplesToTake, PersonStatisticKeys.HasWithoutLegalCapacity, CorrelationFactory, (p, a) => string.IsNullOrEmpty(p.WithoutLegalCapacity) ? 0 : 1); HasValidNin = new BooleanStatistic(numberOfSamplesToTake, PersonStatisticKeys.HasValidNin, CorrelationFactory, (p, a) => NinModel.IsValidNin(p.NIN) ? 1 : 0); HasDufNo = new BooleanStatistic(numberOfSamplesToTake, PersonStatisticKeys.HasDufNo, CorrelationFactory, (p, a) => string.IsNullOrEmpty(p.DufNo) ? 0 : 1); MaritalStatus = new DiscreteStatistic(numberOfSamplesToTake, PersonStatisticKeys.MaritalStatus, CorrelationFactory, (p, a) => p.MaritalStatus.GetValue()); HasOldNIN = new BooleanStatistic(numberOfSamplesToTake, PersonStatisticKeys.HasOldNIN, CorrelationFactory, (p, a) => string.IsNullOrEmpty(p.OldNIN) ? 0 : 1); HasNewNIN = new BooleanStatistic(numberOfSamplesToTake, PersonStatisticKeys.HasNewNIN, CorrelationFactory, (p, a) => string.IsNullOrEmpty(p.NewNIN) ? 0 : 1); ParentalResponsibility = new DiscreteStatistic(numberOfSamplesToTake, PersonStatisticKeys.ParentalResponsibility, CorrelationFactory, (p, a) => p.ParentalResponsibility.GetValue()); RegStatus = new DiscreteStatistic(numberOfSamplesToTake, PersonStatisticKeys.RegStatus, CorrelationFactory, (p, a) => p.RegStatus.GetValue()); StatusCountryCode = new DiscreteStatistic(numberOfSamplesToTake, PersonStatisticKeys.StatusCountryCode, CorrelationFactory, (p, a) => p.StatusCountryCode); HasStatusCountryCode = new BooleanStatistic(numberOfSamplesToTake, PersonStatisticKeys.HasStatusCountryCode, CorrelationFactory, (p, a) => p.StatusCountryCode.HasValue ? 1 : 0); WorkPermit = new DiscreteStringStatistics(numberOfSamplesToTake, ageQuantLevel, PersonStatisticKeys.WorkPermit, CorrelationFactory, (p, a) => p.WorkPermit); HasWorkPermit = new BooleanStatistic(numberOfSamplesToTake, PersonStatisticKeys.HasWorkPermit, CorrelationFactory, (p, a) => string.IsNullOrEmpty(p.WorkPermit) ? 0 : 1); PostalCode = new DiscreteStringStatistics(numberOfSamplesToTake, ageQuantLevel, PersonStatisticKeys.PostalCode, CorrelationFactory, (p, a) => p.Addresses != null && p.Addresses.Any() ? p.Addresses.First().PostalCode : null); HasPostalCode = new BooleanStatistic(numberOfSamplesToTake, PersonStatisticKeys.HasPostalCode, CorrelationFactory, (p, aa) => p.Addresses != null && p.Addresses.Any(a => a.CurrentAddress && !string.IsNullOrEmpty(a.PostalCode)) ? 1 : 0); DateWorkPermit = new DateStatistics(numberOfSamplesToTake, PersonStatisticKeys.DateWorkPermit, CorrelationFactory, (p, a) => new Tuple <string, DateTime?, DateTime?>(p.WorkPermit, p.DateWorkPermit, p.DateOfBirth)); DateParentalResponsibility = new DateStatistics(numberOfSamplesToTake, PersonStatisticKeys.DateParentalResponsibility, CorrelationFactory, (p, a) => new Tuple <string, DateTime?, DateTime?>(p.ParentalResponsibility?.ToString(), p.DateParentalResponsibility, p.DateOfBirth)); DateWithoutLegalCapacity = new DateStatistics(numberOfSamplesToTake, PersonStatisticKeys.DateWithoutLegalCapacity, CorrelationFactory, (p, a) => new Tuple <string, DateTime?, DateTime?>(p.WithoutLegalCapacity, p.DateWithoutLegalCapacity, p.DateOfBirth)); DateCustody = new DateStatistics(numberOfSamplesToTake, PersonStatisticKeys.DateCustody, CorrelationFactory, (p, a) => new Tuple <string, DateTime?, DateTime?>(p.Custody, p.DateCustody, p.DateOfBirth)); DateCitizenship = new DateStatistics(numberOfSamplesToTake, PersonStatisticKeys.DateCitizenship, CorrelationFactory, (p, a) => new Tuple <string, DateTime?, DateTime?>(p.Citizenship, p.DateCitizenship, p.DateOfBirth)); AddEntitiesToBaseDictionary <BooleanStatistic>(); AddEntitiesToBaseDictionary <DiscreteStringStatistics>(); AddEntitiesToBaseDictionary <DiscreteStatistic>(); AddEntitiesToBaseDictionary <DateStatistics>(); Statistics.Add(Age.Name, Age); }
public static void ProcessPong(PongMessage pongMessage) { statistic = new Statistic(statistic.Requests, statistic.Responses + 1); }
protected virtual string GetCompetitorNameText(int position) { return(Statistic.GetCompetitorNameText(position, Competitor)); }
public override void Run(string[] args) { base.Run(args); Validate(); rParser.Run(args); Statistic[] stat = new Statistic[rParser.MapCount + 1]; OpenSource(inputFolder); object data; int i = 0; List <Tuple <int, int, int> > temps = new List <Tuple <int, int, int> >(); Dictionary <Match, double> result = new Dictionary <Match, double>(); Console.WriteLine("Парсинг матчей"); int heroCount = 0; int lastMatchId = -1; while ((data = ReadData()) != null) { var r = ParseData(data); if (r.Item1 == -1) { continue; } if (lastMatchId == r.Item1) { continue; } temps.Add(ParseData(data)); i++; //собираем части воедино if (i == 10) { i = 0; bool flag = false; for (int j = 0; j < 9; j++) { if (temps[j].Item1 != temps[j + 1].Item1) { flag = true; break; } } if (flag == true) { temps.Clear(); continue; } Match m = new Match(); m.Map = rParser.ReplayResult[temps[0].Item1]; m.ProbabilityToWin = 1; int first_i = 0, second_i = 0; for (int j = 0; j < temps.Count; j++) { if (temps[j].Item3 == 1) { m.YourTeam[first_i++] = temps[j].Item2; } else { m.EnemyTeam[second_i++] = temps[j].Item2; } if (temps[j].Item2 > heroCount) { heroCount = temps[j].Item2; } } //обратное Match temp_m = new Match() { YourTeam = m.EnemyTeam, EnemyTeam = m.YourTeam, Map = m.Map }; //пробуем добавить //если запись уже есть if (result.ContainsKey(m)) { //усредняем вероятность double used = result[m]; double newer = m.ProbabilityToWin; double rez = (used + newer) / 2; result[m] = rez; Console.WriteLine(m.ToString() + " Уже существует"); } //если есть противоречие else if (result.ContainsKey(temp_m)) { //усредняем вероятность double used = result[m]; double newer = 1 - m.ProbabilityToWin; double rez = (used + newer) / 2; result[m] = rez; } else { result.Add(m, m.ProbabilityToWin); if (result.Count % 100000 == 0) { Console.WriteLine("Уже обработано " + result.Count); } } lastMatchId = temps.Last().Item1; temps.Clear(); } } Save(output, result, typeof(Dictionary <Match, double>)); for (int j = 0; j < stat.Length; j++) { stat[j] = new Statistic() { Statictic = new StatisticItem() { Matches = new int[heroCount + 1], Wins = new int[heroCount + 1] } }; } Console.WriteLine("Расчет статистики матчей"); ///считаем сколько матчей на каждой карте foreach (var it in rParser.ReplayResult) { stat[it.Value].Statictic.Ammount++; } //данные собраны,считаем статистику Console.WriteLine("Расчет статистики героев"); foreach (var it in result) { Match cur = it.Key; for (int j = 0; j < 5; j++) { stat[cur.Map].Statictic.Matches[cur.YourTeam[j]]++; stat[cur.Map].Statictic.Wins[cur.YourTeam[j]]++; } for (int j = 0; j < 5; j++) { stat[cur.Map].Statictic.Matches[cur.EnemyTeam[j]]++; } } File.WriteAllText(statisticOutput, JSonParser.Save(stat, typeof(Statistic[])), Encoding.Default); Console.WriteLine("Успешно спарсено " + result.Count + " записей"); }