public async Task<IHttpActionResult> PutWarning(int id, Warning warning)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != warning.WarningID)
            {
                return BadRequest();
            }

            db.Entry(warning).State = EntityState.Modified;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!WarningExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }
Esempio n. 2
0
 public void CheckTextWarningForEquality()
 {
     var firstTextWarning = new Warning(TestWarningText);
     var secondTextWarning = new Warning(TestWarningText);
     Assert.AreEqual(firstTextWarning, secondTextWarning);
     Assert.AreEqual(firstTextWarning.GetHashCode(), secondTextWarning.GetHashCode());
 }
Esempio n. 3
0
 public void CheckExceptionWarningForEquality()
 {
     var firstTextWarning = new Warning(new NullReferenceException());
     var secondTextWarning = new Warning(new NullReferenceException());
     Assert.AreEqual(firstTextWarning, secondTextWarning);
     Assert.AreEqual(firstTextWarning.GetHashCode(), secondTextWarning.GetHashCode());
 }
		/// <summary>
		/// Determines whether this IKMappingSpine is valid
		/// </summary>
		public override bool IsValid(IKSolver solver, Warning.Logger logger) {
			if (!base.IsValid(solver, logger)) return false;
			
			foreach (Transform spineBone in spineBones) if (spineBone == null) {
				if (logger != null) logger("Spine bones contains a null reference.");
				return false;
			}
			
			int nodes = 0;
			for (int i = 0; i < spineBones.Length; i++) {
				if (solver.GetPoint(spineBones[i]) != null) nodes ++;
			}
			
			if (nodes == 0) {
				if (logger != null) logger("IKMappingSpine does not contain any nodes.");
				return false;
			}
			
			if (leftUpperArmBone == null) {
				if (logger != null) logger("IKMappingSpine is missing the left upper arm bone.");
				return false;
			}
			
			if (rightUpperArmBone == null) {
				if (logger != null) logger("IKMappingSpine is missing the right upper arm bone.");
				return false;
			}
			
			if (leftThighBone == null) {
				if (logger != null) logger("IKMappingSpine is missing the left thigh bone.");
				return false;
			}
			
			if (rightThighBone == null) {
				if (logger != null) logger("IKMappingSpine is missing the right thigh bone.");
				return false;
			}
			
			if (solver.GetPoint(leftUpperArmBone) == null) {
				if (logger != null) logger("Full Body IK is missing the left upper arm node.");
				return false;
			}
			
			if (solver.GetPoint(rightUpperArmBone) == null) {
				if (logger != null) logger("Full Body IK is missing the right upper arm node.");
				return false;
			}
			
			if (solver.GetPoint(leftThighBone) == null) {
				if (logger != null) logger("Full Body IK is missing the left thigh node.");
				return false;
			}
			
			if (solver.GetPoint(rightThighBone) == null) {
				if (logger != null) logger("Full Body IK is missing the right thigh node.");
				return false;
			}
			return true;
		}
Esempio n. 5
0
		public float weight = 1f; // Added in 0.2
		
		/// <summary>
		/// Determines whether this IKMappingLimb is valid
		/// </summary>
		public override bool IsValid(IKSolver solver, Warning.Logger logger = null) {
			if (!base.IsValid(solver, logger)) return false;
			
			if (!BoneIsValid(bone1, solver, logger)) return false;
			if (!BoneIsValid(bone2, solver, logger)) return false;
			if (!BoneIsValid(bone3, solver, logger)) return false;
			
			return true;
		}
		/// <summary>
		/// Determines whether this IKMappingBone is valid.
		/// </summary>
		public override bool IsValid(IKSolver solver, Warning.Logger logger) {
			if (!base.IsValid(solver, logger)) return false;
			
			if (bone == null) {
				if (logger != null) logger("IKMappingBone's bone is null.");
				return false;
			}

			return true;
		}
Esempio n. 7
0
		/// <summary>
		/// Checks whether this FABRIKChain is valid.
		/// </summary>
		public bool IsValid(Warning.Logger logger) {
			if (ik == null) {
				if (logger != null) logger("IK unassigned in FABRIKChain.");
				return false;
			}
			
			if (!ik.solver.IsValid(logger != null)) return false;

			return true;
		}
        public async Task<IHttpActionResult> PostWarning(Warning warning)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.Warnings.Add(warning);
            await db.SaveChangesAsync();

            return CreatedAtRoute("DefaultApi", new { id = warning.WarningID }, warning);
        }
Esempio n. 9
0
 public void CheckSaveAndLoadWithBinaryDataFactory()
 {
     var warning = new Warning(TestWarningText);
     using (var dataFactory = new BinaryDataFactory())
     using (var dataStream = new MemoryStream())
     {
         dataFactory.Save(warning, new BinaryWriter(dataStream));
         dataStream.Position = 0;
         var loadedWarning = (Warning)dataFactory.Load(new BinaryReader(dataStream));
         Assert.AreEqual(warning, loadedWarning);
     }
 }
Esempio n. 10
0
 protected bool BoneIsValid(Transform bone, IKSolver solver, Warning.Logger logger = null)
 {
     if (bone == null) {
         if (logger != null) logger("IKMappingLimb contains a null reference.");
         return false;
     }
     if (solver.GetPoint(bone) == null) {
         if (logger != null) logger("IKMappingLimb is referencing to a bone '" + bone.name + "' that does not excist in the Node Chain.");
         return false;
     }
     return true;
 }
Esempio n. 11
0
        /// <summary>
        /// Checks whether this FABRIKChain is valid.
        /// </summary>
        public bool IsValid(Warning.Logger logger)
        {
            if (ik == null) {
                if (logger != null) logger("IK unassigned in FABRIKChain.");
                return false;
            }

            if (!ik.solver.IsValid(true)) return false;

            foreach (FABRIKChain c in children) {
                if (!c.IsValid(logger)) return false;
            }

            return true;
        }
Esempio n. 12
0
 public ActionResult ReporteTransferencia(int ID)
 {
     LocalReport localReport = new LocalReport();
     localReport.ReportPath = Server.MapPath("~/Reportes/ReporteTransferencia.rdlc");
     ReportDataSource reportDataSource = new ReportDataSource("DataSet1", repo.ReporteTransferencia(ID));
     localReport.DataSources.Add(reportDataSource);
     string reportType = "PDF";
     string mimeType = "application/pdf";
     string encoding = "utf-8";
     string fileNameExtension = "pdf";
     string deviceInfo = string.Empty;
     Warning[] warnings = new Warning[1];
     string[] streams = new string[1];
     Byte[] renderedBytes;
     //Render the report
     renderedBytes = localReport.Render(reportType, deviceInfo, out mimeType, out encoding, out fileNameExtension, out streams, out warnings);
     return File(renderedBytes, mimeType);
 }
Esempio n. 13
0
		/// <summary>
		/// Determines whether this IKConstraintBend is valid.
		/// </summary>
		public bool IsValid(IKSolverFullBody solver, Warning.Logger logger) {
			if (bone1 == null || bone2 == null || bone3 == null) {
				if (logger != null) logger("Bend Constraint contains a null reference.");
				return false;
			}
			if (solver.GetPoint(bone1) == null) {
				if (logger != null) logger("Bend Constraint is referencing to a bone '" + bone1.name + "' that does not excist in the Node Chain.");
				return false;
			}
			if (solver.GetPoint(bone2) == null) {
				if (logger != null) logger("Bend Constraint is referencing to a bone '" + bone2.name + "' that does not excist in the Node Chain.");
				return false;
			}
			if (solver.GetPoint(bone3) == null) {
				if (logger != null) logger("Bend Constraint is referencing to a bone '" + bone3.name + "' that does not excist in the Node Chain.");
				return false;
			}
			return true;
		}
