예제 #1
0
        private void InitialFormat()
        {
            FormatUtil.SetNumberFormat(this.shtInventorySummary.Columns[(int)eColView.Header], FormatUtil.eNumberFormat.Qty_PCS);
            FormatUtil.SetNumberFormat(this.shtInventorySummary.Columns[(int)eColView.Rolling], FormatUtil.eNumberFormat.Qty_PCS);
            FormatUtil.SetNumberFormat(this.shtInventorySummary.Columns[(int)eColView.Cutting_I], FormatUtil.eNumberFormat.Qty_PCS);
            FormatUtil.SetNumberFormat(this.shtInventorySummary.Columns[(int)eColView.Cutting_E], FormatUtil.eNumberFormat.Qty_PCS);
            FormatUtil.SetNumberFormat(this.shtInventorySummary.Columns[(int)eColView.Plating_I], FormatUtil.eNumberFormat.Qty_PCS);
            FormatUtil.SetNumberFormat(this.shtInventorySummary.Columns[(int)eColView.Plating_E], FormatUtil.eNumberFormat.Qty_PCS);
            FormatUtil.SetNumberFormat(this.shtInventorySummary.Columns[(int)eColView.Heating_E], FormatUtil.eNumberFormat.Qty_PCS);
            FormatUtil.SetNumberFormat(this.shtInventorySummary.Columns[(int)eColView.Others], FormatUtil.eNumberFormat.Qty_PCS);
            FormatUtil.SetNumberFormat(this.shtInventorySummary.Columns[(int)eColView.QC], FormatUtil.eNumberFormat.Qty_PCS);
            FormatUtil.SetNumberFormat(this.shtInventorySummary.Columns[(int)eColView.QC_Hold], FormatUtil.eNumberFormat.Qty_PCS);
            FormatUtil.SetNumberFormat(this.shtInventorySummary.Columns[(int)eColView.Packing], FormatUtil.eNumberFormat.Qty_PCS);
            FormatUtil.SetNumberFormat(this.shtInventorySummary.Columns[(int)eColView.WIP], FormatUtil.eNumberFormat.Qty_PCS);
            FormatUtil.SetNumberFormat(this.shtInventorySummary.Columns[(int)eColView.FG], FormatUtil.eNumberFormat.Qty_PCS);

            FormatUtil.SetNumberFormat(this.shtInventorySummary.Columns[(int)eColView.ItemNo], FormatUtil.eNumberFormat.MasterNo);
        }
예제 #2
0
        private void OutputPoolInfo()
        {
            var msg = $@"

Mining Pool:            {poolConfig.Id}
Coin Type:              {poolConfig.Template.Symbol} [{poolConfig.Template.Symbol}]
Network Connected:      {blockchainStats.NetworkType}
Detected Reward Type:   {blockchainStats.RewardType}
Current Block Height:   {blockchainStats.BlockHeight}
Current Connect Peers:  {blockchainStats.ConnectedPeers}
Network Difficulty:     {blockchainStats.NetworkDifficulty}
Network Hash Rate:      {FormatUtil.FormatHashrate(blockchainStats.NetworkHashrate)}
Stratum Port(s):        {(poolConfig.Ports?.Any() == true ? string.Join(", ", poolConfig.Ports.Keys) : string.Empty)}
Pool Fee:               {(poolConfig.RewardRecipients?.Any() == true ? poolConfig.RewardRecipients.Sum(x => x.Percentage) : 0)}%
";

            logger.Info(() => msg);
        }
