public static GlobalVars GetInstance() { if(Instance == null) { GameObject g = new GameObject("__GlobalVars"); Instance = g.AddComponent<GlobalVars>(); } return Instance; }
private void Awake() { gv = GameObject.Find("GlobalVars").GetComponent<GlobalVars>(); //инициализируем поле if (gv != null) { gv.MobList.Add(gameObject); //добавляем себя в общий лист мобов gv.MobCount++; //увеличиваем счетчик мобов } if (maxHP < 1) maxHP = 1; //если максимальное хп задано менее единицы - ставим единицу }
private void Awake() { gv = GameObject.Find("GlobalVars").GetComponent<GlobalVars>(); //инициализируем поле if (gv != null) { gv.TurretList.Add(gameObject); gv.TurretCount++; } if (maxHP < 1) maxHP = 1; }
private RaycastHit hit; //переменная для рейкаста #endregion Fields #region Methods private void Awake() { gv = GameObject.Find("GlobalVars").GetComponent<GlobalVars>(); //инициализируем поле if (gv == null) Debug.LogWarning("gv variable is not initialized correctly in " + this); //сообщим об ошибке, если gv пуста buyMenu = new Rect(Screen.width - 185.0f, 10.0f, 175.0f, Screen.height - 100.0f); //задаём размеры квадратов, последовательно позиция X, Y, Ширина, Высота. X и Y указывают на левый верхний угол объекта firstTower = new Rect(buyMenu.x + 12.5f, buyMenu.y + 30.0f, 150.0f, 50.0f); secondTower = new Rect(firstTower.x, buyMenu.y + 90.0f, 150.0f, 50.0f); thirdTower = new Rect(firstTower.x, buyMenu.y + 150.0f, 150.0f, 50.0f); fourthTower = new Rect(firstTower.x, buyMenu.y + 210.0f, 150.0f, 50.0f); fifthTower = new Rect(firstTower.x, buyMenu.y + 270.0f, 150.0f, 50.0f); playerStats = new Rect(10.0f, 10.0f, 150.0f, 100.0f); playerStatsPlayerMoney = new Rect(playerStats.x + 12.5f, playerStats.y + 30.0f, 125.0f, 25.0f); towerMenu = new Rect(10.0f, Screen.height - 60.0f, 400.0f, 50.0f); towerMenuSellTower = new Rect(towerMenu.x + 12.5f, towerMenu.y + 20.0f, 75.0f, 25.0f); towerMenuUpgradeTower = new Rect(towerMenuSellTower.x + 5.0f + towerMenuSellTower.width, towerMenuSellTower.y, 75.0f, 25.0f); }
///////////////////////////////////////////////////////////////////////// public void On_AlphaInputChanged(string s) { EMA_alpha = Convert.ToSingle(s, GlobalVars.myNumberFormat()); }
// Unity // ===================================================================== private void Awake() { _globalVars = GlobalVars.instance; _agent = GetComponent <NavMeshAgent>(); currentHealth = maxHealth; }
public async Task RequestEmote(string trigger, string url, bool RequiresTarget, [Remainder] string msg) { if (msg == "") { msg = $"is {trigger}"; } EmoteRequest er = new EmoteRequest(Context.Message.Author, trigger, RequiresTarget, msg, false); string finalURL = ""; string[] imgFileTypes = { ".jpg", ".jpeg", ".gif", ".png" }; foreach (string s in imgFileTypes) { if (url.Substring(url.Length - s.Length, s.Length) == s) { finalURL = url; er.FileExtension = s; } } if (finalURL == "") { finalURL = url.Contains("tenor") ? ImageLogger.GetTenorGIF(url) : url.Contains("gfycat") ? ImageLogger.GetGfyCatAsync(url) : ""; foreach (string s in imgFileTypes) { if (finalURL.Substring(finalURL.Length - s.Length, s.Length) == s) { er.FileExtension = s; } } } if (finalURL != "") { string dir = RequestLocation.Substring(0, RequestLocation.Length - 1); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } using (var c = new WebClient()) { try { c.DownloadFile(finalURL, RequestLocation + er.FileName); } catch (Exception ex) { } while (c.IsBusy) { } } GlobalVars.EmoteRequests.Add(er.RequestID, er); try { await SendRequest(er); var m = await Context.Channel.SendMessageAsync($"Emote requested, emote ID: {er.RequestID}"); GlobalVars.AddRandomTracker(m, 15); var perms = Context.Guild.GetUser(Context.Client.CurrentUser.Id).GetPermissions(Context.Channel as IGuildChannel); if (perms.ManageMessages) { try { await Context.Message.DeleteAsync(); } catch { } } } catch (Discord.Net.HttpException ex) { if (ex.DiscordCode == 40005) { var m = await Context.Channel.SendMessageAsync($"{Context.User.Mention}, the filesize is too large (~{new FileInfo(RequestLocation + er.FileName).Length / 1048576}MB). Max filesize: 8MB\nPlease resize your image or use another."); GlobalVars.AddRandomTracker(m, 15); File.Delete(RequestLocation + er.FileName); GlobalVars.EmoteRequests.Remove(er.RequestID); } await Program.Client_Log(new LogMessage(LogSeverity.Error, "Emote Request", ex.Message, ex)); } } else { var m = await Context.Channel.SendMessageAsync("Could not get the download URL for this image."); GlobalVars.AddRandomTracker(m, 20); } }
void Awake() { globalVars = GlobalVars.Instance; dgSerializer = DelayGramSerializer.Instance; }
public Application() { globals = new GlobalVars(this); }
public async Task OxfordDefine(params string[] term) { string WEBSERVICE_URL = "https://od-api.oxforddictionaries.com:443/api/v2/lemmas/en/" + string.Join(' ', term).ToLower(); string jsonResponse = ""; OxfordEntry oxfEntry = new OxfordEntry(); OxfordLemma oxfLemma = new OxfordLemma(); EmbedBuilder builder = new EmbedBuilder { Title = "Oxford Dictionary Definitions" }; try { var webRequest = WebRequest.Create(WEBSERVICE_URL); if (webRequest != null) { webRequest.Method = "GET"; webRequest.Timeout = 12000; webRequest.ContentType = "application/json"; webRequest.Headers.Add("app_id", _OXFORDID_); webRequest.Headers.Add("app_key", _OXFORDKEY_); using (Stream s = webRequest.GetResponse().GetResponseStream()) { using (StreamReader sr = new StreamReader(s)) { jsonResponse = sr.ReadToEnd(); oxfLemma = JsonConvert.DeserializeObject <OxfordLemma>(jsonResponse); } } } } catch (Exception ex) { await LogWriter.WriteLogFile($"ERROR: Exception thrown : {ex.Message}"); await LogWriter.WriteLogFile($"{ex.StackTrace}"); Console.WriteLine($"Exception: {ex.Message}"); } if (oxfLemma.Results != null) { string newTerm = oxfLemma.Results.First(lex => lex.LexicalEntries[0].Text != null).LexicalEntries[0].Text.ToLower(); WEBSERVICE_URL = "https://od-api.oxforddictionaries.com:443/api/v2/entries/en-gb/" + newTerm; try { var webRequest = WebRequest.Create(WEBSERVICE_URL); if (webRequest != null) { webRequest.Method = "GET"; webRequest.Timeout = 12000; webRequest.ContentType = "application/json"; webRequest.Headers.Add("app_id", _OXFORDID_); webRequest.Headers.Add("app_key", _OXFORDKEY_); using (Stream s = webRequest.GetResponse().GetResponseStream()) { using (StreamReader sr = new StreamReader(s)) { jsonResponse = sr.ReadToEnd(); oxfEntry = JsonConvert.DeserializeObject <OxfordEntry>(jsonResponse); var actualRes = oxfEntry.Results[0].LexicalEntries.First(e => e.Entries[0].Senses[0].Definitions != null).Entries[0].Senses[0]; builder.AddField(newTerm, actualRes.Definitions[0]); } } } } catch (Exception ex) { await LogWriter.WriteLogFile($"ERROR: Exception thrown : {ex.Message}"); await LogWriter.WriteLogFile($"{ex.StackTrace}"); Console.WriteLine($"Exception: {ex.Message}"); } } if (builder.Fields.Count == 0) { var c = (ITextChannel)Context.Channel; RestUserMessage m; if (c.IsNsfw) { m = await Context.Channel.SendMessageAsync("Failed to find this on the Oxford Dictionary, trying again on Urban Dictionary."); await UrbDefine(term); GlobalVars.AddRandomTracker(m); } else { await Context.Channel.SendMessageAsync("Nothing found, try again in a channel marked NSFW."); } return; } else { await Context.Channel.SendMessageAsync(null, false, builder.Build()); } }
public static GameObject CreateGameObject(int spriteValue, Vector2 position) { switch (spriteValue) { case 32: return(GameObjectManager.InstantiatePlayer(position)); case 1: var messages = GlobalVars.GetMessageListAt((int)(position.X / 8), (int)(position.Y / 8)); List <string> messageList = new List <string>(); if (messages != null) { foreach (var m in messages) { messageList.Add((string)m.Value); } } return(GameObjectManager.AddObject( new OldMan(position, spriteValue, messageList) )); case 98: return(GameObjectManager.AddObject( new FirePit( position ) )); case 76: return(GameObjectManager.AddObject( new Chimney( position ) )); case 7: return(GameObjectManager.AddObject(new Blob(position, spriteValue))); case 55: return(GameObjectManager.AddObject(new Bat(position, spriteValue))); case 21: return(GameObjectManager.AddObject(new Tortuga(position, spriteValue))); case 122: return(GameObjectManager.AddObject(new Spike(position, spriteValue))); case 42: return(GameObjectManager.AddObject(new Goose(position, spriteValue))); case 11: return(GameObjectManager.AddObject(new Gate(position))); case 12: return(GameObjectManager.AddObject(new Gate(position, Gate.OpenCondition.NO_ENEMIES))); case 19: return(GameObjectManager.AddObject(new Snake(position, spriteValue))); case 105: return(GameObjectManager.AddObject(new Key(position))); case 78: return(GameObjectManager.AddObject(new Altar(position))); case 126: return(GameObjectManager.AddObject(new Stairs(position, spriteValue))); case 51: return(GameObjectManager.AddObject(new RunningBoots(position))); case 123: return(GameObjectManager.AddObject(new RunningBoots(position))); default: return(GameObjectManager.AddObject(new GameObject(position, new Graphics.P8Sprite(spriteValue)))); } }
private async Task CheckForNewGlobalVarsAsync(bool dontShowFurtherToasts) { //string newURL = String.Format(GlobalVars.GlobalOptionsURLCustomizableURL, TimeZoneInfo.ConvertTime(GlobalVars.lastGlobalVarUpdateTime, TimeZoneInfo.Utc).ToString("yyyy-MM-dd't'HH:mm:ss")); if (GlobalVars.isGlobalVarSyncNeeded || overrideUpdateCheckOptions) { overrideUpdateCheckOptions = false; //bool tapped = await GlobalVars.notifier.Notify(ToastNotificationType.Info, //"Updating Maps and other info", "Now checking for updated information...", TimeSpan.FromSeconds(2)); //var returned = await GlobalVars.notifier.Notify(new NotificationOptions() //{ // Title = "Updating Maps and other info", // Description = "Now checking for updated information..." //}); if (!dontShowFurtherToasts) { GlobalVars.DoToast("Now checking for updated maps or other info...", GlobalVars.ToastType.Yellow); } //using (var client = new HttpClient(new NativeMessageHandler() //{ // Timeout = new TimeSpan(0, 0, 9), // EnableUntrustedCertificates = true, // DisableCaching = true //})) using (var client = new HttpClient()) { client.MaxResponseContentBufferSize = 25600000; DateTime indyTime = DependencyService.Get <ICalendar>().ConvertToIndy(GlobalVars.lastGlobalVarUpdateTime); string newURL = String.Format(GlobalVars.GlobalOptionsURLCustomizableURL, indyTime.ToString("yyyy-MM-dd't'HH:mm:ss")); try { var response = await client.GetAsync(newURL).ConfigureAwait(false); if (response.IsSuccessStatusCode) { var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); if (content.Length > 10) { GlobalVars.FileDownloadProgressUpdated += GlobalVars_FileDownloadProgressUpdated; bool totalSuccess = await GlobalVars.OverwriteOptions(content); GlobalVars.FileDownloadProgressUpdated -= GlobalVars_FileDownloadProgressUpdated; //START HERE DUMMY // PICK UP CODING HERE STUPID //bool tapped2 = await GlobalVars.notifier.Notify(ToastNotificationType.Success, //"Maps and info have been updated.", "**REFRESHING SCREEN**", TimeSpan.FromSeconds(2)); //var tapped2 = await GlobalVars.notifier.Notify(new NotificationOptions() //{ // Title = "Maps and info have been updated.", // Description = "**REFRESHING SCREEN**", //}); GlobalVars.DoToast("Update success - **REFRESHING SCREEN**", GlobalVars.ToastType.Green); searchPage?.UpdateEventInfo(); await searchPage?.CloseAllPickers(); Xamarin.Forms.Device.BeginInvokeOnMainThread(() => { try { App.Current.MainPage = new NavigationPage(new GenHomeTabPage()); } catch (Exception) { } }); } else { //bool tapped2 = await GlobalVars.notifier.Notify(ToastNotificationType.Success, //"Check complete.", "You already have the most recent info.", TimeSpan.FromSeconds(2)); //var tapped2 = await GlobalVars.notifier.Notify(new NotificationOptions() //{ // Title = "Check complete.", // Description = "You already have the most recent info." //}); if (!dontShowFurtherToasts) { GlobalVars.DoToast("You are up to date.", GlobalVars.ToastType.Green); } try { Xamarin.Forms.Device.BeginInvokeOnMainThread(() => { searchPage?.UpdateEventInfo(); }); } catch (Exception) { } GlobalVars.lastGlobalVarUpdateTime = DateTime.Now; } } } catch (Exception) { //bool tapped2 = await GlobalVars.notifier.Notify(ToastNotificationType.Success, // "Check complete.", "Couldn't update now, but we'll try again later.", TimeSpan.FromSeconds(2)); //var tapped2 = await GlobalVars.notifier.Notify(new NotificationOptions() //{ // Title = "Check complete.", // Description = "Couldn't update now, but we'll try again later." //}); if (!dontShowFurtherToasts) { GlobalVars.DoToast("Couldn't update now, but we'll try again later.", GlobalVars.ToastType.Yellow); } } } } }
private void Start() { shatter = GlobalVars.Get("door_shatter").GetComponent <ParticleSystem>(); onDeath = OnDeath; }
public Application(bool initialState) : base(initialState) { System.Diagnostics.Debug.Assert(initialState); globals = new GlobalVars(this); }
//resets the variables for a session //for use after they've been logged static void ResetSessionVariables(GlobalVars.Scenes scene) { if (scene == GlobalVars.Scenes.Crafting) { ElementsUnlockedInSession = 0; TiersUnlockedInSession = 0; TiersCompletedInSession = 0; ElementsCraftedInSession = 0; HintsBoughtInSession = 0; PowerUpUpgradesBoughtInSession = 0; } }
public void OnNavigatedFrom(NavigationEventArgs e) { GlobalVars.OnNavigatedFrom(e); }
public static GlobalVars GetInstance() { if (_instance == null) { _instance = new GlobalVars(); } return _instance; }
public GenSearchView(GenMainPage parentPage) : base(GlobalVars.searchTitle) { GlobalVars.View_GenSearchView = null; _parentPage = parentPage; _lastSyncTime = DateTime.Now; outerContainer = new AbsoluteLayout { Padding = 0 }; var wholePage = new StackLayout { Orientation = StackOrientation.Vertical, Padding = 0, Spacing = 0, HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand }; var searchNavSectionTwo = new Grid { HorizontalOptions = LayoutOptions.FillAndExpand, Padding = 1, ColumnSpacing = 1, ColumnDefinitions = new ColumnDefinitionCollection() { new ColumnDefinition() { Width = new GridLength(4, GridUnitType.Star) }, new ColumnDefinition() { Width = new GridLength(4, GridUnitType.Star) }, new ColumnDefinition() { Width = new GridLength(4, GridUnitType.Star) }, new ColumnDefinition() { Width = new GridLength(3, GridUnitType.Star) }, new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) } }, RowDefinitions = new RowDefinitionCollection() { new RowDefinition() { Height = GridLength.Auto } } }; //START OF UPPER SEARCH SECTION StackLayout searchNavSection = new StackLayout { Orientation = StackOrientation.Horizontal, Padding = 2, Spacing = 0, HorizontalOptions = LayoutOptions.FillAndExpand }; searchEntry = new Entry { Keyboard = Keyboard.Create(0), Placeholder = "Search Here", HorizontalOptions = LayoutOptions.FillAndExpand }; searchTerm = new SearchTerm(); searchEntry.BindingContext = searchTerm; searchEntry.SetBinding(Entry.TextProperty, "searchTerm", BindingMode.TwoWay); searchEntry.Completed += (sender, e) => { SetGenListContent(); }; //run the below on every keypress var clearWatcher = searchTerm.observer .ObserveOn(SynchronizationContext.Current) .Subscribe(final => { searchTerm.isIgnoringNextEvent = false; outerContainer.Children.Remove(autoCompleteHolder); }); //only run the below on legit text entry var autoCompleteWatcher = searchTerm.observer .Throttle(TimeSpan.FromMilliseconds(300)) //Wait for the user to pause typing .Where(x => !string.IsNullOrEmpty(x) && x.Length > 2) //Make sure the search term is long enough .DistinctUntilChanged() .ObserveOn(SynchronizationContext.Current) .Subscribe((x) => { Observable.FromAsync((_) => { string term = x.Trim(); if ((term.Length == 10 || term.Length == 11) && GlobalVars.isTypedEventID(term)) { Device.BeginInvokeOnMainThread(() => { SetGenListContent(); }); return(new Task <IList <GenEvent> >(() => { var returnMe = new List <GenEvent>(); return returnMe; })); } return(GlobalVars.db.GetItemsFTS4(term, new GenconMobileDatabase.DBOptions[] { })); }) //MatchOnEmail returns Task<IEnumerable<T>> .TakeUntil(searchTerm.observer) //If searchterm changes abandon the current request .ObserveOn(SynchronizationContext.Current) //To be safe marshall response to the UI thread .Subscribe(final => //final holds the IEnumerable<T> { try { if (!searchTerm.isIgnoringNextEvent) { AutoCompleteMatches.Clear(); if (final == null || !final.Any()) { MatchCount = 0; //ShowResult = false; RemoveAutoCompleteView(); } else { foreach (var g in final.DistinctBy(d => d.Title).OrderBy(d => d.Title).Take(5)) { AutoCompleteMatches.Add(g); } MatchCount = AutoCompleteMatches.Count; matchListView.ItemsSource = AutoCompleteMatches; var r = AbsoluteLayout.GetLayoutBounds(autoCompleteHolder); r.Y = searchEntry.Y + (searchEntry.Height); r.Height = wholePage.Height; AbsoluteLayout.SetLayoutFlags(autoCompleteHolder, AbsoluteLayoutFlags.HeightProportional); AbsoluteLayout.SetLayoutBounds(autoCompleteHolder, r); //autoCompleteHolder.MinimumHeightRequest = wholePage.Height; matchListView.HeightRequest = searchEntry.Height * Math.Min(AutoCompleteMatches.Count, 3); //ShowResult = true; if (!outerContainer.Children.Contains(autoCompleteHolder)) { outerContainer.Children.Add(autoCompleteHolder); } } } } catch (Exception ex) { string error = ex.Message; } }); }); var clearSearchButton = new Image { Aspect = Aspect.AspectFit, HorizontalOptions = LayoutOptions.End }; clearSearchButton.Source = ImageSource.FromFile("ic_cancel_black_24dp.png"); TapGestureRecognizer clearSearchTap = new TapGestureRecognizer(); clearSearchTap.Tapped += ClearSearchTap_Tapped; clearSearchButton.GestureRecognizers.Add(clearSearchTap); var searchStartButton = new Image { Aspect = Aspect.AspectFit, HorizontalOptions = LayoutOptions.End }; searchStartButton.Source = ImageSource.FromFile("ic_search_black_24dp.png"); TapGestureRecognizer startSearchTap = new TapGestureRecognizer(); startSearchTap.Tapped += StartSearchTap_Tapped; //startSearchTap.Tapped += DEBUGDEMO_Tapped; searchStartButton.GestureRecognizers.Add(startSearchTap); autoCompleteHolder = new StackLayout { Padding = 0, Spacing = 0, VerticalOptions = LayoutOptions.FillAndExpand, HorizontalOptions = LayoutOptions.FillAndExpand, Orientation = StackOrientation.Vertical, BackgroundColor = Color.FromRgba(0.2, 0.2, 0.2, 0.5) }; var matchListTemplate = new DataTemplate(typeof(TextCell)); matchListTemplate.SetBinding(TextCell.TextProperty, "Title"); itemTemplate = new DataTemplate(typeof(GenEventCell)); itemTemplate.CreateContent(); matchListView = new ListView { HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.Start, BindingContext = this, ItemTemplate = matchListTemplate, BackgroundColor = Color.White }; autoCompleteHolder.Children.Add(matchListView); searchNavSection.Children.Add(searchEntry); searchNavSection.Children.Add(clearSearchButton); searchNavSection.Children.Add(searchStartButton); wholePage.Children.Add(searchNavSection); //searchNavSectionTwo dayPicker = new Picker { Title = "Days", VerticalOptions = LayoutOptions.CenterAndExpand, HorizontalOptions = LayoutOptions.FillAndExpand }; dayPicker.Items.Add("ALL"); dayPicker.Items.Add("WED"); dayPicker.Items.Add("THU"); dayPicker.Items.Add("FRI"); dayPicker.Items.Add("SAT"); dayPicker.Items.Add("SUN"); afterPicker = new Picker { Title = "After", VerticalOptions = LayoutOptions.CenterAndExpand, HorizontalOptions = LayoutOptions.FillAndExpand }; afterPicker.Items.Add("---"); afterPicker.Items.Add("01:00AM"); afterPicker.Items.Add("02:00AM"); afterPicker.Items.Add("03:00AM"); afterPicker.Items.Add("04:00AM"); afterPicker.Items.Add("05:00AM"); afterPicker.Items.Add("06:00AM"); afterPicker.Items.Add("07:00AM"); afterPicker.Items.Add("08:00AM"); afterPicker.Items.Add("09:00AM"); afterPicker.Items.Add("10:00AM"); afterPicker.Items.Add("11:00AM"); afterPicker.Items.Add("12:00PM"); afterPicker.Items.Add("01:00PM"); afterPicker.Items.Add("02:00PM"); afterPicker.Items.Add("03:00PM"); afterPicker.Items.Add("04:00PM"); afterPicker.Items.Add("05:00PM"); afterPicker.Items.Add("06:00PM"); afterPicker.Items.Add("07:00PM"); afterPicker.Items.Add("08:00PM"); afterPicker.Items.Add("09:00PM"); afterPicker.Items.Add("10:00PM"); afterPicker.Items.Add("11:00PM"); beforePicker = new Picker { Title = "Before", VerticalOptions = LayoutOptions.CenterAndExpand, HorizontalOptions = LayoutOptions.FillAndExpand }; beforePicker.Items.Add("---"); beforePicker.Items.Add("01:00AM"); beforePicker.Items.Add("02:00AM"); beforePicker.Items.Add("03:00AM"); beforePicker.Items.Add("04:00AM"); beforePicker.Items.Add("05:00AM"); beforePicker.Items.Add("06:00AM"); beforePicker.Items.Add("07:00AM"); beforePicker.Items.Add("08:00AM"); beforePicker.Items.Add("09:00AM"); beforePicker.Items.Add("10:00AM"); beforePicker.Items.Add("11:00AM"); beforePicker.Items.Add("12:00PM"); beforePicker.Items.Add("01:00PM"); beforePicker.Items.Add("02:00PM"); beforePicker.Items.Add("03:00PM"); beforePicker.Items.Add("04:00PM"); beforePicker.Items.Add("05:00PM"); beforePicker.Items.Add("06:00PM"); beforePicker.Items.Add("07:00PM"); beforePicker.Items.Add("08:00PM"); beforePicker.Items.Add("09:00PM"); beforePicker.Items.Add("10:00PM"); beforePicker.Items.Add("11:00PM"); sortPicker = new Picker { Title = "Sort", VerticalOptions = LayoutOptions.CenterAndExpand, HorizontalOptions = LayoutOptions.FillAndExpand }; sortPicker.Items.Add("Time"); sortPicker.Items.Add("Title"); sortPicker.Items.Add("Ticket"); sortPicker.Items.Add("Price"); changeSortButton = new Image { Aspect = Aspect.AspectFit }; changeSortButton.Source = ImageSource.FromFile("ic_arrow_downward_black_24dp.png"); TapGestureRecognizer changeSortTap = new TapGestureRecognizer(); changeSortTap.Tapped += ChangeSort_Tapped; changeSortButton.GestureRecognizers.Add(changeSortTap); searchNavSectionTwo.Children.Add(dayPicker, 0, 0); searchNavSectionTwo.Children.Add(afterPicker, 1, 0); searchNavSectionTwo.Children.Add(beforePicker, 2, 0); searchNavSectionTwo.Children.Add(sortPicker, 3, 0); searchNavSectionTwo.Children.Add(changeSortButton, 4, 0); wholePage.Children.Add(searchNavSectionTwo); //START OF LOWER EVENT SECTION eventDisplayWrapper = new StackLayout { Orientation = StackOrientation.Vertical, Padding = paddingAmount, Spacing = 0, HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand }; eventDisplay = new StackLayout { Orientation = StackOrientation.Vertical, Padding = 0, Spacing = 6, HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand }; lastUpdatedEventsLabel = new Label { Text = GlobalVars.eventsLastUpdatedPretty, FontSize = 10, FontAttributes = FontAttributes.Italic, HorizontalOptions = LayoutOptions.FillAndExpand, HorizontalTextAlignment = TextAlignment.Center }; eventsTotalCountLabel = new Label { Text = GlobalVars.eventsTotalCountPretty, FontSize = 12, FontAttributes = FontAttributes.Bold, HorizontalOptions = LayoutOptions.FillAndExpand, HorizontalTextAlignment = TextAlignment.Center }; var thirdString = new Label { Text = GlobalVars.eventsExplanationPretty, FontSize = 10, HorizontalOptions = LayoutOptions.FillAndExpand, HorizontalTextAlignment = TextAlignment.Center }; var showAllButton = new Button { Text = "SHOW ALL", HorizontalOptions = LayoutOptions.Center }; var fourthString = new Label { Text = GlobalVars.eventsFinalInfoPretty, FontSize = 12, HorizontalOptions = LayoutOptions.FillAndExpand, HorizontalTextAlignment = TextAlignment.Center }; eventDisplay.Children.Add(lastUpdatedEventsLabel); eventDisplay.Children.Add(eventsTotalCountLabel); eventDisplay.Children.Add(thirdString); eventDisplay.Children.Add(showAllButton); eventDisplay.Children.Add(fourthString); eventDisplayWrapper.Children.Add(eventDisplay); wholePage.Children.Add(eventDisplayWrapper); genEventList = new GenEventList { VerticalOptions = LayoutOptions.FillAndExpand }; genEventListView = new ListView(ListViewCachingStrategy.RecycleElement) { RowHeight = (int)GlobalVars.sizeListCellHeight, SeparatorVisibility = SeparatorVisibility.None }; loadingListView = new ListView { RowHeight = (int)GlobalVars.sizeListCellHeight, SeparatorVisibility = SeparatorVisibility.None }; loadingIndicator = new ActivityIndicator() { IsRunning = true, IsVisible = false, VerticalOptions = LayoutOptions.FillAndExpand, HorizontalOptions = LayoutOptions.FillAndExpand, BackgroundColor = Color.Transparent, MinimumWidthRequest = 400, MinimumHeightRequest = 400 }; outerContainer.Children.Add(wholePage); outerContainer.Children.Add(loadingIndicator); AbsoluteLayout.SetLayoutBounds(wholePage, new Rectangle(0, 0, 1, 1)); AbsoluteLayout.SetLayoutFlags(wholePage, AbsoluteLayoutFlags.All); AbsoluteLayout.SetLayoutFlags(loadingIndicator, AbsoluteLayoutFlags.PositionProportional); AbsoluteLayout.SetLayoutBounds(loadingIndicator, new Rectangle(0.5, 0.5, AbsoluteLayout.AutoSize, AbsoluteLayout.AutoSize)); Content = outerContainer; this.ToolbarItems.Add(new ToolbarItem("Font Size", "baseline_format_size_black_24.png", () => { var page = new DisplayOptionsPage(); PopupNavigation.Instance.PushAsync(page); })); this.ToolbarItems.Add(new ToolbarItem("Refresh", "ic_refresh_black_24dp.png", () => { GlobalVars.View_GenEventsLoadingView.StartLoad(); })); //Start of hidden event portion RESUME CODING HERE showAllButton.Clicked += OnShowAllClicked; dayPicker.SelectedIndexChanged += OnDayPickerSelected; sortPicker.SelectedIndexChanged += OnSortPickerSelected; afterPicker.SelectedIndexChanged += OnAfterPickerSelected; beforePicker.SelectedIndexChanged += OnBeforePickerSelected; matchListView.ItemSelected += MatchListView_ItemSelected; //genEventListView.ItemTapped += GenEventListView_ItemTapped; genEventListView.ItemSelected += GenEventListView_ItemSelected; TapGestureRecognizer clearAutoCompleteTap = new TapGestureRecognizer(); clearAutoCompleteTap.Tapped += ClearAutoCompleteTap_Tapped; autoCompleteHolder.GestureRecognizers.Add(clearAutoCompleteTap); this.LayoutChanged += GenNavigationPage_LayoutChanged; this.OnAppearedHandler += Event_CheckForUpdates; this.CheckForUpdateHandler += Event_CheckForUpdates; GlobalVars.View_GenSearchView = this; }
public static GlobalVars GetInstance(string dominio, string periodo) { if (_instance == null) { _instance = new GlobalVars(dominio, periodo); } return _instance; }
void Start() { //если нет объекта GlobalVars, то инстациируем его if (GameObject.Find("GlobalVars") == null) { GameObject gv = GameObject.Instantiate(glvrPrefab); //перемеименуем его, ибо имя будет с приставкой (Clone) gv.name = "GlobalVars"; } //переменная для отображения/неотображения звёзд над картинкой bool stars; //получаем ссылку rectTransform lpRect = GetComponent <RectTransform>(); //получаем все изображения в указанной папке images = Resources.LoadAll <Sprite>("Sprites/Puzzle"); //сохраняем кол-во картинок lpCount = images.Length; //инициализируем переменные с размером [lpCount] для дальнейшей работы lpPos = new Vector2[lpCount]; lpScale = new Vector3[lpCount]; lpGameObjects = new GameObject[lpCount]; textlockGameObjects = new GameObject[lpCount]; starGameObjects = new GameObject[lpCount, 5]; //получаем ссылку на GlobalVars glvr = GameObject.Find("GlobalVars").GetComponent <GlobalVars>(); //Загружаем информации о уровнях из файла glvr.LoadInfo(); for (int i = 0; i < lpCount; i++) { //по умолчанию звёзды не показываются stars = false; //создаём звёзды for (int j = 0; j < 5; j++) { starGameObjects[i, j] = Instantiate(starPrefab, transform, false); } //создаём панель lpGameObjects[i] = Instantiate(lpPrefab, transform, false); //создаём текст неоткрытого уровня textlockGameObjects[i] = Instantiate(textlockPrefab, transform, false); //присваиваем спрайт картинки панели lpGameObjects[i].GetComponent <Image>().overrideSprite = images[i]; //первый уровень всегда доступен, поэтому его игнорим (i!=0) if (i != 0) { //если уровень недоступен if (glvr.GetLevel(images[i].name).isLock) { //пишем что уровень не доступен textlockGameObjects[i].GetComponent <Text>().text = "Complete at least three levels of the previous picture"; //затемняем спрайт панели lpGameObjects[i].GetComponent <Image>().color = new Color(0.3f, 0.3f, 0.3f); //выключаем компонент Button lpGameObjects[i].GetComponent <Button>().enabled = false; } else //если уровень доступен, то просто включаем звёзды { stars = true; } //находим позицию предыдущей панели Transform prevTrans = lpGameObjects[i - 1].transform; //исходя из значений предыдущей панели, перемещаем текущую панель lpGameObjects[i].transform.localPosition = new Vector2(prevTrans.localPosition.x + lpOffset + lpPrefab.GetComponent <RectTransform>().sizeDelta.x *lpPrefab.GetComponent <RectTransform>().localScale.x, lpGameObjects[i - 1].transform.localPosition.y); //изменяем маштаб панели lpGameObjects[i].transform.localScale = new Vector3(0.4f, 0.4f, 1); //изменяем позицию объекта с текстом о недоступности textlockGameObjects[i].transform.localPosition = lpGameObjects[i].transform.localPosition; //запоминаем позицию панели lpPos[i] = -lpGameObjects[i].transform.localPosition; } //если звёзды включены или это первый уровень if (stars || i == 0) { for (int j = 0; j < 5; j++) { //вычисляем и задаём позицию звезды starGameObjects[i, j].transform.localPosition = new Vector3(-lpPos[i].x + 80 * (-2 + j), -lpPos[i].y, 10); //???????????????? подгоняем маштаб звёзд starGameObjects[i, j].transform.localScale = new Vector3(65, 65, 1); //задаём спрайт зелёный звезды, если уровень сложности пройден if (j < glvr.GetLevel(images[i].name).difficult) { starGameObjects[i, j].GetComponent <Image>().overrideSprite = Resources.Load <Sprite>("Sprites/star"); } } } } }
// Start is called before the first frame update void Awake() { GlobalVars.RegisterObject(key, this.gameObject); }
void Start() { TheAnimator = GetComponentInChildren <Animator>(); ThePlayerController = GetComponent <PlayerController>(); Global = FindObjectOfType <GlobalVars>(); }
// Use this for initialization void Start() { globalVars = GlobalVars.Instance; }
private void Start() { _globalVars = GlobalVars.instance; }
public void GlobalVarDef(GlobalVarDef e) { e.Value.Visit(this); e.ExpType = e.Value.ExpType; GlobalVars.Add(e.Name, e.Value.ExpType); }
private void InitConfigVars() { bool useClassPath = false; if (string.ReferenceEquals(this.configFile_, null)) { useClassPath = true; this.configFile_ = "data.config.lexAccess"; } this.conf_ = new Configuration(this.configFile_, useClassPath); if (this.properties_ != null) { this.conf_.OverwriteProperties(this.properties_); } if (string.ReferenceEquals(this.noOutputMsg_, null)) { this.noOutputMsg_ = this.conf_.GetConfiguration("NO_OUTPUT_MSG"); } if (Platform.IsWindow() == true) { this.promptStr_ = "- Please input a term/eui (type \"Ctl-z\" then \"Enter\" to quit) >"; } else { this.promptStr_ = "- Please input a term (type \"Ctl-d\" to quit) >"; } string textIndent = this.conf_.GetConfiguration("TEXT_INDENT"); if (!string.ReferenceEquals(textIndent, null)) { GlobalVars.SetTextIndent(GetStringContent(textIndent)); } string xmlIndent = this.conf_.GetConfiguration("XML_INDENT"); if (!string.ReferenceEquals(xmlIndent, null)) { GlobalVars.SetXmlIndent(GetStringContent(xmlIndent)); } string xmlHeader = this.conf_.GetConfiguration("XML_HEADER"); if (!string.ReferenceEquals(xmlHeader, null)) { GlobalVars.SetXmlHeader(GetStringContent(xmlHeader)); } }
public override void OnCreate() { base.OnCreate(); AddChildComponentMouseClick("CloseBtn", Close); m_minNumber = GetChildComponent <NumberDrawer>("MinNumber"); m_secNumber = GetChildComponent <NumberDrawer>("SecNumber"); m_heartSprite = GetChildComponent <UISprite>("HeartToCull"); //AddChildComponentMouseClick("Buy1HeartBtn", delegate() //{ // if (Unibiller.DebitBalance("gold", 25)) // { // UIWindowManager.Singleton.GetUIWindow<UIMessageBox>().SetString(Localization.instance.Get("PurchaseSucceed")); // UIWindowManager.Singleton.GetUIWindow<UIMessageBox>().SetFunc(delegate() // { // GlobalVars.AddHeart(1); // ContinuePlay(); // }); // UIWindowManager.Singleton.GetUIWindow<UIMessageBox>().ShowWindow(); // } // else // { // HideWindow(); // UIWindowManager.Singleton.GetUIWindow<UIStore>().ShowWindow(); // GlobalVars.OnPurchaseFunc = delegate() // { // UIWindowManager.Singleton.GetUIWindow<UIMessageBox>().SetString(Localization.instance.Get("PurchaseSucceed")); // UIWindowManager.Singleton.GetUIWindow<UIMessageBox>().SetFunc(delegate() // { // Unibiller.DebitBalance("gold", 25); // GlobalVars.AddHeart(1); // ContinuePlay(); // }); // UIWindowManager.Singleton.GetUIWindow<UIMessageBox>().ShowWindow(); // }; // GlobalVars.OnCancelFunc = delegate() // { // Close(); // }; // } //}); AddChildComponentMouseClick("Buy5HeartBtn", delegate() { if (Unibiller.DebitBalance("gold", 60)) { UIWindowManager.Singleton.GetUIWindow <UIMessageBox>().SetString(Localization.instance.Get("PurchaseSucceed")); UIWindowManager.Singleton.GetUIWindow <UIMessageBox>().SetFunc(delegate() { CapsApplication.Singleton.SubmitUseItemData("BuyHearts"); GlobalVars.AddHeart(5); ContinuePlay(); }); UIWindowManager.Singleton.GetUIWindow <UIMessageBox>().ShowWindow(); } else { HideWindow(); GlobalVars.UsingItem = PurchasedItem.Item_Hearts; UIWindowManager.Singleton.GetUIWindow <UIPurchaseNotEnoughMoney>().ShowWindow(); GlobalVars.OnPurchaseFunc = delegate() { GlobalVars.UsingItem = PurchasedItem.None; Unibiller.DebitBalance("gold", 60); CapsApplication.Singleton.SubmitUseItemData("BuyHearts"); GlobalVars.AddHeart(5); ContinuePlay(); }; GlobalVars.OnCancelFunc = delegate() { GlobalVars.UsingItem = PurchasedItem.None; Close(); }; } }); }
public void OnMaxLengthChanged(string value) { MaxLength = Convert.ToSingle(value, GlobalVars.myNumberFormat()); }
public static async Task <string> GetShippingLabelURL(string absenceId, Address_EP myToAddress) { string shippingLabelUrl = ""; try { ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; Address_EP toAddress; Address_EP fromAddress; Parcel_EP parcel; Shipment_EP shipment; absenceId = Helpers.ParseStringToRemoveBrackets(absenceId); Absence _absenceService = new Absence(); string username = GlobalVars.GetEasyPostApiKey(); string password = ""; string svcCredentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(username + ":" + password)); if (client.BaseAddress != null) { client.Dispose(); client = new HttpClient(); } client.BaseAddress = new Uri("https://api.easypost.com/v2/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", svcCredentials); //CREATE TO ADDRESS try { Uri url = await CreateAddressAsync(myToAddress); string addressId = url.OriginalString.Remove(0, url.OriginalString.IndexOf("addresses")); toAddress = await GetAddressByIdAsync(addressId); } catch (Exception ex) { client.Dispose(); Exception e = new Exception(ex.Message + " / Failed to create To Address"); throw e; } //CREATE FROM ADDRESS try { Address_EP address = new Address_EP { Company = "DEALSHIELD RETURNS DEPARTMENT", Street1 = "2002 SUMMIT BLVD", Street2 = "STE 1000", City = "BROOKHAVEN", State = "GA", Zip = "30319", Country = "US", Phone = "855-246-5556" }; var url = await CreateAddressAsync(address); string addressId = url.OriginalString.Remove(0, url.OriginalString.IndexOf("addresses")); fromAddress = await GetAddressByIdAsync(addressId); } catch (Exception ex) { client.Dispose(); Exception e = new Exception(ex.Message + " / Failed to create From Address"); throw e; } //CREATE PARCEL try { Parcel_EP newParcel = new Parcel_EP() { Weight = "3", Predefined_Package = "FedExEnvelope" }; //FOR TESTING //Parcel_EP newParcel = new Parcel_EP() //{ // Weight = "3", // Width = "8", // Length = "11", // Height = ".25" //}; var url = await CreateParcelAsync(newParcel); string parcelId = url.OriginalString.Remove(0, url.OriginalString.IndexOf("parcels")); parcel = await GetParcelByIdAsync(parcelId); } catch (Exception ex) { client.Dispose(); Exception e = new Exception(ex.Message + " / Failed to create Parcel"); throw e; } //CREATE SHIPMENT try { Dictionary <string, object> options = new Dictionary <string, object>(); options.Add("label_format", "PDF"); Shipment_EP newShipment = new Shipment_EP() { Parcel = parcel, To_Address = toAddress, From_Address = fromAddress, Reference = "ShipmentRef", Options = options }; var url = await CreateShipmentAsync(newShipment); string shipmentId = url.OriginalString.Remove(0, url.OriginalString.IndexOf("shipments")); shipment = await GetShipmentByIdAsync(shipmentId); if (shipment != null && shipment.Rates.Count > 0) { //search shipment for cheapest rate ShipmentRate_EP cheapestRate = shipment.GetLowestRate("FedEx", "STANDARD_OVERNIGHT"); if (cheapestRate != null) { try { //buy rate Shipment_EP puchasedShipment = await BuyShipmentRate(shipment.Id, cheapestRate); shippingLabelUrl = puchasedShipment.Postage_Label.Label_Url; client.Dispose(); _absenceService.UpdateDisbursementShippingLabel(shippingLabelUrl, absenceId); } catch (Exception ex) { client.Dispose(); Exception e = new Exception(ex.Message + " / Failed to buy Postage Label"); throw e; } } } } catch (Exception ex) { client.Dispose(); Exception e = new Exception(ex.Message + " / Failed to create Shipment"); throw e; } } catch (Exception ex) { client.Dispose(); Exception e = new Exception(ex.Message + " / Something went wrong."); throw e; } finally { client.Dispose(); } client.Dispose(); return(shippingLabelUrl); }
/// <summary> /// Tapped the splash screen to enter. /// </summary> public static void TappedSplashScreenToEnter(GlobalVars.Scenes toScene) { Mixpanel.SendEvent("Tapped The Splash Screen To Enter Game", new Dictionary<string, object>()); }
void Start() { Global = FindObjectOfType <GlobalVars>(); StartingScale = transform.localScale; CurrentChanges = (float)Global.GetType().GetField(ValueNameCurrent).GetValue(Global); }
// Called when the player exits gathering void HandleOnExitGathering(GlobalVars.Scenes toScene) { // If the playering is going to crafting if (toScene == GlobalVars.Scenes.Crafting) { TappedTheReturnHomeFromGatheringButton(); } // If the player is playing gathering again else if (toScene == GlobalVars.Scenes.Gathering) { TappedTheReplayGatheringButton(); } }
bool GenerateStatement(Statement s, StringBuilder csharp) { switch (s.Type) { case StatementType.Quit: QuitWhenDone = true; break; case StatementType.Macro: if (csharp.Length > 0) { return(ErrorMsg("#macro must be first statement")); } if (!string.IsNullOrEmpty(Name)) { return(ErrorMsg("Only one #macro statement allowed")); } if (s.Args.Count < 1) { return(ErrorMsg("Missing macro name")); } Name = s.Args[0]; break; case StatementType.Thread: if (s.Args.Count < 1) { return(ErrorMsg("Missing thread id")); } if (s.Args[0].Equals("ui", IGNORE_CASE)) { csharp.Append( /** BEGIN generate code **/ @" await SwitchToUIThread();" /** END generate code **/); } else if (s.Args[0].Equals("default", IGNORE_CASE)) { csharp.Append( /** BEGIN generate code **/ @" await SwitchToWorkerThread();" /** END generate code **/); } else { return(ErrorMsg("Unknown thread id")); } break; case StatementType.Reference: if (!s.Args.Any()) { return(ErrorMsg("Missing args for #reference")); } SelectedAssemblies.Add(s.Args.First()); foreach (var ns in s.Args.Skip(1)) { Namespaces.Add(ns); } break; case StatementType.Using: if (!s.Args.Any()) { return(ErrorMsg("Missing args for #using")); } foreach (var ns in s.Args) { Namespaces.Add(ns); } break; case StatementType.Var: if (s.Args.Count < 2) { return(ErrorMsg("Missing args for #var")); } var typeName = s.Args[0]; var varName = s.Args[1]; var initValue = s.Code; if (varName.Where(c => char.IsWhiteSpace(c)).Any()) { return(ErrorMsg("Wrong var name")); } GlobalVars[varName] = new GlobalVar { Type = typeName, Name = varName, InitialValueExpr = initValue }; break; case StatementType.Service: if (s.Args.Count <= 1) { return(ErrorMsg("Missing args for #service")); } var serviceVarName = s.Args[0]; if (serviceVarName.Where(c => char.IsWhiteSpace(c)).Any()) { return(ErrorMsg("Invalid service var name")); } if (ServiceRefs.ContainsKey(serviceVarName)) { return(ErrorMsg("Duplicate service var name")); } ServiceRefs.Add(serviceVarName, new VSServiceRef { Name = serviceVarName, Interface = s.Args[1], Type = s.Args.Count > 2 ? s.Args[2] : s.Args[1] }); break; case StatementType.Call: if (s.Args.Count < 1) { return(ErrorMsg("Missing args for #call")); } var calleeName = s.Args[0]; var callee = GetMacro(calleeName); if (callee == null) { return(ErrorMsg("Undefined macro")); } csharp.AppendFormat( /** BEGIN generate code **/ @" await CallMacro(""{0}"");" /** END generate code **/, calleeName); foreach (var globalVar in callee.GlobalVars.Values) { if (GlobalVars.ContainsKey(globalVar.Name)) { continue; } GlobalVars[globalVar.Name] = new GlobalVar { Type = globalVar.Type, Name = globalVar.Name, IsCallOutput = true }; } break; case StatementType.Wait: if (string.IsNullOrEmpty(s.Code)) { return(ErrorMsg("Missing args for #wait")); } var expr = s.Code; uint timeout = uint.MaxValue; if (s.Args.Count > 0 && !uint.TryParse(s.Args[0], out timeout)) { return(ErrorMsg("Timeout format error in #wait")); } if (s.Args.Count > 2) { var evalVarType = s.Args[1]; var evalVarName = s.Args[2]; csharp.AppendFormat( /** BEGIN generate code **/ @" {0} {1} = default({0}); await WaitExpr({2}, () => {1} = {3});" /** END generate code **/, evalVarType, evalVarName, timeout, expr); } else { csharp.AppendFormat( /** BEGIN generate code **/ @" await WaitExpr({0}, () => {1});" /** END generate code **/, timeout, expr); } break; case StatementType.Ui: if (!GenerateUiStatement(s, csharp)) { return(false); } break; } return(true); }
public void OnNavigatingFrom(NavigatingCancelEventArgs e) { GlobalVars.OnNavigatingFrom(e); }
void OnMouseDown() { GlobalVars.gold = GlobalVars.gold + goldamt; GlobalVars.SaveGold(); Destroy(gameObject); }
public async Task CheckReserves(string coord1 = "*", string coord2 = "*") { if (coord1 != "*") { try { int.TryParse(coord1, out int x); } catch { var m = await Context.Channel.SendMessageAsync($"Invalid parameter"); GlobalVars.AddRandomTracker(m); return; } } if (coord2 != "*") { try { int x; int.TryParse(coord2, out x); } catch { var m = await Context.Channel.SendMessageAsync($"Invalid parameter"); GlobalVars.AddRandomTracker(m); return; } } SqlConnectionStringBuilder sBuilder = new SqlConnectionStringBuilder(); sBuilder.InitialCatalog = GlobalVars.dbSettings.db; sBuilder.UserID = GlobalVars.dbSettings.username; sBuilder.Password = GlobalVars.dbSettings.password; sBuilder.DataSource = GlobalVars.dbSettings.host + @"\" + GlobalVars.dbSettings.instance + "," + GlobalVars.dbSettings.port; SqlConnection conn = new SqlConnection { ConnectionString = sBuilder.ConnectionString }; EmbedBuilder eb = new EmbedBuilder(); eb.Title = $"List of reservations by coords [{coord1} {coord2}]"; using (conn) { conn.Open(); #region Get Reservation SqlCommand cmd = new SqlCommand($"SELECT UserID, Coord1, Coord2, DateStamp FROM Reservations WHERE GuildID = {Context.Guild.Id} AND Coord1 LIKE '{coord1.Replace("*", "%")}' AND Coord2 LIKE '{coord2.Replace("*", "%")}';", conn); SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { ulong userID = Convert.ToUInt64(dr.GetValue(0)); if (userID != 0) { SocketGuildUser usr = Context.Guild.Users.SingleOrDefault(u => u.Id == userID); eb.AddField($"Reserved by {usr} on {dr.GetValue(3)}", $"Location: /goto {dr.GetValue(1)} {dr.GetValue(2)}"); } } #endregion conn.Close(); conn.Dispose(); } eb.WithFooter($"Found {eb.Fields.Count} locations."); if (eb.Fields.Count > 0 && eb.Fields.Count <= 25) { await Context.Channel.SendMessageAsync(null, false, eb.Build()); } else if (eb.Fields.Count > 25) { var t = eb.Fields.Count - 24; List <EmbedFieldBuilder> tmp = new List <EmbedFieldBuilder>(); for (int i = 0; i < 24; i++) { tmp.Add(eb.Fields[i]); } eb.Fields = tmp; eb.AddField($"*and {t} more locations.*", null); await Context.Channel.SendMessageAsync(null, false, eb.Build()); } else { await Context.Channel.SendMessageAsync($"{Context.User.Mention}, there were no matching locations reserved in this alliance."); } }
// Use this for initialization void Start() { vars = GameObject.FindObjectOfType <GlobalVars> (); //checkAllChildren (); //transform.rotation = Quaternion.Euler (Vector3.zero); }
public MainForm() { InitializeComponent(); globalVars = new GlobalVars(); PC = new Computer(); // PC.CPUEnabled = true; PC.GPUEnabled = true; PC.Open(); _log = new LogFile("log"); _error = new LogFile("error"); _http = new Http(); apiResponse = new ApiResponse(); KillDublicateProcess("Informer"); KillDublicateProcess("Launcher_informer"); apiResponse.Params = new Params { Timers = new Timers(), Reboots = new Reboots(), Data_ranges = new Data_ranges(), Version = "1.3.9" }; СheckForNewVersion(); response = apiResponse.Load(); //костыли apiResponse = response; // bool start = false; if (!string.IsNullOrEmpty(response.Params.Token)) { start = true; tbRigName.ReadOnly = true; tbToken.ReadOnly = true; tbRigName.Text = response.Params.Name; tbToken.Text = response.Params.Token; } else { start = false; tbRigName.ReadOnly = true; } if (start) { NextAutoStart.Interval = globalVars.autostart * 1000; NextAutoStart.Enabled = true; AutoStartTimer.Enabled = true; TimeWorkTimer.Enabled = true; } commandProcesser = new CommandProcesser(response); mqttConnect = new MqttConnect(); _monitoringSystem = new OHMMonitoringSystem(); var tempMin = _monitoringSystem.BuildTrigger(new MultiplyHardwareRangeSensor("GPU Core", SensorType.Temperature, MultiplyHardwareRangeSensor.Predicate.Min), new RebootTriggerAction("Temp Min, Reboot!", "reboot_t_min.bat", "token", "rigName", globalVars.host), 300); var tempMax = _monitoringSystem.BuildTrigger(new MultiplyHardwareRangeSensor("GPU Core", SensorType.Temperature, MultiplyHardwareRangeSensor.Predicate.Max), new RebootTriggerAction("Temp Max, Reboot!", "reboot_t_max.bat", "token", "rigName", globalVars.host), 300); var memoryMin = _monitoringSystem.BuildTrigger(new MultiplyHardwareRangeSensor("GPU Memory", SensorType.Clock, MultiplyHardwareRangeSensor.Predicate.Min), new RebootTriggerAction("Memory Min, Reboot!", "reboot_mem_min.bat", "token", "rigName", globalVars.host), 300); var memoryMax = _monitoringSystem.BuildTrigger(new MultiplyHardwareRangeSensor("GPU Memory", SensorType.Clock, MultiplyHardwareRangeSensor.Predicate.Max), new RebootTriggerAction("Memory Max, Reboot!", "reboot_mem_max.bat", "token", "rigName", globalVars.host), 300); var loadMin = _monitoringSystem.BuildTrigger(new MultiplyHardwareRangeSensor("GPU Core", SensorType.Load, MultiplyHardwareRangeSensor.Predicate.Min), new RebootTriggerAction("Load Min, Reboot!", "reboot_load_min.bat", "token", "rigName", globalVars.host), 300); var loadMax = _monitoringSystem.BuildTrigger(new MultiplyHardwareRangeSensor("GPU Core", SensorType.Load, MultiplyHardwareRangeSensor.Predicate.Max), new RebootTriggerAction("Load Max, Reboot!", "reboot_load_max.bat", "token", "rigName", globalVars.host), 300); var fanMin = _monitoringSystem.BuildTrigger(new MultiplyHardwareRangeSensor("GPU Fan", SensorType.Control, MultiplyHardwareRangeSensor.Predicate.Min), new RebootTriggerAction("Fan Min, Reboot!", "reboot_fan_min.bat", "token", "rigName", globalVars.host), 300); var fanMax = _monitoringSystem.BuildTrigger(new MultiplyHardwareRangeSensor("GPU Fan", SensorType.Control, MultiplyHardwareRangeSensor.Predicate.Max), new RebootTriggerAction("Fan Max, Reboot!", "reboot_fan_max.bat", "token", "rigName", globalVars.host), 300); var clockMin = _monitoringSystem.BuildTrigger(new MultiplyHardwareRangeSensor("GPU Core", SensorType.Clock, MultiplyHardwareRangeSensor.Predicate.Min), new RebootTriggerAction("Clock Min, Reboot!", "reboot_clock_min.bat", "token", "rigName", globalVars.host), 300); var clockMax = _monitoringSystem.BuildTrigger(new MultiplyHardwareRangeSensor("GPU Core", SensorType.Clock, MultiplyHardwareRangeSensor.Predicate.Max), new RebootTriggerAction("Clock Max, Reboot!", "reboot_clock_max.bat", "token", "rigName", globalVars.host), 300); var tempMinOnForm = new TriggerOnForm(labelTempMin, tempMin, labelStatusTempMin, labelCounterTempMin); var tempMaxOnForm = new TriggerOnForm(labelTempMax, tempMax, labelStatusTempMax, labelCounterTempMax); var memoryMinOnForm = new TriggerOnForm(labelMemoryMin, memoryMin, labelStatusMemoryMin, labelCounterMemoryMin); var memoryMaxOnForm = new TriggerOnForm(labelMemoryMax, memoryMax, labelStatusMemoryMax, labelCounterMemoryMax); var loadMinOnForm = new TriggerOnForm(labelLoadMin, loadMin, labelStatusLoadMin, labelCounterLoadMin); var loadMaxOnForm = new TriggerOnForm(labelLoadMax, loadMax, labelStatusLoadMax, labelCounterLoadMax); var fanMinOnForm = new TriggerOnForm(labelFanMin, fanMin, labelStatusFanMin, labelCounterFanMin); var fanMaxOnForm = new TriggerOnForm(labelFanMax, fanMax, labelStatusFanMax, labelCounterFanMax); var clockMinOnForm = new TriggerOnForm(labelClockMin, clockMin, labelStatusClockMin, labelCounterClockMin); var clockMaxOnForm = new TriggerOnForm(labelClockMax, clockMax, labelStatusClockMax, labelCounterClockMax); _triggersOnForm.Add(tempMinOnForm); _triggersOnForm.Add(tempMaxOnForm); _triggersOnForm.Add(memoryMinOnForm); _triggersOnForm.Add(memoryMaxOnForm); //вместо lost inet и lost gpu _triggersOnForm.Add(memoryMinOnForm); _triggersOnForm.Add(memoryMaxOnForm); // _triggersOnForm.Add(loadMinOnForm); _triggersOnForm.Add(loadMaxOnForm); _triggersOnForm.Add(fanMinOnForm); _triggersOnForm.Add(fanMaxOnForm); _triggersOnForm.Add(clockMinOnForm); _triggersOnForm.Add(clockMaxOnForm); //LabelOnForm tempMinLabel, tempMaxLabel, fanMinLabel, fanMaxLabel, loadMinLabel, loadMaxLabel, // clockMinLabel, clockMaxLabel, memoryMinLabel, memoryMaxLabel; //Sensor tempMin, tempMax, fanMin, fanMax, loadMin, loadMax, clockMin, clockMax, memoryMin, memoryMax, internetOff; //tempMinLabel = new LabelOnForm(labelStatusTempMin, labelCounterTempMin, response, "Temp Min, Reboot!", "reboot_t_min.bat", reboot); //tempMaxLabel = new LabelOnForm(labelStatusTempMax, labelCounterTempMax, response, "Temp Max, Reboot!", "reboot_t_max.bat", reboot); //fanMinLabel = new LabelOnForm(labelStatusFanMin, labelCounterFanMin, response, "Fan Min, Reboot!", "reboot_fan_min.bat", reboot); //fanMaxLabel = new LabelOnForm(labelStatusFanMax, labelCounterFanMax, response, "Fan Max, Reboot!", "reboot_fan_max.bat", reboot); //loadMinLabel = new LabelOnForm(labelStatusLoadMin, labelCounterLoadMin, response, "Load Min, Reboot!", "reboot_load_min.bat", reboot); //loadMaxLabel = new LabelOnForm(labelStatusLoadMax, labelCounterLoadMax, response, "Load Max, Reboot!", "reboot_load_max.bat", reboot); //clockMinLabel = new LabelOnForm(labelStatusClockMin, labelCounterClockMin, response, "Clock Min, Reboot!", "reboot_clock_min.bat", reboot); //clockMaxLabel = new LabelOnForm(labelStatusClockMax, labelCounterClockMax, response, "Clock Max, Reboot!", "reboot_clock_max.bat", reboot); //memoryMinLabel = new LabelOnForm(labelStatusMemoryMin, labelCounterMemoryMin, response, "Memory Min, Reboot!", "reboot_mem_min.bat", reboot); //memoryMaxLabel = new LabelOnForm(labelStatusMemoryMax, labelCounterMemoryMax, response, "Memory Max, Reboot!", "reboot_memory_max.bat", reboot); //NotInternetLabel = new LabelOnForm(labelStatusInternet, labelCounterInternet, response, "Dont Have Internet", "reboot_internet.bat", reboot); //tempMin = new Sensor(tempMinLabel, Sensor.Predicate.Min, "GPU Core", SensorType.Temperature); //tempMax = new Sensor(tempMaxLabel, Sensor.Predicate.Max, "GPU Core", SensorType.Temperature); //fanMin = new Sensor(fanMinLabel, Sensor.Predicate.Min, "GPU Fan", SensorType.Control); //fanMax = new Sensor(fanMaxLabel, Sensor.Predicate.Max, "GPU Fan",SensorType.Control); //loadMin = new Sensor(loadMinLabel, Sensor.Predicate.Min, "GPU Core", SensorType.Load); //loadMax = new Sensor(loadMaxLabel, Sensor.Predicate.Max, "GPU Core", SensorType.Load); //clockMin = new Sensor(clockMinLabel,Sensor.Predicate.Min, "GPU Core",SensorType.Clock); //clockMax = new Sensor(clockMaxLabel,Sensor.Predicate.Max, "GPU Core",SensorType.Clock); //memoryMin = new Sensor(memoryMinLabel,Sensor.Predicate.Min,"GPU Memory",SensorType.Clock); //memoryMax = new Sensor(memoryMaxLabel,Sensor.Predicate.Max,"GPU Memory",SensorType.Clock); //dangers = new Sensor[] { // tempMin, tempMax, fanMin, fanMax, loadMin,loadMax, // clockMin,clockMax, memoryMin, memoryMax //}; }
// Unity // ===================================================================== private void Start() { _globalVars = GlobalVars.instance; StartCoroutine("Process"); }
public void OnFragmentNavigation(FragmentNavigationEventArgs e) { GlobalVars.OnFragmentNavigation(e); }
private int eventIndex; // Index into event results // Use this for initialization void Start() { globalVars = GlobalVars.Instance; serializer = DelayGramSerializer.Instance; eventContainer = null; }
private Bitmap GetRankImage(GlobalVars.Rank rank) { switch (rank) { case GlobalVars.Rank.S: return Resources.S_small; case GlobalVars.Rank.A: return Resources.A_small; case GlobalVars.Rank.X: return Resources.X_small; case GlobalVars.Rank.SH: return Resources.SH_small; case GlobalVars.Rank.XH: return Resources.XH_small; case GlobalVars.Rank.B: return Resources.B_small; case GlobalVars.Rank.C: return Resources.C_small; case GlobalVars.Rank.D: return Resources.D_small; default: return null; } }
private GlobalVars gv; //поле для объекта глобальных переменных #endregion Fields #region Methods private void Awake() { SpawnPoints = GameObject.FindGameObjectsWithTag("Spawnpoint"); //забираем все точки спауна в массив gv = GameObject.Find("GlobalVars").GetComponent<GlobalVars>(); //инициализируем поле }