Esempio n. 14
0
        public ActionResult ReporteAmortizacion(int ID ,string FECHA_INICIO ,string FECHA_FINAL)
        {
            DateTime fechaIni = DateTime.ParseExact(FECHA_INICIO, "dd/MM/yyyy", null);
            DateTime fechaFin = DateTime.ParseExact(FECHA_FINAL, "dd/MM/yyyy", null);

            LocalReport localReport = new LocalReport();
            localReport.ReportPath = Server.MapPath("~/Reportes/ReporteAmortizacion.rdlc");
            ReportDataSource reportDataSource = new ReportDataSource("DataSet1", repo.ReporteKardexCliente(ID, fechaIni, fechaFin));
            localReport.DataSources.Add(reportDataSource);
            string reportType = "PDF";
            string mimeType = "application/pdf";
            string encoding = "utf-8";
            string fileNameExtension = "pdf";
            string deviceInfo = string.Empty;
            Warning[] warnings = new Warning[1];
            string[] streams = new string[1];
            Byte[] renderedBytes;
            //Render the report
            renderedBytes = localReport.Render(reportType, deviceInfo, out mimeType, out encoding, out fileNameExtension, out streams, out warnings);
            return File(renderedBytes, mimeType);
        }
Esempio n. 15
0
 /// <summary>
 /// 调用方法
 /// </summary>
 public object Invoke( object instance, object[] inputs, out object[] outputs ) {
     object result = null;
     try {
         InvokeBefore( inputs );
         result = _invoker.Invoke( instance, inputs, out outputs );
         return result;
     }
     catch ( Warning ex ) {
         ex.TraceId = _log.TraceId;
         throw;
     }
     catch ( Exception ex ) {
         var warning = new Warning( ex );
         warning.TraceId = _log.TraceId;
         warning.Level = LogLevel.Error;
         throw warning;
     }
     finally {
         InvokeAfter( result );
     }
 }
Esempio n. 16
0
 private void nameBox_ButtonClicked(object sender, EventArgs e)
 {
     if (DataTree.SelectedNode == null)
     {
         return;
     }
     if (DataTree.SelectedNode.Tag is WzFile)
     {
         ((WzFile)DataTree.SelectedNode.Tag).Header.Copyright = nameBox.Text;
         ((WzFile)DataTree.SelectedNode.Tag).Header.RecalculateFileStart();
     }
     else if (WzNode.CanNodeBeInserted((WzNode)DataTree.SelectedNode.Parent, nameBox.Text))
     {
         string text = nameBox.Text;
         ((WzNode)DataTree.SelectedNode).ChangeName(text);
         nameBox.Text          = text;
         nameBox.ButtonEnabled = false;
     }
     else
     {
         Warning.Error("A node with that name already exists. Please choose a different name");
     }
 }
Esempio n. 17
0
        private void FakeReport()
        {
            ShimReport.AllInstances.LoadReportDefinitionStream = (x1, x2) => { };
            ShimLocalReport.AllInstances.SetParametersIEnumerableOfReportParameter = (x1, x2) => { };
            ShimReport.AllInstances.RenderStringStringStringOutStringOutStringOutStringArrayOutWarningArrayOut =
                (Report instance, string format, string deviceInfo, out string mimeType, out string encoding, out string fileNameExtension, out string[] streams, out Warning[] warnings) =>
            {
                mimeType          = DummyText;
                encoding          = DummyText;
                fileNameExtension = DummyText;
                streams           = new string[0];
                warnings          = new Warning[0];

                return(new Byte[0]);
            };
            ShimUnsubscribeReasonDetail.GetReportStringStringDateTimeDateTimeInt32String =
                (searchField, searchCriteria, fromDate, toDate, customerID, reason) => new List <UnsubscribeReasonDetail>
            {
                new UnsubscribeReasonDetail {
                    EmailSubject = DummyText
                }
            };
        }
Esempio n. 18
0
        protected override void InitiateSolver()
        {
            string message = "";

            if (BipedReferences.SetupError(this.references, ref message))
            {
                Warning.Log(message, this.references.root, false);
                return;
            }
            this.solvers.AssignReferences(this.references);
            if (this.solvers.spine.bones.Length > 1)
            {
                this.solvers.spine.Initiate(base.transform);
            }
            this.solvers.lookAt.Initiate(base.transform);
            this.solvers.aim.Initiate(base.transform);
            IKSolverLimb[] limbs = this.solvers.limbs;
            for (int i = 0; i < limbs.Length; i++)
            {
                limbs[i].Initiate(base.transform);
            }
            this.solvers.pelvis.Initiate(this.references.pelvis);
        }
Esempio n. 19
0
        public void AddWarning(int entityID, string message)
        {
            var warning = new Warning()
            {
                DateTime = DateTime.Now,
                Day      = GameHelper.CurrentDay,
                EntityID = entityID,
                Unread   = true,
                Message  = message
            };

            using (NoSaveChanges)
            {
                var entity = entityRepository.GetById(entityID);
                if (entity.GetEntityType() == EntityTypeEnum.Country)
                {
                    var countryLink      = EntityLinkCreator.Create(entity);
                    var presidentMessage = $"[Redirected from {countryLink}] {message}";
                    if (entity.Country.PresidentID.HasValue)
                    {
                        AddWarning(entity.Country.PresidentID.Value, presidentMessage);
                    }
                }
                else if (entity.GetEntityType() == EntityTypeEnum.Party)
                {
                    var president = entity.Party.GetPresident();
                    if (president != null)
                    {
                        var partyLink        = EntityLinkCreator.Create(entity);
                        var presidentMessage = $"[Redirected from {partyLink}] {message}";
                        AddWarning(president.CitizenID, presidentMessage);
                    }
                }
            }
            warningRepository.Add(warning);
            ConditionalSaveChanges(warningRepository);
        }
Esempio n. 20
0
        /// <summary>
        /// Initiate the solver with specified root Transform. Use only if this %IKSolver is not a member of an %IK component.
        /// </summary>
        public void Initiate(Transform root)
        {
            if (executedInEditor)
            {
                return;
            }
            if (OnPreInitiate != null)
            {
                OnPreInitiate();
            }

            if (root == null)
            {
                Debug.LogError("Initiating IKSolver with null root Transform.");
            }
            this.root = root;
            initiated = false;

            string message = string.Empty;

            if (!IsValid(ref message))
            {
                Warning.Log(message, root, false);
                return;
            }


            OnInitiate();
            StoreDefaultLocalState();
            initiated       = true;
            firstInitiation = false;

            if (OnPostInitiate != null)
            {
                OnPostInitiate();
            }
        }
        private void SetupWebControlFakes()
        {
            ShimPerformanceByDayAndTimeReport
            .AllInstances.MasterGet = report => new MasterPages.Communicator();

            ShimCompositeControl.AllInstances.DataBind = control =>
            {
                _dataBind = true;
            };

            ShimLocalReport.AllInstances.SetParametersIEnumerableOfReportParameter = (_, parameters) =>
            {
                parameters.Count().ShouldBe(5);
            };

            ShimLocalReport
            .AllInstances
            .RenderStringStringPageCountModeStringOutStringOutStringOutStringArrayOutWarningArrayOut = (
                LocalReport format,
                string renderers,
                string info,
                PageCountMode mode,
                out string type,
                out string encoding,
                out string extension,
                out string[] streams,
                out Warning[] warnings) =>
            {
                type      = Type;
                encoding  = string.Empty;
                extension = Extension;
                streams   = new string[0];
                warnings  = new Warning[0];

                return(_reportData);
            };
        }