예제 #3
0
        public async Task UpdateBalancesAsync(IDbConnection con, IDbTransaction tx, PoolConfig poolConfig,
                                              IPayoutHandler payoutHandler, Block block, decimal blockReward)
        {
            var payoutConfig    = poolConfig.PaymentProcessing.PayoutSchemeConfig;
            var window          = payoutConfig?.ToObject <Config>()?.Factor ?? 2.0m;
            var shares          = new Dictionary <string, double>();
            var rewards         = new Dictionary <string, decimal>();
            var shareCutOffDate = await CalculateRewardsAsync(poolConfig, block, blockReward, shares, rewards);

            // update balances
            foreach (var address in rewards.Keys)
            {
                var amount = rewards[address];

                if (amount > 0)
                {
                    logger.Info(() => $"Adding {payoutHandler.FormatAmount(amount)} to balance of {address} for {FormatUtil.FormatQuantity(shares[address])} ({shares[address]}) shares for block {block.BlockHeight}");
                    await balanceRepo.AddAmountAsync(con, tx, poolConfig.Id, address, amount, $"Reward for {FormatUtil.FormatQuantity(shares[address])} shares for block {block.BlockHeight}");
                }
            }

            // delete discarded shares
            if (shareCutOffDate.HasValue)
            {
                var cutOffCount = await shareRepo.CountSharesBeforeCreatedAsync(con, tx, poolConfig.Id, shareCutOffDate.Value);

                if (cutOffCount > 0)
                {
                    await LogDiscardedSharesAsync(poolConfig, block, shareCutOffDate.Value);

                    logger.Info(() => $"Deleting {cutOffCount} discarded shares before {shareCutOffDate.Value:O}");
                    await shareRepo.DeleteSharesBeforeCreatedAsync(con, tx, poolConfig.Id, shareCutOffDate.Value);
                }
            }

            // diagnostics
            var totalShareCount = shares.Values.ToList().Sum(x => new decimal(x));
            var totalRewards    = rewards.Values.ToList().Sum(x => x);

            if (totalRewards > 0)
            {
                logger.Info(() => $"{FormatUtil.FormatQuantity((double) totalShareCount)} ({Math.Round(totalShareCount, 2)}) shares contributed to a total payout of {payoutHandler.FormatAmount(totalRewards)} ({totalRewards / blockReward * 100:0.00}% of block reward) to {rewards.Keys.Count} addresses");
            }
        }
예제 #4
0
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Usage();
            }
            else
            {
                string filename = Path.GetFullPath(args[0]);

                using (FileStream fs = File.Open(filename, FileMode.Open, FileAccess.Read))
                {
                    Type dataType = FormatUtil.getObjectType(fs);

                    if (dataType != null)
                    {
                        string tagHashValue;
                        char[] trimNull = new char[] { '\0' };

                        // initialize data
                        IFormat vgmData = (IFormat)Activator.CreateInstance(dataType);
                        vgmData.Initialize(fs, filename);
                        Dictionary <string, string> tagHash = vgmData.GetTagHash();

                        // loop over hash and output information
                        foreach (string s in tagHash.Keys)
                        {
                            tagHashValue = tagHash[s];

                            if (!String.IsNullOrEmpty(tagHashValue))
                            {
                                tagHashValue = tagHashValue.TrimEnd(trimNull);
                            }
                            else
                            {
                                tagHashValue = String.Empty;
                            }

                            Console.WriteLine(s + ": " + tagHashValue);
                        }
                    }
                }
            }
        }
예제 #5
0
파일: Xsf.cs 프로젝트: qyf0310/vgmtoolbox
        public bool IsFileLibrary()
        {
            bool ret = false;

            FileStream fs;
            Type       formatType;
            Xsf        checkFile;
            ArrayList  libPathArray;

            string libDirectory = Path.GetDirectoryName(Path.GetFullPath(this.filePath));

            foreach (string f in Directory.GetFiles(libDirectory))
            {
                try
                {
                    fs         = File.OpenRead(f);
                    formatType = FormatUtil.getObjectType(fs);

                    if (formatType == this.GetType())
                    {
                        fs.Seek(0, SeekOrigin.Begin);
                        checkFile = new Xsf();
                        checkFile.Initialize(fs, f);
                        libPathArray = new ArrayList(checkFile.GetLibPathArray());

                        if (libPathArray.Contains(this.filePath.ToUpper()))
                        {
                            ret = true;
                            fs.Close();
                            fs.Dispose();
                            break;
                        }
                    }
                    fs.Close();
                    fs.Dispose();
                }
                catch (Exception)
                {
                    // Do nothing for now, if the file cannot be read than it cannot need a lib
                }
            }

            return(ret);
        }
예제 #6
0
        public static bool Load(ref ConcurrentDictionary <string, HashSet <string> > addTo, string tagsRecordDirectoryPath = "")
        {
            var success = false;

            FileStream   fs   = null;
            StreamReader file = null;

            try
            {
                if (string.IsNullOrEmpty(tagsRecordDirectoryPath) || !File.Exists(tagsRecordDirectoryPath))
                {
                    tagsRecordDirectoryPath = Path.Combine(TagsRecordDirectory, defaultTagRecordFilename + tagRecordFileExtension);
                    string[] files = Directory.GetFiles(TagsRecordDirectory, "*" + tagRecordFileExtension);
                    Array.Sort(files);
                    if (files.Length > 0)
                    {
                        tagsRecordDirectoryPath = files[0];
                    }
                }
                fs   = new FileStream(tagsRecordDirectoryPath, FileMode.OpenOrCreate);
                file = new StreamReader(fs);
                var fileString      = file.ReadToEnd();
                var tagsRecordDirty = JsonConvert.DeserializeObject <Dictionary <string, List <string> > >(fileString);

                foreach (string category in tagsRecordDirty.Keys)
                {
                    addTo.TryAdd(FormatUtil.FixCategory(category), new HashSet <string>(tagsRecordDirty[category].Select((s) => { return(FormatUtil.FixTag(s)); })));
                }
                Debug.WriteLine("successfully loaded tags record.\n" + fileString);
                success = true;
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
            }
            finally
            {
                file?.Close();
                fs?.Close();
                Persist(addTo);// <-- so any user changes that have been formatted are persisted
            }
            return(success);
        }
