public BirthdayEvent(Core core, User owner, User user, int year) : base(core) { this.owner = owner; this.user = user; if (!user.IsFriend(owner.ItemKey)) { throw new InvalidEventException(); } UnixTime tz = new UnixTime(core, user.UserInfo.TimeZoneCode); this.eventId = ~user.Id; this.subject = user.TitleNameOwnership + " birthday"; this.description = string.Empty; this.views = 0; this.attendeeCount = 0; this.ownerKey = new ItemKey(owner.Id, owner.TypeId); this.userId = user.Id; this.startTimeRaw = tz.GetUnixTimeStamp(new DateTime(year, user.Profile.DateOfBirth.Month, user.Profile.DateOfBirth.Day, 0, 0, 0)); this.endTimeRaw = tz.GetUnixTimeStamp(new DateTime(year, user.Profile.DateOfBirth.Month, user.Profile.DateOfBirth.Day, 23, 59, 59)); this.allDay = true; this.invitees = 0; this.category = 0; this.location = string.Empty; }
/// <summary> /// Initializes a new instance of the ControlPanelSubModule class. /// </summary> /// <param name="core">The Core token.</param> public ControlPanelSubModule(Core core, Primitive owner) { this.core = core; this.db = core.Db; this.session = core.Session; this.tz = core.Tz; this.LoggedInMember = session.LoggedInMember; this.Owner = owner; core.Prose.AddApplication(Assembly.GetAssembly(this.GetType()).GetName().Name); }
public DateTime GetLastMessageDate(UnixTime tz) { return tz.DateTimeFromMysql(messageTimeLast); }
/// <summary> /// Gets the date the blog post was last modified. /// </summary> /// <param name="tz">Timezone</param> /// <returns>DateTime object</returns> public DateTime GetModifiedDate(UnixTime tz) { return tz.DateTimeFromMysql(modifiedRaw); }
public void StartSession(OAuthToken token) { core.Session = new SessionState(core, db, token, httpContext.Request, httpContext.Response); if (core.Session.LoggedInMember != null) { tz = core.Session.LoggedInMember.UserInfo.GetTimeZone; } // move it here core.Tz = tz; }
/// <summary> /// /// </summary> /// <param name="o"></param> /// <returns></returns> protected bool CancelOrder(HuobiOrder o) { bool traded = false; try { HuobiSimpleResult cancelResult = m_huobi.CancelOrder(m_market, o.id); } catch (HuobiException e) { // ignore order which have been filled, or cancelled if (e.m_error.code != 41 && e.m_error.code != 42) { throw; } else { if (e.m_error.code == 41) { // not found, so filled m_renderer.AddMarker(o.type == HuobiOrderType.buy, true, o.order_price, UnixTime.ConvertToDateTime(o.order_time)); traded = true; } m_lastOpenOrders.RemoveAll(loo => loo.id == o.id); } } return(traded); }
private static void Main() { Console.Write("\n\nConnecting to {0} {1}Net via RPC at {2}...", CoinService.Parameters.CoinLongName, (CoinService.Parameters.UseTestnet ? "Test" : "Main"), CoinService.Parameters.SelectedDaemonUrl); // Network difficulty try { Double networkDifficulty = CoinService.GetDifficulty(); Console.WriteLine("[OK]\n\n{0} Network Difficulty: {1}", CoinService.Parameters.CoinLongName, networkDifficulty.ToString("#,###", CultureInfo.InvariantCulture)); } catch (Exception exception) { Console.WriteLine("[Failed]\n\nPlease check your configuration and make sure that the daemon is up and running and that it is synchronized. \n\nException: " + exception); return; } // My balance Decimal myBalance = CoinService.GetBalance(); Console.WriteLine("\nMy balance: {0} {1}", myBalance, CoinService.Parameters.CoinShortName); // Current block Console.WriteLine("Current block: {0}", CoinService.GetBlockCount().ToString("#,#", CultureInfo.InvariantCulture)); // Wallet state Console.WriteLine("Wallet state: {0}", CoinService.IsWalletEncrypted() ? "Encrypted" : "Unencrypted"); // Keys and addresses if (myBalance > 0) { // My non-empty addresses Console.WriteLine("\n\nMy non-empty addresses:"); List <ListReceivedByAddressResponse> myNonEmptyAddresses = CoinService.ListReceivedByAddress(); foreach (ListReceivedByAddressResponse address in myNonEmptyAddresses) { Console.WriteLine("\n--------------------------------------------------"); Console.WriteLine("Account: " + (String.IsNullOrWhiteSpace(address.Account) ? "(no label)" : address.Account)); Console.WriteLine("Address: " + address.Address); Console.WriteLine("Amount: " + address.Amount); Console.WriteLine("Confirmations: " + address.Confirmations); Console.WriteLine("--------------------------------------------------"); } // My private keys if (Boolean.Parse(ConfigurationManager.AppSettings["ExtractMyPrivateKeys"]) && myNonEmptyAddresses.Count > 0 && CoinService.IsWalletEncrypted()) { const Int16 secondsToUnlockTheWallet = 3; try { Console.Write("\nWill now unlock the wallet for " + secondsToUnlockTheWallet + ((secondsToUnlockTheWallet > 1) ? " seconds" : " second") + "..."); BitcoinService.WalletPassphrase(CoinService.Parameters.WalletPassword, secondsToUnlockTheWallet); Console.WriteLine("[OK]\n\nMy private keys for non-empty addresses:\n"); foreach (ListReceivedByAddressResponse address in myNonEmptyAddresses) { Console.WriteLine("Private Key for address " + address.Address + ": " + CoinService.DumpPrivKey(address.Address)); } } catch (NullReferenceException) { Console.WriteLine("[Failed]. The wallet could not be unlocked, did you use the correct password?\n"); throw; } finally { Console.Write("\nLocking wallet..."); CoinService.WalletLock(); Console.WriteLine("[OK]"); } } // My transactions Console.WriteLine("\n\nMy transactions: "); List <ListTransactionsResponse> myTransactions = CoinService.ListTransactions(null, Int32.MaxValue, 0); foreach (ListTransactionsResponse transaction in myTransactions) { Console.WriteLine("\n---------------------------------------------------------------------------"); Console.WriteLine("Account: " + (String.IsNullOrWhiteSpace(transaction.Account) ? "(no label)" : transaction.Account)); Console.WriteLine("Address: " + transaction.Address); Console.WriteLine("Category: " + transaction.Category); Console.WriteLine("Amount: " + transaction.Amount); Console.WriteLine("Confirmations: " + transaction.Confirmations); Console.WriteLine("BlockHash: " + transaction.BlockHash); Console.WriteLine("BlockIndex: " + transaction.BlockIndex); Console.WriteLine("BlockTime: " + transaction.BlockTime + " - " + UnixTime.UnixTimeToDateTime(transaction.BlockTime)); Console.WriteLine("TxId: " + transaction.TxId); Console.WriteLine("Time: " + transaction.Time + " - " + UnixTime.UnixTimeToDateTime(transaction.Time)); Console.WriteLine("TimeReceived: " + transaction.TimeReceived + " - " + UnixTime.UnixTimeToDateTime(transaction.TimeReceived)); Console.WriteLine("---------------------------------------------------------------------------"); } // Transaction Details Console.WriteLine("\n\nMy transactions' details:"); foreach (ListTransactionsResponse transaction in myTransactions) { GetTransactionResponse localWalletTransaction = CoinService.GetTransaction(transaction.TxId); IEnumerable <PropertyInfo> localWalletTrasactionProperties = localWalletTransaction.GetType().GetProperties(); IList <GetTransactionResponseDetails> localWalletTransactionDetailsList = localWalletTransaction.Details.ToList(); Console.WriteLine("\nTransaction\n-----------"); foreach (PropertyInfo propertyInfo in localWalletTrasactionProperties) { String propertyInfoName = propertyInfo.Name; if (propertyInfoName != "Details" && propertyInfoName != "WalletConflicts") { Console.WriteLine(propertyInfoName + ": " + propertyInfo.GetValue(localWalletTransaction, null)); } } foreach (GetTransactionResponseDetails details in localWalletTransactionDetailsList) { IEnumerable <PropertyInfo> detailsProperties = details.GetType().GetProperties(); Console.WriteLine("\nTransaction details " + (localWalletTransactionDetailsList.IndexOf(details) + 1) + " of total " + localWalletTransactionDetailsList.Count + "\n--------------------------------"); foreach (PropertyInfo propertyInfo in detailsProperties) { Console.WriteLine(propertyInfo.Name + ": " + propertyInfo.GetValue(details, null)); } } } // Unspent transactions Console.WriteLine("My unspent transactions:"); List <ListUnspentResponse> unspentList = CoinService.ListUnspent(); foreach (ListUnspentResponse unspentResponse in unspentList) { IEnumerable <PropertyInfo> detailsProperties = unspentResponse.GetType().GetProperties(); Console.WriteLine("\nUnspent transaction " + (unspentList.IndexOf(unspentResponse) + 1) + " of " + unspentList.Count + "\n--------------------------------"); foreach (PropertyInfo propertyInfo in detailsProperties) { Console.WriteLine(propertyInfo.Name + " : " + propertyInfo.GetValue(unspentResponse, null)); } } } Console.ReadLine(); }
/// <summary> /// We do this so we don't have to keep re-declaring the same /// constructor /// </summary> /// <param name="core">Core token</param> /// <param name="owner">Owner</param> public void ModuleVector(Core core, Primitive owner, VariableCollection vc) { if (core == null) { throw new NullCoreException(); } this.core = core; this.db = core.Db; this.session = core.Session; this.tz = core.Tz; this.Owner = owner; this.LoggedInMember = session.LoggedInMember; this.parentModulesVariableCollection = vc; CreateTemplate(); string mode = core.Http["mode"]; EventHandler loadHandler = Load; if (loadHandler != null) { loadHandler(this, new EventArgs()); } if (string.IsNullOrEmpty(mode) || !HasModeHandler(mode)) { EventHandler showHandler = Show; if (showHandler != null) { showHandler(this, new EventArgs()); } } else if (!string.IsNullOrEmpty(mode)) { ShowMode(mode); } RenderTemplate(); }
/// <nodoc /> public ContentLocationEntry Touch(UnixTime accessTime) { return(new ContentLocationEntry(Locations, ContentSize, accessTime > LastAccessTimeUtc ? accessTime : LastAccessTimeUtc, CreationTimeUtc)); }
public DateTime GetCreatedDate(UnixTime tz) { return tz.DateTimeFromMysql(articleTime); }
public DateTime GetCompletedTime(UnixTime tz) { return tz.DateTimeFromMysql(completedTimeRaw); }
public DateTime GetInvitedTime(UnixTime tz) { return tz.DateTimeFromMysql(inviteTimeRaw); }
public DateTime GetReleaseDate(UnixTime tz) { return tz.DateTimeFromMysql(releaseDateRaw); }
public List<UserRelation> GetFriendsBirthdays(long startTimeRaw, long endTimeRaw) { DateTime st = core.Tz.DateTimeFromMysql(startTimeRaw - 24 * 60 * 60); DateTime et = core.Tz.DateTimeFromMysql(endTimeRaw + 48 * 60 * 60); List<UserRelation> friends = new List<UserRelation>(); SelectQuery query = UserRelation.GetSelectQueryStub(core, UserLoadOptions.All); query.AddCondition("relation_me", userId); query.AddCondition("relation_type", "FRIEND"); query.AddCondition("profile_date_of_birth_month_cache * 31 + profile_date_of_birth_day_cache", ConditionEquality.GreaterThanEqual, st.Month * 31 + st.Day); query.AddCondition("profile_date_of_birth_month_cache * 31 + profile_date_of_birth_day_cache", ConditionEquality.LessThanEqual, et.Month * 31 + et.Day); System.Data.Common.DbDataReader friendsReader = db.ReaderQuery(query); while (friendsReader.Read()) { UserRelation friend = new UserRelation(core, friendsReader, UserLoadOptions.All); UnixTime tz = new UnixTime(core, friend.UserInfo.TimeZoneCode); DateTime dob = new DateTime(st.Year, friend.Profile.DateOfBirth.Month, friend.Profile.DateOfBirth.Day); long dobUt = tz.GetUnixTimeStamp(dob); if ((dobUt >= startTimeRaw && dobUt <= endTimeRaw) || (dobUt + 24 * 60 * 60 - 1 >= startTimeRaw && dobUt + 24 * 60 * 60 - 1 <= endTimeRaw)) { friends.Add(friend); } } friendsReader.Close(); friendsReader.Dispose(); return friends; }
public DateTime GetSentDate(UnixTime tz) { return tz.DateTimeFromMysql(messageTime); }
public PutevoiForm(long _putevoi) { InitializeComponent(); conn = new SQLiteConnection("Data Source='db/database.db'; Version=3;"); conn.Open(); putevoi = Putevoi.Find(_putevoi, conn); List <ComboItem> itemlistdrivers = new List <ComboItem>(); var driverlist = Driver.All(conn); int drivercount = -1; int driveriterator = 0; foreach (Driver driver in driverlist) { itemlistdrivers.Add(new ComboItem(driver.id, driver.Name())); if (driver.id != putevoi.driver_id) { driveriterator++; } else { drivercount = driveriterator; } } comboSelectDriver.DataSource = itemlistdrivers; if (drivercount == -1) { comboSelectDriver.SelectedValue = -1; comboSelectDriver.SelectedText = "Выберите водителя"; } else { comboSelectDriver.SelectedItem = comboSelectDriver.Items[drivercount]; } List <ComboItem> itemlistengines = new List <ComboItem>(); var enginelist = Engine.All(conn); int enginecount = -1; int engineiterator = 0; foreach (Engine engine in enginelist) { itemlistengines.Add(new ComboItem(engine.id, engine.Name())); if (engine.id != putevoi.engine_id) { engineiterator++; } else { enginecount = engineiterator; } } comboSelectEngine.DataSource = itemlistengines; if (enginecount == -1) { comboSelectEngine.SelectedValue = -1; comboSelectEngine.SelectedText = "Выберите автомобиль"; } else { comboSelectEngine.SelectedItem = comboSelectEngine.Items[enginecount]; } List <ComboItem> itemlistcars = new List <ComboItem>(); var carlist = Car.All(conn); int carcount = -1; int cariterator = 0; foreach (Car car in carlist) { itemlistcars.Add(new ComboItem(car.id, car.Name())); if (car.id != putevoi.car_id) { cariterator++; } else { carcount = cariterator; } } comboSelectCar.DataSource = itemlistcars; if (carcount == -1) { comboSelectCar.SelectedValue = -1; comboSelectCar.SelectedText = "Выберите прицеп"; } else { comboSelectCar.SelectedItem = comboSelectCar.Items[carcount]; } List <ComboItem> listHw = new List <ComboItem>(); listHw.Add(new ComboItem(130, "Диз. топливо (1.3)")); listHw.Add(new ComboItem(200, "Бензин (2)")); listHw.Add(new ComboItem(264, "Нефтяной газ (2.64)")); listHw.Add(new ComboItem(200, "Природный газ (2)")); comboBoxHw.DataSource = listHw; textBoxFuelStart.Text = putevoi.fuel_start.ToString(); textBoxFuelZapravka.Text = putevoi.fuel_zapravka.ToString(); textBoxFuelKarta.Text = putevoi.fuel_karta.ToString(); textBoxFuelCash.Text = putevoi.fuel_cash.ToString(); textBoxFuelEnd.Text = putevoi.fuel_end.ToString(); textBoxFuelNorma.Text = putevoi.fuel_norma.ToString(); textBoxProbegStart.Text = putevoi.probeg_start.ToString(); textBoxProbegSGruzom.Text = putevoi.probeg_s_gruzom.ToString(); textBoxProbegBezGruza.Text = putevoi.probeg_bez_gruza.ToString(); textBoxProbegEnd.Text = putevoi.probeg_end.ToString(); dateTimePutevoiDateStart.Value = UnixTime.From(putevoi.date_start); dateTimePutevoiDateEnd.Value = UnixTime.From(putevoi.date_end); recalculateFuelNorm(); }
private void ImportClaim(RoleData roleData) { if (Claims.ContainsKey(roleData.id)) { return; } var claim = new Claim { Project = Project, ProjectId = Project.ProjectId, Character = null, //see later Group = null, // see later Comments = new List <Comment>() { new Comment() { Author = Project.ProjectAcls.Single(acl => acl.IsOwner).User, CommentText = new CommentText() { Text = new MarkdownString($"<a href=\"http://site.allrpg.info/orders/orders/{roleData.id}/act=view&site={Project.Details.AllrpgId}\">Заявка в allrpg</a>") }, CreatedTime = UnixTime.ToDateTime(roleData.datesent), IsCommentByPlayer = false, IsVisibleToPlayer = false, LastEditTime = UnixTime.ToDateTime(roleData.datesent), ParentCommentId = null, Project = Project, } }, CreateDate = UnixTime.ToDateTime(roleData.datesent), Player = Users[roleData.sid], MasterDeclinedDate = roleData.todelete2 == 0 && roleData.status != 4 ? (DateTime?)null : UnixTime.ToDateTime(roleData.date), PlayerDeclinedDate = roleData.todelete == 0 ? (DateTime?)null : UnixTime.ToDateTime(roleData.date), PlayerAcceptedDate = UnixTime.ToDateTime(roleData.datesent), LastUpdateDateTime = UnixTime.ToDateTime(roleData.date) }; foreach (var virtualField in roleData.@virtual) { if (virtualField.Key == 7152) //Known steam2016 "responsible master" { int responsibleMasterIdx; if (int.TryParse(virtualField.Value, out responsibleMasterIdx)) { var responsibleSid = Steam2016ResponsibleMasters[responsibleMasterIdx]; claim.ResponsibleMasterUser = responsibleSid == null ? null : Users[(int)responsibleSid]; } } else if (ConvertToCommentVirtualFields.Contains(virtualField.Key) && !string.IsNullOrWhiteSpace(virtualField.Value)) { claim.Comments.Add(new Comment() { Author = Users[roleData.sid], CommentText = new CommentText() { Text = new MarkdownString(virtualField.Value) }, CreatedTime = claim.CreateDate, IsCommentByPlayer = true, IsVisibleToPlayer = true, LastEditTime = DateTime.UtcNow, ParentCommentId = null, Project = Project, }); } } bool canbeApproved = false; Character character; CharacterGroup characterGroup; if (Characters.TryGetValue(roleData.vacancy, out character)) { claim.Character = character; canbeApproved = true; } else if (LocationsFromVacancies.TryGetValue(roleData.vacancy, out characterGroup)) { claim.Group = characterGroup; } else if (Locations.TryGetValue(roleData.locat, out characterGroup)) { claim.Group = characterGroup; } else { claim.Group = Project.RootGroup; } claim.MasterAcceptedDate = canbeApproved && roleData.status == 3 ? UnixTime.ToDateTime(roleData.date) : (DateTime?)null; claim.ClaimStatus = ConvertAllrpgStatus(roleData, canbeApproved); Claims.Add(roleData.id, claim); }
public DateTime DateCreated(UnixTime tz) { return tz.DateTimeFromMysql(timestampCreated); }
[InlineData("1900-01-01 0:00:00")] //Too low public void FromDateTime_OutOfRange_ExpectException(string dtStr) { DateTime input = DateTime.Parse(dtStr); Assert.Throws <ArgumentOutOfRangeException>(() => UnixTime.FromDateTime(input)); }
public DateTime DateCreated(UnixTime tz) { return groupInfo.DateCreated(tz); }
/// <summary> /// Generates a Time-Based One-Time Password for the current time /// </summary> /// <returns></returns> public string GeneratePassword() { long currentUnixTime = UnixTime.GetUnixTime(); return(GeneratePassword(currentUnixTime)); }
public void OnClientEvent(Client Player, string eventName, params object[] arguments) //arguments param can contain multiple params { if (eventName == "SC_race_house_get_listchange") { onRaceHouseUpdataToPlayer(Player, "手動刷新"); } if (eventName == "SC_race_createhouse") { //createhousefunctoin var roadname = arguments[0].ToString(); foreach (RaceRoad v in track.raceRoad) { if (v.getRaceName() == roadname) { if (v.getEditState() == true) { API.sendNotificationToPlayer(Player, "比賽:" + roadname + "\n創建~r~失敗~w~\n~g~原因 ~w~賽道正在被編輯"); API.triggerClientEvent(Player, "SC_race_house_join_false"); return; } if (v.getRaceCheckPointRows() <= 3) { API.sendNotificationToPlayer(Player, "比賽:" + roadname + "\n創建~r~失敗~w~\n~g~原因 ~w~該賽道檢查點數量不足"); API.triggerClientEvent(Player, "SC_race_house_join_false"); return; } var time = new Random().Next(0, 10000).ToString(); var h = new RaceHouse("#" + time + " " + roadname, Player, v); House.Add(h); API.sendChatMessageToAll("賽事大廳", API.getPlayerName(Player) + "~w~ 建立了一場 ~g~" + roadname + "~w~ 的比賽,趕緊加入吧!"); //傳遞給客戶端賽事大廳信息 //房間名、房間ID、房間主人名、房間玩家列表名、賽道名 h.addPlayer(Player); onRaceHouseUpdata(); //,刷新所有客戶端的賽事大廳列表 API.setEntityData(Player, "SC_race_house", h); API.setEntitySyncedData(Player, "SC_race_house_state", 1); h = null; break; } } } if (eventName == "SC_race_house_quit") { var h = API.getEntityData(Player, "SC_race_house"); h.sendMessageToPlayer("~g~" + API.getPlayerName(Player) + "~w~ 離開了這個房間."); h.removePlayer(Player); API.resetEntitySyncedData(Player, "SC_race_house_state"); API.resetEntityData(Player, "SC_race_house"); if (h.getRaceHousePlayers() == 0) { //房間關閉 API.consoleOutput("人退光了,房間關閉"); House.Remove(h); } onRaceHouseUpdata(); h = null; } if (eventName == "SC_race_house_nocar_quit") { var h = API.getEntityData(Player, "SC_race_house"); h.sendMessageToPlayer("~g~" + API.getPlayerName(Player) + "~w~ 被踢出了比賽,原因:~r~不在車裏/不是駕駛"); API.triggerClientEvent(Player, "SC_race_houseinfo_close", "close"); h = null; } if (eventName == "SC_race_house_start") { //race start! var h = API.getEntityData(Player, "SC_race_house"); h.startRace(); } if (eventName == "SC_race_house_join_house") { RaceHouse h = null; var hid = Convert.ToInt32(arguments[0]); var c = -1; foreach (RaceHouse v in House) { if (v.getRaceHouseId() == hid) { h = v; c = 1; } } if (c == -1) { API.sendNotificationToPlayer(Player, "房間加入~r~失敗~w~\n~g~原因 ~w~房間不存在\n請重新打開賽事大廳刷新列表"); return; } if (h.getRaceHouseState() == true) { API.sendNotificationToPlayer(Player, "房間:" + h.getRaceHouseName() + "\n加入~r~失敗~w~\n~g~原因 ~w~ 該房比賽已經開始了!"); return; } if (API.getEntitySyncedData(Player, "SC_race_house_state") == 1) { API.sendNotificationToPlayer(Player, "房間:" + h.getRaceHouseName() + "\n加入~r~失敗~w~\n~g~原因 ~w~你已經在一個房間裏了"); return; } h.addPlayer(Player); API.setEntityData(Player, "SC_race_house", h); API.setEntitySyncedData(Player, "SC_race_house_state", 1); h = null; } if (eventName == "SC_race_house_finisRace") { var h = API.getEntityData(Player, "SC_race_house"); var time = (UnixTime.getUnixTimeToMS() - h.getRaceHouseStartTick()); var nT = (float)time / 1000; var vT = nT.ToString(); var win = h.finishRace(Player, time, vT); var b = h.getRaceRoad().getTimeInTopTime(time); var scb = 0; var maxTime = (h.getRaceRoad().getRaceTopTimeToLong(1) / 1000) * 1.25; var topjl = 0; var drop = new Random().Next(100); API.triggerClientEvent(Player, "SC_race_house_finishrace_mission", h.getRaceRoad().getRaceName(), vT); if (b == true) { var us = API.getEntityData(Player, "SC_USERINFO"); us.setUserInfo("RACERANK", us.getUserInfo("RACERANK").infoValue + 50); us.setUserInfo("RACETOPS", us.getUserInfo("RACETOPS").infoValue + 1); h.sendMessageToPlayer("~g~" + API.getPlayerName(Player) + "~w~ 完成 ~g~" + h.getRaceRoad().getRaceName() + " ~w~獲得第 ~y~" + win.ToString() + " ~w~名"); API.sendNotificationToAll("~y~" + h.getRaceRoad().getRaceName() + " ~g~記錄刷新!~y~\n" + API.getPlayerName(Player) + "(" + vT + "s)", true); new TeamMain().teamRoadBoss(); if (API.hasEntityData(Player, "SC_TEAM") == true) { var t = API.getEntityData(Player, "SC_TEAM"); t.addTeamDynamic(Player.name + "~w~:以 ~y~" + vT + "s 的成績刷新了 ~y~" + h.getRaceRoad().getRaceName() + " ."); t.updataTeamDynamic(); t.saveTeam(); } API.triggerClientEventForAll("SC_race_toptimeupdata"); topjl = 1; drop = 100; } else { h.sendMessageToPlayer("~g~" + API.getPlayerName(Player) + "~w~ 完成 ~g~" + h.getRaceRoad().getRaceName() + " ~w~獲得第 ~r~" + win.ToString() + " ~w~名"); //API.consoleOutput(vT); } if (nT >= 60) { //比賽時間在60秒以上時才能獲得scb; var timeAdd = (double)Convert.ToInt64(h.getRaceRoad().getRaceTopTime(1)) / time; //基礎SCB獎勵,根據與記錄時間的比例來決定獲得多少 timeAdd = timeAdd * 800; var winsS = 0.1; //名次SCB獎勵系數 var winsAdd = 0.0; if (h.getRaceHouseRacePlayers() > 1) { if (API.hasEntityData(Player, "SC_TEAM") == true) { var t = API.getEntityData(Player, "SC_TEAM"); t.addTeamDynamic(Player.name + "~w~:在 ~y~" + h.getRaceRoad().getRaceName() + " 的" + h.getRaceHouseRacePlayers().ToString() + " 人比賽中獲得了 ~y~#" + win.ToString() + "(" + vT.ToString() + "s) ."); t.updataTeamDynamic(); t.saveTeam(); } var us = API.getEntityData(Player, "SC_USERINFO"); if (win == 1) { us.setUserInfo("RACEWINS", us.getUserInfo("RACEWINS").infoValue + 1); } else { us.setUserInfo("RACELOSES", us.getUserInfo("RACELOSES").infoValue + 1); } var maxSCB = h.getRaceHouseRacePlayers() * 1500; if (win == 1) { winsS = 1; us.setUserInfo("RACERANK", us.getUserInfo("RACERANK").infoValue + 40); } if (win == 2) { winsS = 0.7; us.setUserInfo("RACERANK", us.getUserInfo("RACERANK").infoValue - 30); } if (win == 3) { winsS = 0.5; us.setUserInfo("RACERANK", us.getUserInfo("RACERANK").infoValue - 35); } if (win > 3) { winsS = 0.3; us.setUserInfo("RACERANK", us.getUserInfo("RACERANK").infoValue - 38); } winsAdd = winsS * maxSCB; //名次SCB獎勵,與人數和排名有關 } var heal = API.getVehicleHealth(API.getPlayerVehicle(Player)) / 1000; heal = heal * 500; if (nT < maxTime || maxTime == -1) { timeAdd = timeAdd + ((nT * 8) * winsS); } scb = (int)timeAdd + (int)winsAdd + (int)heal; if (topjl == 1) { scb = scb * 2; API.sendNotificationToPlayer(Player, "~g~獎勵\n時間 ~y~" + Convert.ToInt32(timeAdd).ToString() + "~g~\n名次 ~y~" + Convert.ToInt32(winsAdd).ToString() + "\n~g~技術 ~y~" + Convert.ToInt32(heal).ToString() + "\n~g~記錄 ~y~" + Convert.ToInt32(scb / 2).ToString() + "\n~g~合計 ~y~" + scb.ToString(), false); } else { API.sendNotificationToPlayer(Player, "~g~獎勵\n時間 ~y~" + Convert.ToInt32(timeAdd).ToString() + "~g~\n名次 ~y~" + Convert.ToInt32(winsAdd).ToString() + "\n~g~技術 ~y~" + Convert.ToInt32(heal).ToString() + "\n~g~合計 ~y~" + scb.ToString(), false); } var m = API.getEntityData(Player, "SC_money"); m.addMoney(scb); m = null; if (drop >= 60) { new item_drop().itemDrop(Player); } } if (API.hasEntityData(Player, "SC_TEAM") == true) { var t = API.getEntityData(Player, "SC_TEAM"); t.updataPlayerRank(Player); t.updataTeamRank(); t.updataTeamRankToPlayer(); var acc = (float)t.getTeamBoss() / 100; var mon = Convert.ToInt32(scb * acc); API.sendNotificationToPlayer(Player, "~g~車隊獎勵\n~g~金錢 ~y~+" + (acc * 100).ToString() + "%\n~g~合計 ~y~" + mon.ToString(), true); var m = API.getEntityData(Player, "SC_money"); m.addMoney(mon); m = null; } h = null; } if (eventName == "SC_race_house_getlist") { onRaceHouseUpdata(); } }
public override void SetValue(IDbDataParameter parameter, DateTime?value) => parameter.Value = (value == null) ? null : (object)UnixTime.FromDateTime(value.Value);
public static string CreateFileName(string pruductId, string ext) { return(pruductId + FilseSeparator + UnixTime.UtcNow() + ext); }
public DateTime GetReleasedDate(UnixTime tz) { return tz.DateTimeFromMysql(documentRevisionReleasedDate); }
static void Main() { // attach graph renderer Rendering renderer = new Rendering(800, 400); long lastTradeId = -1; var marketAccesses = JsonConvert.DeserializeObject <List <MarketAccess> >(File.ReadAllText("accessKeys.txt")); var huobiAccess = marketAccesses.First(e => e.Name == "Huobi"); var btceAccess = marketAccesses.First(e => e.Name == "BTCE"); IMarket huobi = new Huobi(huobiAccess.AccessKey, huobiAccess.SecretKey); //huobi = new BTCeMarket(btceAccess.AccessKey, btceAccess.SecretKey); AlgoBase alogo = new NaiveMarketMaker(huobi, HuobiMarket.btc, renderer); BcwTrade lastTrade = null; TimeSpan timeOffset = new TimeSpan(); DateTime lastTime = new DateTime(); while (true) { try { List <BcwTrade> newTrades = huobi.GetPublicTrades(BcwMarket.huobibtccny, lastTradeId); newTrades.Reverse(); HuobiMarketSummary depth = huobi.GetMarketSummary(HuobiMarket.btc); BcwTicker ticker = huobi.GetTicker(BcwMarket.huobibtccny); DateTime now = UnixTime.ConvertToDateTime(ticker.date) + timeOffset; if (newTrades.Count > 0) { if (timeOffset.TotalSeconds == 0) { DateTime firstTradeDate = UnixTime.ConvertToDateTime(newTrades[0].date); if (firstTradeDate < lastTime) { timeOffset = firstTradeDate - lastTime; } } foreach (BcwTrade t in newTrades) { if (t.trade_type == BcwOrderType.ask) { // this condition means that a BUY ORDER was filled } else { // this condition means that a SELL ORDER was filled } renderer.AddDataPoint(depth.GetBidPrice(0), depth.GetAskPrice(0), t.price, UnixTime.ConvertToDateTime(t.date)); } lastTrade = newTrades.Last(); lastTradeId = newTrades.Last().tid; now = UnixTime.ConvertToDateTime(lastTrade.date); } else { renderer.AddDataPoint(depth.GetBidPrice(0), depth.GetAskPrice(0), lastTrade.price, now); } // // update the algorithm // alogo.Update(now); } catch (HuobiApi.RetryCountExceededException) { } catch (Newtonsoft.Json.JsonReaderException e) { Console.WriteLine(e.ToString()); } Thread.Sleep(5000); } }
public DateTime GetReadTime(UnixTime tz) { return tz.DateTimeFromMysql(readTime); }
public Dictionary <string, Person> GetPeople(HashSet <String> ids, HashSet <String> fields, CollectionOptions options) { var result = new Dictionary <string, Person>(); using (var db = new AzureRayaDataContext()) { // TODO filter first then fill dictionary foreach (var id in ids) { var p = db.persons.Where(x => x.PartitionKey == id).SingleOrDefault(); if (p == null) { continue; } string personId = p.id; var name = new Name(); var person = new Person(); name.givenName = p.first_name; name.familyName = p.last_name; name.formatted = p.first_name + " " + p.last_name; person.displayName = name.formatted; person.name = name; person.id = personId; if (fields.Contains("about_me") || fields.Contains("@all")) { person.aboutMe = p.about_me; } if (fields.Contains("age") || fields.Contains("@all")) { person.age = p.age; } if (fields.Contains("children") || fields.Contains("@all")) { person.children = p.children; } if (fields.Contains("date_of_birth") || fields.Contains("@all")) { if (p.date_of_birth.HasValue) { person.birthday = UnixTime.ToDateTime(p.date_of_birth.Value); } } if (fields.Contains("ethnicity") || fields.Contains("@all")) { person.ethnicity = p.ethnicity; } if (fields.Contains("fashion") || fields.Contains("@all")) { person.fashion = p.fashion; } if (fields.Contains("happiest_when") || fields.Contains("@all")) { person.happiestWhen = p.happiest_when; } if (fields.Contains("humor") || fields.Contains("@all")) { person.humor = p.humor; } if (fields.Contains("job_interests") || fields.Contains("@all")) { person.jobInterests = p.job_interests; } if (fields.Contains("living_arrangement") || fields.Contains("@all")) { person.livingArrangement = p.living_arrangement; } if (fields.Contains("looking_for") || fields.Contains("@all")) { person._lookingFor = p.looking_for; } if (fields.Contains("nickname") || fields.Contains("@all")) { person.nickname = p.nickname; } if (fields.Contains("pets") || fields.Contains("@all")) { person.pets = p.pets; } if (fields.Contains("political_views") || fields.Contains("@all")) { person.politicalViews = p.political_views; } if (fields.Contains("profile_song") || fields.Contains("@all")) { if (!string.IsNullOrEmpty(p.profile_song)) { person.profileSong = new Url(p.profile_song, "", ""); } } if (fields.Contains("profileUrl") || fields.Contains("@all")) { person.profileUrl = urlPrefix + "/profile/" + personId; } if (fields.Contains("profile_video") || fields.Contains("@all")) { if (!string.IsNullOrEmpty(p.profile_video)) { person.profileVideo = new Url(p.profile_video, "", ""); } } if (fields.Contains("relationship_status") || fields.Contains("@all")) { person.relationshipStatus = p.relationship_status; } if (fields.Contains("religion") || fields.Contains("@all")) { person.religion = p.religion; } if (fields.Contains("romance") || fields.Contains("@all")) { person.romance = p.romance; } if (fields.Contains("scared_of") || fields.Contains("@all")) { person.scaredOf = p.scared_of; } if (fields.Contains("sexual_orientation") || fields.Contains("@all")) { person.sexualOrientation = p.sexual_orientation; } if (fields.Contains("status") || fields.Contains("@all")) { person.status = p.status; } if (fields.Contains("thumbnailUrl") || fields.Contains("@all")) { person.thumbnailUrl = !string.IsNullOrEmpty(p.thumbnail_url) ? urlPrefix + p.thumbnail_url : ""; if (!string.IsNullOrEmpty(p.thumbnail_url)) { person.photos = new List <ListField> { new Url(urlPrefix + p.thumbnail_url, "thumbnail", "thumbnail") }; } } if (fields.Contains("time_zone") || fields.Contains("@all")) { person.utcOffset = p.time_zone; // force "-00:00" utc-offset format } if (fields.Contains("drinker") || fields.Contains("@all")) { if (!String.IsNullOrEmpty(p.drinker)) { person.drinker = (Drinker)Enum.Parse(typeof(Drinker), p.drinker); } } if (fields.Contains("gender") || fields.Contains("@all")) { if (!String.IsNullOrEmpty(p.gender)) { person.gender = (Person.Gender)Enum.Parse(typeof(Person.Gender), p.gender, true); } } if (fields.Contains("smoker") || fields.Contains("@all")) { if (!String.IsNullOrEmpty(p.smoker)) { person.smoker = (Smoker)Enum.Parse(typeof(Smoker), p.smoker); } } if (fields.Contains("activities") || fields.Contains("@all")) { var activities = db.activities.Where(a => a.PartitionKey == personId); person.activities = new List <string>(); foreach (var act in activities) { person.activities.Add(act.title); } } if (fields.Contains("addresses") || fields.Contains("@all")) { var personAddresses = db.addressesPerson .Where(x => x.PartitionKey == personId); List <Address> addresses = new List <Address>(); foreach (var row in personAddresses) { if (String.IsNullOrEmpty(row.unstructured_address)) { row.unstructured_address = (row.street_address + " " + row.region + " " + row.country).Trim(); } var addr = new Address(row.unstructured_address); addr.country = row.country; addr.latitude = row.latitude; addr.longitude = row.longitude; addr.locality = row.locality; addr.postalCode = row.postal_code; addr.region = row.region; addr.streetAddress = row.street_address; addr.type = row.address_type; //FIXME quick and dirty hack to demo PC addr.primary = true; addresses.Add(addr); } person.addresses = addresses; } if (fields.Contains("bodyType") || fields.Contains("@all")) { var row = db.personBodyTypes.Where(x => x.PartitionKey == personId).SingleOrDefault(); if (row != null) { BodyType bodyType = new BodyType(); bodyType.build = row.build; bodyType.eyeColor = row.eye_color; bodyType.hairColor = row.hair_color; bodyType.height = row.height; bodyType.weight = row.weight; person.bodyType = bodyType; } } if (fields.Contains("books") || fields.Contains("@all")) { var books = db.personBooks.Where(x => x.PartitionKey == personId); var bookList = new List <string>(); foreach (var book in books) { bookList.Add(book.book); } person.books = bookList; } if (fields.Contains("cars") || fields.Contains("@all")) { var cars = db.personCars.Where(x => x.PartitionKey == personId); var carList = new List <string>(); foreach (var car in cars) { carList.Add(car.car); } person.cars = carList; } if (fields.Contains("currentLocation") || fields.Contains("@all")) { var row = db.personCurrentLocations .Where(x => x.PartitionKey == personId).SingleOrDefault(); if (row != null) { if (string.IsNullOrEmpty(row.unstructured_address)) { row.unstructured_address = (row.street_address + " " + row.region + " " + row.country).Trim(); } var addr = new Address(row.unstructured_address); addr.country = row.country; addr.latitude = row.latitude; addr.longitude = row.longitude; addr.locality = row.locality; addr.postalCode = row.postal_code; addr.region = row.region; addr.streetAddress = row.street_address; addr.type = row.address_type; person.currentLocation = addr; } } if (fields.Contains("emails") || fields.Contains("@all")) { var emails = db.personEmails.Where(x => x.PartitionKey == personId); List <ListField> emailList = new List <ListField>(); foreach (var email in emails) { emailList.Add(new ListField(email.email_type, email.address)); // TODO: better email canonicalization; remove dups } person.emails = emailList; } if (fields.Contains("food") || fields.Contains("@all")) { var foods = db.personFoods.Where(x => x.PartitionKey == personId); var foodList = new List <string>(); foreach (var food in foods) { foodList.Add(food.food); } person.food = foodList; } if (fields.Contains("heroes") || fields.Contains("@all")) { var heroes = db.personHeroes.Where(x => x.PartitionKey == personId); var heroList = new List <string>(); foreach (var hero in heroes) { heroList.Add(hero.hero); } person.heroes = heroList; } if (fields.Contains("interests") || fields.Contains("@all")) { var interests = db.personInterests.Where(x => x.PartitionKey == personId); var interestList = new List <string>(); foreach (var interest in interests) { interestList.Add(interest.interest); } person.interests = interestList; } List <Organization> organizations = new List <Organization>(); bool fetchedOrg = false; if (fields.Contains("jobs") || fields.Contains("@all")) { var jobs = db.personJobs .Where(x => x.PartitionKey == personId); foreach (var job in jobs) { var organization = new Organization(); organization.description = job.description; if (job.end_date.HasValue) { organization.endDate = UnixTime.ToDateTime(job.end_date.Value); } organization.field = job.field; organization.name = job.name; organization.salary = job.salary; if (job.start_date.HasValue) { organization.startDate = UnixTime.ToDateTime(job.start_date.Value); } organization.subField = job.sub_field; organization.title = job.title; organization.webpage = job.webpage; organization.type = "job"; if (!string.IsNullOrEmpty(job.id)) { var addresses = db.addressesOrganization.Where(x => x.organization_id == job.id).Single(); if (string.IsNullOrEmpty(addresses.unstructured_address)) { addresses.unstructured_address = (addresses.street_address + " " + addresses.region + " " + addresses.country).Trim(); } var addr = new Address(addresses.unstructured_address); addr.country = addresses.country; addr.latitude = addresses.latitude; addr.longitude = addresses.longitude; addr.locality = addresses.locality; addr.postalCode = addresses.postal_code; addr.region = addresses.region; addr.streetAddress = addresses.street_address; addr.type = addresses.address_type; organization.address = addr; } organizations.Add(organization); } fetchedOrg = true; } if (fields.Contains("schools") || fields.Contains("@all")) { var schools = db.personSchools .Where(x => x.PartitionKey == personId); foreach (var school in schools) { var organization = new Organization(); organization.description = school.description; if (school.end_date.HasValue) { organization.endDate = UnixTime.ToDateTime(school.end_date.Value); } organization.field = school.field; organization.name = school.name; organization.salary = school.salary; if (school.start_date.HasValue) { organization.startDate = UnixTime.ToDateTime(school.start_date.Value); } organization.subField = school.sub_field; organization.title = school.title; organization.webpage = school.webpage; organization.type = "school"; if (!string.IsNullOrEmpty(school.id)) { var res3 = db.addressesOrganization.Where(x => x.organization_id == school.id).Single(); if (string.IsNullOrEmpty(res3.unstructured_address)) { res3.unstructured_address = (res3.street_address + " " + res3.region + " " + res3.country).Trim(); } var addres = new Address(res3.unstructured_address); addres.country = res3.country; addres.latitude = res3.latitude; addres.longitude = res3.longitude; addres.locality = res3.locality; addres.postalCode = res3.postal_code; addres.region = res3.region; addres.streetAddress = res3.street_address; addres.type = res3.address_type; organization.address = addres; } organizations.Add(organization); } fetchedOrg = true; } if (fetchedOrg) { person.organizations = organizations; } //TODO languagesSpoken, currently missing the languages / countries tables so can"t do this yet if (fields.Contains("movies") || fields.Contains("@all")) { var movies = db.personMovies.Where(x => x.PartitionKey == personId); var movieList = new List <string>(); foreach (var movie in movies) { movieList.Add(movie.movie); } person.movies = movieList; } if (fields.Contains("music") || fields.Contains("@all")) { var musics = db.personMusics.Where(x => x.PartitionKey == personId); var musicList = new List <string>(); foreach (var music in musics) { musicList.Add(music.music); } person.music = musicList; } if (fields.Contains("phoneNumbers") || fields.Contains("@all")) { List <ListField> numList = new List <ListField>(); var numbers = db.personPhoneNumbers.Where(x => x.PartitionKey == personId); foreach (var number in numbers) { numList.Add(new ListField(number.number_type, number.number)); } person.phoneNumbers = numList; } /* * if (_fields.Contains("ims") || _fields.Contains("@all")) * { * var _ims = array(); * _res2 = mysqli_query(this._db, "select value, value_type from person_ims where person_id = " + _person_id); * while (list(_value, _type) = @mysqli_fetch_row(_res2)) * { * _ims[] = new Im(_value, _type); * } * _person.Ims = _ims; * } * if (_fields.Contains("accounts") || _fields.Contains("@all")) { * _accounts = array(); * _res2 = mysqli_query(this._db, "select domain, userid, username from person_accounts where person_id = " + _person_id); * while (list(_domain, _userid, _username) = @mysqli_fetch_row(_res2)) { * _accounts[] = new Account(_domain, _userid, _username); * } * _person.Accounts = _accounts; * }*/ /* * if (fields.Contains("quotes") || fields.Contains("@all")) * { * var _strings = db.person_quotes.Where(x => x.person_id == personId).Select(x => x.quote); * person.quotes = _strings.ToList(); * } * if (fields.Contains("sports") || fields.Contains("@all")) * { * var _strings = db.person_sports.Where(x => x.person_id == personId).Select(x => x.sport); * person.sports = _strings.ToList(); * } * * if (fields.Contains("tags") || fields.Contains("@all")) * { * var _strings = db.person_tags.Where(x => x.person_id == personId).Select(x => x.tag); * person.tags = _strings.ToList(); * } * * if (fields.Contains("turnOns") || fields.Contains("@all")) * { * var _strings = db.person_turn_ons.Where(x => x.person_id == personId).Select(x => x.turn_on); * person.turnOns = _strings.ToList(); * } * if (fields.Contains("turnOffs") || fields.Contains("@all")) * { * var _strings = db.person_turn_offs.Where(x => x.person_id == personId).Select(x => x.turn_off); * person.turnOffs = _strings.ToList(); * } * */ if (fields.Contains("urls") || fields.Contains("@all")) { var urls = db.personUrls.Where(x => x.PartitionKey == personId); List <ListField> urllist = new List <ListField>(); foreach (var u in urls) { var url = new Url(u.url, null, null); urllist.Add(url); } //urllist.Add(new Url(urlPrefix + "/profile/" + personId, null, "profile")); person.urls = urllist; } result.Add(personId, person); } // foreach } return(result); }
public void ReturnsValueAsString() { var unixTime = new UnixTime(1432754581121); Assert.Equal("1432754581121", unixTime.ToString()); }
public DateTime GetFeaturedDate(UnixTime tz) { return tz.DateTimeFromMysql(featuredDate); }
//jsonをパースしてリストにする private void StoreItem(dynamic json, List <NicoNicoMylistData> ret) { foreach (var entry in json.mylistitem) { NicoNicoMylistData data = new NicoNicoMylistData(); data.CreateTime = UnixTime.FromUnixTime((long)entry.create_time).ToString(); data.Description = entry.description; data.ItemId = entry.item_id; var item = entry.item_data; data.Title = HttpUtility.HtmlDecode(item.title); if (entry.item_type is string) { data.Type = int.Parse(entry.item_type); } else if (entry.item_type is double) { data.Type = (int)entry.item_type; } //動画 if (data.Type == 0) { data.UpdateTime = UnixTime.FromUnixTime((long)item.update_time).ToString(); data.FirstRetrieve = UnixTime.FromUnixTime((long)item.first_retrieve).ToString(); data.Length = NicoNicoUtil.ConvertTime(long.Parse(item.length_seconds)); data.Id = item.video_id; data.ViewCounter = int.Parse(item.view_counter); data.CommentCounter = int.Parse(item.num_res); data.MylistCounter = int.Parse(item.mylist_counter); data.ThumbNailUrl = item.thumbnail_url; } else if (data.Type == 5) //静画 { data.UpdateTime = UnixTime.FromUnixTime((long)item.update_time).ToString(); data.FirstRetrieve = UnixTime.FromUnixTime((long)item.create_time).ToString(); data.Id = item.id.ToString(); data.ViewCounter = (int)item.view_count; data.CommentCounter = (int)item.comment_count; data.MylistCounter = (int)item.mylist_count; data.ThumbNailUrl = item.thumbnail_url; } else if (data.Type == 6) //書籍 { data.UpdateTime = UnixTime.FromUnixTime((long)entry.update_time).ToString(); data.FirstRetrieve = UnixTime.FromUnixTime((long)item.released_at).ToString(); data.Id = "bk" + item.id; data.ViewCounter = (int)item.view_count; data.CommentCounter = (int)item.comment_count; data.MylistCounter = (int)item.mylist_count; data.ThumbNailUrl = item.thumbnail; } else if (data.Type == 13) //ブロマガ { data.UpdateTime = UnixTime.FromUnixTime((long)item.commented_time).ToString(); data.FirstRetrieve = UnixTime.FromUnixTime((long)item.create_time).ToString(); data.Id = "ar" + item.id; data.CommentCounter = (int)item.comment_count; data.MylistCounter = int.Parse(item.mylist_count); data.ThumbNailUrl = item.thumbnail_url; } ret.Add(data); } }
public DateTime GetRegisteredDate(UnixTime tz) { return tz.DateTimeFromMysql(registeredDate); }
public DateTime GetTime(UnixTime tz) { if (tz == null) { return core.Tz.DateTimeFromMysql(tz); } return tz.DateTimeFromMysql(trackBackTimeRaw); }
public DateTime GetVisit(UnixTime tz) { return tz.DateTimeFromMysql(lastVisitRaw); }
public DateTime GetMemberDate(UnixTime tz) { return tz.DateTimeFromMysql(memberDateRaw); }
public DateTime GetStart(UnixTime tz) { return tz.DateTimeFromMysql(sessionStartRaw); }
/// <summary> /// Factory method that creates a valid content location. /// </summary> public static ContentLocationEntry Create(MachineIdSet locations, long contentSize, UnixTime lastAccessTimeUtc, UnixTime?creationTimeUtc = null) { Contract.Requires(lastAccessTimeUtc != default); return(new ContentLocationEntry(locations, contentSize, lastAccessTimeUtc, creationTimeUtc)); }
public IList <AllianceRequestMessageDataModel> RejectRequestToAlliance(IDbConnection connection, AllianceUserDataModel currentUser, int rejectUserId, AllianceRoleDataModel role = null) { var permition = role ?? AllianceRoleHelper.GetByRoleId(currentUser.RoleId); if (!permition.AcceptNewMembers) { throw new SecurityException(Error.NotPermitted); } var data = _armCache.LocalOperation(connection, col => { return(col.Where(i => i.FromId == currentUser.AllianceId && i.ToId == rejectUserId && i.SourceType == MessageSourceType.IsAlliance || i.FromId == rejectUserId && i.ToId == currentUser.AllianceId && i.SourceType == MessageSourceType.IsUser).ToList()); }); if (!data.Any()) { return(data); } foreach (var request in data) { request.AllianceAccepted = ArmAllianceAcceptedStatus.Reject; } var dbData = _armRepo.AddOrUpdateAllModels(connection, data); var newData = _armCache.UpdateLocalItems(connection, dbData); var alData = newData.FirstOrDefault(i => i.FromId == currentUser.AllianceId && i.SourceType == MessageSourceType.IsAlliance); var rejectedUser = data.First(i => i.FromId == rejectUserId && i.SourceType == MessageSourceType.IsUser); var armModel = new AllianceRequestMessageDataModel { AllianceAccepted = ArmAllianceAcceptedStatus.Reject, ToId = rejectUserId, DateCreate = UnixTime.UtcNow(), FromId = currentUser.AllianceId, Message = "Rejected", UserAccepted = false, SourceType = MessageSourceType.IsAlliance, ToName = rejectedUser.FromName }; armModel.AllianceAccepted = ArmAllianceAcceptedStatus.Reject; if (alData == null) { var allaince = GetAllianceById(connection, currentUser.AllianceId, false); if (allaince == null) { throw new NullReferenceException(Error.AllianceNotExist); } armModel.FromName = allaince.Name; armModel.CreatorIcon = allaince.Images.Icon; } else { armModel.FromName = alData.FromName; armModel.CreatorIcon = alData.CreatorIcon; } var messageForUser = AddArmItem(connection, armModel); newData.Add(messageForUser); return(newData); }
public DateTime ToDateTime() { return(UnixTime.ToDateTime(ToInt64())); }
public OrderList GetOrderList( int?from = null, int?count = null, int?fromId = null, int?endId = null, bool?orderAsc = null, DateTime?since = null, DateTime?end = null, BtcePair?pair = null, bool?active = null ) { var args = new Dictionary <string, string>() { { "method", "OrderList" } }; if (from != null) { args.Add("from", from.Value.ToString()); } if (count != null) { args.Add("count", count.Value.ToString()); } if (fromId != null) { args.Add("from_id", fromId.Value.ToString()); } if (endId != null) { args.Add("end_id", endId.Value.ToString()); } if (orderAsc != null) { args.Add("order", orderAsc.Value ? "ASC" : "DESC"); } if (since != null) { args.Add("since", UnixTime.GetFromDateTime(since.Value).ToString()); } if (end != null) { args.Add("end", UnixTime.GetFromDateTime(end.Value).ToString()); } if (pair != null) { args.Add("pair", BtcePairHelper.ToString(pair.Value)); } if (active != null) { args.Add("active", active.Value ? "1" : "0"); } var result = JObject.Parse(Query(args)); if (result.Value <int>("success") == 0) { throw new Exception(result.Value <string>("error")); } return(OrderList.ReadFromJObject(result["return"] as JObject)); }
static void Main(string[] args) { TradeioApi api = new TradeioApi("aaaaaaaa-bbbb-cccc-dddd-eeeeeeee", "aaaaaaaa-bbbb-cccc-dddd-eeeeeeee"); string symbol = "btc_usdt"; Console.WriteLine("******PAIRS******"); PairsResponse pairsResponse = api.GetPairs().Result; Console.WriteLine(string.Join(',', pairsResponse.Pairs)); Console.WriteLine("******CANDLES******"); CandlesResponse candles = api.GetCandles("btc_usdt", CandleInterval.OneDay, DateTime.UtcNow.AddMonths(-1), DateTime.UtcNow, 20).Result; foreach (CandleInfo candle in candles.Candles) { Console.WriteLine($"open: {candle.Open}; close: {candle.Close}; low: {candle.Low}; high: {candle.High}"); } Console.WriteLine("******ORDER BOOK******"); OrderBookResponse orderBookResponse = api.GetOrderBook(symbol, 2).Result; Console.WriteLine("***ASK***"); foreach (var askArray in orderBookResponse.Book.Asks) { Console.WriteLine($"Price: {askArray[0]}; Count: {askArray[1]}"); } Console.WriteLine("***BID***"); foreach (var bidArray in orderBookResponse.Book.Bids) { Console.WriteLine($"Price: {bidArray[0]}; Count: {bidArray[1]}"); } Console.WriteLine("******TICKER******"); TickerResponse tickerResponse = api.GetTicker(symbol).Result; Console.WriteLine($"ASK price: {tickerResponse.Ticker.AskPrice}, qty: {tickerResponse.Ticker.AskQty}; BID price: {tickerResponse.Ticker.BidPrice}, qty: {tickerResponse.Ticker.BidQty}"); //tickers for all pairs //var tickers = api.GetTickers().Result; Console.WriteLine("******RECENT TRADES******"); TradesResponse tradesResponse = api.GetRecentTrades("btc_usdt", 2).Result; foreach (TradeInfo trade in tradesResponse.Trades) { Console.WriteLine($"{trade.Symbol} price: {trade.Price}, qty: {trade.Quantity}, side: {trade.Type}, date: {UnixTime.GetDateTime(trade.Time)} UTC"); } //PRIVATE METHODS. NOT WORKING WITHOUT PUBLIC AND PRIVATE KEY Console.WriteLine("******CURRENT BALANCES******"); AccountBalanceResponse accountBalance = api.GetAccount().Result; foreach (BalanceInfo balanceInfo in accountBalance.Balances) { Console.WriteLine($"{balanceInfo.Asset}:{balanceInfo.Available} (locked: {balanceInfo.Locked})"); } Console.WriteLine("******OPEN ORDERS******"); OrdersResponse ordersResponse = api.GetOpenOrders(symbol).Result; foreach (OrderInfoResponse order in ordersResponse.Orders) { Console.WriteLine($"{order.Side} {order.Instrument} for {order.Price}. Filled: {order.UnitsFilled}"); } Console.WriteLine("******CLOSED ORDERS******"); FilteredResponse <OrderInfoResponse> closeOrdersResponse = api.GetClosedOrders(symbol, UnixTime.Get(DateTime.UtcNow.AddDays(-1)), UnixTime.Get(DateTime.UtcNow)).Result; foreach (OrderInfoResponse order in closeOrdersResponse.Data) { Console.WriteLine($"{order.Side} {order.Instrument} for {order.Price}. Filled: {order.UnitsFilled}. Status: {order.Status}"); } Console.WriteLine("******PLACE ORDER******"); var orderResponse = api.PlaceOrder(new Models.OrderRequest() { Price = 4000, Quantity = 10, Side = Models.OrderSide.Buy, Symbol = symbol, Type = Models.OrderType.Limit }).Result; Console.WriteLine("******CANCEL ORDER******"); Response response = api.CancelOrder(orderResponse.Order.OrderId).Result; if (response.Code == 200) { Console.WriteLine("Order canceled"); } Console.ReadLine(); }
public void CurrentUnixTimeMilliseconds() { Assert.True(UnixTime.CurrentUnixTimeMilliseconds() > 1530237889000); Assert.True((new DateTime(2018, 1, 1)).CurrentUnixTimeMilliseconds() > 1530237889000); Assert.True(((DateTime?)null).CurrentUnixTimeMilliseconds() > 1530237889000); }
/// <summary> /// Generates a Time-Based One-Time Password for a given DateTime /// </summary> /// <param name="dateTime">The date time.</param> /// <returns></returns> public string GeneratePassword(DateTime dateTime) { long givenUnixTime = UnixTime.GetUnixTime(dateTime); return(GeneratePassword(givenUnixTime)); }
public void ToUtcDateTimeUIntTest() { Assert.Equal(new DateTime(2018, 06, 29, 02, 04, 49, DateTimeKind.Utc), UnixTime.UnixTimeToUtcDateTime((uint)1530237889)); }
public override void SetValue(IDbDataParameter parameter, DateTime value) => parameter.Value = UnixTime.FromDateTime(value);
public void ToUtcDateTimeNullableLongTest() { Assert.Equal(new DateTime(2018, 06, 29, 02, 04, 49, DateTimeKind.Utc), UnixTime.UnixTimeToUtcDateTime((long?)1530237889L)); Assert.Equal(default(DateTime), UnixTime.UnixTimeToUtcDateTime((long?)null)); }
public static long FormDate(Core core, string name, UnixTime tz) { if (core == null) { throw new NullCoreException(); } long datetime = 0; DateTime dt = tz.Now; string dateExpression = core.Http.Form[name + "--expression"]; string timeExpression = core.Http.Form[name + "--time"]; string dateMode = core.Http.Form[name + "--mode"]; if (dateMode == "ajax" && (!string.IsNullOrEmpty(dateExpression))) { dateExpression = core.Functions.InterpretDate(dateExpression, DisplayMedium.Desktop); timeExpression = core.Functions.InterpretTime(timeExpression); string expression = dateExpression + " " + timeExpression; if (!DateTime.TryParse(expression, out dt)) { int year = core.Functions.FormInt(name + "--date-year", dt.Year); int month = core.Functions.FormInt(name + "--date-month", dt.Month); int day = core.Functions.FormInt(name + "--date-day", dt.Day); int hour = core.Functions.FormInt(name + "--date-hour", dt.Hour); int minute = core.Functions.FormInt(name + "--date-minute", dt.Minute); int second = core.Functions.FormInt(name + "--date-second", 0); dt = new DateTime(year, month, day, hour, minute, second); } } else { int year = core.Functions.FormInt(name + "--date-year", dt.Year); int month = core.Functions.FormInt(name + "--date-month", dt.Month); int day = core.Functions.FormInt(name + "--date-day", dt.Day); int hour = core.Functions.FormInt(name + "--date-hour", dt.Hour); int minute = core.Functions.FormInt(name + "--date-minute", dt.Minute); int second = core.Functions.FormInt(name + "--date-second", 0); dt = new DateTime(year, month, day, hour, minute, second); } datetime = tz.GetUnixTimeStamp(dt); return datetime; }
public void ToUtcDateTimeULongTest() { Assert.Equal(new DateTime(2018, 06, 29, 02, 04, 49, DateTimeKind.Utc), UnixTime.UnixTimeToUtcDateTime(1530237889UL)); }
public void ContentTouched(OperationContext context, MachineId sender, IReadOnlyList <ShortHash> hashes, UnixTime accessTime) { Events.Add(new TouchContentLocationEventData(sender, hashes, accessTime.ToDateTime())); }
public override void OnInspectorGUI() { if (Context.ProjectToken == null) { GUILayout.Label("サインインしてプロジェクトを選択してください。"); if (GUILayout.Button("サインイン")) { EditorWindow.GetWindow(typeof(SigninWindow), true, "Sign-in to GS2").Show(); } return; } if (_manifest == null) { _manifest = Manifest.Load(this); } if (_installing || _updating || _uninstalling) { if (_installing) { EditorGUILayout.LabelField("インストール中..."); } else if (_updating) { EditorGUILayout.LabelField("アップデート中..."); } else if (_uninstalling) { EditorGUILayout.LabelField("アンインストール中..."); } if (GUILayout.Button("Back")) { _installing = false; _updating = false; _uninstalling = false; _status = null; Repaint(); } using (new GUILayout.VerticalScope(GUI.skin.box)) { if (events != null) { foreach (var e in events) { using (new GUILayout.HorizontalScope()) { if (e.eventAt != null) { GUILayout.Label(UnixTime.FromUnixTime(e.eventAt.Value).ToShortTimeString()); } GUILayout.Label(e.resourceName); GUILayout.Label(e.type); GUILayout.Label(e.message); } } } } return; } if (_postProcess == null) { _postProcess = PostProcess(); } if (_status == null) { EditorCoroutineUtility.StartCoroutineOwnerless( WeaveInstaller.GetStatus( _manifest, r => { _status = r.Result.status; Repaint(); } ) ); } else if (_status == "CREATE_COMPLETE" || _status == "UPDATE_COMPLETE") { if (GUILayout.Button("アンインストール")) { EditorCoroutineUtility.StartCoroutineOwnerless( WeaveInstaller.Uninstall( _manifest, e => { Repaint(); events = e; }, () => { Repaint(); _uninstalling = false; _status = null; } ) ); _uninstalling = true; Repaint(); } EditorGUILayout.LabelField(""); if (GUILayout.Button("設定値をサーバから取得")) { EditorCoroutineUtility.StartCoroutineOwnerless( WeaveInstaller.GetOutputs( _manifest, r => { if (r.Error != null) { EditorUtility.DisplayDialog("Error", r.Error.Message, "OK"); } else { Repaint(); outputs = r.Result.items; } } ) ); } if (_postProcess != null) { EditorGUILayout.LabelField(""); if (GUILayout.Button("設定変更を反映")) { EditorCoroutineUtility.StartCoroutineOwnerless( WeaveInstaller.Update( _manifest, e => { Repaint(); events = e; }, () => { Repaint(); _updating = false; _status = null; }, _postProcess ) ); _updating = true; Repaint(); } } } else if (_status == "DELETE_COMPLETE") { if (GUILayout.Button("インストール")) { if (Validate()) { EditorCoroutineUtility.StartCoroutineOwnerless( WeaveInstaller.Install( _manifest, e => { events = e; }, () => { _installing = false; _status = null; Repaint(); }, _postProcess ) ); _installing = true; void RunOutputCoroutine() { EditorCoroutineUtility.StartCoroutineOwnerless( WeaveInstaller.GetOutputs( _manifest, r => { if (_installing) { RunOutputCoroutine(); } if (r.Error == null) { Repaint(); outputs = r.Result.items; } } ) ); } RunOutputCoroutine(); Repaint(); } else { EditorUtility.DisplayDialog("Validation Error", "インストールパラメータの入力値に問題があります", "OK"); } } } else if (_status == "ROLLBACK_COMPLETE") { EditorGUILayout.LabelField("インストールに失敗しました"); using (new GUILayout.VerticalScope(GUI.skin.box)) { if (events != null) { foreach (var e in events) { using (new GUILayout.HorizontalScope()) { if (e.eventAt != null) { GUILayout.Label(UnixTime.FromUnixTime(e.eventAt.Value).ToShortTimeString()); } GUILayout.Label(e.resourceName); GUILayout.Label(e.type); GUILayout.Label(e.message); } } } } if (GUILayout.Button("アンインストール")) { EditorCoroutineUtility.StartCoroutineOwnerless( WeaveInstaller.Uninstall( _manifest, e => { Repaint(); events = e; }, () => { Repaint(); _uninstalling = false; _status = null; } ) ); _uninstalling = true; Repaint(); } } else { EditorGUILayout.LabelField("状態を取得中..."); _status = null; } }
public DateTime GetTime(UnixTime tz) { return tz.DateTimeFromMysql(timeRaw); }
// Visible for testing. public Block CreateNextBlock(Address to) { return(CreateNextBlock(to, (uint)UnixTime.ToUnixTime(DateTime.UtcNow))); }
public DateTime GetTime(UnixTime tz) { return tz.DateTimeFromMysql(gigTime); }
public static DateTime FromJsonUnixTime(this JToken unixTimeValue) { return(UnixTime.UnixTimeToDateTime(unixTimeValue.ToObject <int>())); }
/// <summary> /// Gets the date the blog post was made. /// </summary> /// <param name="tz">Timezone</param> /// <returns>DateTime object</returns> public DateTime GetCreatedDate(UnixTime tz) { return tz.DateTimeFromMysql(createdRaw); }
/// <inheritdoc /> public Task <Result <IReadOnlyList <ContentLocationEntry> > > GetBulkAsync(OperationContext context, IReadOnlyList <ContentHash> contentHashes) { return(context.PerformOperationAsync( Tracer, async() => { var results = new ContentLocationEntry[contentHashes.Count]; UnixTime now = _clock.UtcNow; int dualResultCount = 0; foreach (var page in contentHashes.AsIndexed().GetPages(_configuration.RedisBatchPageSize)) { var batchResult = await _raidedRedis.ExecuteRedisAsync(context, async(redisDb, token) => { var redisBatch = redisDb.CreateBatch(RedisOperation.GetBulkGlobal); foreach (var indexedHash in page) { var key = GetRedisKey(indexedHash.Item); redisBatch.AddOperationAndTraceIfFailure(context, key, async batch => { var redisEntry = await batch.StringGetAsync(key); ContentLocationEntry entry; if (redisEntry.IsNullOrEmpty) { entry = ContentLocationEntry.Missing; } else { entry = ContentLocationEntry.FromRedisValue(redisEntry, now, missingSizeHandling: true); } var originalEntry = Interlocked.CompareExchange(ref results[indexedHash.Index], entry, null); if (originalEntry != null) { // Existing entry was there. Merge the entries. entry = ContentLocationEntry.MergeEntries(entry, originalEntry); results[indexedHash.Index] = entry; Interlocked.Increment(ref dualResultCount); } return Unit.Void; }); } // TODO ST: now this operation may fail with TaskCancelledException. But this should be traced differently! return await redisDb.ExecuteBatchOperationAsync(context, redisBatch, token); }, _configuration.RetryWindow); if (!batchResult) { return new Result <IReadOnlyList <ContentLocationEntry> >(batchResult); } } if (_raidedRedis.HasSecondary) { Counters[GlobalStoreCounters.GetBulkEntrySingleResult].Add(contentHashes.Count - dualResultCount); } return Result.Success <IReadOnlyList <ContentLocationEntry> >(results); }, Counters[GlobalStoreCounters.GetBulk], traceErrorsOnly: true)); }
/// <summary> /// Gets the date the blog post was published. /// </summary> /// <param name="tz">Timezone</param> /// <returns>DateTime object</returns> public DateTime GetPublishedDate(UnixTime tz) { return tz.DateTimeFromMysql(publishedRaw); }
public void OnClientEvent(Client Player, string eventName, params object[] arguments) //arguments param can contain multiple params { if (eventName == "SC_GETVEHICLETIMELIMIT") { var veh = API.getPlayerVehicle(Player); var days = Convert.ToInt64(API.getEntitySyncedData(veh, "SC_VehicleMain_VehicleData_TimeLimit")); if (days != 0) { var nowtime = UnixTime.getUnixTimeToS(); days = Convert.ToInt64((days - nowtime) / 86400); API.sendChatMessageToPlayer(Player, "~w~該栽具還有" + days.ToString() + "天到期."); } } if (eventName == "SC_VehicleMain_VehicleData_Rank") { var v = API.getEntityData((NetHandle)arguments[0], "SC_VehicleMain_VehicleData"); v.setRank(arguments[1].ToString()); API.setEntitySyncedData((NetHandle)arguments[0], "SC_VehicleMain_VehicleData_Rank", v.getRank()); } if (eventName == "SC_VehicleMain_VehicleData_RankLevel") { var v = API.getEntityData((NetHandle)arguments[0], "SC_VehicleMain_VehicleData"); v.setRankLevel(Convert.ToInt32(arguments[1])); API.setEntitySyncedData((NetHandle)arguments[0], "SC_VehicleMain_VehicleData_RankLevel", v.getRankLevel()); } if (eventName == "SC_vehicle_testetetete") { API.consoleOutput(arguments[0].ToString()); } if (eventName == "SC_Vehicle_CALL_VEH") { var p = API.getEntityData(Player, "SC_VehicleList"); foreach (var i in p) { if (i.getSQLID() == Convert.ToInt32(arguments[0])) { var f = false; if (i.getAlive() == false) { var m = API.getEntityData(Player, "SC_money"); var fix = i.getMoney() * 0.02; fix = (int)fix; if (m.getMoney() < fix) { API.sendNotificationToPlayer(Player, "~g~召喚車輛大失敗!\n~g~原因 ~w~車輛損壞,無錢修理"); return; } else { m.addMoney(-fix); i.setAlive(true); f = true; updataPlayerVehicleList(Player); } } var veh = i.getVeh(); var targetPos = API.getEntityPosition(Player); var targetRot = API.getEntityRotation(Player); if (f == true) { i.respawnVeh(); veh = i.getVeh(); } //API.repairVehicle(veh); if (API.isPlayerInAnyVehicle(Player) == false) { API.setEntityPosition(veh, targetPos); API.setEntityRotation(veh, targetRot); API.setPlayerIntoVehicle(Player, veh, -1); } else { if (veh != API.getPlayerVehicle(Player)) { API.setEntityPosition(veh, new Vector3(targetPos.X, targetPos.Y, targetPos.Z + 10)); API.setEntityRotation(veh, targetRot); } } break; } } p = null; } if (eventName == "SC_Vehicle_Control_Engine") { var veh = API.getPlayerVehicle(Player); var d = API.getEntityData(veh, "SC_VehicleMain_VehicleData"); if (d.getMaster() == API.getPlayerName(Player)) { if (d.getAlive() == true) { API.setVehicleEngineStatus(veh, !API.getVehicleEngineStatus(veh)); } } else { API.sendChatMessageToPlayer(Player, "~r~*哎呀!你好像沒有鑰匙"); } d = null; } if (eventName == "SC_Vehicle_Control_Door") { var veh = API.getPlayerVehicle(Player); var d = API.getEntityData(veh, "SC_VehicleMain_VehicleData"); var door = Convert.ToInt32(arguments[0]); if (d.getMaster() == API.getPlayerName(Player)) { if (d.getAlive() == true) { API.setVehicleDoorState(veh, door, !API.getVehicleDoorState(veh, door)); } } else { API.sendChatMessageToPlayer(Player, "~r~*哎呀!你好像沒有遙控器"); } d = null; } if (eventName == "SC_Vehicle_NUMBER7_FIX") { var m = API.getEntityData(Player, "SC_money"); if (m.getMoney() < RepairVehicleMoney) { API.sendChatMessageToAll("[ ~r~!~w~ ] 你的錢不夠啊."); } else { API.repairVehicle(API.getPlayerVehicle(Player)); m.addMoney(-RepairVehicleMoney); API.sendChatMessageToPlayer(Player, "你修復了這輛載具."); } } if (eventName == "SC_Vehicle_Control_Neon") { var veh = API.getPlayerVehicle(Player); var d = API.getEntityData(veh, "SC_VehicleMain_VehicleData"); var js = API.fromJson(d.getSlotJson()); if (js.Property("霓虹燈") != null) { var v = js["霓虹燈"].ToString(); if (v.Length != 0) { string[] type = v.Split(':'); foreach (var i in type) { var id = Convert.ToInt32(i); API.setVehicleNeonState(veh, id, !API.getVehicleNeonState(veh, id)); } } } } }
public void ConvertsToCorrectDate() { var unixTime = new UnixTime(1432754581121); Assert.Equal(DateTimeOffset.Parse("2015-05-27T19:23:01.1210000+00:00"), unixTime.ToDateTimeOffsetUtc()); }
public DateTime GetFanDate(UnixTime tz) { return tz.DateTimeFromMysql(fanDateRaw); }