Esempio n. 22
0
        public void DoPaste()
        {
            if (!Warning.Warn(Properties.Resources.MainConfirmPaste))
            {
                return;
            }
            yesToAll = false;
            noToAll  = false;
            WzNode   parent    = (WzNode)DataTree.SelectedNode;
            WzObject parentObj = (WzObject)parent.Tag;

            if (parentObj is WzFile)
            {
                parentObj = ((WzFile)parentObj).WzDirectory;
            }

            foreach (WzObject obj in clipboard)
            {
                if (((obj is WzDirectory || obj is WzImage) && parentObj is WzDirectory) || (obj is WzImageProperty && parentObj is IPropertyContainer))
                {
                    WzNode node  = new WzNode(obj);
                    WzNode child = WzNode.GetChildNode(parent, node.Text);
                    if (child != null)
                    {
                        if (ShowReplaceDialog(node.Text))
                        {
                            child.Delete();
                        }
                        else
                        {
                            return;
                        }
                    }
                    parent.AddNode(node);
                }
            }
        }
Esempio n. 23
0
        /*
         * Initiates all bones to match their current state
         * */
        protected void InitiateBones()
        {
            chainLength = 0;

            for (int i = 0; i < bones.Length; i++)
            {
                // Find out which local axis is directed at child/target position
                if (i < bones.Length - 1)
                {
                    bones[i].length = (bones[i].transform.position - bones[i + 1].transform.position).magnitude;
                    chainLength    += bones[i].length;

                    Vector3 nextPosition = bones[i + 1].transform.position;
                    bones[i].axis = Quaternion.Inverse(bones[i].transform.rotation) * (nextPosition - bones[i].transform.position);

                    // Disable Rotation Limits from updating to take control of their execution order
                    if (bones[i].rotationLimit != null)
                    {
                        if (XY)
                        {
                            if (bones[i].rotationLimit is RotationLimitHinge)
                            {
                            }
                            else
                            {
                                Warning.Log("Only Hinge Rotation Limits should be used on 2D IK solvers.", bones[i].transform);
                            }
                        }
                        bones[i].rotationLimit.Disable();
                    }
                }
                else
                {
                    bones[i].axis = Quaternion.Inverse(bones[i].transform.rotation) * (bones[bones.Length - 1].transform.position - bones[0].transform.position);
                }
            }
        }
Esempio n. 24
0
        public void DoPaste()
        {
            if (!Warning.Warn("Paste WZ nodes from clipboard? (warning - can take a lot of time if many nodes are pasted)"))
            {
                return;
            }
            yesToAll = false;
            noToAll  = false;
            WzNode    parent    = (WzNode)DataTree.SelectedNode;
            IWzObject parentObj = (IWzObject)parent.Tag;

            if (parentObj is WzFile)
            {
                parentObj = ((WzFile)parentObj).WzDirectory;
            }

            foreach (IWzObject obj in clipboard)
            {
                if (((obj is WzDirectory || obj is WzImage) && parentObj is WzDirectory) || (obj is IWzImageProperty && parentObj is IPropertyContainer))
                {
                    WzNode node  = new WzNode(obj);
                    WzNode child = WzNode.GetChildNode(parent, node.Text);
                    if (child != null)
                    {
                        if (ShowReplaceDialog(node.Text))
                        {
                            child.Delete();
                        }
                        else
                        {
                            return;
                        }
                    }
                    parent.AddNode(node);
                }
            }
        }
Esempio n. 25
0
        public void AddDevWarn(WarningTypeE warntype, ushort devid, uint transid = 0, uint trackid = 0)
        {
            Warning warn = List.Find(c => c.type == (byte)warntype && c.dev_id == devid && !c.resolve);

            if (warn == null)
            {
                if (stopwarnadding)
                {
                    return;
                }
                if ((DateTime.Now - inittime).TotalSeconds < 20)
                {
                    return;
                }
                warn = new Warning()
                {
                    dev_id   = devid,
                    type     = (byte)warntype,
                    trans_id = transid,
                    track_id = (ushort)trackid
                };
                string devname = PubMaster.Device.GetDeviceName(devid);
                warn.area_id = (ushort)PubMaster.Device.GetDeviceArea(devid);
                string warnmsg = PubMaster.Dic.GetDtlStrCode(warntype.ToString(), out byte level);
                if (trackid > 0)
                {
                    string trackname = PubMaster.Track.GetTrackName(trackid);
                    warn.content = devname + ": (" + trackname + ") " + warnmsg;
                }
                else
                {
                    warn.content = devname + ": " + warnmsg;
                }
                warn.level = level;
                AddWaring(warn);
            }
        }
Esempio n. 26
0
        public void Log_ConfiguredForFileAndDatabaseWithMessagesWarningsAndErrors_ShouldLogToFileAndDatabase()
        {
            var jobLogger = JobLogger.GetInstance();

            var loggerConfiguration = new LoggerConfiguration(new List <ILogger> {
                FileLogger.GetInstance(), new DatabaseLogger()
            }, new List <LogLevel> {
                LogLevel.Message, LogLevel.Warning, LogLevel.Error
            });

            jobLogger.Configure(loggerConfiguration);

            var message = new Message("This is the message");

            jobLogger.Log(message);

            var warning = new Warning("This is the warning");

            jobLogger.Log(warning);

            var error = new Error("This is the error");

            jobLogger.Log(error);

            var loggedContent = File.ReadAllLines(_filePath);

            Assert.AreEqual(3, loggedContent.Count());
            AssertFileContent(loggedContent, new List <ILogMessage> {
                message, warning, error
            });

            var count = AssertDatabaseContent(new List <ILogMessage> {
                message, warning, error
            });

            Assert.AreEqual(3, count);
        }
Esempio n. 27
0
        /// <summary>
        /// Gets any warnings <see cref="Warning"/>
        /// </summary>
        /// <param name="socket">socket for executing command to brick</param>
        /// <returns></returns>
        public static async Task <IEnumerable <Warning> > GetWarnings(ISocket socket)
        {
            Command cmd = null;

            using (CommandBuilder cb = new CommandBuilder(CommandType.DIRECT_COMMAND_REPLY, 1, 0))
            {
                GetWarning_BatchCommand(cb, 0);
                cmd = cb.ToCommand();
            }
            Response response = await socket.Execute(cmd);

            byte bitField = response.PayLoad[0];

            if (bitField == 0)
            {
                return new List <Warning> {
                           Warning.None
                }
            }
            ;
            Warning warning = (Warning)bitField;

            return(warning.GetFlags());
        }
        /// <inheritdoc />
        public async Task <Warning> AddWarning(SocketGuildUser user, FilterType warningType)
        {
            var settings = await _moderationModuleUtils.GetModerationSettings(user.Guild.Id);

            var userData = await _userWarningService.GetUser(user.Id, user.Guild.Id, u => u.Warnings);

            using (var scope = _scopeFactory.CreateScope())
            {
                var warningService = scope.ServiceProvider.GetRequiredService <IEntityService <Warning> >();

                var specificWarningDuration = await GetWarningDuration(settings.GuildId, warningType);

                var expireDate = DateTimeOffset.Now.AddMinutes(specificWarningDuration);

                // 0 means punishment lasts forever.
                if (specificWarningDuration == 0)
                {
                    expireDate = DateTimeOffset.MaxValue;
                }

                var warning = new Warning
                {
                    UserId          = userData.Id,
                    WarningRecieved = DateTimeOffset.Now,
                    WarningExpires  = expireDate,
                    WarningType     = warningType
                };

                await warningService.Create(warning);

                _logger.LogInformation($"Moderation Module: User {user.Username} warned. Added warning to database. " +
                                       $"Guild Id: {user.Guild.Id}, User Id: {user.Id}");

                return(warning);
            }
        }