예제 #7
0
        public static void Serialize(Wall w, ISerializer s)
        {
            s.EnumU8(nameof(w.Properties), () => w.Properties, x => w.Properties             = x, x => ((byte)x, x.ToString()));
            s.ByteArray(nameof(w.CollisionData), () => w.CollisionData, x => w.CollisionData = x, 3);
            s.UInt16(nameof(w.TextureNumber),
                     () => FormatUtil.Untweak((ushort?)w.TextureNumber),
                     x => w.TextureNumber = (DungeonWallId?)FormatUtil.Tweak(x));
            s.Dynamic(w, nameof(w.AnimationFrames));
            s.Dynamic(w, nameof(w.AutoGfxType));
            s.Dynamic(w, nameof(w.TransparentColour));
            s.Dynamic(w, nameof(w.Unk9));
            s.Dynamic(w, nameof(w.Width));
            s.Dynamic(w, nameof(w.Height));

            ushort overlayCount = (ushort)w.Overlays.Count;

            s.UInt16("overlayCount", () => overlayCount, x => overlayCount = x);
            s.List(w.Overlays, overlayCount, Overlay.Serialize, () => new Overlay());
        }
예제 #8
0
        public static MapNpc Load(BinaryReader br)
        {
            var npc = new MapNpc();

            npc.Id          = (NpcCharacterId)br.ReadByte(); // +0
            npc.Sound       = br.ReadByte();                 // +1
            npc.EventNumber = br.ReadUInt16();               // +2
            if (npc.EventNumber == 0xffff)
            {
                npc.EventNumber = null;
            }

            npc.ObjectNumber = FormatUtil.Tweak(br.ReadUInt16()) ?? 0; // +4
            npc.Flags        = (NpcFlags)br.ReadByte();                // +6 // Combine this & MovementType ?
            npc.Movement     = (MovementType)br.ReadByte();            // +7
            npc.Unk8         = br.ReadByte();                          // +8
            npc.Unk9         = br.ReadByte();                          // +9
            return(npc);
        }
예제 #9
0
        public string LoginCheck(string user, string pass)
        {
            //加密
            string u = Encryption.MD5(user);
            string p = Encryption.MD5(pass);

            User account = _repository.GetAll()
                           .Where(x => x.Is_delete == 0 & x.Account == u)
                           .FirstOrDefault();

            if (account == null)
            {
                return(FormatUtil.JsonFormat("用户名不存在", -1, null, null, null, null));
            }

            if (account.Status == 0)
            {
                return(FormatUtil.JsonFormat("无权访问或已被禁用", -1, null, null, null, null));
            }

            //密码校验
            User password = _repository.GetAll()
                            .Where(x => x.Account == u && x.Password == p)
                            .FirstOrDefault();

            if (password == null)
            {
                return(FormatUtil.JsonFormat("密码错误", -2, null, null, null, null));
            }

            //角色校验
            Role role = _role.GetAll()
                        .Where(x => x.Status == 1 & x.Id == account.RoleId)
                        .FirstOrDefault();

            if (role == null)
            {
                return(FormatUtil.JsonFormat("无权访问或已被禁用", -1, null, null, null, null));
            }

            //写入token,账号,头像数据返回
            return(FormatUtil.JsonFormat("登录成功", 0, null, account.Account, account.Icon, account.Name));
        }
