public static AllData LoadData(string path) { Debug.Log(path); Debug.Log(Application.dataPath + path + ".europa"); if (File.Exists(Application.dataPath + path + ".europa")) { BinaryFormatter bf = new BinaryFormatter(); FileStream stream = new FileStream(Application.dataPath + path + ".europa", FileMode.Open); AllData data = bf.Deserialize(stream) as AllData; stream.Close(); return(data); } else { Debug.LogError("NO FILE AT PATH BROTHER!"); return(new AllData(null, null, null, null, null, null, null, null, null, null, null, null, null, null)); } }
public IActionResult Search(AllData allData) { Console.WriteLine(allData.search_data); var client = new RestClient(tMDB.makequery_movie(allData.search_data)); var request = new RestRequest(Method.GET); request.AddParameter("undefined", "{}", ParameterType.RequestBody); IRestResponse response = client.Execute(request); if (response.IsSuccessful) { var temp = JsonConvert.DeserializeObject <MovieArray>(response.Content); for (int i = 0; i < temp.results.Length; i++) { temp.results[i].media_type = "movie"; temp.results[i].poster_path = "https://image.tmdb.org/t/p/w300_and_h450_bestv2" + temp.results[i].poster_path; temp.results[i].backdrop_path = "https://image.tmdb.org/t/p/w1400_and_h450_face" + temp.results[i].backdrop_path; } allData.movieArray = temp; } client = new RestClient(tMDB.makequery_tv(allData.search_data)); request = new RestRequest(Method.GET); request.AddParameter("undefined", "{}", ParameterType.RequestBody); response = client.Execute(request); if (response.IsSuccessful) { var temp = JsonConvert.DeserializeObject <TVArray>(response.Content); for (int i = 0; i < temp.results.Length; i++) { temp.results[i].poster_path = "https://image.tmdb.org/t/p/w300_and_h450_bestv2" + temp.results[i].poster_path; temp.results[i].backdrop_path = "https://image.tmdb.org/t/p/w1400_and_h450_face" + temp.results[i].backdrop_path; temp.results[i].media_type = "tv"; } allData.tVArray = temp; } return(View(allData)); }
static int _CreateAllData(IntPtr L) { try { int count = LuaDLL.lua_gettop(L); if (count == 0) { AllData obj = new AllData(); ToLua.PushObject(L, obj); return(1); } else { return(LuaDLL.luaL_throw(L, "invalid arguments to ctor method: AllData.New")); } } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
private static async Task Demo() { // Fetch your account's credentials from somewhere. var auth = new EmailAuthenticationProvider("", ""); // Log in to the community to authenticate with chat. _ = auth.Login("stackexchange.com"); // Create an instance of the ActionScheduler. This will // allow us to execute chat actions like: posting messages, // kicking users, moving messages, etc. using var actionScheduler = new ActionScheduler(auth, roomUrl); // Create an instance of the RoomWatcher class. Here we // specify (via the type parameter) what WebSocket implementation // we'd like to use. This class allows you to subscribe to chat events. using var roomWatcher = new RoomWatcher <DefaultWebSocket>(auth, roomUrl); // Subscribe to the UserMentioned event. _ = roomWatcher.AddUserMentionedEventHandler(async m => await actionScheduler.CreateReplyAsync("hello!", m.MessageId)); // Besides being able to subscribe to the default events, // you can also create (and listen to) your own. Your class must // implement the ChatEventDataProcessor class, you can also // optionally implement IChatEventHandler or IChatEventHandler<T>. var customEventHanlder = new AllData(); // Add a very basic handler. customEventHanlder.OnEvent += data => Console.WriteLine(data); // Add our custom event handler so we can // begin processing the incoming event data. roomWatcher.EventRouter.AddProcessor(customEventHanlder); // Post a simple message. var messageId = await actionScheduler.CreateMessageAsync("Hello world."); while (Console.ReadKey(true).Key != ConsoleKey.Q) { } }
void LoadGameData() { try { Debug.Log(Application.persistentDataPath); if (File.Exists(Application.persistentDataPath + "/LearningData.json")) { StreamReader kanjiFileReader = new StreamReader(Application.persistentDataPath + "/LearningData.json"); string json = kanjiFileReader.ReadToEnd(); GameData = JsonUtility.FromJson <AllData>(json); } else { string json = Resources.Load <TextAsset>("LearningData").text; GameData = JsonUtility.FromJson <AllData>(json); SaveGameData(); } } catch (Exception e) { Debug.LogError("Error while reading Data: " + e.Message); } }
private void AddDataToListView(object sender, RoutedEventArgs e) { daysleft = new List <AllData>(); ReadAllData alldata = new ReadAllData(); DB_DaysLeft = alldata.GetAllDays(); foreach (var Date in DB_DaysLeft) { AllData ad = new AllData(); DateTime dt = Convert.ToDateTime(Date); TimeSpan diff = DateTime.Now - Date.Date; int days = (int)Math.Abs(Math.Round(diff.TotalDays)); ad.diff = days; ad.myEvent = events; daysleft.Add(ad); } DaysLeftListView.ItemsSource = DB_DaysLeft.OrderByDescending(i => i.Id).ToList(); }
public APIResponse CreatePayment(PaymentRequest request) { APIResponse response = null; request.baseRequest.redirect_uri = RedirectUri; try { response = PaymentsSandbox.WithOAuthBearerToken(request.baseRequest.access_token).PostJsonAsync(request.baseRequest).ReceiveJson <APIResponse>().Result; //write to csv file foreach (var result in response.results) { AllData.Add(new Transaction() { simp_id = result.simp_id, amount = result.amount, beneficiary_name = result.beneficiary_name, beneficiary_account_number = result.beneficiary_account_number, beneficiary_sort_code = result.beneficiary_sort_code, status = result.status }); } if (File.Exists(FilePath)) { CsvConfiguration.HasHeaderRecord = false; } using (var writer = new StreamWriter(FilePath, true)) { using (var csv = new CsvWriter(writer, CsvConfiguration)) { csv.WriteRecords(AllData); } } } catch (Exception e) { Debug.WriteLine(e.Message); } return(response); }
public MainWindow() { InitializeComponent(); // Initialize and display data: this.allData = DataLoader.Load(); lbCompanies.ItemsSource = allData.Companies; //Initialize Glue42 and register the current app: var applicationName = "CompanyManager"; var glue = new Glue42(); glue.Initialize(applicationName); //Instantiate the service instance and register to Glue42: var companyService = new CompanyService((code) => { this.handleCompanyCodeChange(code); }); glue.Interop.RegisterService <ICompanyService>(companyService); // Initialize Window Stickiness and read from config: var swOptions = glue.StickyWindows?.GetStartupOptions() ?? new SwOptions(); glue.StickyWindows?.RegisterWindow(this, swOptions); }
public static bool CheckPinNumber() { Console.Clear(); AllData data = new AllData(); Cards = data.GetCardList(); Console.WriteLine("Enter your pin number, or type exit. "); int pin = UserInput.InputInteger(1, 9999); try { Card card = Cards.Single(crd => crd.PinNumber == pin); MainMenu.SetCard(card); return(true); } catch (Exception e) { Console.Write("Wrong pin number, Goodbye"); Console.ReadKey(true); } return(false); }
public async Task <PlaceItem> PlaceItemDataAsync(int id) { var uri = new Uri(string.Format(url + "places/" + id, string.Empty)); Console.WriteLine("Dev_BefResp:"); var response = await client.GetAsync(uri); Console.WriteLine("Dev_statusCode:" + response.IsSuccessStatusCode); if (response.IsSuccessStatusCode) { var content = await response.Content.ReadAsStringAsync(); AllData <PlaceItem> d = JsonConvert.DeserializeObject <AllData <PlaceItem> >(content); Console.WriteLine("Dev_is_sucess:" + d.is_success); Console.WriteLine("Dev_error_code:" + d.error_code); Console.WriteLine("Dev_error_message:" + d.error_message); return(d.data); } return(null); }
public void SerializeMyClass() // Save to file { AllData ad = new AllData(); ad.AddClass(sel); ad.AddClass(skl); ad.AddClass(sc); byte[] bytes; IFormatter formatter = new BinaryFormatter(); using (MemoryStream stream = new MemoryStream()) { formatter.Serialize(stream, ad); bytes = stream.ToArray(); } Response.Clear(); Response.ContentType = "application/octet-stream"; Response.AddHeader("Content-Disposition", "attachment; filename={your file name}"); Response.OutputStream.Write(bytes, 0, bytes.Length); Response.End(); }
public static AllData GetNewData() { HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(WebSource(WebSiteToScrape)); HtmlNode table = doc.DocumentNode.SelectSingleNode("//*[@id=\"main_table_countries_today\"]"); HtmlNode rows = table.SelectSingleNode("//tbody[1]"); List <HtmlNode> td = rows.Descendants().Where((e) => e.Name == "tr").ToList(); AllData data = new AllData(); data.CountryData = new List <CountryData>(); foreach (HtmlNode node in td) { CountryData newData = new CountryData(); newData.Load(node); data.CountryData.Add(newData); } List <HtmlNode> totalData = doc.DocumentNode.SelectSingleNode("//*[@id=\"main_table_countries_today\"]/tbody[2]/tr").Descendants().Where((e) => e.Name == "td").ToList(); data.TotalCases = totalData[1].InnerText.Trim(); data.NewCases = totalData[2].InnerText.Trim(); data.TotalDeaths = totalData[3].InnerText.Trim(); data.NewDeaths = totalData[4].InnerText.Trim(); data.TotalRecovered = totalData[5].InnerText.Trim(); data.ActiveCases = totalData[6].InnerText.Trim(); data.Serious = totalData[7].InnerText.Trim(); data.TotCases = totalData[8].InnerText.Trim(); return(data); }
public void TestForMakeBooking() { HotelSearchDetails obj = new HotelSearchDetails(); obj.CheckIn = DateTime.Parse("2018-11-17"); obj.CheckOut = DateTime.Parse("2018-11-19"); obj.Ac = false; obj.Wifi = false; obj.HotelId = 510; SelectedRoomsViewModel list = new SelectedRoomsViewModel(); list.RoomPrice = 3500; list.HotelContact = "9876234546"; list.HotelName = "Hotel Wow"; list.RoomId = 219; list.City = "Indore"; AllData data = new AllData(); data.CustomerId = 104; data.payMode = "DC"; data.SelectedRooms = new List <SelectedRoomsViewModel>() { list }; data.userinfo = obj; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ var result = (OkObjectResult)controller2.BookingDetails(data); PaymentInvoiceNo = (int)result.Value; Assert.IsInstanceOfType(result, typeof(OkObjectResult)); }
/// <summary> /// 是否可以选择目标 /// </summary> /// <param name="selectWeightData">选择方权重数据</param> /// <param name="targetAllData">目标方基础数据</param> /// <returns>是否可以选择</returns> public static bool CouldSelectTarget(SelectWeightData selectWeightData, AllData targetAllData) { var result = true; var targetData = targetAllData.MemberData; // 如果不可攻击建筑并且是建筑 // 或不可攻击空中并且是空中 // 或不可攻击地面并且是地面 // 或处于死亡或假死状态 // 或目标是障碍物 // 则不能选择该单位 // 排除阵营 if ((selectWeightData.BuildWeight < 0 && targetData.GeneralType == Utils.GeneralTypeBuilding) || (selectWeightData.AirWeight < 0 && targetData.GeneralType == Utils.GeneralTypeAir) || (selectWeightData.SurfaceWeight < 0 && targetData.GeneralType == Utils.GeneralTypeSurface) || targetData.CurrentHP <= 0) { return(false); } // 判断阵营 if ((selectWeightData.CampWeight != 1 || targetData.Camp != 1) && (selectWeightData.CampWeight != 2 || targetData.Camp != 2) && selectWeightData.CampWeight != 0) { return(false); } // 判断生命区间 if (selectWeightData.HpScopeMaxValue >= 0 && selectWeightData.HpScopeMinValue >= 0) { // 区分判断类型 switch (selectWeightData.HpScopeType) { case 0: // 计算生命值百分比 var percent = targetData.CurrentHP / targetData.TotalHp; if (percent < selectWeightData.HpScopeMinValue || percent > selectWeightData.HpScopeMaxValue) { return(false); } break; case 1: if (targetData.CurrentHP < selectWeightData.HpScopeMinValue || targetData.CurrentHP > selectWeightData.HpScopeMaxValue) { return(false); } break; } } //// 判断负面buff //if (selectWeightData.DeBuffWeight > 0) //{ // // 必须有负面buff // result = targetAllData.BuffInfoList.Any(buff => !buff.IsBeneficial); //} //else if (selectWeightData.DeBuffWeight < 0) //{ // // 必须没有负面buff // result = targetAllData.BuffInfoList.All(buff => buff.IsBeneficial); //} //// 判断正面buff //if (selectWeightData.BuffWeight > 0) //{ // // 必须有正面buff // result = targetAllData.BuffInfoList.Any(buff => buff.IsBeneficial); //} //else if (selectWeightData.BuffWeight < 0) //{ // // 必须没有正面buff // result = targetAllData.BuffInfoList.All(buff => !buff.IsBeneficial); //} //// 如果目标隐形并且选择者反隐, 或者不隐形 //if ((targetData.IsHide && selectWeightData.HideWeight < 0)) //{ // result = false; //} return(result); }
public IActionResult BookingDetails(AllData allData) { InvoiceData Info = service.MakeBooking(allData); return(Ok(Info)); }
public AllData <T> DeserializeStudentGEneric(string path) { AllData <T> list = JsonConvert.DeserializeObject <AllData <T> >(File.ReadAllText(path)); return(list); }
public BlockingCollection <string> ReadFilesWriteToFile(string folder, string fileNameWC, string toFile) { var matchesCollection = new BlockingCollection <string>(); var files = Directory.GetFiles(folder, fileNameWC, SearchOption.TopDirectoryOnly); Console.WriteLine("Reading Folder: " + folder); var exceptions = new ValueTuple <string, Regex>[] { ("change password", new Regex("CMD: echo \"root")), ("change password", new Regex("CMD: echo -e \"")), ("change password", new Regex(@"\|passwd")), ("change password", new Regex(" > /tmp/up.txt")) }; var readTask = Task.Run(() => { using (var writer = new StreamWriter(toFile)) { //List<string> cmds = new List<string>(); List <DisplayData> cmds = new List <DisplayData>(); try { foreach (var file in files) { string line2 = ""; try { using (var reader = new StreamReader(file)) { string line; while ((line = reader.ReadLine()) != null) { line2 = line; EventDTO _event = null; try { _event = JsonConvert.DeserializeObject <EventDTO>(line); } catch (Exception) { continue; } if (_event.eventid != "cowrie.session.file_upload") { continue; } foreach (var item in dls) { if (item.Value.ips == null) { continue; } foreach (var ii in item.Value.ips) { if (ii.sha2 == _event.shasum) { ii.ip = _event.src_ip; ii.date = DateTime.Parse(_event.timestamp); } } } foreach (var item in dls) { if (item.Value.ips == null) { continue; } foreach (var ii in item.Value.ips) { if (ii.sha2 == _event.shasum) { var ad = new AllData() { df = item.Value, ed = _event }; cmds.Add(DisplayData.Parse(ad)); } } } } } } catch (DirectoryNotFoundException e) { Console.WriteLine(e.StackTrace); } catch (Exception e) { Console.WriteLine(line2); Console.WriteLine(e.StackTrace); } } } finally { matchesCollection.CompleteAdding(); } writer.WriteLine(JsonConvert.SerializeObject(cmds, Formatting.Indented)); } }); Task.WaitAll(readTask); return(matchesCollection); }
public JsonResult Save(AllData obj) { DataTable dt = ToDataTable(obj.Dt1); return(Json("1", JsonRequestBehavior.AllowGet)); }
public void NewSimulation(AllData data) { savedData = new AllData(); savedData = data; // adatok betöltése int mID = 1, cID = 10001, pID = 20001, tID = 30001, rID = 40001; //mezo: 1-10000, cel: 10001-20000, polc: 20001-30000, tolto: 30001-40000, robot: 40001-50000 totalEnergyUsed = 0; totalSteps = 0; goodsDelivered = 0; celallomasCount = 0; tableSize = data.tableSize; table = new NewmazonClasses[tableSize, tableSize]; startingEnergy = data.robotEnergy; robots = new List <Robot>(); robotEnergyUsed = new List <int>(); for (int i = 0; i < tableSize; ++i) { for (int j = 0; j < tableSize; ++j) { switch (data.dataTable[i, j]) { case 'R': //Robot table[i, j] = new Mezo(mID, i, j); mID++; robots.Add(new Robot(rID, i, j, startingEnergy, 0, null)); robotEnergyUsed.Add(0); rID++; break; case 'M': //Mező table[i, j] = new Mezo(mID, i, j); mID++; break; case 'P': //Polc table[i, j] = new Polc(pID, i, j); pID++; break; case 'T': //Töltőállomás table[i, j] = new Toltoallmoas(tID, i, j); tID++; break; case 'F': //Fal table[i, j] = new Fal(0, i, j); break; case 'C': //Célállomás table[i, j] = new Celallomas(cID, i, j); celallomasCount++; cID++; break; } } } goods = new List <Goods>(); // áruk listájának betöltése a datából foreach (Goods good in data.goods) { goods.Add(good); } paths = new List <List <Step> >(robots.Count); // minden robotnak saját útvonal létrehozása for (int i = 0; i < robots.Count; ++i) { paths.Add(new List <Step>()); } foreach (Goods good in data.goods) // polcokon lévő áruk beöltése { foreach (int i in good.destinations) { table[good.x, good.y].goods.Add(i); } } }
public ArabaRepository(AllData db) : base(db) { }
IEnumerator Load(string scene, string path) { //wait until the scene is loaded to instantiate, otherwise shit gets overwritten //start loading animation currentPath = path; loading = true; Transition trans = GameObject.FindObjectOfType <Transition>(); trans.LoadingScene(); AsyncOperation async = SceneManager.LoadSceneAsync(scene); while (!async.isDone) { yield return(new WaitForSeconds(1f)); } //now delete and stop any generated ores GameObject.FindObjectOfType <WorldGen>().CancelGen(); //now that the scene is loaded, send it brother AllData allData = SaveLoadManager.LoadData(path); //Launchers first float waitTime = 0.1f; Cannons(allData); yield return(new WaitForSeconds(waitTime)); Fans(allData); yield return(new WaitForSeconds(waitTime)); Crafters(allData); yield return(new WaitForSeconds(waitTime)); Miners(allData); yield return(new WaitForSeconds(waitTime)); Ores(allData); yield return(new WaitForSeconds(waitTime)); LoadInventory(allData); yield return(new WaitForSeconds(waitTime)); UnPackers(allData); yield return(new WaitForSeconds(waitTime)); Packers(allData); yield return(new WaitForSeconds(waitTime)); Eggs(allData); yield return(new WaitForSeconds(waitTime)); Splitters(allData); yield return(new WaitForSeconds(waitTime)); Pumps(allData); yield return(new WaitForSeconds(waitTime)); ZapTowers(allData); yield return(new WaitForSeconds(waitTime)); Items(allData); yield return(new WaitForSeconds(waitTime)); Rockets(allData); trans.EndLoadingScene(); loading = false; }
// ---------------------------公共方法------------------------------ public PositionObject([NotNull] AllData allData, [NotNull] FightUnitBase mapCell) { // 设置MemberData this.allData = allData; this.MapCell = mapCell; }
public ActionResult RmForm() { var alldata = new AllData(); return(PartialView(alldata)); }
private void ImportDataFromJsonString(string fileAsString) { AllData allData = JsonConvert.DeserializeObject <AllData>(fileAsString); string deleteAllSql = @" DELETE FROM ""Feedback"" WHERE 1 = 1; DELETE FROM ""DraftReturns"" WHERE 1 = 1; DELETE FROM ""InactiveUserOrganisations"" WHERE 1 = 1; DELETE FROM ""ReturnStatus"" WHERE 1 = 1; DELETE FROM ""Returns"" WHERE 1 = 1; DELETE FROM ""AuditLogs"" WHERE 1 = 1; UPDATE ""Organisations"" SET ""LatestPublicSectorTypeId"" = NULL WHERE 1 = 1; DELETE FROM ""OrganisationPublicSectorTypes"" WHERE 1 = 1; DELETE FROM ""OrganisationSicCodes"" WHERE 1 = 1; DELETE FROM ""OrganisationScopes"" WHERE 1 = 1; DELETE FROM ""UserOrganisations"" WHERE 1 = 1; DELETE FROM ""OrganisationStatus"" WHERE 1 = 1; DELETE FROM ""OrganisationReferences"" WHERE 1 = 1; DELETE FROM ""OrganisationAddresses"" WHERE 1 = 1; DELETE FROM ""OrganisationNames"" WHERE 1 = 1; DELETE FROM ""Organisations"" WHERE 1 = 1; DELETE FROM ""ReminderEmails"" WHERE 1 = 1; DELETE FROM ""UserStatus"" WHERE 1 = 1; DELETE FROM ""Users"" WHERE 1 = 1; DELETE FROM ""PublicSectorTypes"" WHERE 1 = 1; DELETE FROM ""SicCodes"" WHERE 1 = 1; DELETE FROM ""SicSections"" WHERE 1 = 1; "; WriteParagraph($"About to delete existing data"); dataRepository.ExecuteRawSql(deleteAllSql); WriteParagraph($"Deleted existing data"); WriteParagraph($"Starting DataProtectionKey"); dataRepository.GetAll <DataProtectionKey>().ToList().ForEach(dpk => dataRepository.Delete(dpk)); dataRepository.Insert(allData.DataProtectionKeys); dataRepository.SaveChanges(); WriteParagraph($"DataProtectionKey done"); InsertData(allData.Feedbacks); InsertData(allData.DraftReturns); InsertData(allData.PublicSectorTypes); InsertData(allData.SicSections); InsertData(allData.SicCodes); InsertData(allData.Users); InsertData(allData.UserStatuses); InsertData(allData.ReminderEmails); WriteParagraph($"Starting Organisations and OrganisationPublicSectorTypes"); var newDataRepository = Global.ContainerIoC.Resolve <IDataRepository>(); newDataRepository.Insert(allData.Organisations); newDataRepository.Insert(allData.OrganisationPublicSectorTypes); newDataRepository.SaveChanges(); allData.Organisations.Clear(); allData.OrganisationPublicSectorTypes.Clear(); WriteParagraph($"Organisations and OrganisationPublicSectorTypes done"); InsertData(allData.OrganisationNames); InsertData(allData.OrganisationAddresses); InsertData(allData.OrganisationReferences); InsertData(allData.OrganisationStatuses); InsertData(allData.InactiveUserOrganisations); InsertData(allData.UserOrganisations); InsertData(allData.OrganisationScopes); InsertData(allData.OrganisationSicCodes); InsertData(allData.AuditLogs); InsertData(allData.Returns); InsertData(allData.ReturnStatuses); string updateSequencesSql = @" SELECT setval('""AuditLogs_AuditLogId_seq""', (SELECT max(""AuditLogId"") FROM ""AuditLogs""), true); SELECT setval('""DataProtectionKeys_Id_seq""', (SELECT max(""Id"") FROM ""DataProtectionKeys""), true); SELECT setval('""DraftReturns_DraftReturnId_seq""', (SELECT max(""DraftReturnId"") FROM ""DraftReturns""), true); SELECT setval('""Feedback_FeedbackId_seq""', (SELECT max(""FeedbackId"") FROM ""Feedback""), true); SELECT setval('""OrganisationAddresses_AddressId_seq""', (SELECT max(""AddressId"") FROM ""OrganisationAddresses""), true); SELECT setval('""OrganisationNames_OrganisationNameId_seq""', (SELECT max(""OrganisationNameId"") FROM ""OrganisationNames""), true); SELECT setval('""OrganisationPublicSectorTypes_OrganisationPublicSectorTypeI_seq""', (SELECT max(""OrganisationPublicSectorTypeId"") FROM ""OrganisationPublicSectorTypes""), true); SELECT setval('""OrganisationReferences_OrganisationReferenceId_seq""', (SELECT max(""OrganisationReferenceId"") FROM ""OrganisationReferences""), true); SELECT setval('""Organisations_OrganisationId_seq""', (SELECT max(""OrganisationId"") FROM ""Organisations""), true); SELECT setval('""OrganisationScopes_OrganisationScopeId_seq""', (SELECT max(""OrganisationScopeId"") FROM ""OrganisationScopes""), true); SELECT setval('""OrganisationSicCodes_OrganisationSicCodeId_seq""', (SELECT max(""OrganisationSicCodeId"") FROM ""OrganisationSicCodes""), true); SELECT setval('""OrganisationStatus_OrganisationStatusId_seq""', (SELECT max(""OrganisationStatusId"") FROM ""OrganisationStatus""), true); SELECT setval('""PublicSectorTypes_PublicSectorTypeId_seq""', (SELECT max(""PublicSectorTypeId"") FROM ""PublicSectorTypes""), true); SELECT setval('""ReminderEmails_ReminderEmailId_seq""', (SELECT max(""ReminderEmailId"") FROM ""ReminderEmails""), true); SELECT setval('""Returns_ReturnId_seq""', (SELECT max(""ReturnId"") FROM ""Returns""), true); SELECT setval('""ReturnStatus_ReturnStatusId_seq""', (SELECT max(""ReturnStatusId"") FROM ""ReturnStatus""), true); SELECT setval('""Users_UserId_seq""', (SELECT max(""UserId"") FROM ""Users""), true); SELECT setval('""UserStatus_UserStatusId_seq""', (SELECT max(""UserStatusId"") FROM ""UserStatus""), true); "; WriteParagraph($"About to update sequences"); dataRepository.ExecuteRawSql(updateSequencesSql); WriteParagraph($"Updated sequences"); }
public KonutRepository(AllData db) : base(db) { }
public BaseRepositories(AllData db) { _db = db; }
public void PriceUpdate(BrokerInfo brokerInfo, List<Sector> Sec,List<AllStockMarketRecords> AllData,string Action) { int turn = cache.Get<Records>("Turn").Turns; bool Flag=false; SectorTrend SectorTrend = new SectorTrend(); MainEventRecord mer = new MainEventRecord(); MainEventRecord temp = new MainEventRecord(); int sectortemp,stocktemp; var Event = EventGenerate(turn, calculatePreValue(turn)); switch (Event.Type) { case "Stock": { mer.Stock = brokerInfo.Stock; mer.Sector = brokerInfo.Sector; mer.Value = (int)Event.EventSum; break; } case "Sector": { mer.Sector = brokerInfo.Sector; mer.Stock = null; mer.Value = (int)Event.EventSum; break; } case "Same": { temp = cache.Get<MainEventRecord>("MainEventRecord"); if(temp.Stock!=null) { stocktemp = temp.Value; } else { sectortemp = temp.Value; } } break; case null: { mer.Sector = null; mer.Stock = null; mer.Value = (int)Event.EventSum; break; } } if (cache.Get<MainEventRecord>("MainEventRecord") != null && Event.Type!="Same") { cache.Remove("MainEventRecord"); cache.Set("MainEventRecord", mer, Constants.cacheTime); } else { cache.Set("MainEventRecord", mer, Constants.cacheTime); } var match= Sec.Where(e => e.SectorName.Contains(brokerInfo.Sector)).FirstOrDefault(); if(match!=null) { if (turn == 1) { var change = (Action == "Buy") ? 1 : -1; SectorTrend.SectorTrendValue = change; cache.Set(match.SectorName + "_ScoreArray", SectorTrend, Constants.cacheTime); } else { var check = cache.Get<SectorTrend>(match.SectorName + "_ScoreArray"); var TempValue = (check != null) ? check.SectorTrendValue : 0; SectorTrend.SectorTrendValue = GTValueChange(TempValue, Action); cache.Remove(match.SectorName + "_ScoreArray"); cache.Set(match.SectorName + "_ScoreArray", SectorTrend, Constants.cacheTime); } } temp = cache.Get<MainEventRecord>("MainEventRecord"); int last = turn - 1; foreach (var Market in AllData) { foreach(var Stock in Market.Sectors) { ScoreArray ScoreArray = new ScoreArray(); AllData alldata = new AllData(); var strnow = turn + "_" + Market.StockMarket.CompanyName + "_" + Stock.SectorName; var strlast = last + "_" + Market.StockMarket.CompanyName + "_" + Stock.SectorName; var strRec = "R_" + strnow; ScoreArray.EventComponent = (Stock.SectorName == temp.Sector && temp.Stock == null) ? temp.Value : 0; ScoreArray.EventComponent = (Stock.SectorName == temp.Sector && Market.StockMarket.CompanyName == temp.Stock) ? temp.Value : 0; var TempValue = (cache.Get<SectorTrend>(Stock.SectorName + "_ScoreArray") != null) ? cache.Get<SectorTrend>(Stock.SectorName + "_ScoreArray").SectorTrendValue : 0; var check = cache.Get<ScoreArray>(strlast); var GeneralTrend = (check != null) ? check.GeneralTrend : 0; if (Market.StockMarket.CompanyName==brokerInfo.Stock && Stock.SectorName==brokerInfo.Sector ) { Flag = true; if (turn == 1) { var change = (Action == "Buy") ? 1 : -1; ScoreArray.GeneralTrend = change; } else { ScoreArray.GeneralTrend = GTValueChange(GeneralTrend, Action); } } else { ScoreArray.GeneralTrend = (cache.Get<ScoreArray>(strlast) != null) ? cache.Get<ScoreArray>(strlast).GeneralTrend : 0; } decimal percentage= calculateValue(PriceUpdate(TempValue, ScoreArray, Flag)) + 1; decimal updatedprice = Stock.StockPrice * (percentage); Market.Sectors.Where(w => w.SectorName == Stock.SectorName).ToList().ForEach(s => s.StockPrice = updatedprice); alldata.Value = updatedprice; if (cache.Get<ScoreArray>(strnow) == null) { cache.Set(strnow, ScoreArray, Constants.cacheTime); cache.Set(strRec, alldata, Constants.cacheTime); } else { cache.Remove(strnow); cache.Set(strnow, ScoreArray, Constants.cacheTime); } } } }
private void FixedUpdate() { TargetSet(); GrabObject(); if (!doing_action) { if (action_count == 0 && !Item_Object.GetComponent <SpawnObject>().get_fixed_check()) { // print("Am I stuck??"); // print(doing_action); // print(Item_Object.GetComponent<SpawnObject>().get_spawn_finish()); Item_Object.GetComponent <SpawnObject>().Do_check(); return; } if (action_count == 0) { ground_Object.GetComponent <Ground_SC>().Reset(); } if (action_count >= 11) { doing_action = true; int reward = ground_Object.GetComponent <Ground_SC>().Get_count() + 1; Item_Object.GetComponent <SpawnObject>().Reset(); ground_Object.GetComponent <Ground_SC>().Reset(); //float reward = Item_Object.GetComponent<SpawnObject>().Evaluate_Action(); Done(); SetReward(reward); //print(reward); } else { action_count += 1; actVoxRew = new AllData(); randProb = UnityEngine.Random.Range(0.0f, 1.0f); cur_rew = ground_Object.GetComponent <Ground_SC>().Get_count() + 1 - prev_rew; prev_rew = ground_Object.GetComponent <Ground_SC>().Get_count() + 1; if (cur_rew > Reward_MAX) { for (int iii = Reward_MAX; iii <= cur_rew; iii++) { reward_count_list.Add(0.0f); threshold_list.Add(threshold_value); } Reward_MAX = cur_rew; } float sum_val = reward_count_list.Sum() + 1; double[] reward_distb = new double[Reward_MAX + 1]; double kl_val = .0f; for (int c = 0; c <= Reward_MAX; c++) { if (c == cur_rew) { reward_distb[c] = (reward_count_list[c] + 1) / (sum_val); } else { reward_distb[c] = reward_count_list[c] / (sum_val); } kl_val += reward_distb[c] * Math.Log(reward_distb[c] * Reward_MAX + 0.0000001); } if (prev_kl_val > kl_val) { prev_kl_val = kl_val; reward_count_list[cur_rew] += 1.0f; collect_data = true; } else if (randProb < threshold_list[cur_rew]) { prev_kl_val = kl_val; reward_count_list[cur_rew] += 1.0f; collect_data = true; } else { collect_data = false; } //print(randProb); //print("entering coroutine"); //print("collect_data: " + collect_data); doing_action = true; Item_Object.GetComponent <SpawnObject>().GetEulers(action_count, voxelTransform, objectTypes, objectVisiblity, collect_data); RequestDecision(); } } }
public JsonResult Upload_data_file_text(string upload_text) { var check_id = System.Web.HttpContext.Current.User.Identity.GetUserId(); AllData data = null; try { data = JsonConvert.DeserializeObject <AllData>(upload_text); } catch { return(Json(false)); //bad request } //db.Articles.RemoveRange(db.Articles.Where(x1 => x1.UserId == check_id)); //db.Sections.RemoveRange(db.Sections.Where(x1 => x1.UserId == check_id)); //TODO тут данные не удалять а изменять??? //идти по бд и сравнивать со строкой и удалять менять //идти по файлу и сравнивать с бд менять //если в файле есть блок которого нет в бд то добавлять Dictionary <int, int> change_sec_id = new Dictionary <int, int>(); using (ApplicationDbContext db = new ApplicationDbContext()) { var lst_sec = db.Sections.Where(x1 => x1.UserId == check_id).ToList(); foreach (var i in lst_sec) { var tmp_sec = data.Sections.FirstOrDefault(x1 => x1.Id == i.Id); if (tmp_sec == null) { db.Sections.Remove(i); } else { if (!i.Head.Equals(tmp_sec.Head)) { tmp_sec.Head = tmp_sec.Head; } i.Order = tmp_sec.Order; bool owner_sec = true; if (i.SectionParrentId != tmp_sec.SectionParrentId) { CheckAccessSection(check_id, tmp_sec.SectionParrentId, out owner_sec); } if (owner_sec) { i.SectionParrentId = tmp_sec.SectionParrentId; } data.Sections.Remove(tmp_sec); } } db.SaveChanges(); foreach (var i in data.Sections) { bool owner_sec = true; //тут мб при ошибке проставлять Section_parrentId id главной секции? CheckAccessSection(check_id, i.SectionParrentId, out owner_sec); if (i.SectionParrentId == null || owner_sec) { int old_id = i.Id; i.Id = 0; i.UserId = check_id; db.Sections.Add(i); db.SaveChanges(); change_sec_id.Add(old_id, i.Id); } } var lst_art = db.Articles.Where(x1 => x1.UserId == check_id).ToList(); foreach (var i in lst_art) { var tmp_art = data.Articles.FirstOrDefault(x1 => x1.Id == i.Id); if (tmp_art == null) { db.Articles.Remove(i); } else { if (!i.Head.Equals(tmp_art.Head)) { tmp_art.Head = tmp_art.Head; } if (!i.Body.Equals(tmp_art.Body)) { tmp_art.Body = tmp_art.Body; } i.Order = tmp_art.Order; bool owner_sec = true; if (i.SectionParrentId != tmp_art.SectionParrentId) { CheckAccessSection(check_id, tmp_art.SectionParrentId, out owner_sec); } if (owner_sec) { i.SectionParrentId = tmp_art.SectionParrentId; } data.Articles.Remove(tmp_art); } } db.SaveChanges(); foreach (var i in data.Articles) { //i.Section_parrentId ==0 НЕ УВЕРЕН ЧТО НУЖНО не знаю как json парсит null для типов INT //i.Section_parrentId ==0|| bool owner_sec = true; //тут мб при ошибке проставлять Section_parrentId id главной секции? var ch_c_i = change_sec_id.FirstOrDefault(x1 => x1.Key == i.SectionParrentId); if (ch_c_i.Value != 0 && ch_c_i.Key != 0) { i.SectionParrentId = ch_c_i.Value; } CheckAccessSection(check_id, i.SectionParrentId, out owner_sec); if (owner_sec) { //var tmp_a = data.Articles.Where(x1 => x1.SectionParrentId == i.Id).ToList(); //foreach (var i2 in tmp_a) //{ // i2.SectionParrentId = i.Id; //} i.Id = 0; i.UserId = check_id; db.Articles.Add(i); } } db.SaveChanges(); var lst_img = db.ImagesInfo.Where(x1 => x1.UserId == check_id).ToList(); foreach (var i in lst_img) { var tmp_img = data.Images.FirstOrDefault(x1 => x1.Id == i.Id); if (tmp_img == null) { db.ImagesInfo.Remove(i); } else { i.Data = tmp_img.Data; bool owner_sec = true; if (i.Article_parrentId != tmp_img.Article_parrentId) { CheckAccessSection(check_id, db.Articles.FirstOrDefault(x1 => x1.Id == tmp_img.Article_parrentId)?.SectionParrentId, out owner_sec); } if (owner_sec) { i.Article_parrentId = tmp_img.Article_parrentId; } data.Images.Remove(tmp_img); } } db.SaveChanges(); foreach (var i in data.Images) { if (i.Article_parrentId == null || db.Articles.FirstOrDefault(x1 => x1.Id == i.Article_parrentId && x1.UserId == check_id) != null) { i.Id = 0; i.UserId = check_id; db.ImagesInfo.Add(i); } } db.SaveChanges(); } return(Json(true)); }
IEnumerator ConnectToGetData(Server_RequestType _RequestType, Action successCallback, Action failCallback, bool needShowConnecting) { isConnecting = true; UnityWebRequest requestCountry = UnityWebRequest.Get(getdata_uri_dic[Server_RequestType.GetLocalCountry]); yield return(requestCountry.SendWebRequest()); if (requestCountry.isNetworkError || requestCountry.isHttpError) { OnConnectServerFail(); failCallback?.Invoke(); } else { string downText = requestCountry.downloadHandler.text; LocalCountryData countryData = JsonMapper.ToObject <LocalCountryData>(downText); localCountry = countryData.country.ToLower(); } requestCountry.Dispose(); if (string.IsNullOrEmpty(Save.data.uuid)) { UnityWebRequest requestUUID = UnityWebRequest.Get(getdata_uri_dic[Server_RequestType.GetUUID]); yield return(requestUUID.SendWebRequest()); if (requestUUID.isNetworkError || requestUUID.isHttpError) { OnConnectServerFail(); failCallback?.Invoke(); } else { string downText = requestUUID.downloadHandler.text; Save.data.uuid = downText; } requestUUID.Dispose(); } List <IMultipartFormSection> iparams = new List <IMultipartFormSection>(); if (!string.IsNullOrEmpty(deviceID)) { iparams.Add(new MultipartFormDataSection("device_id", deviceID)); } iparams.Add(new MultipartFormDataSection("uuid", Save.data.uuid)); iparams.Add(new MultipartFormDataSection("app_name", Bi_name)); if (_RequestType == Server_RequestType.AllData) { iparams.Add(new MultipartFormDataSection("country", localCountry)); iparams.Add(new MultipartFormDataSection("ad_ios", Platform)); } if (needShowConnecting) { OnConnectingServer(); } UnityWebRequest www = UnityWebRequest.Post(getdata_uri_dic[_RequestType], iparams); yield return(www.SendWebRequest()); isConnecting = false; if (www.isNetworkError || www.isHttpError) { OnConnectServerFail(); failCallback?.Invoke(); } else { OnConnectServerSuccess(); string downText = www.downloadHandler.text; if (downText == "-1" || downText == "-2" || downText == "-3" || downText == "-4" || downText == "-5") { ShowConnectErrorTip(downText); failCallback?.Invoke(); } else { switch (_RequestType) { case Server_RequestType.AllData: try { AllData allData = JsonMapper.ToObject <AllData>(downText); Save.data.allData = allData; Save.data.uuid = string.IsNullOrEmpty(allData.user_uuid) ? Save.data.uuid : allData.user_uuid; Ads._instance.InitFyber(allData.user_panel.user_id); } catch (Exception e) { failCallback?.Invoke(); ShowConnectErrorTip(e.Message); yield break; } break; case Server_RequestType.TaskData: AllData_TaskData taskData = JsonMapper.ToObject <AllData_TaskData>(downText); Save.data.allData.lucky_schedule = taskData; break; default: break; } successCallback?.Invoke(); } } www.Dispose(); }