Esempio n. 29
0
#pragma warning disable 4014 //Code does not need to be awaited
        public void LogoutButton_Click(object sender, RoutedEventArgs e)
        {
            Properties.Settings.Default.AutoLogin = false;
            if (Client.IsLoggedIn && Client.GameStatus.ToLower() != "championSelect".ToLower())
            {
                Client.ReturnButton.Visibility = Visibility.Hidden;
                Client.MainWin.FullNotificationOverlayContainer.Visibility = Visibility.Hidden;
                LoginPage page = new LoginPage();
                Client.Pages.Clear();
                Client.PVPNet.QuitGame();
                Client.PVPNet.Disconnect();
                Client.ChatClient.OnDisconnect -= Client.ChatClient_OnDisconnect;
                Client.ChatClient.Close();
                Client.ChatClient = null;
                Client.ChatClient = new JabberClient();
                Client.chatlistview.Children.Clear();
                Client.IsLoggedIn = false;
                Client.StatusContainer.Visibility = Visibility.Hidden;
                Client.Container.Margin           = new Thickness(0, 0, 0, 0);
                Client.SwitchPage(new LoginPage());
                Client.ClearPage(typeof(MainPage));
            }
            else if (Properties.Settings.Default.warnClose && Client.IsInGame)
            {
                Warn = new Warning();
                Warn.Title.Content            = "Logout while in Game";
                Warn.MessageText.Text         = "Are You Sure You Want To Quit? This will result in a dodge.";
                Warn.backtochampselect.Click += HideWarning;
                Warn.AcceptButton.Click      += Quit;
                Warn.hide.Click += HideWarning;
                Warn.backtochampselect.Content = "Return to Champ Select";
                Warn.AcceptButton.Content      = "Dodge game and logout";
                Client.FullNotificationOverlayContainer.Content    = Warn.Content;
                Client.FullNotificationOverlayContainer.Visibility = Visibility.Visible;
            }
        }
Esempio n. 30
0
 public void LogoutButton_Click(object sender, RoutedEventArgs e)
 {
     Settings.Default.AutoLogin = false;
     if (Client.IsLoggedIn && !string.Equals(Client.GameStatus, "championSelect", StringComparison.CurrentCultureIgnoreCase))
     {
         Client.ReturnButton.Visibility = Visibility.Hidden;
         // ReSharper disable once PossibleNullReferenceException
         (Client.MainWin as MainWindow).FullNotificationOverlayContainer.Visibility = Visibility.Hidden;
         Client.Pages.Clear();
         RiotCalls.QuitGame();
         Client.RiotConnection.Disconnected -= Client.RiotConnection_Disconnected;
         Client.RiotConnection.Close();
         Client.XmppConnection.OnError -= Client.XmppConnection_OnError;
         Client.XmppConnection.Close();
         Client.XmppConnection = null;
         Client.chatlistview.Children.Clear();
         Client.IsLoggedIn = false;
         Client.StatusContainer.Visibility = Visibility.Hidden;
         Client.Container.Margin           = new Thickness(0, 0, 0, 0);
         Client.SwitchPage(new LoginPage());
         Client.ClearPage(typeof(MainPage));
     }
     else if (Settings.Default.warnClose && Client.IsInGame)
     {
         _warn = new Warning {
             Header = { Content = "Logout while in Game" }, MessageText = { Text = "Are You Sure You Want To Quit? This will result in a dodge." }
         };
         _warn.backtochampselect.Click += HideWarning;
         _warn.AcceptButton.Click      += Quit;
         _warn.hide.Click += HideWarning;
         _warn.backtochampselect.Content = "Return to Champ Select";
         _warn.AcceptButton.Content      = "Dodge game and logout";
         Client.FullNotificationOverlayContainer.Content    = _warn.Content;
         Client.FullNotificationOverlayContainer.Visibility = Visibility.Visible;
     }
 }
Esempio n. 31
0
 /// <summary>
 /// Add a warning to the user's amountr
 /// </summary>
 /// <param name="userId">The user ID to look for</param>
 /// <param name="serverId">The guild ID to look for</param>
 /// <param name="username">The username of the user</param>
 public static async Task AddWarnings(ulong userId, ulong serverId, string username)
 {
     using (SqliteDbContext DbContext = new SqliteDbContext())
     {
         //Check if the guild has a spot
         if (DbContext.Warnings.Where(x => x.UserId == userId && x.Serverid == serverId).Count() < 1)
         {
             DbContext.Warnings.Add(new Warning
             {
                 Serverid         = serverId,
                 UserId           = userId,
                 AmountOfWarnings = 1,
                 Username         = username
             });
         }
         else
         {
             Warning Current = DbContext.Warnings.Where(x => x.UserId == userId && x.Serverid == serverId).FirstOrDefault();
             Current.AmountOfWarnings += 1;
             DbContext.Warnings.Update(Current);
         }
         await DbContext.SaveChangesAsync();
     }
 }
Esempio n. 32
0
        private string MapType(JTokenType type)
        {
            switch (type)
            {
            case JTokenType.Boolean:
                return("http://www.w3.org/2001/XMLSchema#boolean");

            case JTokenType.Float:
                return("http://www.w3.org/2001/XMLSchema#double");

            case JTokenType.Integer:
                return("http://www.w3.org/2001/XMLSchema#integer");

            default:
                if (Warning != null)
                {
                    Warning.Invoke(String.Format("Token of type '{0}' could not be mapped to literal data type.", type));
                }

                break;
            }

            return(null);
        }
Esempio n. 33
0
        /// <summary>
        /// 生成代码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Create(/*object sender, RoutedEventArgs e*/)
        {
            try
            {
                if (!IsGenerate)
                {
                    sider = new List <MySidebar>();
                    foreach (dynamic ds in grid.Children)
                    {
                        string name = ds.Name as string;
                        if (!string.IsNullOrEmpty(name) && name.Contains("BAR"))
                        {
                            sider.Add(ds);
                        }
                    }

                    vm.result  = GetData(sider);
                    IsGenerate = true;
                }
                //生成界面
                vm.IsEnabled = false;
                //create.IsEnabled = true;
                vm.Genetate(vm.result);

                Warning warning = new Warning("生成成功");
                warning.ShowDialog();
            }
            catch (Exception ex)
            {
                App.Current.Dispatcher.Invoke(new Action(() =>
                {
                    Warning warning = new Warning("生成失败:" + ex.Message);
                    warning.ShowDialog();
                }));
            }
        }