예제 #10
0
        static void Main()
        {
            var baseDir       = FormatUtil.FindBasePath();
            var generalConfig = GeneralConfig.Load(baseDir);
            var config        = FullAssetConfig.Load(baseDir);

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            void SaveChanges(object sender, EventArgs e) => config.Save(baseDir);

            var form = new MainFrm(generalConfig, config);

            form.SaveClicked += SaveChanges;
            Application.Run(form);
            form.SaveClicked -= SaveChanges;

            SaveChanges(null, EventArgs.Empty);
        }
        public string EditUsers(
            Guid id,
            string name,
            string account,
            string password,
            string email,
            Guid roleid
            //string icon
            //int status
            )
        {
            string u   = Encryption.MD5(account);
            string p   = Encryption.MD5(password);
            var    obj = _user.GetAll()
                         .Where(x => x.Account == u)
                         .FirstOrDefault();

            if (obj != null)
            {
                return(FormatUtil.Result(0, "该账号已存在", 1, ""));
            }
            var singleone = _user.GetSingle(id);

            singleone.Name     = name;
            singleone.Account  = u;
            singleone.Password = p;
            singleone.Email    = email;
            singleone.RoleId   = roleid;
            //singleone.Icon= "../Content/UploaFile/UserIcon/userdefult.jpg";//默认头像
            //singleone.Status= status;
            singleone.Update_time = DateTime.Now;
            int statu = _user.EditAndSave(singleone);

            if (statu != 1)
            {
                return(FormatUtil.Result(0, "编辑失败,稍后重试", 1, ""));
            }
            else
            {
                return(FormatUtil.Result(0, "编辑成功", 0, ""));
            }
        }
        public string RoleSwitch(Guid id, int sta)
        {
            Role role = _role.GetSingle(id);

            role.Status = sta;
            int statu = _role.EditAndSave(role);

            if (statu == 0)
            {
                return(FormatUtil.Result(0, "更改失败,稍后重试", 1, ""));
            }
            if (sta == 1)
            {
                return(FormatUtil.Result(0, "已开启", 1, ""));
            }
            else
            {
                return(FormatUtil.Result(0, "已禁用", 1, ""));
            }
        }
예제 #13
0
        private void InitialFormat()
        {
            FormatUtil.SetNumberFormat(this.shtCustomerOrderList.Columns[(int)eColView.AMOUNT], FormatUtil.eNumberFormat.Amount);
            FormatUtil.SetNumberFormat(this.shtCustomerOrderList.Columns[(int)eColView.AMOUNT_THB], FormatUtil.eNumberFormat.Amount_THB);
            FormatUtil.SetNumberFormat(this.shtCustomerOrderList.Columns[(int)eColView.EXCHANGE_RATE], FormatUtil.eNumberFormat.ExchangeRate);
            FormatUtil.SetNumberFormat(this.shtCustomerOrderList.Columns[(int)eColView.PRICE], FormatUtil.eNumberFormat.UnitPrice);
            FormatUtil.SetNumberFormat(this.shtCustomerOrderList.Columns[(int)eColView.QTY], FormatUtil.eNumberFormat.Qty_PCS);

            FormatUtil.SetDateFormat(this.shtCustomerOrderList.Columns[(int)eColView.ITEM_DELIVERY_DATE]);
            FormatUtil.SetDateFormat(this.shtCustomerOrderList.Columns[(int)eColView.RECEIVE_DATE]);
            FormatUtil.SetDateFormat(this.shtCustomerOrderList.Columns[(int)eColView.PO_DATE]);

            FormatUtil.SetNumberFormat(this.txtAmount, FormatUtil.eNumberFormat.Amount);
            FormatUtil.SetNumberFormat(this.txtAmountTHB, FormatUtil.eNumberFormat.Amount_THB);
            FormatUtil.SetNumberFormat(this.txtQty, FormatUtil.eNumberFormat.Total_Qty_PCS);

            FormatUtil.SetNumberFormat(this.shtCustomerOrderList.Columns[(int)eColView.ITEM_CD], FormatUtil.eNumberFormat.MasterNo);

            CtrlUtil.EnabledControl(false, txtAmount, txtAmountTHB, txtQty);
        }
        public string UserSwitch(Guid id, int sta)
        {
            User user = _user.GetSingle(id);

            user.Status = sta;
            int statu = _user.EditAndSave(user);

            if (statu == 0)
            {
                return(FormatUtil.Result(0, "更改失败,稍后重试", 1, ""));
            }
            if (sta == 1)
            {
                return(FormatUtil.Result(0, "已开启", 1, ""));
            }
            else
            {
                return(FormatUtil.Result(0, "已禁用", 1, ""));
            }
        }
