public Unhash( NFSRaiderForm sender, HashFactory hashFactory, bool checkForHashesInFile, bool tryToBruteForce, string txtPrefixes, string txtSuffixes, string txtVariations, string txtWordsBetweenVariations, string txtMinVariations, string txtMaxVariations, string processorCount, GenerateOption generateOption, Endianness unhashingEndianness, CaseOptions caseOption) { Sender = sender; HashFactory = hashFactory; CaseOption = caseOption; Hashes = new HashSet <uint>(); Prefixes = new HashSet <string>(txtPrefixes.SplitBy(new[] { ',' }, '\\')); Suffixes = new HashSet <string>(txtSuffixes.SplitBy(new[] { ',' }, '\\')); WordsBetweenVariations = new HashSet <string>(txtWordsBetweenVariations.SplitBy(new[] { ',' }, '\\')); ProcessorCount = Convert.ToInt32(processorCount); VariationsGroups = new List <Variation>(); VariationModel = new Variation { MinVariations = Convert.ToInt32(txtMinVariations), MaxVariations = Convert.ToInt32(txtMaxVariations), GenerateOption = generateOption, }; UnhashingEndianness = unhashingEndianness; CheckForHashesInFile = checkForHashesInFile; TryToBruteForce = tryToBruteForce; InitializeVariatons(txtVariations.SplitBy(new[] { ',' }, '\\')); }
public void TestGetVariationSavesANewUserProfile() { Experiment experiment = ProjectConfig.Experiments[6]; Variation variation = experiment.Variations[0]; Decision decision = new Decision(variation.Id); UserProfile expectedUserProfile = new UserProfile(UserProfileId, new Dictionary <string, Decision> { { experiment.Id, decision } }); var mockBucketer = new Mock <Bucketer>(LoggerMock.Object); mockBucketer.Setup(m => m.Bucket(ProjectConfig, experiment, UserProfileId, UserProfileId)).Returns(variation); Dictionary <string, object> userProfile = null; UserProfileServiceMock.Setup(up => up.Lookup(UserProfileId)).Returns(userProfile); DecisionService decisionService = new DecisionService(mockBucketer.Object, ErrorHandlerMock.Object, ProjectConfig, UserProfileServiceMock.Object, LoggerMock.Object); Assert.IsTrue(TestData.CompareObjects(variation, decisionService.GetVariation(experiment, UserProfileId, new UserAttributes()))); UserProfileServiceMock.Verify(_ => _.Save(It.IsAny <Dictionary <string, object> >()), Times.Once); }
public async Task <Variation> Update(Variation Variation) { if (!await VariationValidator.Update(Variation)) { return(Variation); } try { var oldData = await UOW.VariationRepository.Get(Variation.Id); await UOW.Begin(); await UOW.VariationRepository.Update(Variation); await UOW.Commit(); var newData = await UOW.VariationRepository.Get(Variation.Id); await UOW.AuditLogRepository.Create(newData, oldData, nameof(VariationService)); return(newData); } catch (Exception ex) { await UOW.Rollback(); await UOW.SystemLogRepository.Create(ex, nameof(VariationService)); throw new MessageException(ex); } }
public ActionResult CreateVariation(VariationViewModel viewModel) { if (!ModelState.IsValid) { ModelState.AddModelError("", "VariationProblem"); return(View()); //Redirect tek nje error page } Variation variation = new Variation() { VariationCode = viewModel.VariationCode, DateReleased = DateTime.Now, Contract = viewModel.Contract, Location = viewModel.Location, Description = viewModel.Description, Comment = viewModel.Comment, Price = viewModel.Price, EOT = viewModel.EOT, Status = viewModel.Status, Claimed = viewModel.Claimed, Paid = viewModel.Paid, PaymentDate = DateTime.Now }; _context.Variations.Add(variation); _context.SaveChanges(); return(View()); }
/// <summary> /// Sends impression event. /// </summary> /// <param name="experiment">The experiment</param> /// <param name="variation">The variation entity</param> /// <param name="userId">The user ID</param> /// <param name="userAttributes">The user's attributes</param> /// <param name="flagKey">It can either be experiment key in case if ruleType is experiment or it's feature key in case ruleType is feature-test or rollout</param> /// <param name="ruleType">It can either be experiment in case impression event is sent from activate or it's feature-test or rollout</param> private void SendImpressionEvent(Experiment experiment, Variation variation, string userId, UserAttributes userAttributes, ProjectConfig config, string flagKey, string ruleType, bool enabled) { if (experiment != null && !experiment.IsExperimentRunning) { Logger.Log(LogLevel.ERROR, @"Experiment has ""Launched"" status so not dispatching event during activation."); } var userEvent = UserEventFactory.CreateImpressionEvent(config, experiment, variation, userId, userAttributes, flagKey, ruleType, enabled); if (userEvent == null) { return; } EventProcessor.Process(userEvent); if (experiment != null) { Logger.Log(LogLevel.INFO, $"Activating user {userId} in experiment {experiment.Key}."); } // Kept For backwards compatibility. // This notification is deprecated and the new DecisionNotifications // are sent via their respective method calls. if (NotificationCenter.GetNotificationCount(NotificationCenter.NotificationType.Activate) > 0) { var impressionEvent = EventFactory.CreateLogEvent(userEvent, Logger); NotificationCenter.SendNotifications(NotificationCenter.NotificationType.Activate, experiment, userId, userAttributes, variation, impressionEvent); } }
/// <summary> /// Speichert die Variation /// </summary> /// <param name="variation"></param> public void Save(Variation variation) { GraphClient.Cypher.Match("".Variation("v")) .Where((Variation v) => v.Id == variation.Id) .Set("v.Name={Name}").WithParam("Name", variation.Name) .ExecuteWithoutResults(); }
/// <summary> /// Get the variation the user has been whitelisted into. /// </summary> /// <param name = "experiment" >in which user is to be bucketed.</param> /// <param name = "userId" > User Identifier</param> /// <returns>if the user is not whitelisted into any variation {@link Variation} /// the user is bucketed into if the user has a specified whitelisted variation.</returns> public Variation GetWhitelistedVariation(Experiment experiment, string userId) { //if a user has a forced variation mapping, return the respective variation Dictionary <string, string> userIdToVariationKeyMap = experiment.UserIdToKeyVariations; if (!userIdToVariationKeyMap.ContainsKey(userId)) { return(null); } string forcedVariationKey = userIdToVariationKeyMap[userId]; Variation forcedVariation = experiment.VariationKeyToVariationMap.ContainsKey(forcedVariationKey) ? experiment.VariationKeyToVariationMap[forcedVariationKey] : null; if (forcedVariation != null) { Logger.Log(LogLevel.INFO, string.Format("User \"{0}\" is forced in variation \"{1}\".", userId, forcedVariationKey)); } else { Logger.Log(LogLevel.ERROR, string.Format("Variation \"{0}\" is not in the datafile. Not activating user \"{1}\".", forcedVariationKey, userId)); } return(forcedVariation); }
public GwentCard(GwentCardData data) { CardData = data; Category = new Category(); foreach (var item in CardData.Categories) { if (item.Key == "href") { Category.Href = item.Value; } else if (item.Key == "name") { Category.Name = item.Value; } } Variations = new Variation(); foreach (var item in CardData.Variations) { if (item.Key == "href") { Variations.Href = item.Value; } else if (item.Key == "availability") { Variations.Availability = item.Value; } else if (item.Key == "rarity") { Variations.Rarity = new Rarity() { Href = item.Value }; } } }
public void ActivateGenetics() { if (geneticsState.currentPopulation != null) { ResumeGenetics(); return; } FindObjectOfType <UserSettings>().OnParamsChanged += OnUserSkillIncreased; currentBotSkillPoints = baseBotSkillPoints; prevLastGivenVariationFitness = float.NaN; Population firstPopulation = GetFirstPopulation(); CalcFitnessValues(firstPopulation); float maxFitnessValue = float.MinValue; for (int i = 0; i < firstPopulation.variations.Length; i++) { if (firstPopulation.variations[i].fitnessValue > maxFitnessValue) { currentBestVariation = firstPopulation.variations[i]; maxFitnessValue = currentBestVariation.fitnessValue; } } geneticsState.currentPopulation = firstPopulation; geneticsState.stop = false; System.Threading.ThreadPool.QueueUserWorkItem(CalculateGenetics, geneticsState); }
public static void GenerateNounVariations(Variation variation, List <Variation> variations) { Match match = NameTools.OptionalWordPartRegex.Match(variation.Text); if (!match.Success) { variations.Add(variation); return; } string v1Str = variation.Text.Replace(match.Value, string.Empty); string v2Str = variation.Text.Replace(match.Value, match.Groups["word"].Value); Variation v1 = new Variation(v1Str, variation.Tags); Variation v2 = new Variation(v2Str, variation.Tags); if (match.Groups["tags"].Success) { if (string.IsNullOrEmpty(v2.Tags)) { v2.Tags = match.Groups["tags"].Value; } else { v2.Tags += "," + match.Groups["tags"].Value; } } GenerateNounVariations(v1, variations); GenerateNounVariations(v2, variations); }
private Variation[] SelectParents(Population population) { int maxParents = parentsAmount < population.variations.Length ? parentsAmount : population.variations.Length; Variation[] retval = new Variation[maxParents]; List <Variation> variations = new List <Variation>(population.variations); for (int i = 0; i < maxParents; i++) { int maxInd = 0; float maxFitness = float.MinValue; for (int j = 0; j < variations.Count; j++) { Variation variation = variations[j]; if (variation.fitnessValue > maxFitness) { maxFitness = variation.fitnessValue; maxInd = j; } } retval[i] = variations[maxInd]; variations.RemoveAt(maxInd); } return(retval); }
/// <summary> /// Save from Gesture struct /// </summary> /// <param name="name"></param> /// <param name="boneOrder"></param> /// <param name="worldPose"></param> /// <param name="relativePose"></param> public SkeletonV1(string name, HumanBodyBones[] boneOrder, Pose[] worldPose, Pose[] relativePose) { this.variation = Variation.skeletonv1posture; this.name = name; this.hasSkeleton = true; this.centerOffset = Vector3.zero; this.overallConf = 1f; this.upperConf = 1f; this.lowerConf = 1f; this.distanceShoulder = Vector3.zero; var arr = new List <Joint>(); int relativePoseTypeShift = 50; for (int i = 0; i < boneOrder.Length; i++) { var jt = new Joint(); jt.type = (int)boneOrder[i]; jt.conf = 1f; jt.pos = worldPose[i].position; jt.rot = worldPose[i].rotation; arr.Add(jt); var jt2 = new Joint(); jt2.type = (int)boneOrder[i] + relativePoseTypeShift; jt2.conf = 1f; jt2.pos = relativePose[i].position; jt2.rot = relativePose[i].rotation; arr.Add(jt2); } this.joints = arr.ToArray(); }
public VariationViewModel(Variation variation) { _variation = variation; _colorHex = variation.ColorHex; _image = variation.Image; IsSelected = false; }
public async Task <Variation> CreateAsync(Variation newVariation) { _variationRepository.Add(newVariation); await _variationRepository.SaveChangesAsync(); return(newVariation); }
public void TestBucketLogsCorrectlyWhenUserProfileFailsToSave() { Experiment experiment = ProjectConfig.Experiments[6]; Variation variation = experiment.Variations[0]; Decision decision = new Decision(variation.Id); Bucketer bucketer = new Bucketer(LoggerMock.Object); UserProfileServiceMock.Setup(up => up.Save(It.IsAny <Dictionary <string, object> >())).Throws(new System.Exception()); var experimentBucketMap = new Dictionary <string, Decision>(); experimentBucketMap[experiment.Id] = decision; UserProfile expectedUserProfile = new UserProfile(UserProfileId, experimentBucketMap); UserProfile saveUserProfile = new UserProfile(UserProfileId, new Dictionary <string, Decision>()); DecisionService decisionService = new DecisionService(bucketer, ErrorHandlerMock.Object, ProjectConfig, UserProfileServiceMock.Object, LoggerMock.Object); decisionService.SaveVariation(experiment, variation, saveUserProfile); LoggerMock.Verify(l => l.Log(LogLevel.ERROR, string.Format ("Failed to save variation \"{0}\" of experiment \"{1}\" for user \"{2}\".", variation.Id, experiment.Id, UserProfileId)) , Times.Once); ErrorHandlerMock.Verify(er => er.HandleError(It.IsAny <OptimizelySDK.Exceptions.OptimizelyRuntimeException>()), Times.Once); }
/// <summary> /// Get the variation if the user is bucketed for one of the experiments on this feature flag. /// </summary> /// <param name = "featureFlag" >The feature flag the user wants to access.</param> /// <param name = "userId" >User Identifier</param> /// <param name = "filteredAttributes" >The user's attributes. This should be filtered to just attributes in the Datafile.</param> /// <returns>null if the user is not bucketed into the rollout or if the feature flag was not attached to a rollout. /// Otherwise the FeatureDecision entity</returns> public virtual Result <FeatureDecision> GetVariationForFeatureExperiment(FeatureFlag featureFlag, OptimizelyUserContext user, UserAttributes filteredAttributes, ProjectConfig config, OptimizelyDecideOption[] options) { var reasons = new DecisionReasons(); var userId = user.GetUserId(); if (featureFlag == null) { Logger.Log(LogLevel.ERROR, "Invalid feature flag provided."); return(Result <FeatureDecision> .NullResult(reasons)); } if (featureFlag.ExperimentIds == null || featureFlag.ExperimentIds.Count == 0) { Logger.Log(LogLevel.INFO, reasons.AddInfo($"The feature flag \"{featureFlag.Key}\" is not used in any experiments.")); return(Result <FeatureDecision> .NullResult(reasons)); } foreach (var experimentId in featureFlag.ExperimentIds) { var experiment = config.GetExperimentFromId(experimentId); Variation decisionVariation = null; if (string.IsNullOrEmpty(experiment.Key)) { continue; } var forcedDecisionResponse = user.FindValidatedForcedDecision( new OptimizelyDecisionContext(featureFlag.Key, experiment?.Key), config); reasons += forcedDecisionResponse.DecisionReasons; if (forcedDecisionResponse?.ResultObject != null) { decisionVariation = forcedDecisionResponse.ResultObject; } else { var decisionResponse = GetVariation(experiment, user, config, options); reasons += decisionResponse?.DecisionReasons; decisionVariation = decisionResponse.ResultObject; } if (!string.IsNullOrEmpty(decisionVariation?.Id)) { Logger.Log(LogLevel.INFO, reasons.AddInfo($"The user \"{userId}\" is bucketed into experiment \"{experiment.Key}\" of feature \"{featureFlag.Key}\".")); var featureDecision = new FeatureDecision(experiment, decisionVariation, FeatureDecision.DECISION_SOURCE_FEATURE_TEST); return(Result <FeatureDecision> .NewResult(featureDecision, reasons)); } } Logger.Log(LogLevel.INFO, reasons.AddInfo($"The user \"{userId}\" is not bucketed into any of the experiments on the feature \"{featureFlag.Key}\".")); return(Result <FeatureDecision> .NullResult(reasons)); }
public ComponentsModel(int id, ComponentListMode mode) { if (mode == ComponentListMode.Variation) { Variation variation = Database.GetVariation(id); foreach (Component component in variation.Components.Values) { ComponentModel newComponentModel = new ComponentModel(component); componentModels.Add(newComponentModel); } componentModels.Sort(); } else { Component component = Database.GetComponent(id); foreach (Component subComponent in component.Components.Values) { ComponentModel newComponentModel = new ComponentModel(subComponent); componentModels.Add(newComponentModel); } componentModels.Sort(); } }
public async Task <IActionResult> Edit(int id, [Bind("Id,Code,Title")] Variation variation) { if (id != variation.Id) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(variation); await _context.SaveChangesAsync(); var user = _userManger.GetUserName(HttpContext.User); logger.Info(user + " edited to " + variation.Title); } catch (DbUpdateConcurrencyException) { if (!VariationExists(variation.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction("Index")); } return(View(variation)); }
/// <summary> /// Get the variation the user has been whitelisted into. /// </summary> /// <param name = "experiment" >in which user is to be bucketed.</param> /// <param name = "userId" > User Identifier</param> /// <param name = "reasons" > Decision log messages.</param> /// <returns>if the user is not whitelisted into any variation {@link Variation} /// the user is bucketed into if the user has a specified whitelisted variation.</returns> public Result <Variation> GetWhitelistedVariation(Experiment experiment, string userId) { var reasons = new DecisionReasons(); //if a user has a forced variation mapping, return the respective variation Dictionary <string, string> userIdToVariationKeyMap = experiment.UserIdToKeyVariations; if (!userIdToVariationKeyMap.ContainsKey(userId)) { return(Result <Variation> .NullResult(reasons)); } string forcedVariationKey = userIdToVariationKeyMap[userId]; Variation forcedVariation = experiment.VariationKeyToVariationMap.ContainsKey(forcedVariationKey) ? experiment.VariationKeyToVariationMap[forcedVariationKey] : null; if (forcedVariation != null) { Logger.Log(LogLevel.INFO, reasons.AddInfo($"User \"{userId}\" is forced in variation \"{forcedVariationKey}\".")); } else { Logger.Log(LogLevel.ERROR, reasons.AddInfo($"Variation \"{forcedVariationKey}\" is not in the datafile. Not activating user \"{userId}\".")); } return(Result <Variation> .NewResult(forcedVariation, reasons)); }
private void ChangeInVariation(Variation variation, Unit[,] newFillArray, bool state) { foreach (var item in variation.VariationPoints) { newFillArray[(int)item.X, (int)item.Y].IsInVariation = state; } }
public void TestGetVariationEvaluatesUserProfileBeforeAudienceTargeting() { Experiment experiment = ProjectConfig.Experiments[8]; Variation variation = experiment.Variations[0]; Decision decision = new Decision(variation.Id); UserProfile userProfile = new UserProfile(UserProfileId, new Dictionary <string, Decision> { { experiment.Id, decision } }); UserProfileServiceMock.Setup(up => up.Lookup(WhitelistedUserId)).Returns(userProfile.ToMap()); DecisionService decisionService = new DecisionService(BucketerMock.Object, ErrorHandlerMock.Object, ProjectConfig, UserProfileServiceMock.Object, LoggerMock.Object); decisionService.GetVariation(experiment, GenericUserId, new UserAttributes()); LoggerMock.Verify(l => l.Log(LogLevel.INFO, string.Format("User \"{0}\" does not meet conditions to be in experiment \"{1}\".", GenericUserId, experiment.Key)), Times.Once); // ensure that a user with a saved user profile, sees the same variation regardless of audience evaluation decisionService.GetVariation(experiment, UserProfileId, new UserAttributes()); BucketerMock.Verify(_ => _.Bucket(It.IsAny <ProjectConfig>(), It.IsAny <Experiment>(), It.IsAny <string>(), It.IsAny <string>()), Times.Never); }
/// <summary> /// Sends impression event. /// </summary> /// <param name="experiment">The experiment</param> /// <param name="variationId">The variation entity</param> /// <param name="userId">The user ID</param> /// <param name="userAttributes">The user's attributes</param> private void SendImpressionEvent(Experiment experiment, Variation variation, string userId, UserAttributes userAttributes) { if (experiment.IsExperimentRunning) { var impressionEvent = EventBuilder.CreateImpressionEvent(Config, experiment, variation.Id, userId, userAttributes); Logger.Log(LogLevel.INFO, string.Format("Activating user {0} in experiment {1}.", userId, experiment.Key)); Logger.Log(LogLevel.DEBUG, string.Format("Dispatching impression event to URL {0} with params {1}.", impressionEvent.Url, impressionEvent.GetParamsAsJson())); try { EventDispatcher.DispatchEvent(impressionEvent); } catch (Exception exception) { Logger.Log(LogLevel.ERROR, string.Format("Unable to dispatch impression event. Error {0}", exception.Message)); } NotificationCenter.SendNotifications(NotificationCenter.NotificationType.Activate, experiment, userId, userAttributes, variation, impressionEvent); } else { Logger.Log(LogLevel.ERROR, @"Experiment has ""Launched"" status so not dispatching event during activation."); } }
public Game(Variation variation, AlgorithmType algorithmType) : this() { Variation = variation; AlgorithmType = algorithmType; Initialize(); }
public async Task <bool> Delete(Variation Variation) { if (await ValidateId(Variation)) { } return(Variation.IsValidated); }
public void SelectVariation(int selectIndex) { if (SelectedGrade == null) { throw new ArgumentException("Wenn diese Methode aufgerufen wird, kann die ausgewählte Note(Grade) nicht null sein."); } if (selectIndex == -1) { SelectedVariation = null; SelectedVariationBackup = null; } else if (selectIndex < 0 || selectIndex >= SelectedGrade.Variations.Count) { throw new IndexOutOfRangeException("Der Index liegt nicht in den auswählbaren Varianten(Variation)."); } else { SelectedVariation = SelectedGrade.Variations[selectIndex]; SelectedVariationBackup = SelectedGrade.Variations[selectIndex].CreateBackup();; } if (Viewstate != ViewState.IsRefreshing) { view.RefreshView(); } }
/// <summary> /// Save a { @link Variation } of an { @link Experiment } for a user in the {@link UserProfileService}. /// </summary> /// <param name = "experiment" > The experiment the user was buck</param> /// <param name = "variation" > The Variation to save.</param> /// <param name = "userProfile" > instance of the user information.</param> public void SaveVariation(Experiment experiment, Variation variation, UserProfile userProfile) { //only save if the user has implemented a user profile service if (UserProfileService == null) { return; } Decision decision; if (userProfile.ExperimentBucketMap.ContainsKey(experiment.Id)) { decision = userProfile.ExperimentBucketMap[experiment.Id]; decision.VariationId = variation.Id; } else { decision = new Decision(variation.Id); } userProfile.ExperimentBucketMap[experiment.Id] = decision; try { UserProfileService.Save(userProfile.ToMap()); Logger.Log(LogLevel.INFO, string.Format("Saved variation \"{0}\" of experiment \"{1}\" for user \"{2}\".", variation.Id, experiment.Id, userProfile.UserId)); } catch (Exception exception) { Logger.Log(LogLevel.ERROR, string.Format("Failed to save variation \"{0}\" of experiment \"{1}\" for user \"{2}\".", variation.Id, experiment.Id, userProfile.UserId)); ErrorHandler.HandleError(new Exceptions.OptimizelyRuntimeException(exception.Message)); } }
public void TestCreateAndGetAll() { ICountryDao countryDao = new CountryDao(_graphClient); Country country = new Country() {Name = "D"}; countryDao.Create(country); IRoutesDao routeDao = new RouteDao(_graphClient); Route route = new Route() {Name = "Route1"}; routeDao.CreateIn(country, route); IDifficultyLevelScaleDao scaleDao = new DifficultyLevelScaleDao(_graphClient); DifficultyLevelScale scale = new DifficultyLevelScale() {Name = "sächsisch"}; scaleDao.Create(scale); IDifficultyLevelDao levelDao = new DifficultyLevelDao(_graphClient); DifficultyLevel level = new DifficultyLevel() {Name = "7b"}; levelDao.Create(scale, level); IVariationDao variationDao = new VariationDao(_graphClient); Variation variation = new Variation() {Name = "Ein Weg der Route1 als 7b"}; Variation created = variationDao.Create(variation, route, level); IList<Variation> variationsOnRoute = variationDao.GetAllOn(route); Assert.AreEqual(1, variationsOnRoute.Count); Assert.AreEqual(variation.Name, variationsOnRoute.First().Name); Assert.AreEqual(variation.Id, variationsOnRoute.First().Id); Assert.AreEqual(created.Id, variationsOnRoute.First().Id); }
public VariationModel(Variation variation) { this.id = variation.Id; this.parentId = variation.ParentId; this.name = variation.Name; this.position = variation.Position; }
public async Task <Variation> Delete(Variation Variation) { if (!await VariationValidator.Delete(Variation)) { return(Variation); } try { await UOW.Begin(); await UOW.VariationRepository.Delete(Variation); await UOW.Commit(); await UOW.AuditLogRepository.Create("", Variation, nameof(VariationService)); return(Variation); } catch (Exception ex) { await UOW.Rollback(); await UOW.SystemLogRepository.Create(ex, nameof(VariationService)); throw new MessageException(ex); } }
public void TestGetVariationSavesBucketedVariationIntoUserProfile() { Experiment experiment = ProjectConfig.Experiments[6]; Variation variation = experiment.Variations[0]; Decision decision = new Decision(variation.Id); UserProfile originalUserProfile = new UserProfile(UserProfileId, new Dictionary <string, Decision>()); UserProfileServiceMock.Setup(ups => ups.Lookup(UserProfileId)).Returns(originalUserProfile.ToMap()); UserProfile expectedUserProfile = new UserProfile(UserProfileId, new Dictionary <string, Decision> { { experiment.Id, decision } }); var mockBucketer = new Mock <Bucketer>(LoggerMock.Object); mockBucketer.Setup(m => m.Bucket(ProjectConfig, experiment, UserProfileId, UserProfileId)).Returns(variation); DecisionService decisionService = new DecisionService(mockBucketer.Object, ErrorHandlerMock.Object, ProjectConfig, UserProfileServiceMock.Object, LoggerMock.Object); Assert.IsTrue(TestData.CompareObjects(variation, decisionService.GetVariation(experiment, UserProfileId, new UserAttributes()))); LoggerMock.Verify(l => l.Log(LogLevel.INFO, string.Format("Saved variation \"{0}\" of experiment \"{1}\" for user \"{2}\".", variation.Id, experiment.Id, UserProfileId)), Times.Once); UserProfileServiceMock.Verify(_ => _.Save(It.IsAny <Dictionary <string, object> >()), Times.Once); }
private bool Delete() { bool boRetValue = false; string stIDs = ""; foreach (DataListItem item in lstItem.Items) { HtmlInputCheckBox chkList = (HtmlInputCheckBox)item.FindControl("chkList"); if (chkList != null) { if (chkList.Checked == true) { stIDs += chkList.Value + ","; boRetValue = true; } } } if (boRetValue) { Variation clsVariation = new Variation(); clsVariation.Delete(stIDs.Substring(0, stIDs.Length - 1)); clsVariation.CommitAndDispose(); } return(boRetValue); }
/// <summary> /// Speichert die Variation /// </summary> /// <param name="variation"></param> public void Save(Variation variation) { GraphClient.Cypher.Match("".Variation("v")) .Where((Variation v)=>v.Id == variation.Id) .Set("v.Name={Name}").WithParam("Name", variation.Name) .ExecuteWithoutResults(); }
/// <summary> /// Löscht eine Variation, wenn diese nicht mehr verwendet wird. /// </summary> /// <param name="variation"></param> public void Delete(Variation variation) { if (variation == null) throw new ArgumentNullException(nameof(variation)); if (_variationDao.IsInUse(variation)) { throw new NodeInUseException(); } _variationDao.Delete(variation); }
/// <summary> /// Liefert das verwendete <see cref="DifficultyLevel" /> an einer <see cref="Variation" /> /// </summary> /// <param name="variation"></param> /// <returns></returns> public DifficultyLevel GetLevelOnVariation(Variation variation) { string match = "".Variation("v").Has().DifficultyLevel("dl"); return GraphClient.Cypher.Match(match) .Where((Variation v) => v.Id == variation.Id) .Return(dl => dl.As<DifficultyLevel>()) .Results.First(); }
/// <summary> /// Löscht die Variation, wenn diese nicht mehr verwendet wird. /// </summary> /// <param name="variation"></param> public void Delete(Variation variation) { if (variation == null) throw new ArgumentNullException(nameof(variation)); if (IsInUse(variation)) { throw new NodeInUseException(); } GraphClient.Cypher.Match("".Route().AnyOutboundRelationAs("routeAssignment").Variation("v").AnyOutboundRelationAs("levelAssignment").DifficultyLevel()) .Where((Variation v)=>v.Id == variation.Id).Delete("v, levelAssignment, routeAssignment").ExecuteWithoutResults(); }
/// <summary> /// Erstellt eine neue Variation einer Route zu einer bestimmen Schwierigkeit /// </summary> public Variation Create(Variation variation, Route route, DifficultyLevel difficultyLevel) { var query = GraphClient.Cypher .Match("(r:Route),(dl:DifficultyLevel)") .Where((Route r, DifficultyLevel dl) => r.Id == route.Id && dl.Id == difficultyLevel.Id) .Create("".Node("r").Has().VariationWithParam().Has().Node("dl")) .WithParam("variation", variation); return query.Return(v => v.As<Variation>()).Results.First(); }
public void TestCreateWithSomeMissing(bool useVariation, string name) { Variation fakeVariation = null; if (useVariation) { fakeVariation = new Variation(); } Mock<ILogEntryDao> logEntryDaoMock = new Mock<ILogEntryDao>(); new LogEntryService(logEntryDaoMock.Object).Create(fakeVariation, DateTime.Today, name); }
/// <summary> /// Erstellt einen neuen Logeintrag einer Variation /// </summary> public LogEntry Create(Variation variation, LogEntry logEntry) { ICypherFluentQuery query = GraphClient.Cypher .Match("".Variation("v")) .Where((Variation v) => v.Id == variation.Id) .Create("".Node("v").Has().LogEntryWithParam()) .WithParam("logEntry", logEntry); return query.Return(le=>le.As<LogEntry>()).Results.First(); }
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) { // We put the selected variation in session and redirect user to EditVariation page Variation v = new Variation(); v.Number = GridView1.SelectedRow.Cells[1].Text; v.Discipline = Server.HtmlDecode(GridView1.SelectedRow.Cells[7].Text); v.Description = Server.HtmlDecode(GridView1.SelectedRow.Cells[8].Text); v.Completed = ((CheckBox)GridView1.SelectedRow.Cells[9].Controls[0]).Checked; HttpContext.Current.Session.Add("currentVariation", v); HttpContext.Current.Response.Redirect("./EditVariation.aspx"); }
public void TestCreate() { Mock<ILogEntryDao> logDaoMock = new Mock<ILogEntryDao>(); logDaoMock.Setup(x => x.Create(It.IsAny<Variation>(), It.IsAny<LogEntry>())); Variation fakeVariation = new Variation(); ILogEntryService logService = new LogEntryService(logDaoMock.Object); logService.Create(fakeVariation, DateTime.Today, "freeclimb"); logDaoMock.Verify(x=>x.Create(fakeVariation, It.Is<LogEntry>(y=>y.Memo == "freeclimb" && y.DateTime == DateTime.Today)), Times.Once); }
public void TestGetAll() { Mock<ILogEntryDao> logDaoMock = new Mock<ILogEntryDao>(); logDaoMock.Setup(x => x.GetAllIn(It.IsAny<Variation>())).Returns(new List<LogEntry> {new LogEntry()}); Variation fakeVariation = new Variation(); ILogEntryService logService = new LogEntryService(logDaoMock.Object); IList<LogEntry> logsInVariation = logService.GetAllIn(fakeVariation); Assert.AreEqual(1, logsInVariation.Count); logDaoMock.Verify(x=>x.GetAllIn(fakeVariation), Times.Once); }
public void TestChangeDifficultyLevel() { Mock<IVariationDao> variationDaoMock = new Mock<IVariationDao>(); variationDaoMock.Setup(x => x.ChangeDifficultyLevel(It.IsAny<Variation>(), It.IsAny<DifficultyLevel>())); Variation variation = new Variation(); DifficultyLevel newLevel = new DifficultyLevel(); IVariationService variationService = new VariationService(variationDaoMock.Object); variationService.ChangeDifficultyLevel(variation, newLevel); variationDaoMock.Verify(x => x.ChangeDifficultyLevel(variation, newLevel), Times.Once); }
public void TestDelete(bool isInUse) { Mock<IVariationDao> variationDaoMock = new Mock<IVariationDao>(); variationDaoMock.Setup(x => x.IsInUse(It.IsAny<Variation>())).Returns(isInUse); variationDaoMock.Setup(x => x.Delete(It.IsAny<Variation>())); Variation variation = new Variation(); IVariationService service = new VariationService(variationDaoMock.Object); service.Delete(variation); variationDaoMock.Verify(x => x.IsInUse(variation), Times.Once); variationDaoMock.Verify(x => x.Delete(variation), Times.Once); }
public static double[] GetCoefficients(Variation Variation) { int suits = Variation.NumberOfSuits; switch (Variation.NumberOfSuits) { case 1: return OneSuitCoefficients; case 2: return TwoSuitCoefficients; case 4: return FourSuitCoefficients; default: throw new Exception("invalid number of suits"); } }
public void TestChangeDifficultyLevelWithNull(bool variationExists, bool levelExists) { Variation variation = null; DifficultyLevel level = null; if (variationExists) { variation = new Variation(); } if (levelExists) { level = new DifficultyLevel(); } Action action = () => new VariationService(null).ChangeDifficultyLevel(variation, level); action.ShouldThrow<ArgumentNullException>(); }
public void TestGetForVariation() { DifficultyLevel level = new DifficultyLevel(); Mock<IDifficultyLevelDao> difficultyLevelDaoMock = new Mock<IDifficultyLevelDao>(); difficultyLevelDaoMock.Setup(x => x.GetLevelOnVariation(It.IsAny<Variation>())).Returns(level); Variation variation = new Variation(); IDifficultyLevelService difficultyLevelService = new DifficultyLevelService(difficultyLevelDaoMock.Object); DifficultyLevel levelForVariation = difficultyLevelService.GetForVariation(variation); levelForVariation.Should().NotBeNull(); levelForVariation.Id.Should().Be(level.Id); difficultyLevelDaoMock.Verify(x=>x.GetLevelOnVariation(variation), Times.Once); }
public void TestSave() { Mock<IVariationDao> variationDaoMock = new Mock<IVariationDao>(); variationDaoMock.Setup(x => x.Save(It.IsAny<Variation>())); Variation variation = new Variation(); IVariationService variationService = new VariationService(variationDaoMock.Object); variationService.Save(variation); variationDaoMock.Verify(x => x.Save(variation), Times.Once); }
public Game(Variation variation) : this() { Variation = variation; Initialize(); }
/// <summary> /// Ändert den Schwierigkeitsgrad der Variation /// </summary> /// <param name="variation"></param> /// <param name="newLevel"></param> public void ChangeDifficultyLevel(Variation variation, DifficultyLevel newLevel) { GraphClient.Cypher.Match("".Variation("v").Has("dlc").DifficultyLevel()) .Where((Variation v)=>v.Id == variation.Id) .Delete("dlc") .ExecuteWithoutResults(); GraphClient.Cypher .Match("(v:Variation),(dl:DifficultyLevel)") .Where((Variation v, DifficultyLevel dl) => v.Id == variation.Id && dl.Id == newLevel.Id) .Create("".Node("v").Has().Node("dl")) .ExecuteWithoutResults(); }
public void TestIsInUse() { Mock<IVariationDao> variationDaoMock = new Mock<IVariationDao>(); variationDaoMock.Setup(x => x.IsInUse(It.IsAny<Variation>())).Returns(true); Variation variation = new Variation(); IVariationService service = new VariationService(variationDaoMock.Object); bool isInUse = service.IsInUse(variation); Assert.IsTrue(isInUse); variationDaoMock.Verify(x => x.IsInUse(variation), Times.Once); }
/// <summary> /// Liefert den Schwierigkeitsgrad einer Variation /// </summary> /// <param name="variation"></param> /// <returns></returns> public DifficultyLevel GetForVariation(Variation variation) { if (variation == null) throw new ArgumentNullException(nameof(variation)); return _difficultyLevelDao.GetLevelOnVariation(variation); }
void OnGUI() { if (!this.loggedin) { this.email = GUI.TextField (new Rect (10, 10, 800, 100), this.email); GUI.Label (new Rect (10, 220, 500, 1000), this.message); if (GUI.Button (new Rect (10, 115, 250, 100), "Create User")) { KiiUser user = KiiUser.BuilderWithEmail (this.email).WithName ("U" + Environment.TickCount).Build (); user.Register ("pa$$sword", (KiiUser registeredUser, Exception e)=>{ if (e != null) { this.message = "ERROR: failed to register user " + e.GetType () + " " + e.Message + "\n" + e.StackTrace; } else { this.message = "SUCCESS"; this.loggedin = true; this.message = ""; } }); } } else { GUI.Label (new Rect (10, 220, 500, 1000), message); if (!this.initializedExperiment) { this.initializedExperiment = true; Debug.Log("#####Call KiiExperiment.GetByID"); KiiExperiment.GetByID ("f1b00500-eae2-11e3-a0e4-22000a84b8f5", (KiiExperiment experiment, Exception e)=>{ Debug.Log("#####End KiiExperiment.GetByID"); if (e != null) { Debug.Log("#####Error KiiExperiment.GetByID"); this.message = "ERROR: KiiExperiment.GetByID failed!! " + e.GetType () + " " + e.Message + "\n" + e.StackTrace; return; } Debug.Log("#####Success KiiExperiment.GetByID"); this.experiment = experiment; this.appliedVariation = this.experiment.GetAppliedVariation(this.experiment.Variations[0]); ConversionEvent viewCnvEvent = this.experiment.GetConversionEventByName("viewed"); KiiEvent viewKiiEvent = this.appliedVariation.EventForConversion(viewCnvEvent); KiiAnalytics.Upload((Exception e1)=>{ if (e1 != null) { this.message = "ERROR: KiiAnalytics.Upload('viewed') failed!! " + e1.GetType () + " " + e1.Message + "\n" + e1.StackTrace; } else { this.message = "Event 'viewed' is Uploaded!!"; } } ,viewKiiEvent); if (this.buttonCaption == null) { JsonObject json = this.appliedVariation.VariableSet; this.buttonCaption = json.GetString("caption"); } }); } if (GUI.Button (new Rect (10, 10, 250, 100), this.buttonCaption)) { ConversionEvent cnvEvent = this.experiment.GetConversionEventByName("clicked"); KiiEvent kiiEvent = this.appliedVariation.EventForConversion(cnvEvent); KiiAnalytics.Upload((Exception e2)=>{ if (e2 != null) { this.message = "ERROR: KiiAnalytics.Upload(clicked) failed!! " + e2.GetType () + " " + e2.Message + "\n" + e2.StackTrace; } else { this.message = "Event 'clicked' is Uploaded!!"; } }, kiiEvent); } if (GUI.Button (new Rect (265, 10, 250, 100), "Cancel")) { Application.Quit(); } } }
/// <summary> /// Liefert alle Logeinträge einer Variation /// </summary> /// <param name="variation"></param> /// <returns></returns> public IList<LogEntry> GetAllIn(Variation variation) { if (variation == null) throw new ArgumentNullException(nameof(variation)); return _logEntryDao.GetAllIn(variation).OrderByDescending(x=>x.DateTime).ToList(); }
/// <summary> /// Ändert den Schwierigkeitsgrad einer Variation /// </summary> /// <param name="variation"></param> /// <param name="newLevel"></param> public void ChangeDifficultyLevel(Variation variation, DifficultyLevel newLevel) { if (variation == null) throw new ArgumentNullException(nameof(variation)); if (newLevel == null) throw new ArgumentNullException(nameof(newLevel)); _variationDao.ChangeDifficultyLevel(variation, newLevel); }
Color GetColor(Variation variation, float t) { return LerpColorInHSV (variation.color1, variation.color2, t); }
/// <summary> /// Erstellt ein neuen Logeintrag zur Variation /// </summary> /// <param name="variation"></param> /// <param name="date"></param> /// <param name="memo"></param> public void Create(Variation variation, DateTime date, string memo) { if (variation == null) throw new ArgumentNullException(nameof(variation)); _logEntryDao.Create(variation, new LogEntry() {Memo = memo, DateTime = date}); }
/// <summary> /// Speichert die Variante /// </summary> /// <param name="variation"></param> public void Save(Variation variation) { if (variation == null) throw new ArgumentNullException(nameof(variation)); _variationDao.Save(variation); }
public LogEntry CreateLogEntry(Variation variation = null, string memo = "Ich war hier", DateTime? logDate = null) { //if (variation == null) //{ // variation = CreateVariation(); //} if (!logDate.HasValue) { logDate = new DateTime(2015,01,01); } return new LogEntryDao(_graphClient).Create(variation, new LogEntry() { DateTime = logDate.Value, Memo = memo }); }
/// <summary> /// Prüft, ob eine Varation noch in Verwendung ist. /// </summary> /// <param name="variation"></param> /// <returns></returns> public bool IsInUse(Variation variation) { if (variation == null) throw new ArgumentNullException(nameof(variation)); return _variationDao.IsInUse(variation); }