Esempio n. 34
0
        private void CheckForMixedReferences()
        {
            Processing?.Invoke("Check for mixed references...");

            var refGroups = References.GroupBy(r => r.RefId)
                            .Select(g => g.AsQueryable().ToList())
                            .Where(rl => rl.Count > 1)
                            .ToList();

            var warningRefs = refGroups.Select(g => g.GroupBy(r => r.SourceId).ToList())
                              .Where(rg => rg.Count > 1)
                              .ToList();

            foreach (var warningRef in warningRefs)
            {
                var wref     = warningRef.First().AsEnumerable().First();
                var versions = string.Join(" <-> ",
                                           warningRef.SelectMany(w => w.AsEnumerable())
                                           .Select(r => r.SourceVersion).Distinct()
                                           );

                var warning = $"{wref.Name} {wref.Version}, used: {versions}";
                solution.Warnings.Add(warning);
                Warning?.Invoke(warning);
            }

            var referenced = warningRefs
                             .SelectMany(g => g.AsEnumerable())
                             .Select(g => g.Key)
                             .ToList();

            foreach (var reference in References)
            {
                reference.IsWarning = referenced.Contains(reference.SourceId);
            }
        }
Esempio n. 35
0
        internal bool SetValue(byte data)
        {
            Warning newValue = (Warning)data;

            bool hasChanged = (Value != newValue);

            if (hasChanged)
            {
                Value = newValue;
                if (Value != Warning.None)
                {
                    IEnumerable <Warning> warnings = Value.GetFlags();
                    if (MonitorEvents)
                    {
                        WarningReceived?.Invoke(warnings);
                    }
                    foreach (Warning warning in warnings)
                    {
                        Brick.Logger.LogWarning($"Brick warning: {warning}");
                    }
                }
            }
            return(hasChanged);
        }
Esempio n. 36
0
        internal void AddWarning(Warning warning)
        {
            WarningCount++;
            if (warning.IsError)
            {
                ErrorCount++;
            }
            else if (warning.IsSuggestion)
            {
                SuggestionCount++;
            }

            if (WarningsByFile.TryGetValue(warning.Location.RelativeFilePath, out List <Warning> warnings))
            {
                warnings.Add(warning);
            }
            else
            {
                WarningsByFile.Add(warning.Location.RelativeFilePath, new List <Warning>()
                {
                    warning
                });
            }
        }
Esempio n. 37
0
        // Calculates all bone lengths as well as lengths between the chains
        private void CalculateBoneLengths(IKSolverFullBody solver)
        {
            // Calculating bone lengths
            length = 0f;

            for (int i = 0; i < nodes.Length - 1; i++)
            {
                //计算链中 两个骨骼之间的长度
                nodes[i].length = Vector3.Distance(nodes[i].transform.position, nodes[i + 1].transform.position);
                length         += nodes[i].length;

                if (nodes[i].length == 0)
                {
                    Warning.Log("Bone " + nodes[i].transform.name + " - " + nodes[i + 1].transform.name + " length is zero, can not solve.", nodes[i].transform);
                    return;
                }
            }

            for (int i = 0; i < children.Length; i++)
            {
                solver.chain[children[i]].rootLength = (solver.chain[children[i]].nodes[0].transform.position - nodes[nodes.Length - 1].transform.position).magnitude;

                if (solver.chain[children[i]].rootLength == 0f)
                {
                    return;
                }
            }

            if (nodes.Length == 3)
            {
                // Square magnitude of the limb lengths
                sqrMag1   = nodes[0].length * nodes[0].length;
                sqrMag2   = nodes[1].length * nodes[1].length;
                sqrMagDif = sqrMag1 - sqrMag2;
            }
        }
Esempio n. 38
0
        /// <summary>
        /// 重写基类的异常处理方法
        /// </summary>
        /// <param name="context"></param>
        public override void OnException(ExceptionContext context)
        {
            base.OnException(context);
            context.ExceptionHandled = true;
            string errorMsg = "";
            AbpValidationException abpValidationException = context.Exception as AbpValidationException;

            if (abpValidationException?.ValidationErrors?.Count > 0)
            {
                foreach (var validationError in abpValidationException.ValidationErrors)
                {
                    errorMsg += validationError.ErrorMessage + ",";
                }
            }
            else
            {
                Warning warning = context.Exception as Warning;
                if (warning != null)
                {
                    errorMsg = "500-" + warning.Message;
                }
                else
                {
                    errorMsg = "500-" + ExceptionPrompt.Instance.GetPrompt(context.Exception);
                }
            }
            context.Result = new ContentResult
            {
                Content = Spring.Helpers.Json.ToJson(new
                {
                    code      = StateCode.SystemError.Value(),
                    message   = errorMsg,
                    timestamp = DateTimeOffset.Now.ToUnixTimeSeconds()
                })
            };
        }
Esempio n. 39
0
        // Applies the weight curves and multipliers to the FBBIK solver
        public void Apply(IKSolverFullBodyBiped solver, FullBodyBipedEffector effector, InteractionTarget target, float timer, float weight)
        {
            for (int i = 0; i < weightCurves.Length; i++)
            {
                float mlp = target == null? 1f: target.GetValue(weightCurves[i].type);

                Apply(solver, effector, weightCurves[i].type, weightCurves[i].GetValue(timer), weight * mlp);
            }

            for (int i = 0; i < multipliers.Length; i++)
            {
                if (multipliers[i].curve == multipliers[i].result)
                {
                    if (!Warning.logged)
                    {
                        Warning.Log("InteractionObject Multiplier 'Curve' " + multipliers[i].curve.ToString() + "and 'Result' are the same.", transform);
                    }
                }

                int curveIndex = GetWeightCurveIndex(multipliers[i].curve);

                if (curveIndex != -1)
                {
                    float mlp = target == null? 1f: target.GetValue(multipliers[i].result);

                    Apply(solver, effector, multipliers[i].result, multipliers[i].GetValue(weightCurves[curveIndex], timer), weight * mlp);
                }
                else
                {
                    if (!Warning.logged)
                    {
                        Warning.Log("InteractionObject Multiplier curve " + multipliers[i].curve.ToString() + "does not exist.", transform);
                    }
                }
            }
        }
        private opens CreateOpens(out Mock <HttpResponseBase> response, out Mock <IReportViewer> reportViewer)
        {
            var emailClients = new Mock <IEmailClients>();

            emailClients.Setup(x => x.Get()).Returns(new List <EmailClients>());
            var platforms = new Mock <IPlatforms>();

            platforms.Setup(x => x.Get()).Returns(new List <Platforms>());
            var master = new Mock <IMasterCommunicator>();

            master.Setup(x => x.GetCustomerID()).Returns(0);
            var server = new Mock <IServer>();

            server.Setup(x => x.MapPath(It.IsAny <string>())).Returns(string.Empty);
            var blastReport = new Mock <IBlastReport>();

            blastReport.Setup(x => x.Get(It.IsAny <int>())).Returns(new List <BlastReport>());
            response = new Mock <HttpResponseBase>();
            response.SetupGet(x => x.OutputStream).Returns(new MemoryStream());
            reportViewer = new Mock <IReportViewer>();
            reportViewer.Setup(x => x.DataBind());
            reportViewer.Setup(x => x.SetParameters(It.IsAny <ReportParameter[]>()));
            var outString       = string.Empty;
            var outStringArray  = new string[] { };
            var outWarningArray = new Warning[] { };

            reportViewer.Setup(x => x.Render(
                                   It.IsAny <string>(),
                                   It.IsAny <string>(),
                                   out outString,
                                   out outString,
                                   out outString,
                                   out outStringArray,
                                   out outWarningArray)).Returns(new byte[] { });
            return(new opens(emailClients.Object, platforms.Object, master.Object, server.Object, blastReport.Object, reportViewer.Object));
        }