예제 #15
0
        private void InitializeScreen()
        {
            if (DesignMode)
            {
                return;
            }

            dtAdjustDate.KeyPress += CtrlUtil.SetNextControl;
            //rdoIncrease.KeyPress += CtrlUtil.SetNextControl;
            //rdoDecrease.KeyPress += CtrlUtil.SetNextControl;
            cboReasonCode.KeyPress    += CtrlUtil.SetNextControl;
            txtMasterNo.KeyPress      += CtrlUtil.SetNextControl;
            txtItemDesc.KeyPress      += CtrlUtil.SetNextControl;
            txtCustomerName.KeyPress  += CtrlUtil.SetNextControl;
            cboStoredLoc.KeyPress     += CtrlUtil.SetNextControl;
            txtPackNo.KeyPress        += CtrlUtil.SetNextControl;
            txtFGNo.KeyPress          += CtrlUtil.SetNextControl;
            txtLotNo.KeyPress         += CtrlUtil.SetNextControl;
            txtCustomerLotNo.KeyPress += CtrlUtil.SetNextControl;
            txtAdjustQty.KeyPress     += CtrlUtil.SetNextControl;
            //txtAdjustWeight.KeyPress += CtrlUtil.SetNextControl;
            txtRemark.KeyPress += CtrlUtil.SetNextControl;

            btnItemCode.Click += btnItemCode_Click;

            dtAdjustDate.Format = Common.CurrentUserInfomation.DateFormatString;

            CtrlUtil.EnabledControl(false, cboInventoryUM);

            FormatUtil.SetNumberFormat(this.txtOnhandQty, FormatUtil.eNumberFormat.Qty_PCS);
            FormatUtil.SetNumberFormat(this.txtAdjustQty, FormatUtil.eNumberFormat.Qty_Adjust_PCS);
            FormatUtil.SetNumberFormat(this.txtAdjustWeight, FormatUtil.eNumberFormat.Qty_Adjust_KG);

            InitializeComboBox();

            InitializeControlBinding();

            InitializeScreenMode();

            CheckCurrentInvPeriod();
        }
예제 #16
0
        public object Load(BinaryReader br, long streamLength, string name, AssetInfo config)
        {
            IDictionary <int, string> strings = new Dictionary <int, string>();
            var startOffset   = br.BaseStream.Position;
            var stringCount   = br.ReadUInt16();
            var stringLengths = new int[stringCount];

            for (int i = 0; i < stringCount; i++)
            {
                stringLengths[i] = br.ReadUInt16();
            }

            for (int i = 0; i < stringCount; i++)
            {
                var bytes = br.ReadBytes(stringLengths[i]);
                strings[i] = FormatUtil.BytesTo850String(bytes);
            }

            Debug.Assert(br.BaseStream.Position == startOffset + streamLength);
            return(strings);
        }
        public string GetRolesList(int page = 1, int limit = 5)
        {
            var DataList = _role
                           .GetAll()
                           .OrderBy(x => x.Id)
                           .Skip(limit * (page - 1)) //跳过指定条数【数量*(页码-1)】
                           .Take(limit)              //返回指定条数
                           .ToList();

            //获取数据总条数
            int count = _role.GetAll().Count();

            if (DataList.Count() == 0)
            {
                return(FormatUtil.Result(count, "没有数据", 1, ""));
            }
            else
            {
                return(FormatUtil.Result(count, "查询成功", 0, DataList));
            }
        }
예제 #18
0
        private void InitializeSpread()
        {
            shtView.ActiveSkin = Common.ACTIVE_SKIN;
            m_keyboardSpread   = new KeyboardSpread(fpView);

            shtView.Columns[(int)eColView.CHECKBOX].CellType            = CtrlUtil.CreateCheckboxCellType();
            shtView.Columns[(int)eColView.CHECKBOX].HorizontalAlignment = FarPoint.Win.Spread.CellHorizontalAlignment.Center;

            m_keyboardSpread.RowAdding   += new KeyboardSpread.RowAddingHandler(m_keyboardSpread_RowAdding);
            m_keyboardSpread.RowAdded    += new KeyboardSpread.RowAddedHandler(m_keyboardSpread_RowAdded);
            m_keyboardSpread.RowRemoving += new KeyboardSpread.RowRemovingHandler(m_keyboardSpread_RowRemoving);

            fpView.ContextMenuStrip  = null;
            fpView.SubEditorOpening += CtrlUtil.SpreadDisableSubEditorOpening;
            LookupDataBIZ biz = new LookupDataBIZ();

            FormatUtil.SetNumberFormat(shtView.Columns[(int)eColView.ONHAND_QTY], FormatUtil.eNumberFormat.Qty_PCS);

            //shtView.Columns[(int)eColView.INV_UM_CLS].CellType = CtrlUtil.CreateReadOnlyPairCellType(biz.LoadLookupClassType(DataDefine.UM_CLS.ToNZString()));
            CtrlUtil.MappingDataFieldWithEnum(shtView, typeof(eColView));
        }
