static void Main(string[] args) { Jarvis j = new Jarvis(); Thread.Sleep(1000); Console.Write("Port Number for client: "); int port = Convert.ToInt32(Console.ReadLine()); Client client = new Client(port, new IPAddress(new byte[] { 127, 0, 0, 1 })); client.RxMessageEvent += OnRxMessageEvent; client.Start(); Thread.Sleep(1000); Console.WriteLine("Client initialized, type away!"); string msg = ""; do { Thread.Sleep(100); Console.Write(">>> "); msg = Console.ReadLine(); client.SendMessage(msg); } while (msg != "Connection.Close"); j.ServerStop(); }
public async void Kick(Message message, Jarvis jarvis) { if (!await IsAuthorizedInChat(message.From, message.Chat, jarvis)) { await jarvis.ReplyAsync(message, "I'm sorry, I don't think you are authorized to ask for that."); return; } var targetUserId = ExtractUserIfOnlyOne(message) ?? message.ReplyToMessage?.From.Id ?? ExtractIdIfOnlyOne(message.Text); if (!targetUserId.HasValue) { await jarvis.ReplyAsync(message, "I'm sorry, I can't quite tell who you are talking about...\n" + "You can reply to one of their messages, teach me their username by forwarding one to me or just use their ID."); return; } var target = targetUserId.Value; try { await jarvis.UnbanChatMemberAsync(message.Chat.Id, target); // Why use unban to kick a user? Because KickChatMember bans them. // (By the way, to unban a user use RestrictChatMember with everything set to true. // Obviously.) } catch (ApiRequestException) { await jarvis.ReplyAsync(message, "Sorry, I cannot kick this user. Perhaps I lack the necessary rights to do so?"); return; } await jarvis.ReplyAsync(message, "As you wish."); }
public static void Main() // 100/100 { Jarvis jarvis = new Jarvis(); long energy = long.Parse(Console.ReadLine()); string[] command = Console.ReadLine().Split(); while (command[0] != "Assemble!") { jarvis.Apply(PartFactory.Get(command)); command = Console.ReadLine().Split(); } switch (jarvis.Assemble(energy)) { case 1: Console.WriteLine("We need more parts!"); break; case 2: Console.WriteLine("We need more power!"); break; default: Console.WriteLine(jarvis); break; } }
private void saveButton_Click(object sender, EventArgs e) { try { // check for a project name if (string.IsNullOrEmpty(this.projectNameTextbox.Text)) { MessageBox.Show("Project Name Required."); return; } List <IPolygon> polygons; if (this.selectionTypecomboBox.SelectedIndex == 1) { polygons = Jarvis.GetPolygons(ArcMap.Document.FocusMap); // check to make sure an aoi(s) have been selected. if (polygons.Count == 0) { MessageBox.Show("Please select polygon(s)"); return; } } else { if (this.drawnPolygon == null) { MessageBox.Show( "Please draw a bounding box by clicking Draw button and clicking and dragging on the map"); return; } polygons = new List <IPolygon> { this.drawnPolygon }; } var projectJson = this.CreateProjectJson(polygons); var request = new RestRequest("/answer-factory-project-service/api/project", Method.POST); request.AddHeader("Authorization", "Bearer " + this.token); request.AddHeader("Content-Type", "application/json"); request.AddParameter("application/json", projectJson, ParameterType.RequestBody); this.CheckBaseUrl(); this.client.ExecuteAsync(request, resp => { Jarvis.Logger.Info(resp.ResponseUri.ToString()); }); this.projectNameTextbox.Clear(); this.availableRecipesCombobox.SelectedIndex = -1; this.ProjIdRepo.Clear(); this.RecipeRepo.Clear(); this.GetProjects(this.token); } catch (Exception error) { Jarvis.Logger.Error(error); } }
// Удаление данных о поездке private void DellLine_Click(object sender, RoutedEventArgs e) { // Получаем поездку Trip order = (Trip)((Button)sender).DataContext; // удаляем её Jarvis.Dellete(order); Refresh(); }
public void RemovePoint(Transform transf) { points.RemoveAt(pointsTr.findIndex(transf)); points.sortX(); convexHull = Jarvis.GetConvexHull(points); triangulation = new Delaunay(points); voronoi = new Voronoi(triangulation); RecreatePoints(); }
static void Main(string[] args) { var jarvisPower = long.Parse(Console.ReadLine()); string inputs = null; Jarvis jarvis = new Jarvis(); jarvis.Energy = jarvisPower; while ((inputs = Console.ReadLine()) != "Assemble!") { var input = inputs.Split().ToArray(); var typeOfComponent = input[0]; var energyConsumption = int.Parse(input[1]); var property1 = input[2]; var property2 = input[3]; switch (typeOfComponent) { case "Head": Head head = new Head(); head.EnergyConsumption = energyConsumption; head.IQ = int.Parse(property1); head.SkinMaterial = property2; jarvis.AddHead(head); break; case "Torso": Torso torso = new Torso(); torso.EnergyConsumption = energyConsumption; torso.ProcessorCentimeterSize = double.Parse(property1); torso.HousingMaterial = property2; jarvis.AddTorso(torso); break; case "Arm": Arm arm = new Arm(); arm.EnergyConsumption = energyConsumption; arm.ReachDistance = int.Parse(property1); arm.CountFingers = int.Parse(property2); jarvis.AddArms(arm); break; case "Leg": Leg leg = new Leg(); leg.EnergyConsumption = energyConsumption; leg.Strength = int.Parse(property1); leg.Speed = int.Parse(property2); jarvis.AddLegs(leg); break; default: break; } } Console.WriteLine(jarvis.ToString()); }
}//createMeshes public void addPoint(Vector2 pos) { points.Add(pos); points.sortX(); convexHull = Jarvis.GetConvexHull(points); triangulation = new Delaunay(points); voronoi = new Voronoi(triangulation); RecreatePoints(); }
public override void Start(Jarvis jarvis) { base.Start(jarvis); jarvis.OnMessage += (sender, e) => { AddOrUpdateUser(e.Message.From); AddOrUpdateUser(e.Message.ReplyToMessage?.From); AddOrUpdateUser(e.Message.ForwardFrom); AddOrUpdateUser(e.Message.ReplyToMessage?.ForwardFrom); }; }
static Jarvis ReadJarvisParts() { Jarvis jarvis = new Jarvis(); while (true) { string[] input = Console.ReadLine().Split(); if (input[0] == "Assemble!") { break; } } }
// Добавление строк из таблицы к файлу private void AddToFile_Click(object sender, RoutedEventArgs e) { Refresh(); OpenFileDialog myDialog = new OpenFileDialog(); myDialog.Filter = "Данные(*.csv;)|*.csv;"; myDialog.CheckFileExists = true; if (myDialog.ShowDialog() == true) { Jarvis.AddToFile(myDialog.FileName); MessageBox.Show("Строки из даблицы добавлены в файл", "Сообщение"); } }
// Открытие файла private void Open_Click(object sender, RoutedEventArgs e) { SortName.SelectedIndex = 12; OpenFileDialog myDialog = new OpenFileDialog(); myDialog.Filter = "Данные(*.csv;)|*.csv;"; myDialog.CheckFileExists = true; if (myDialog.ShowDialog() == true) { Jarvis.Connect(myDialog.FileName); Refresh(); } }
// Сохранить как private void SaveAs_Click(object sender, RoutedEventArgs e) { Refresh(); SaveFileDialog myDialog = new SaveFileDialog(); myDialog.Filter = "Данные(*.csv;)|*.csv;"; myDialog.CheckFileExists = true; if (myDialog.ShowDialog() == true) { Jarvis.SaveAs(myDialog.FileName); MessageBox.Show("Информация сохранена", "Сообщение"); } }
//Обновление данных в таблице void Refresh() { Jarvis.Synchronization(SortName.SelectedIndex); // Вывод названий компаний MostPopular.Content = Jarvis.MostPopular == String.Empty ? String.Empty : "Самая популярная компания: " + Jarvis.MostPopular; LeastPopular.Content = Jarvis.LeastPopular == String.Empty ? String.Empty : "Самая непопулярная компания: " + Jarvis.LeastPopular; Filtration(); // Отображение столбцов table.Columns[1].Visibility = Visibility.Hidden; table.Columns[0].Visibility = table.IsReadOnly ? Visibility.Hidden : Visibility.Visible; table.Columns[0].DisplayIndex = table.Columns.Count - 1; // Обновление table.Items.Refresh(); }
private void ShapeAoi(IPolygon poly = null) { this.query = string.Empty; var geometries = new List <IGeometry>(); if (poly == null) { geometries = Jarvis.GetSelectedGeometries(ArcMap.Document.FocusMap); } else { // project the geometry to WGS84 only projection compatible on the backend var projectedPoly = Jarvis.ProjectToWGS84(poly); geometries.Add(projectedPoly); } // check to see if features were selected if (geometries.Count == 0) { MessageBox.Show(GbdxResources.noFeaturesSelected); return; } this.Aoi = Jarvis.CreateGeometryCollectionGeoJson(geometries); this.treeView1.CheckBoxes = false; this.treeView1.Nodes.Clear(); var searchingNode = new VectorIndexSourceNode { Text = GbdxResources.SearchingText }; this.treeView1.Nodes.Add(searchingNode); this.currentApplicationState = this.applicationStateGenerator.Next(); if (this.textBoxSearch.Text.Equals(GbdxResources.EnterSearchTerms) || this.textBoxSearch.Text == string.Empty) { this.query = string.Empty; this.GetSources(this.currentApplicationState); } else { this.query = this.textBoxSearch.Text; this.GetGeometries(searchingNode, this.currentApplicationState); } }
public IActionResult PlayMove(int column, int row, int player) { var owner = player == 1 ? Owner.PlayerOne : Owner.PlayerTwo; var moveSuccess = _gameBoard.Place(owner, column, row); if (moveSuccess && _aiEnabled) { var aiMove = Jarvis.PlayMove(_gameBoard); return(Ok(aiMove)); } if (moveSuccess) { Ok(); } return(BadRequest("Move non succses")); }
public async Task <bool> IsAuthorizedInChat(User user, Chat chat, Jarvis jarvis) { if (jarvis.IsGlobalAdmin(user.Id)) { return(true); } int[] adminIdList; if (!adminCache.Contains(chat.Id.ToString()) || (adminIdList = (int[])adminCache.Get(chat.Id.ToString())).Length == 0) { var admins = await jarvis.GetChatAdministratorsAsync(chat.Id); adminIdList = admins.Select(x => x.User.Id).ToArray(); adminCache.Add(chat.Id.ToString(), adminIdList, DateTimeOffset.Now + adminCachePersistenceTimeSpan); } return(adminIdList.Contains(user.Id)); }
private void clear() { points = new List <Vector2>(); for (int i = 0; i < numberOfPoints; i++) { points.Add(new Vector2(Random.Range(-area, area), Random.Range(-area, area))); } points.sortX(); convexHull = Jarvis.GetConvexHull(points); triangulation = null; OnTriangulate(); if (Application.isPlaying) { RecreatePoints(); } }
private static void AddLayerToMap(string tableName, string layerName) { try { lock (Jarvis.FeatureClassLockerObject) { var featureWorkspace = (IFeatureWorkspace)Jarvis.OpenWorkspace(Settings.Default.geoDatabase); var featureClass = featureWorkspace.OpenFeatureClass(tableName); ILayer featureLayer; featureLayer = VectorIndexHelper.CreateFeatureLayer(featureClass, layerName); VectorIndexHelper.AddFeatureLayerToMap(featureLayer); } } catch (Exception error) { Jarvis.Logger.Error(error); } }
private string CreateProjectJson(List <IPolygon> polygons) { // get the geojson of the aois var aoi = Jarvis.ConvertPolygonsToGeoJson(polygons); var newProject = new Project(); newProject.aois.Add(aoi); newProject.originalGeometries.Add(aoi); newProject.namedBuffers.Add(new NamedBuffer { name = "original AOI", buffer = aoi }); newProject.name = this.projectNameTextbox.Text; if (this.availableRecipesCombobox.SelectedIndex != -1) { var recName = this.availableRecipesCombobox.Items[this.availableRecipesCombobox.SelectedIndex].ToString(); var recipe = this.GetRecipe(recName); if (recipe != null) { var recipeConfig = new RecipeConfig { recipeId = recipe.id, recipeName = recipe.name }; newProject.recipeConfigs.Add(recipeConfig); } } var projectJson = JsonConvert.SerializeObject(newProject).Replace("\\", ""); projectJson = projectJson.Replace("\"aois\":[\"{\"", "\"aois\":[{\""); projectJson = projectJson.Replace("\"],\"recipeConfigs\"", "],\"recipeConfigs\""); projectJson = projectJson.Replace("\"originalGeometries\":[\"", "\"originalGeometries\":["); projectJson = projectJson.Replace("\"],\"namedBuffers\"", "],\"namedBuffers\""); projectJson = projectJson.Replace("\"buffer\":\"{", "\"buffer\":{"); projectJson = projectJson.Replace("]]}\"}]}", "]]}}]}"); return(projectJson); }
public void updateTriangulation() { bool recalculate = false; for (int i = 0; i < points.Count; i++) { if (Vector2.Distance(points[i], (Vector2)pointsTr[i].position) > 0.01f) { recalculate = true; } points[i] = pointsTr[i].position; } if (recalculate) { points.sortX(); convexHull = Jarvis.GetConvexHull(points); triangulation = new Delaunay(points); voronoi = new Voronoi(triangulation); createMeshes(); } }
private void ConvertPagesToFeatureClass(string filepath, string layerName) { try { var json = MergeJsonStrings(filepath); json = MergeProperties(json); var jsonOutput = json.ToString(Formatting.None); var workspace = Jarvis.OpenWorkspace(Settings.Default.geoDatabase); IFieldChecker fieldChecker = new FieldCheckerClass(); fieldChecker.ValidateWorkspace = workspace; var proposedTableName = string.Format("AnswerFactory{0}", Guid.NewGuid()); string tableName; fieldChecker.ValidateTableName(proposedTableName, out tableName); WriteToTable(workspace, jsonOutput, tableName); this.Invoke((MethodInvoker)(() => { this.loadingCircle.Active = false; this.loadingCircle.Visible = false; AddLayerToMap(tableName, layerName); })); if (File.Exists(filepath)) { File.Delete(filepath); } } catch (Exception error) { Jarvis.Logger.Error(error); } }
private void BtnStart_Click(object sender, EventArgs e) { Jarvis.ConvexHull(Jarvis.Points); List <Point> JRpoints = new List <Point>(); foreach (Point point in Jarvis.ConvexHull(Jarvis.Points)) { Engine.g.FillEllipse(Brushes.Red, point.X - 3, point.Y - 3, 6, 6); JRpoints.Add(point); } for (int i = 0; i < JRpoints.Count; i++) { if (JRpoints[JRpoints.Count - 1] == JRpoints[i]) { Engine.g.DrawLine(new Pen(Color.Purple, 3), JRpoints[JRpoints.Count - 1], JRpoints[0]); } else { Engine.g.DrawLine(new Pen(Color.Purple, 3), JRpoints[i], JRpoints[i + 1]); } } pictureBox1.Image = Engine.b; }
private static bool AddLayerToMap(string tableName, string layerName) { var success = false; try { lock (locker) { var featureWorkspace = (IFeatureWorkspace)Jarvis.OpenWorkspace(Settings.Default.geoDatabase); var featureClass = featureWorkspace.OpenFeatureClass(tableName); ILayer featureLayer; featureLayer = VectorIndexHelper.CreateFeatureLayer(featureClass, layerName); VectorIndexHelper.AddFeatureLayerToMap(featureLayer); success = true; } } catch (Exception error) { Jarvis.Logger.Error(error); success = false; } return(success); }
static void Main(string[] args) { long maximumEnergyCapacity = long.Parse(Console.ReadLine()); var jarvis = new Jarvis(); jarvis.EnergyConsumption = maximumEnergyCapacity; jarvis.listOfArms = new List <Arm>(); jarvis.listOfLegs = new List <Leg>(); jarvis.listOfTorso = new List <Torso>(); jarvis.listOfHeads = new List <Head>(); var input = Console.ReadLine(); while (input != "Assemble!") { var inputTokens = input.Split(' ').ToArray(); string component = inputTokens[0]; switch (component) { case "Leg": var leg = new Leg(); leg.EnergyConsumption = int.Parse(inputTokens[1]); leg.Strength = int.Parse(inputTokens[2]); leg.Speed = int.Parse(inputTokens[3]); jarvis.listOfLegs.Add(leg); break; case "Arm": var arm = new Arm(); arm.EnergyConsumption = int.Parse(inputTokens[1]); arm.ReachDistance = int.Parse(inputTokens[2]); arm.FingerCount = int.Parse(inputTokens[3]); jarvis.listOfArms.Add(arm); break; case "Head": var head = new Head(); head.EnergyConsumption = int.Parse(inputTokens[1]); head.IQ = int.Parse(inputTokens[2]); head.SkinMaterial = inputTokens[3]; jarvis.listOfHeads.Add(head); break; case "Torso": var torso = new Torso(); torso.EnergyConsumption = int.Parse(inputTokens[1]); torso.ProcessorSize = double.Parse(inputTokens[2]); torso.Material = inputTokens[3]; jarvis.listOfTorso.Add(torso); break; } input = Console.ReadLine(); } // checking if parts are enough bool headIsThere = jarvis.listOfHeads.Count > 0; bool torsoIsThere = jarvis.listOfTorso.Count > 0; bool twoArms = jarvis.listOfArms.Count > 1; bool twoLegs = jarvis.listOfLegs.Count > 1; bool weNeedMoreParts = !(headIsThere && torsoIsThere && twoArms && twoLegs); if (weNeedMoreParts == true) { Console.WriteLine("We need more parts!"); Environment.Exit(0); } // Choosing the best components var theHead = jarvis.listOfHeads.OrderBy(x => x.EnergyConsumption).First(); var theTorso = jarvis.listOfTorso.OrderBy(x => x.EnergyConsumption).First(); var arrayOfLegs = jarvis.listOfLegs.OrderBy(x => x.EnergyConsumption).Take(2).ToArray(); var arrayOfArms = jarvis.listOfArms.OrderBy(x => x.EnergyConsumption).Take(2).ToArray(); // checking if enough Energy long totalComponentEnergy = 0; totalComponentEnergy += theHead.EnergyConsumption; totalComponentEnergy += theTorso.EnergyConsumption; for (int leg = 0; leg < 2; leg++) { totalComponentEnergy += arrayOfLegs[leg].EnergyConsumption; } for (int arm = 0; arm < 2; arm++) { totalComponentEnergy += arrayOfArms[arm].EnergyConsumption; } bool notEnoughEnergy = jarvis.EnergyConsumption < totalComponentEnergy; if (notEnoughEnergy == true) { Console.WriteLine("We need more power!"); Environment.Exit(0); } // if enough parts and enough energy this is output: Console.WriteLine("Jarvis:"); Console.WriteLine("#Head:"); Console.WriteLine($"###Energy consumption: {theHead.EnergyConsumption}"); Console.WriteLine($"###IQ: {theHead.IQ}"); Console.WriteLine($"###Skin material: {theHead.SkinMaterial}"); Console.WriteLine("#Torso: "); Console.WriteLine($"###Energy consumption: {theTorso.EnergyConsumption}"); Console.WriteLine($"###Processor size: {theTorso.ProcessorSize:f1}"); Console.WriteLine($"###Corpus material: {theTorso.Material}"); arrayOfArms.OrderBy(x => x.EnergyConsumption); // maybe do arrayOfArms = arrayOfArms..... Console.WriteLine("#Arm: "); Console.WriteLine($"###Energy consumption: {arrayOfArms[0].EnergyConsumption}"); Console.WriteLine($"###Reach: {arrayOfArms[0].ReachDistance}"); Console.WriteLine($"###Fingers: {arrayOfArms[0].FingerCount}"); Console.WriteLine("#Arm: "); Console.WriteLine($"###Energy consumption: {arrayOfArms[1].EnergyConsumption}"); Console.WriteLine($"###Reach: {arrayOfArms[1].ReachDistance}"); Console.WriteLine($"###Fingers: {arrayOfArms[1].FingerCount}"); arrayOfLegs.OrderBy(x => x.EnergyConsumption); Console.WriteLine("#Leg: "); Console.WriteLine($"###Energy consumption: {arrayOfLegs[0].EnergyConsumption}"); Console.WriteLine($"###Strength: {arrayOfLegs[0].Strength}"); Console.WriteLine($"###Speed: {arrayOfLegs[0].Speed}"); Console.WriteLine("#Leg: "); Console.WriteLine($"###Energy consumption: {arrayOfLegs[1].EnergyConsumption}"); Console.WriteLine($"###Strength: {arrayOfLegs[1].Strength}"); Console.WriteLine($"###Speed: {arrayOfLegs[1].Speed}"); }
// Сохранение в файл, к которому мы обращались в последний раз private void Save_Click(object sender, RoutedEventArgs e) { Refresh(); Jarvis.Save(); MessageBox.Show("Информация сохранена", "Сообщение"); }
// Создание пустой таблицы private void NewFile_Click(object sender, RoutedEventArgs e) { Jarvis.NewFile(); Refresh(); MessageBox.Show("Пустая таблица создана ", "Сообщение"); }
/// <summary> /// Combine all the pages of json results into one big json collection and convert it to a feature class /// </summary> /// <param name="node"></param> /// <param name="resp">IRestResponse</param> /// <param name="applicationState"></param> /// <param name="strCount"></param> /// <param name="pageId">page id for the next page of results</param> /// <param name="layerName">name of the layer that will be made</param> /// <param name="fileStreamWriter">streamwriter to the tempfile</param> /// <param name="attempts">number of attempts to make before erroring out</param> private void ProcessPage(TreeNode node, IRestResponse <PagedData2> resp, int applicationState, string strCount, string pageId, string layerName, StreamWriter fileStreamWriter, int attempts) { Jarvis.Logger.Info(resp.ResponseUri.ToString()); // If we have a problem getting the page try again up to max attempts if ((resp.Data == null || resp.StatusCode != HttpStatusCode.OK) && attempts <= MaxAttempts) { this.GetPages(node, pageId, applicationState, strCount, layerName, fileStreamWriter, attempts + 1); return; } // there are items so write them to the temp file. // one page of results per line if (resp.Data.item_count != "0") { // Write entire page of data to one line in the temp file fileStreamWriter.WriteLine(resp.Data.data.Replace("\r", "").Replace("\n", "")); if (applicationState == this.currentApplicationState) { int count; var result = int.TryParse(resp.Data.item_count, out count); int currentCount = int.Parse(strCount); if (result) { currentCount += count; } int total; if (int.TryParse(resp.Data.total_count, out total)) { double percentage = Math.Floor(((double)currentCount / total) * 100); var message = $"Downloading {percentage}%"; this.Invoke(new UpdateStatusText(this.UpdateTreeNodeStatus), node, message); } // Continue getting the rest of the associated pages. this.GetPages(node, resp.Data.next_paging_id, applicationState, currentCount.ToString(), layerName, fileStreamWriter); } else { // application states changed mid download so stop future paging and delete the temp file. var filepath = GetFileNameCloseStream(fileStreamWriter); if (File.Exists(filepath)) { File.Delete(filepath); } } } else { var filepath = GetFileNameCloseStream(fileStreamWriter); // make sure that the application state matches before proceeding with creating the feature class if (applicationState == this.currentApplicationState) { var message = "Processing"; this.Invoke(new UpdateStatusText(this.UpdateTreeNodeStatus), node, message); var tableName = Jarvis.ConvertPagesToFeatureClass(filepath, layerName); if (!string.IsNullOrEmpty(tableName)) { this.Invoke(new AddLayerToMapDelegate(AddLayerToMap), tableName, layerName); message = "Complete"; this.Invoke(new UpdateStatusText(this.UpdateTreeNodeStatus), node, message); } } // delete the file after everything has finished processing if (File.Exists(filepath)) { File.Delete(filepath); } } }
private void recalculateHull() { convexHull = Jarvis.GetConvexHull(points); }
void Default_SpeechRecognized(object sender, SpeechRecognizedEventArgs e) { int ranNum; string speech = e.Result.Text; switch (speech) { #region Greetings case "Hello": case "Hello Jarvis": timenow = DateTime.Now; if (timenow.Hour >= 5 && timenow.Hour < 12) { Jarvis.SpeakAsync("Goodmorning " + Settings.Default.User); } if (timenow.Hour >= 12 && timenow.Hour < 18) { Jarvis.SpeakAsync("Good afternoon " + Settings.Default.User); } if (timenow.Hour >= 18 && timenow.Hour < 24) { Jarvis.SpeakAsync("Good evening " + Settings.Default.User); } if (timenow.Hour < 5) { Jarvis.SpeakAsync("Hello " + Settings.Default.User + ", it's getting late"); } break; case "Goodbye": case "Goodbye Jarvis": case "Close Jarvis": Jarvis.Speak("Farewell"); Close(); break; case "Jarvis": ranNum = rnd.Next(1, 5); if (ranNum == 1) { QEvent = ""; Jarvis.SpeakAsync("Yes sir"); } else if (ranNum == 2) { QEvent = ""; Jarvis.SpeakAsync("Yes?"); } else if (ranNum == 3) { QEvent = ""; Jarvis.SpeakAsync("How may I help?"); } else if (ranNum == 4) { QEvent = ""; Jarvis.SpeakAsync("How may I be of assistance?"); } break; case "What's my name?": Jarvis.SpeakAsync(Settings.Default.User); break; case "Stop talking": Jarvis.SpeakAsyncCancelAll(); ranNum = rnd.Next(1, 5); if (ranNum == 5) { Jarvis.Speak("fine"); } break; #endregion #region Condition of the Day case "What time is it": timenow = DateTime.Now; string time = timenow.GetDateTimeFormats('t')[0]; Jarvis.SpeakAsync(time); break; case "What day is it": Jarvis.SpeakAsync(DateTime.Today.ToString("dddd")); break; case "Whats the date": case "Whats todays date": Jarvis.SpeakAsync(DateTime.Today.ToString("dd-MM-yyyy")); break; case "Hows the weather": case "Whats the weather like": case "Whats it like outside": RSSReader.GetWeather(); if (QEvent == "connected") { Jarvis.SpeakAsync("The weather in " + Town + " is " + Condition + " at " + Temperature + " degrees. There is a humidity of " + Humidity + " and a windspeed of " + WinSpeed + " miles per hour"); } else if (QEvent == "failed") { Jarvis.SpeakAsync("I seem to be having a bit of trouble connecting to the server. Just look out the window"); } break; case "What will tomorrow be like": case "Whats tomorrows forecast": case "Whats tomorrow like": RSSReader.GetWeather(); if (QEvent == "connected") { Jarvis.SpeakAsync("Tomorrows forecast is " + TFCond + " with a high of " + TFHigh + " and a low of " + TFLow); } else if (QEvent == "failed") { Jarvis.SpeakAsync("I could not access the server, are you sure you have the right W O E I D?"); } break; case "Whats the temperature": case "Whats the temperature outside": RSSReader.GetWeather(); if (QEvent == "connected") { Jarvis.SpeakAsync(Temperature + " degrees"); } else if (QEvent == "failed") { Jarvis.SpeakAsync("I could not connect to the weather service"); } break; #endregion #region Application Commands case "Switch Window": SendKeys.SendWait("%{TAB " + count + "}"); count += 1; break; case "Close window": SendKeys.SendWait("%{F4}"); break; case "Out of the way": if (WindowState == FormWindowState.Normal) { WindowState = FormWindowState.Minimized; Jarvis.SpeakAsync("My apologies"); } break; case "Come back": if (WindowState == FormWindowState.Minimized) { Jarvis.SpeakAsync("Alright"); WindowState = FormWindowState.Normal; } break; case "Are Lights on?": JARVIS_SpeakCompleted.SpeakAsync("Let Me Check"); break; case "Show default commands": string[] defaultcommands = (File.ReadAllLines(@"Default Commands.txt")); Jarvis.SpeakAsync("Very well"); lstCommands.Items.Clear(); lstCommands.SelectionMode = SelectionMode.None; lstCommands.Visible = true; foreach (string command in defaultcommands) { lstCommands.Items.Add(command); } break; case "Show shell commands": Jarvis.SpeakAsync("Here we are"); lstCommands.Items.Clear(); lstCommands.SelectionMode = SelectionMode.None; lstCommands.Visible = true; foreach (string command in ArrayShellCommands) { lstCommands.Items.Add(command); } break; case "Show social commands": Jarvis.SpeakAsync("Alright"); lstCommands.Items.Clear(); lstCommands.SelectionMode = SelectionMode.None; lstCommands.Visible = true; foreach (string command in ArraySocialCommands) { lstCommands.Items.Add(command); } break; case "Show web commands": Jarvis.SpeakAsync("Ok"); lstCommands.Items.Clear(); lstCommands.SelectionMode = SelectionMode.None; lstCommands.Visible = true; foreach (string command in ArrayWebCommands) { lstCommands.Items.Add(command); } break; case "Show Music Library": lstCommands.SelectionMode = SelectionMode.One; lstCommands.Items.Clear(); lstCommands.Visible = true; Jarvis.SpeakAsync("OK"); i = 0; foreach (string file in MyMusicPaths) { lstCommands.Items.Add(MyMusicNames[i]); i += 1; } QEvent = "Play music file"; break; case "Show Video Library": lstCommands.SelectionMode = SelectionMode.One; lstCommands.Items.Clear(); lstCommands.Visible = true; i = 0; foreach (string file in MyVideoPaths) { if (file.Contains(".mp4") || file.Contains(".avi") || file.Contains(".mkv")) { lstCommands.Items.Add(MyVideoNames[i]); i += 1; } else { i += 1; } } QEvent = "Play video file"; break; case "Show Email List": lstCommands.SelectionMode = SelectionMode.One; lstCommands.Items.Clear(); lstCommands.Visible = true; foreach (string line in MsgList) { lstCommands.Items.Add(line); } QEvent = "Checkfornewemails"; break; case "Show listbox": lstCommands.Visible = true; break; case "Hide listbox": lstCommands.Visible = false; break; #endregion #region Shutdown / Restart / Logoff case "Shutdown": if (ShutdownTimer.Enabled == false) { QEvent = "shutdown"; Jarvis.SpeakAsync("Are you sure you want to " + QEvent + "?"); } break; case "Log off": if (ShutdownTimer.Enabled == false) { QEvent = "logoff"; Jarvis.SpeakAsync("Are you sure you want to " + QEvent + "?"); } break; case "Restart": if (ShutdownTimer.Enabled == false) { QEvent = "restart"; Jarvis.SpeakAsync("Are you sure you want to " + QEvent + "?"); } break; case "Abort": if (ShutdownTimer.Enabled == true) { timer = 11; lblTimer.Text = timer.ToString(); ShutdownTimer.Enabled = false; lblTimer.Visible = false; } break; #endregion #region Media Control Commands case "Play": axWindowsMediaPlayer1.Ctlcontrols.play(); axWindowsMediaPlayer1.Visible = true; break; case "Play a random song": int Ran = rnd.Next(0, MyMusicPaths.Count()); SelectedMusicFile = Ran; Jarvis.SpeakAsync("I hope you're in the mood for " + MyMusicNames[SelectedMusicFile]); axWindowsMediaPlayer1.URL = MyMusicPaths[SelectedMusicFile]; break; case "You decide": if (QEvent == "Play music") { Ran = rnd.Next(0, MyMusicPaths.Count()); SelectedMusicFile = Ran; Jarvis.SpeakAsync("How about " + MyMusicNames[SelectedMusicFile] + "?"); axWindowsMediaPlayer1.URL = MyMusicPaths[SelectedMusicFile]; } break; case "Pause": tmrMusic.Stop(); axWindowsMediaPlayer1.Ctlcontrols.pause(); break; case "Turn Shuffle On": Settings.Default.Shuffle = true; Settings.Default.Save(); Jarvis.SpeakAsync("Shuffle enabled"); break; case "Turn Shuffle Off": Settings.Default.Shuffle = false; Settings.Default.Save(); Jarvis.SpeakAsync("Shuffle disabled"); break; case "Turn Up": axWindowsMediaPlayer1.settings.volume += 10; lblVolume.Text = axWindowsMediaPlayer1.settings.volume.ToString() + "%"; tbarVolume.Value = axWindowsMediaPlayer1.settings.volume; break; case "Turn Down": axWindowsMediaPlayer1.settings.volume -= 10; lblVolume.Text = axWindowsMediaPlayer1.settings.volume.ToString() + "%"; tbarVolume.Value = axWindowsMediaPlayer1.settings.volume; break; case "Mute": axWindowsMediaPlayer1.settings.mute = true; lblVolume.Text = "mute"; break; case "Unmute": axWindowsMediaPlayer1.settings.mute = false; lblVolume.Text = axWindowsMediaPlayer1.settings.volume.ToString() + "%"; break; case "Next Song": if (SelectedMusicFile != MyMusicPaths.Count() - 1) { if (Settings.Default.Shuffle == true) { Ran = rnd.Next(0, MyMusicPaths.Count()); SelectedMusicFile = Ran; } else if (Settings.Default.Shuffle == false) { SelectedMusicFile += 1; } axWindowsMediaPlayer1.URL = MyMusicPaths[SelectedMusicFile]; } break; case "Previous Song": if (SelectedMusicFile != 0) { SelectedMusicFile -= 1; axWindowsMediaPlayer1.URL = MyMusicPaths[SelectedMusicFile]; } break; case "Fast Forward": axWindowsMediaPlayer1.Ctlcontrols.fastForward(); break; case "Stop Music": tmrMusic.Stop(); axWindowsMediaPlayer1.URL = String.Empty; axWindowsMediaPlayer1.Ctlcontrols.stop(); lblMusicTime.Visible = false; lblVolume.Visible = false; axWindowsMediaPlayer1.Visible = false; tbarVolume.Visible = false; tbarMusicTime.Visible = false; axWindowsMediaPlayer1.fullScreen = false; break; case "Fullscreen": try { axWindowsMediaPlayer1.fullScreen = true; } catch { } break; case "Exit Fullscreen": axWindowsMediaPlayer1.fullScreen = false; break; case "What song is playing": string filesourceURL = axWindowsMediaPlayer1.currentMedia.sourceURL; if (axWindowsMediaPlayer1.playState == WMPLib.WMPPlayState.wmppsPlaying) { Jarvis.SpeakAsync(MyMusicNames[SelectedMusicFile]); } else { Jarvis.SpeakAsync("No song is currently being played"); } break; #endregion #region Other Commands case "I want to add custom commands": case "I want to add a custom command": case "I want to add a command": Customize customwindow = new Customize(); customwindow.ShowDialog(); break; case "Update commands": Jarvis.SpeakAsync("This may take a few seconds"); _recognizer.UnloadGrammar(shellcommandgrammar); _recognizer.UnloadGrammar(webcommandgrammar); _recognizer.UnloadGrammar(socialcommandgrammar); ArrayShellCommands = File.ReadAllLines(scpath); ArrayShellResponse = File.ReadAllLines(srpath); ArrayShellLocation = File.ReadAllLines(slpath); ArrayWebCommands = File.ReadAllLines(webcpath); ArrayWebResponse = File.ReadAllLines(webrpath); ArrayWebURL = File.ReadAllLines(weblpath); ArraySocialCommands = File.ReadAllLines(socpath); ArraySocialResponse = File.ReadAllLines(sorpath); try { shellcommandgrammar = new Grammar(new GrammarBuilder(new Choices(ArrayShellCommands))); _recognizer.LoadGrammar(shellcommandgrammar); } catch { Jarvis.SpeakAsync("I've detected an in valid entry in your shell commands, possibly a blank line. Shell commands will cease to work until it is fixed."); } try { webcommandgrammar = new Grammar(new GrammarBuilder(new Choices(ArrayWebCommands))); _recognizer.LoadGrammar(webcommandgrammar); } catch { Jarvis.SpeakAsync("I've detected an in valid entry in your web commands, possibly a blank line. Web commands will cease to work until it is fixed."); } try { socialcommandgrammar = new Grammar(new GrammarBuilder(new Choices(ArraySocialCommands))); _recognizer.LoadGrammar(socialcommandgrammar); } catch { Jarvis.SpeakAsync("I've detected an in valid entry in your social commands, possibly a blank line. Social commands will cease to work until it is fixed."); } Jarvis.SpeakAsync("All commands updated"); break; case "Refresh libraries": Jarvis.SpeakAsync("Loading libraries"); try { _recognizer.UnloadGrammar(MusicGrammar); _recognizer.UnloadGrammar(VideoGrammar); } catch { Jarvis.SpeakAsync("Previous grammar was invalid"); } File.Delete(@"C:\Users\" + Environment.UserName + "\\Documents\\Jarvis Custom Commands\\Filenames.txt"); QEvent = "ReadDirectories"; ReadDirectories(); break; case "Change video directory": Jarvis.SpeakAsync("Please choose a directory to load your video files"); VideoFBD.SelectedPath = Settings.Default.VideoFolder; VideoFBD.Description = "Please select your video directory"; DialogResult videoresult = VideoFBD.ShowDialog(); if (videoresult == DialogResult.OK) { Settings.Default.VideoFolder = VideoFBD.SelectedPath; Settings.Default.Save(); QEvent = "ReadDirectories"; ReadDirectories(); } break; case "Change music directory": Jarvis.SpeakAsync("Please choose a directory to load your music files"); MusicFBD.SelectedPath = Settings.Default.MusicFolder; MusicFBD.Description = "Please select your music directory"; DialogResult musicresult = MusicFBD.ShowDialog(); if (musicresult == DialogResult.OK) { Settings.Default.MusicFolder = MusicFBD.SelectedPath; Settings.Default.Save(); QEvent = "ReadDirectories"; ReadDirectories(); } break; case "Stop listening": Jarvis.SpeakAsync("I will await further commands"); _recognizer.RecognizeAsyncCancel(); startlistening.RecognizeAsync(RecognizeMode.Multiple); break; #endregion #region Gmail Notification case "Check for new emails": QEvent = "Checkfornewemails"; Jarvis.SpeakAsyncCancelAll(); EmailNum = 0; RSSReader.CheckForEmails(); break; case "Open the email": try { Jarvis.SpeakAsyncCancelAll(); Jarvis.SpeakAsync("Very well"); System.Diagnostics.Process.Start(MsgLink[EmailNum]); } catch { Jarvis.SpeakAsync("There are no emails to read"); } break; case "Read the email": Jarvis.SpeakAsyncCancelAll(); try { Jarvis.SpeakAsync(MsgList[EmailNum]); } catch { Jarvis.SpeakAsync("There are no emails to read"); } break; case "Next email": Jarvis.SpeakAsyncCancelAll(); try { EmailNum += 1; Jarvis.SpeakAsync(MsgList[EmailNum]); } catch { EmailNum -= 1; Jarvis.SpeakAsync("There are no further emails"); } break; case "Previous email": Jarvis.SpeakAsyncCancelAll(); try { EmailNum -= 1; Jarvis.SpeakAsync(MsgList[EmailNum]); } catch { EmailNum += 1; Jarvis.SpeakAsync("There are no previous emails"); } break; case "Clear email list": Jarvis.SpeakAsyncCancelAll(); MsgList.Clear(); MsgLink.Clear(); lstCommands.Items.Clear(); EmailNum = 0; Jarvis.SpeakAsync("Email list has been cleared"); break; #endregion #region Updating case "Change Language": AskForACountry(); break; case "Check for new updates": Jarvis.SpeakAsync("Let me see if Michael has posted anything"); RSSReader.CheckBloggerForUpdates(); break; case "Yes": if (QEvent == "UpdateYesNo") { Jarvis.SpeakAsync("Thank you. I shall initialize the download immediately. Simply uninstall me and then install the new me. Would you like me to open the blog for specific information on the update?"); System.Diagnostics.Process.Start(Settings.Default.RecentUpdate); QEvent = "OpenBlog"; } else if (QEvent == "OpenBlog") { Jarvis.SpeakAsync("Very well, consider it done"); System.Diagnostics.Process.Start("http://michaelcjarvis.blogspot.com/2013/09/michael- cs-customizable-jarvis.html"); QEvent = String.Empty; } else if (QEvent == "shutdown" || QEvent == "logoff" || QEvent == "restart") { Jarvis.SpeakAsync("I will begin the countdown to " + QEvent); ShutdownTimer.Enabled = true; lblTimer.Visible = true; } break; case "No": if (QEvent == "UpdateYesNo") { Jarvis.SpeakAsync("Very well. I guess I don't need any improvement"); Settings.Default.RecentUpdate = String.Empty; Settings.Default.Save(); QEvent = String.Empty; } else if (QEvent == "OpenBlog") { Jarvis.SpeakAsync("Learn by doing I suppose"); QEvent = String.Empty; } else if (QEvent == "shutdown" || QEvent == "logoff" || QEvent == "restart") { Jarvis.SpeakAsync("My mistake"); QEvent = String.Empty; } break; #endregion } } void startlistening_SpeechRecognized(object sender, SpeechRecognizedEventArgs e) { string speech = e.Result.Text; switch (speech) { case "Jarvis": startlistening.RecognizeAsyncCancel(); Jarvis.SpeakAsync("Yes?"); _recognizer.RecognizeAsync(RecognizeMode.Multiple); break; } } }