Esempio n. 41
0
        private void HandleDeadLetter(DeadLetter message)
        {
            var msg = message.Message;
            var rcp = message.Recipient;
            var snd = message.Sender;

            if (!(msg is Terminate))
            {
                var recipientPath = rcp.Path.ToString();
                var recipientType = rcp.GetType();
                var warning       = new Warning(recipientPath, recipientType, message);
                if (!ShouldFilter(warning))
                {
                    var msgStr = (msg is ISystemMessage)
                        ? "Received dead system message: " + msg
                        : "Received dead letter from " + snd + ": " + msg;
                    var warning2 = new Warning(recipientPath, recipientType, new DeadLetter(msgStr, snd, rcp));
                    if (!ShouldFilter(warning2))
                    {
                        Print(warning2);
                    }
                }
            }
        }
        public FileContentResult Index()
        {
            Dictionary <string, string> reportParameters = new Dictionary <string, string>();

            Request.QueryString.AllKeys.Where(x => !x.Equals("ReportName")).ForEach(x => reportParameters.Add(x, Request.QueryString[x]));

            byte[] byteResult = new byte[0];
            string extension, mimeType, encoding;

            Warning[]        warnings  = new Warning[0];
            string[]         streamIds = new string[0];
            ServerInfoHeader serverInfoHeader;
            ExecutionInfo2   execInfo = new ExecutionInfo2();
            ReportExecutionServiceSoapClient rsServiceClient = new ReportExecutionServiceSoapClient();

            rsServiceClient.ClientCredentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation;
            ExecutionHeader execHeader = rsServiceClient.LoadReport2(null, "/Axis.ReportDB/" + Request.QueryString["ReportName"], null,
                                                                     out serverInfoHeader, out execInfo);

            rsServiceClient.SetExecutionParameters2(execHeader, null,
                                                    reportParameters.Select(x => new ParameterValue {
                Name = x.Key, Value = x.Value
            }).ToArray(), "en-us",
                                                    out execInfo);
            string sessionId = execInfo.ExecutionID;

            try
            {
                serverInfoHeader = rsServiceClient.Render2(execHeader, null, "PDF", @"<DeviceInfo><Toolbar>True</Toolbar></DeviceInfo>", PageCountMode.Actual, out byteResult, out extension, out mimeType, out encoding, out warnings, out streamIds);
            }
            catch (Exception)
            {
                throw;
            }
            return(new FileContentResult(byteResult, "application/pdf"));
        }
Esempio n. 43
0
        public void Log_ConfiguredForDatabaseAndConsoleWithMessagesWarningsAndErrors_ShouldLogToDatabaseAndConsole()
        {
            var jobLogger           = JobLogger.GetInstance();
            var mockedConsoleWriter = new MockedConsoleWriter();

            var loggerConfiguration = new LoggerConfiguration(new List <ILogger> {
                new DatabaseLogger(), new ConsoleLogger(mockedConsoleWriter)
            }, new List <LogLevel> {
                LogLevel.Message, LogLevel.Warning, LogLevel.Error
            });

            jobLogger.Configure(loggerConfiguration);

            var message = new Message("This is the message");

            jobLogger.Log(message);

            var warning = new Warning("This is the warning");

            jobLogger.Log(warning);

            var error = new Error("This is the error");

            jobLogger.Log(error);

            var count = AssertDatabaseContent(new List <ILogMessage> {
                message, warning, error
            });

            Assert.AreEqual(3, count);

            AssertConsoleContent(mockedConsoleWriter.MockedMessages, new List <ILogMessage> {
                message, warning, error
            });
            Assert.AreEqual(3, mockedConsoleWriter.MockedMessages.Count);
        }
Esempio n. 44
0
        public async Task ReinterpretTest()
        {
            FullResultRequest req = new FullResultRequest("cantalope duck");

            req.Reinterpret = true;

            FullResultResponse res = await Client.FullResultAsync(req).ConfigureAwait(false);

            Assert.True(res.IsSuccess);
            Assert.False(res.IsError);

            Warning warning = Assert.Single(res.Warnings);

            Assert.Equal("Using closest Wolfram|Alpha interpretation:", warning.Reinterpret.Text);
            Assert.Equal("cantalope", warning.Reinterpret.New);
            Assert.NotEqual(0, warning.Reinterpret.Score);
            Assert.Equal(Level.Medium, warning.Reinterpret.Level);

            Alternative alternative = Assert.Single(warning.Reinterpret.Alternatives);

            Assert.NotEqual(0, alternative.Score);
            Assert.Equal(Level.Low, alternative.Level);
            Assert.Equal("duck", alternative.Value);
        }
Esempio n. 45
0
        public void AddTaskWarn(uint areaid, WarningTypeE warntype, ushort devid, uint transid = 0, string result = "")
        {
            Warning warn = List.Find(c => c.type == (byte)warntype && c.dev_id == devid && c.trans_id == transid && !c.resolve);

            if (warn == null)
            {
                if (stopwarnadding)
                {
                    return;
                }
                if ((DateTime.Now - inittime).TotalSeconds < 20)
                {
                    return;
                }
                warn = new Warning()
                {
                    area_id  = (ushort)areaid,
                    dev_id   = devid,
                    type     = (byte)warntype,
                    trans_id = transid
                };
                string devname = PubMaster.Device.GetDeviceName(devid);
                //warn.area_id = (ushort)PubMaster.Device.GetDeviceArea(devid);
                string warnmsg = PubMaster.Dic.GetDtlStrCode(warntype.ToString(), out byte level);
                if (devid != 0)
                {
                    warn.content = devname + ": " + warnmsg + " > " + result;
                }
                else
                {
                    warn.content = "任务[" + transid + "] : " + warnmsg + " > " + result;
                }
                warn.level = level;
                AddWaring(warn);
            }
        }
Esempio n. 46
0
File: Log.cs Progetto: NetUtil/Util
 /// <summary>
 /// 初始化异常
 /// </summary>
 private void InitException() {
     if ( Exception == null )
         return;
     var warning = new Warning( Exception );
     ErrorMessage = warning.Message;
     StackTrace = warning.StackTrace;
 }
Esempio n. 47
0
        /*
         * Check if this chain is valid or not.
         * */
        public bool IsValid(Warning.Logger logger = null)
        {
            if (nodes.Length == 0) {
                if (logger != null) logger("FBIK chain contains no nodes.");
                return false;
            }

            foreach (IKSolver.Node node in nodes) if (node.transform == null) {
                if (logger != null) logger("Node transform is null in FBIK chain.");
                return false;
            }

            return true;
        }
Esempio n. 48
0
		/*
		 * Determines whether this IKEffector is valid or not.
		 * */
		public bool IsValid(IKSolver solver, Warning.Logger logger) {
			if (bone == null) {
				if (logger != null) logger("IK Effector bone is null.");
				return false;
			}
			
			if (solver.GetPoint(bone) == null) {
				if (logger != null) logger("IK Effector is referencing to a bone '" + bone.name + "' that does not excist in the Node Chain.");
				return false;
			}

			foreach (Transform b in childBones) {
				if (b == null) {
					if (logger != null) logger("IK Effector contains a null reference.");
					return false;
				}
			}
			
			foreach (Transform b in childBones) {
				if (solver.GetPoint(b) == null) {
					if (logger != null) logger("IK Effector is referencing to a bone '" + b.name + "' that does not excist in the Node Chain.");
					return false;
				}
			}

			if (planeBone1 != null && solver.GetPoint(planeBone1) == null) {
				if (logger != null) logger("IK Effector is referencing to a bone '" + planeBone1.name + "' that does not excist in the Node Chain.");
				return false;
			}

			if (planeBone2 != null && solver.GetPoint(planeBone2) == null) {
				if (logger != null) logger("IK Effector is referencing to a bone '" + planeBone2.name + "' that does not excist in the Node Chain.");
				return false;
			}

			if (planeBone3 != null && solver.GetPoint(planeBone3) == null) {
				if (logger != null) logger("IK Effector is referencing to a bone '" + planeBone3.name + "' that does not excist in the Node Chain.");
				return false;
			}

			return true;
		}