예제 #19
0
        public DateTimeParseResult Parse(ExtractResult er, DateObject refDate)
        {
            var referenceTime = refDate;
            var extra         = er.Data as DateTimeExtra <TimeType>;

            if (extra == null)
            {
                var result = TimeExtractor.Extract(er.Text);
                extra = result[0]?.Data as DateTimeExtra <TimeType>;
            }
            if (extra != null)
            {
                var timeResult  = FunctionMap[extra.Type](extra);
                var parseResult = TimeFunctions.PackTimeResult(extra, timeResult, referenceTime);
                if (parseResult.Success)
                {
                    parseResult.FutureResolution = new Dictionary <string, string>
                    {
                        { TimeTypeConstants.TIME, FormatUtil.FormatTime((DateObject)parseResult.FutureValue) }
                    };
                    parseResult.PastResolution = new Dictionary <string, string>
                    {
                        { TimeTypeConstants.TIME, FormatUtil.FormatTime((DateObject)parseResult.PastValue) }
                    };
                }
                var ret = new DateTimeParseResult
                {
                    Start         = er.Start,
                    Text          = er.Text,
                    Type          = er.Type,
                    Length        = er.Length,
                    Value         = parseResult,
                    Data          = timeResult,
                    ResolutionStr = "",
                    TimexStr      = parseResult.Timex
                };
                return(ret);
            }
            return(null);
        }
        public DateTimeParseResult Parse(ExtractResult er, DateObject refDate)
        {
            var    referenceDate = refDate;
            object value         = null;

            if (er.Type.Equals(ParserName))
            {
                var innerResult = ParseHolidayRegexMatch(er.Text, referenceDate);

                if (innerResult.Success)
                {
                    innerResult.FutureResolution = new Dictionary <string, string>
                    {
                        { TimeTypeConstants.DATE, FormatUtil.FormatDate((DateObject)innerResult.FutureValue) }
                    };

                    innerResult.PastResolution = new Dictionary <string, string>
                    {
                        { TimeTypeConstants.DATE, FormatUtil.FormatDate((DateObject)innerResult.PastValue) }
                    };

                    innerResult.IsLunar = IsLunarCalendar(er.Text);
                    value = innerResult;
                }
            }

            var ret = new DateTimeParseResult
            {
                Text          = er.Text,
                Start         = er.Start,
                Length        = er.Length,
                Type          = er.Type,
                Data          = er.Data,
                Value         = value,
                TimexStr      = value == null ? "" : ((DateTimeResolutionResult)value).Timex,
                ResolutionStr = ""
            };

            return(ret);
        }
예제 #21
0
 private void button1_Click(object sender, EventArgs e)
 {
     try
     {
         IStudentBl.LoadDates();
         DataGrid.DataSource = IStudentBl.GetAll(TypeFormat.Txt);
         FormatUtil.ChangeFormat("Txt");
         MessageBox.Show($"Archivo de registro seleccionado {FormatUtil.Format()}", "Registro", MessageBoxButtons.OK, MessageBoxIcon.Information);
     }
     catch (NullReferenceException ex)
     {
         MessageError("Problema interno");
         Log.Error(ex);
     }
     catch (ArgumentNullException ex)
     {
         MessageError(ex.Message);
         Log.Error(ex);
     }
     catch (FileNotFoundException ex)
     {
         MessageError(ex.Message);
         Log.Error(ex);
     }
     catch (FileLoadException ex)
     {
         MessageError("Fallo en el registro , no se pudo cargar el archivo");
         Log.Error(ex);
     }
     catch (FormatException ex)
     {
         MessageError("Los datos introducidos no tienen el formato correcto");
         Log.Error(ex);
     }
     catch (UnauthorizedAccessException ex)
     {
         MessageError("No se tiene autarizacion para escribir en el archivo");
         Log.Error(ex);
     }
 }
예제 #22
0
        static string Test(string scriptFormat, string expectedToStringResult, IMapEvent e)
        {
            if (!string.Equals(e.ToString(), expectedToStringResult, StringComparison.OrdinalIgnoreCase))
            {
                return($"Event \"{e}\" did not serialise to the expected string \"{expectedToStringResult}\"");
            }

            IMapEvent parsed;

            try { parsed = (IMapEvent)Event.Parse(scriptFormat); }
            catch (Exception ex) { return($"Could not parse \"{scriptFormat}\": {ex}"); }


            var bytes1 = EventToBytes(e);
            var bytes2 = EventToBytes(parsed);
            var hex1   = FormatUtil.BytesToHexString(bytes1);
            var hex2   = FormatUtil.BytesToHexString(bytes2);

            if (!string.Equals(hex1, hex2, StringComparison.Ordinal))
            {
                return($"The literal event ({e}) serialised to {hex1}, but the parsed event ({scriptFormat}) serialised to {hex2}");
            }

            if (scriptFormat != expectedToStringResult)
            {
                IMapEvent roundTripped;
                try { roundTripped = (IMapEvent)Event.Parse(expectedToStringResult); }
                catch (Exception ex) { return($"Could not parse \"{expectedToStringResult}\": {ex}"); }

                var bytes3 = EventToBytes(roundTripped);
                var hex3   = FormatUtil.BytesToHexString(bytes3);
                if (!string.Equals(hex1, hex2, StringComparison.Ordinal))
                {
                    return($"The literal event ({e}) serialised to {hex1}, but after round-tripping through text ({expectedToStringResult}) it serialised to {hex3}");
                }
            }

            return(null);
        }