Esempio n. 49
0
		/// <summary>
		/// Determines whether this IKMapping is valid.
		/// </summary>
		public virtual bool IsValid(IKSolver solver, Warning.Logger logger) {
			return true;
		}
Esempio n. 50
0
 protected override void WarningInternal(Warning message)
 {
 }
 /// <remarks/>
 public string EndCreateReportHistorySnapshot(System.IAsyncResult asyncResult, out Warning[] Warnings)
 {
     object[] results = this.EndInvoke(asyncResult);
     Warnings = ((Warning[])(results[1]));
     return ((string)(results[0]));
 }
Esempio n. 52
0
 /**
  * Returns true if the given warning is in
  * the warning-set of this Preprocessor.
  */
 public bool getWarning(Warning w)
 {
     return (warnings & w) != Warning.NONE;
 }
Esempio n. 53
0
 /**
  * Adds warnings to the warning-set of this Preprocessor.
  */
 public void addWarnings(Warning w)
 {
     warnings |= w;
 }
Esempio n. 54
0
        public Preprocessor()
        {
            this.inputs = new List<Source>();

            this.macros = new Dictionary<String,Macro>();
            macros.Add(__LINE__.getName(), __LINE__);
            macros.Add(__FILE__.getName(), __FILE__);
            macros.Add(__COUNTER__.getName(), __COUNTER__);
            this.states = new Stack<State>();
            states.Push(new State());
            this.source = null;

            this.counter = 0;

            this.quoteincludepath = new List<String>();
            this.sysincludepath = new List<String>();
            this.frameworkspath = new List<String>();
            this.features = Feature.NONE;
            this.warnings = Warning.NONE;
            this.filesystem = new JavaFileSystem();
            this.listener = null;
        }