예제 #23
0
        public void ListEntriesUtilTest()
        {
            string text;

            text = " dsa=b\n\t\t{\n\t}\n\ta=n\n\t\tabcdefgh={\n\t\t\tcba=\"3\"\n\t\t}";
            var entries = FormatUtil.ListEntriesWithIndexes(text).ToDictionary();

            Assert.AreEqual(entries[9], "");
            Assert.AreEqual(4, entries.Count);

            text = File.ReadAllText(TestsReference.MIN_TEST_PATH).Substring(6);
            if (text.StartsWith(FormattedReader.SAVE_HEADER)) //the header, specified in the constant above, is not part of the hierarchy
            {
                text = text.Substring(FormattedReader.SAVE_HEADER.Length);
            }
            text = text.TrimEnd(new char[] { ' ', '\n', '\t', '\r' });
            if (text.EndsWith(FormattedReader.SAVE_FOOTER)) //same for footer
            {
                text = text.Substring(0, text.Length - FormattedReader.SAVE_FOOTER.Length);
            }
            entries = FormatUtil.ListEntriesWithIndexes(text).ToDictionary();
            Dictionary <int, string> expected = new Dictionary <int, string>();

            expected.Add(3, "version");
            expected.Add(23, "date");
            expected.Add(40, "player");
            expected.Add(82, "player_realm");
            expected.Add(111, "dyn_title");
            expected.Add(221, "dyn_title");
            expected.Add(286, "dyn_title");
            expected.Add(353, "rebel");
            expected.Add(363, "unit");
            expected.Add(377, "sub_unit");
            expected.Add(395, "start_date");
            expected.Add(418, "flags");
            expected.Add(559, "dynasties");
            expected.Add(1217, "character");
            Assert.IsTrue(entries.Count == expected.Count && entries.SequenceEqual(expected));
        }
        public string AdminLoginCheck(string users, string pass)
        {
            string data = Invoke.PostRequestApi("http://localhost:8848/api/AdminLoginCheck?" + "user="******"&pass="******"icon"]; //头像
            string    name      = (string)obj["name"]; //用户昵称
            string    AdminUser = (string)obj["user"];
            int       code      = int.Parse(obj["code"].ToString());
            string    msg       = (string)obj["msg"];

            if (code == 0)
            {
                Session["AdminUser"] = AdminUser;
                Session["Icon"]      = icon;
                return(FormatUtil.LoginResult(msg, code, icon, name));
            }
            return(FormatUtil.LoginResult(msg, 1, icon, name));
        }
예제 #25
0
        public override void Write(Dictionary <string, string> data, string[] extras)
        {
            if (Formatter == null)
            {
                var tmp = FormatUtil.MakeExtraFields(extras);

                foreach (var entry in data)
                {
                    tmp = entry.Value + " " + tmp;
                }

                Console.WriteLine(tmp);
            }
            else
            {
                Formatter.SetLevel(Level);
                Formatter.SetName(Name);
                var textFormated = Formatter.Format(data, extras);

                Console.WriteLine(textFormated);
            }
        }
예제 #26
0
        public void bind()
        {
            List <Attendance> attenList = Session["attenList"] as List <Attendance>;

            CourseTableBLL ctBLL    = new CourseTableBLL();
            TeacherBLL     teachBll = new TeacherBLL();
            CourseBLL      courBLL  = new CourseBLL();
            ClassBLL       classBLL = new ClassBLL();


            CourseTable ct    = ctBLL.get(attenList[0].CourTableID);
            Class       clazz = classBLL.get(ct.ClassID);

            #region 页面数据绑定
            className.Text    = clazz.Name;
            courseName.Text   = courBLL.get(ct.CourId).Name;
            teacherName.Text  = teachBll.get(ct.TeachID).Name;
            week.Text         = "第" + ct.Week + "周";
            weekDay.Text      = ct.WeekDay;
            classtTime.Text   = ct.CourseTime;
            classAddress.Text = ct.Place;

            lateNumber.Text = attenList.Where(x => x.Status.Equals("迟到")).ToList().Count.ToString();
            absences.Text   = attenList.Where(x => !x.Status.Equals("正常")).ToList().Count.ToString();
            allNumber.Text  = clazz.StudCount;
            attRate.Text    = FormatUtil.doubleToPercent(attenList.Where(x => x.Status.Equals("正常")).ToList().Count / Convert.ToDouble(clazz.StudCount));

            DataTable dt = transferListToDataTable(attenList);

            AspNetPager1.RecordCount = dt.Rows.Count;

            int from = (AspNetPager1.CurrentPageIndex - 1) * AspNetPager1.PageSize + 1;
            int to   = from + AspNetPager1.PageSize - 1 > AspNetPager1.RecordCount ? AspNetPager1.RecordCount : from + AspNetPager1.PageSize - 1;

            GridView1.DataSource = PageUtil.resort(PageUtil.getPaged(dt, from, to));
            GridView1.DataBind();
            #endregion
        }
예제 #27
0
        protected DateTimeResolutionResult InnerParser(string text, DateObject reference)
        {
            var innerResult = ParseBasicRegexMatch(text, reference);

            if (!innerResult.Success)
            {
                innerResult = ParseImplicitDate(text, reference);
            }

            if (!innerResult.Success)
            {
                innerResult = ParseWeekdayOfMonth(text, reference);
            }

            if (!innerResult.Success)
            {
                innerResult = ParserDurationWithBeforeAndAfter(text, reference);
            }

            if (innerResult.Success)
            {
                innerResult.FutureResolution = new Dictionary <string, string>
                {
                    { TimeTypeConstants.DATE, FormatUtil.FormatDate((DateObject)innerResult.FutureValue) }
                };

                innerResult.PastResolution = new Dictionary <string, string>
                {
                    { TimeTypeConstants.DATE, FormatUtil.FormatDate((DateObject)innerResult.PastValue) }
                };

                innerResult.IsLunar = IsLunarCalendar(text);

                return(innerResult);
            }

            return(null);
        }
예제 #28
0
        public GetToDosDataResponse Post(GetToDosDataRequest request)
        {
            GetToDosDataResponse response = new GetToDosDataResponse();

            try
            {
                if (string.IsNullOrEmpty(request.UserId))
                {
                    throw new UnauthorizedAccessException("SchedulingDD:Post()::Unauthorized Access");
                }

                response         = Manager.GetToDos(request);
                response.Version = request.Version;
            }
            catch (Exception ex)
            {
                FormatUtil.FormatExceptionResponse(response, base.Response, ex);

                string aseProcessID = ConfigurationManager.AppSettings.Get("ASEProcessID") ?? "0";
                Helpers.LogException(int.Parse(aseProcessID), ex);
            }
            return(response);
        }
예제 #29
0
파일: StringId.cs 프로젝트: lucorp/ualbion
 public static StringId ToStringId(TextId id) => FormatUtil.ResolveTextId(id);
예제 #30
0
        public DateTimeParseResult Parse(ExtractResult er, DateObject refDate)
        {
            var referenceTime = refDate;
            var extra         = er.Data as DateTimeExtra <PeriodType>;

            if (extra == null)
            {
                var result = new TimeExtractorChs().Extract(er.Text, refDate);
                extra = result[0]?.Data as DateTimeExtra <PeriodType>;
            }

            if (extra != null)
            {
                // Handle special case like '上午', '下午'
                var parseResult = ParseChineseTimeOfDay(er.Text, referenceTime);

                if (!parseResult.Success)
                {
                    parseResult = TimePeriodFunctions.Handle(this.config.TimeParser, extra, referenceTime);
                }

                if (parseResult.Success)
                {
                    parseResult.FutureResolution = new Dictionary <string, string>
                    {
                        {
                            TimeTypeConstants.START_TIME,
                            FormatUtil.FormatTime(((Tuple <DateObject, DateObject>)parseResult.FutureValue).Item1)
                        },
                        {
                            TimeTypeConstants.END_TIME,
                            FormatUtil.FormatTime(((Tuple <DateObject, DateObject>)parseResult.FutureValue).Item2)
                        }
                    };

                    parseResult.PastResolution = new Dictionary <string, string>
                    {
                        {
                            TimeTypeConstants.START_TIME,
                            FormatUtil.FormatTime(((Tuple <DateObject, DateObject>)parseResult.PastValue).Item1)
                        },
                        {
                            TimeTypeConstants.END_TIME,
                            FormatUtil.FormatTime(((Tuple <DateObject, DateObject>)parseResult.PastValue).Item2)
                        }
                    };
                }

                var ret = new DateTimeParseResult
                {
                    Start         = er.Start,
                    Text          = er.Text,
                    Type          = er.Type,
                    Length        = er.Length,
                    Value         = parseResult,
                    ResolutionStr = "",
                    TimexStr      = parseResult.Timex
                };

                return(ret);
            }

            return(null);
        }