Esempio n. 55
0
        //Синтаксический анализ кода
        public bool GoAnalyze()
        {
            if (Code.SyntError != "none") return false;

            Gramma.Init();
            #if DEBUG
            Gramma.Check();
            #endif
            Configuration config = new Configuration();

            //История конфигураций
            Stack<Configuration> history = new Stack<Configuration>();
            history.Push(config);

            while (true) //додумать условие цикла
            {
                //Отношение перехода делаем на токенах

                if (config.s == 'q')
                {
                    if (config.L2.Count != 0)
                    {
                        //1 пункт отношения, "На верху L2 не терминал, растим дерево"
                        if (!config.L2.Peek().term)
                        {

                            Configuration.elem item = new Configuration.elem(config.L2.Pop());
                            Pravilo current = Gramma.p.Find(x => x.leftSide == item.value); //текущее правило
                            if (item.value != "string")    //првоеряю не ожидалась ли строка
                            {
                                if (item.value != "chislo" && item.value != "integer" && item.value != "real")
                                {
                                    if (item.value != "id")
                                    {

                                        config.L1.Push(new Configuration.elem(current.leftSide, false, 1));//в магазин L1 суём левую часть правила
                                        for (int altIndex = current.rightSide[0].Count - 1; altIndex >= 0; altIndex--)//суём первую альтернативу в магазин L2 по элементно
                                        {
                                            if (current.rightSide[0][altIndex].notTerminal != "")
                                            {
                                                config.L2.Push(new Configuration.elem(current.rightSide[0][altIndex].notTerminal, false, 1));
                                            }
                                            else
                                            {
                                                config.L2.Push(new Configuration.elem(current.rightSide[0][altIndex].terminal, true, 1));
                                            }
                                        }
                                    }
                                    else
                                    {
                                        //Успешное прохождение идентификатора
                                        if (Code.Tokens[config.i].klass == "идентификатор")
                                        {
                                            config.L1.Push(new Configuration.elem(current.leftSide, false, 1));
                                            config.L2.Push(new Configuration.elem(Code.Tokens[config.i].value, true, 1));

                                        }
                                        else
                                        {
                                            config.L1.Push(new Configuration.elem(current.leftSide, false, 1));//в магазин L1 суём левую часть правила
                                            for (int altIndex = current.rightSide[0].Count - 1; altIndex >= 0; altIndex--)//суём первую альтернативу в магазин L2 по элементно
                                            {
                                                if (current.rightSide[0][altIndex].notTerminal != "")
                                                {
                                                    config.L2.Push(new Configuration.elem(current.rightSide[0][altIndex].notTerminal, false, 1));
                                                }
                                                else
                                                {
                                                    config.L2.Push(new Configuration.elem(current.rightSide[0][altIndex].terminal, true, 1));
                                                }
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    //Успешное прохождение числа
                                    if (Code.Tokens[config.i].klass == "число   ")
                                    {
                                        if (Code.Tokens[config.i].type == "real")
                                        {
                                            config.L1.Push(new Configuration.elem(current.leftSide, false, 2));
                                            config.L2.Push(new Configuration.elem(Code.Tokens[config.i].value, true, 2));
                                        }
                                        else
                                        {
                                            config.L1.Push(new Configuration.elem(current.leftSide, false, 1));
                                            config.L2.Push(new Configuration.elem(Code.Tokens[config.i].value, true, 1));
                                        }
                                    }
                                    else
                                    {
                                        /*
                                        Code.SyntError = "В строке " + Code.Tokens[config.i].str_num + " столбце " + Code.Tokens[config.i].pos_num + " ожидалось число";
                                        return false;
                                         */
                                        config.L1.Push(new Configuration.elem(current.leftSide, false, 1));//в магазин L1 суём левую часть правила
                                        for (int altIndex = current.rightSide[0].Count - 1; altIndex >= 0; altIndex--)//суём первую альтернативу в магазин L2 по элементно
                                        {
                                            if (current.rightSide[0][altIndex].notTerminal != "")
                                            {
                                                config.L2.Push(new Configuration.elem(current.rightSide[0][altIndex].notTerminal, false, 1));
                                            }
                                            else
                                            {
                                                config.L2.Push(new Configuration.elem(current.rightSide[0][altIndex].terminal, true, 1));
                                            }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                //Успешное прохождение строки
                                if (Code.Tokens[config.i].klass == "строка")
                                {
                                    config.L1.Push(new Configuration.elem(current.leftSide, false, 1));
                                    config.L2.Push(new Configuration.elem(Code.Tokens[config.i].value, true, 1));
                                }
                                else
                                {
                                    /*
                                    Code.SyntError = "В строке " + Code.Tokens[config.i].str_num + " столбце " + Code.Tokens[config.i].pos_num + " ожидалась строка";
                                    return false;
                                        */
                                    config.L1.Push(new Configuration.elem(current.leftSide, false, 1));//в магазин L1 суём левую часть правила
                                    for (int altIndex = current.rightSide[0].Count - 1; altIndex >= 0; altIndex--)//суём первую альтернативу в магазин L2 по элементно
                                    {
                                        if (current.rightSide[0][altIndex].notTerminal != "")
                                        {
                                            config.L2.Push(new Configuration.elem(current.rightSide[0][altIndex].notTerminal, false, 1));
                                        }
                                        else
                                        {
                                            config.L2.Push(new Configuration.elem(current.rightSide[0][altIndex].terminal, true, 1));
                                        }
                                    }
                                }
                            }
                            history.Push(config);
                        }

                        //2 пункт отношения, "На верху L2 терминал сравниваем входной токен"
                        else
                        {
                            if (config.i < Code.Tokens.Count)
                            {
                                Configuration.elem item = new Configuration.elem(config.L2.Peek());
                                //"Успешное сравнение"
                                if ((Code.Tokens[config.i].value == item.value) || (item.value == "lambda"))
                                {
                                    if ((warn != null) && (warn.id < config.i))
                                    {
                                        //Убираем подозрительный токен
                                        warn = new Warning();
                                    }
                                    config.L2.Pop();
                                    config.L1.Push(item);
                                    if (item.value != "lambda") config.i++;
                                }
                                //4 пункт отношения. Не успешное сравнение
                                else
                                {
                                    //Сохраняем подозрительный токен
                                    if (warn.id < config.i)
                                    {
                                        warn = new Warning();
                                        warn.nTerm = config.L1.Peek();
                                        warn.term = item;
                                        warn.id = config.i;
                                    }
                                    config.s = 'b';
                                }
                            }
                            else
                            {
                                Code.SyntError = "Неожиданный конец файла";
                                return false;
                            }
                            history.Push(config);
                        }
                    }
                    else
                    {
                        //3 пункт отншения. Успешное завершение
                        if (config.i == Code.Tokens.Count)
                        {
                            config.s = 't';
                            config.L2.Push(new Configuration.elem("lambda", true, 0));
                            history.Push(config);
                            Code.conclusion = config.Seq();
                            return true;
                        }
                        else
                        {
                            ErrorForm(warn);
                            //Code.SyntError = "Неожиданный конец файла";
                            return false;
                        }
                    }

                }
                else
                {
                    if (!config.L1.Peek().term)
                    //6. Испытание очередной альтернативы
                    {
                        //тестовый костыль
                        if (!config.L2.Peek().term || !(config.L1.Peek().value == "id"))
                        {

                            Configuration.elem item = new Configuration.elem(config.L1.Pop());
                            Pravilo current = Gramma.p.Find(x => x.leftSide == item.value); //текущее правило
                            if (current.rightSide.Count > item.altIndex)
                            //a. замена альтернативы если существует следующая альтернатива
                            {
                                for (int elemIndex = 0; elemIndex < current.rightSide[item.altIndex - 1].Count; elemIndex++)
                                {
                                    if (config.L2.Count != 0)
                                    {
                                        config.L2.Pop();
                                    }
                                    else
                                    {
                                        ErrorForm(warn);
                                        return false;
                                    }
                                }
                                for (int elemIndex = current.rightSide[item.altIndex].Count - 1; elemIndex >= 0; elemIndex--)//суём j+1 альтернативу в магазин L2 по элементно
                                {
                                    if (current.rightSide[item.altIndex][elemIndex].notTerminal != "")
                                    {
                                        config.L2.Push(new Configuration.elem(current.rightSide[item.altIndex][elemIndex].notTerminal, false, item.altIndex + 1));
                                    }
                                    else
                                    {
                                        config.L2.Push(new Configuration.elem(current.rightSide[item.altIndex][elemIndex].terminal, true, item.altIndex + 1));
                                    }
                                }
                                item.altIndex++;
                                config.L1.Push(item);
                                config.s = 'q';
                            }
                            else
                            {
                                if (config.i == 0 && item.value == "main")
                                //б. прекращение разбора
                                {
                                    ErrorForm(warn);
                                    //Code.SyntError = "Цепочка не принадлежит языку";
                                    return false;
                                }
                                else
                                //в. Отмена результата
                                {
                                    for (int elemIndex = 0; elemIndex < current.rightSide[item.altIndex - 1].Count; elemIndex++)
                                    {
                                        config.L2.Pop();
                                    }
                                    config.L2.Push(new Configuration.elem(item.value, false, 1));
                                }
                            }

                        }
                        else
                        {
                            config.L2.Pop();
                            config.L2.Push(new Configuration.elem(config.L1.Pop().value, false, 1));
                        }
                    }

                    else
                    //5 Возврат по ходу
                    {
                        Configuration.elem item = new Configuration.elem(config.L1.Pop());
                        config.L2.Push(item);
                        //config.L2.Push(config.L1.Pop()); //на будующее когда всё будет работать
                        if (item.value != "lambda") config.i--;
                    }
                    history.Push(config);
                }
            }
        }
Esempio n. 56
0
        //Формируем ошибку
        void ErrorForm(Warning w)
        {
            Code.SyntError = "";
            Code.SyntError += "В строке " + Code.Tokens[warn.id].str_num + " столбце " + Code.Tokens[warn.id].pos_num + " встречено \"" + Code.Tokens[warn.id].value + "\" ";
            if (!w.term.term)
            {
                Pravilo current = Gramma.p.Find(x => x.leftSide == warn.term.value);
                if ((current.leftSide != "letter") && (current.leftSide != "digit"))
                    while (current.rightSide[0][0].terminal != "")
                    {
                        current = Gramma.p.Find(x => x.leftSide == current.rightSide[0][0].notTerminal);
                    }
                else
                {
                    if (current.leftSide == "letter")
                        Code.SyntError += "ожидался идентификатор.";
                    if (current.leftSide == "digit")
                        Code.SyntError += "ожидалась цифра.";
                    return;
                }
                Code.SyntError += "ожидалось \"" + current.rightSide[0][0].terminal + "\".";
            }
            {
                if (!w.nTerm.term)
                {
                    if (w.nTerm.value == "letter")
                        Code.SyntError += "ожидался идентификатор.";
                    else
                    {
                        if (w.nTerm.value == "digit")
                            Code.SyntError += "ожидалась цифра.";
                        else
                            Code.SyntError += "ожидалось \"" + w.term.value + "\" или возможная альтернатива.";
                    }
                }
                else
                    Code.SyntError += "ожидалось \"" + w.term.value + "\" или возможная альтернатива.";
                /*Code.SyntError += "ожидалось ";
                Pravilo current = Gramma.p.Find(x => x.leftSide == warn.nTerm.value);
                foreach (var item in current.rightSide)
                {
                    if (item[0].terminal!="")
                    {
                        Code.SyntError +="\""+item[0].terminal + "\" или ";
                    }
                }
                Code.SyntError=Code.SyntError.Remove(Code.SyntError.LastIndexOf("или"));
                Code.SyntError += ".";    */

            }
        }
 public void setWarning(Warning Warning)
 {
     this.mWarning = Warning;
 }
 /// <summary>
 /// 是否数据库外键约束错误
 /// </summary>
 private static bool IsRefrenceError( Exception exception )
 {
     var message = new Warning( exception ).Message;
     return message.Contains( "DELETE 语句与 REFERENCE 约束" )
         || message.Contains( "a foreign key constraint fails" );
 }
Esempio n. 59
0
 static bool HasWarningExpired(Warning warning)
 {
     //TODO: hardcoded as 1 hour, maybe make configurable?
     return (DateTime.UtcNow - warning.Created).TotalHours >= 1.0;
 }
 public string CreateReportHistorySnapshot(string Report, out Warning[] Warnings)
 {
     object[] results = this.Invoke("CreateReportHistorySnapshot", new object[] {
                 Report});
     Warnings = ((Warning[])(results[1]));
     return ((string)(results[0]));
 }