How do i keep an integer after the code ran once? - if-statement

I just started out on C# and I wanted to make a voice recognition program that counts your words and for now, warns you after a said number is passed. I have asked someone on discord and they said I should use a dictionary in order to do that but I don't know how to implement that into this so I made it with if statements, here is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Speech.Recognition;
using System.Speech.Synthesis;
namespace VoiceRecognition
{
public partial class SpeechRecognition : Form
{
SpeechRecognitionEngine recEngine = new SpeechRecognitionEngine();
SpeechSynthesizer synthesizer = new SpeechSynthesizer();
public SpeechRecognition()
{
InitializeComponent();
}
private void On_Click(object sender, EventArgs e)
{
recEngine.RecognizeAsync(RecognizeMode.Multiple);
On.Enabled = true;
}
private void SpeechRecognition_Load(object sender, EventArgs e)
{
Choices commands = new Choices();
commands.Add(new string[] { "bad" });
GrammarBuilder gBuilder = new GrammarBuilder();
gBuilder.Append(commands);
Grammar grammar = new Grammar(gBuilder);
recEngine.LoadGrammarAsync(grammar);
recEngine.SetInputToDefaultAudioDevice();
recEngine.SpeechRecognized += recEngine_SpeechRecognized;
}
void recEngine_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
switch (e.Result.Text)
{
case "bad":
int badwordcount = 0;
if (badwordcount == 0)
{
synthesizer.SpeakAsync("i will suggest you to stop.");
badwordcount +=1;
}
else if (badwordcount == 1)
{
synthesizer.SpeakAsync("You are getting quite annoying.");
badwordcount += 1;
}
if(badwordcount == 2)
{
synthesizer.SpeakAsync("Thats it, you are done.");
}
break;
}
}
private void Off_Click(object sender, EventArgs e)
{
recEngine.RecognizeAsyncStop();
Off.Enabled = false;
}
}
}
The problem lies in the integer from line 51 (badwordcount), no matter how much I repeat the word bad, it just does not respond with the "You are getting quite annoying." line. Any ideas on how do I save the integer so it knows what to say after it hears it a second time? (sorry for the long text, I don't know how to express my words very well).

Related

Unity3D TestRunner hangs when using NSubstitute to mock a Monobehavior class

I have stripped my project down to the bare minimum to try to figure out this instance where Unity TestRunner hangs. I have two Monobehaviors classes, GameController and TrialController. I followed Jason Wiemann's excellent testing videos Everything you need to know about Testing in Unity3D and Testing Against Monobehaviors Using Mocks to create an interface class, ITrialController, so that I can mock it for testing GameController. The TestRunner hangs when I try to run TestWithGetNextSubstitute(). What am I doing wrong here?
============== GameCtrlTest.cs ===========================
using System.Collections;
using System.Collections.Generic;
using NSubstitute;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.TestTools;
namespace Tests
{
public class GameCtrlTest
{
GameController gameCtrl;
[SetUp]
public void TestSetup()
{
GameObject gameObject = new GameObject("GameController");
gameCtrl = gameObject.AddComponent<GameController>();
gameCtrl.trialCtrl = Substitute.For<ITrialController>();
Assert.IsNotNull(gameCtrl.trialCtrl);
Debug.Log("Test Setup() done");
}
[UnityTest]
public IEnumerator TestWithGetNextSubstitute()
{
gameCtrl.trialCtrl.GetNextTrial().Returns( "test-1", "test-2", null);
yield return null;
}
}
}
================== TrialController.cs ================================
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
public class TrialController : MonoBehaviour, ITrialController
{
int trialsLeft = 2;
public string GetNextTrial()
{
if (trialsLeft == 0)
return null;
else
{
string returnString = "trial--" + trialsLeft;
trialsLeft--;
return (returnString);
}
}
}
==================== ITrialController.cs =================
public interface ITrialController
{
string GetNextTrial();
}
==================== GameController.cs ==================
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// give Test Runner access to internal variables and methods
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Tests")]
public class GameController : MonoBehaviour
{
public ITrialController trialCtrl { get; set; }
//=================== MonoBehavior interface =======================
void Awake()
{
Debug.Log("gameController Awake()");
}
// Start is called before the first frame update
void Start()
{
Debug.Log("gameController Start()");
if (trialCtrl != null)
Debug.Log("trialCtrl already set");
else
{
Debug.Log("calling FindObjectOfType(typeof(TrialController)");
trialCtrl = (ITrialController)FindObjectOfType(typeof(TrialController));
Debug.Assert(trialCtrl != null, "Problem finding TrialController");
}
}
// Update is called once per frame
static bool levelInitialized = false;
void Update()
{
if (!levelInitialized)
{
Debug.Log("gameController first Update()");
levelInitialized = true;
}
string trialName = trialCtrl.GetNextTrial();
while (trialName != null)
{
Debug.Log($"GameController got {trialName} from GetNextTrial");
trialName = trialCtrl.GetNextTrial();
}
}
}
The fix was to move the GetNextTrial().Returns() call from the [UnityTest] to the [Setup]. This initially seems very limiting, but there is probably a way to move the parameter list ("test-1", "test-2", null) into a variable so I can change it for different tests.
=============== GameCtrlTest.cs ===================================
using System.Collections;
using System.Collections.Generic;
using NSubstitute;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.TestTools;
namespace Tests
{
public class GameCtrlTest
{
GameController gameCtrl;
[SetUp]
public void TestSetup()
{
GameObject gameObject = new GameObject("GameController");
gameCtrl = gameObject.AddComponent<GameController>();
gameCtrl.trialCtrl = Substitute.For<ITrialController>();
Assert.IsNotNull(gameCtrl.trialCtrl);
gameCtrl.trialCtrl.GetNextTrial().Returns("test-1", "test-2", null);
Debug.Log("Test Setup() done");
}
[UnityTest]
public IEnumerator TestWithGetNextSubstitute()
{
yield return null;
}
}
}

How to wait for data on a COM port

I am using .Net framework's SerialPort class (System.IO.Ports) and am trying to wait to receive data. I've looked around and the WaitCommEvent function seems to be what people suggest using, however it expects a HANDLE as the first parameter. I would like to know either how to get a handle from the SerialPort or a different way to wait for data compatible with the SerialPort class.
The SerialPort class has a DataReceived event:
Indicates that data has been received through a port represented by the SerialPort object.
The documentation provides the following C++/CLI example:
#using <System.dll>
using namespace System;
using namespace System::IO::Ports;
ref class PortDataReceived
{
public:
static void Main()
{
SerialPort^ mySerialPort = gcnew SerialPort("COM1");
mySerialPort->BaudRate = 9600;
mySerialPort->Parity = Parity::None;
mySerialPort->StopBits = StopBits::One;
mySerialPort->DataBits = 8;
mySerialPort->Handshake = Handshake::None;
mySerialPort->RtsEnable = true;
mySerialPort->DataReceived += gcnew SerialDataReceivedEventHandler(DataReceivedHandler);
mySerialPort->Open();
Console::WriteLine("Press any key to continue...");
Console::WriteLine();
Console::ReadKey();
mySerialPort->Close();
}
private:
static void DataReceivedHandler(
Object^ sender,
SerialDataReceivedEventArgs^ e)
{
SerialPort^ sp = (SerialPort^)sender;
String^ indata = sp->ReadExisting();
Console::WriteLine("Data Received:");
Console::Write(indata);
}
};
int main()
{
PortDataReceived::Main();
}

Unit test just returns 1 result of 10 cases from loop

i am trying to get all 10 results of 10 cases from For loop. but when i run, it just returns for me the first result of the first time. any help for this condition, this is my whole code, it includes
2 files, i have tried many times to fix it.
//file BankAccount.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Bank //just want to demo this thing, it hasn't completed
{
namespace BankAccountNS
{
public class BankAccount
{
private double m_balance;
public BankAccount(double balance)
{
m_balance = balance;
}
public bool getMoney(double amount) //funtion get money from account
{
if (amount > m_balance || amount < 0) //check money
{
return false;
}
return true;
}
}
}
}
//file BankAccountTests.cs
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Bank.BankAccountNS;
namespace BankTest
{
[TestClass]
public class BankAccountTests
{
[TestMethod]
public void TestEveryDebit(BankAccount Ba) //test every case from TestAll
{
Assert.IsTrue(Ba.getMoney(24000));
}
[TestMethod]
public void TestAll() //create all cases
{
for(int i = 0; i < 10; i++)
{
BankAccount Ba = new BankAccount(23996 + i);
TestEveryDebit(Ba);
}
}
}
}
I'm not really clear on what your (attempted) loop asserts would be accomplishing, but the method getMoney seemingly has 2 (or 3) useful unit tests:
Is the amount greater than the balance I have? - return false
Is my account balance less than zero - return false
Is my amount less than or equal too my balance? - return true
In your current setup (if it were to work) you're simply testing getMoney is returning true for amounts even greater than the balance - this is incorrect and does not adhere to the logic you have coded too.
I see your unit tests looking like:
private double _balance = 50;
private BankAccount _unitTestObject;
[TestMethod]
public void getMoney_returnsFalseWithInsufficientFunts() //create all cases
{
_unitTestObject = new BankAccount(_balance );
var results = _unitTestObject.getMoney(_balance+1);
Assert.IsFalse(results);
}
[TestMethod]
public void getMoney_returnsFalseWhenAccountHasLessThanZero() //create all cases
{
_unitTestObject = new BankAccount(-1);
var results = _unitTestObject.getMoney(1);
Assert.IsFalse(results);
}
[TestMethod]
public void getMoney_returnsTrueWhenAccountSufficientBalance() //create all cases
{
_unitTestObject = new BankAccount(_balance);
var results = _unitTestObject.getMoney(_balance);
Assert.IsTrue(results);
}
As I stated in comments, MSTest can't do parameterized tests, and what it looks like you're attempting to do (assert specific logic 10 times) could be done like this:
[TestClass]
public class BankAccountTests
{
[TestMethod]
public void TestAll() //create all cases
{
for(int i = 0; i < 10; i++)
{
BankAccount Ba = new BankAccount(23996 + i);
TestEveryDebit(Ba);
}
}
private void TestEveryDebit(BankAccount Ba) //test every case from TestAll
{
Assert.IsTrue(Ba.getMoney(24000));
}
}
But the test TestAll will always fail, because at some point in your loop, you're going to be trying to take out more amount than you have balance.
When Asserting based on a loop, the "success or failure" of the test is based on the whole, not each individual assert. So even though a few runs of your loop will "pass", the test will fail as a whole.

print error while null value for SQL safety

How can I print "Error" while the JTextfield is empty
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
String sn =jX1.getText();
if (sn==null){
System.out.println("Error");
System.out.println("T");
}
Thanks
Try using a fail-safe method. Also Expanding on the comments, you should be logging data, in a better format. Java hosts a huge array of different way to log certain data. look here
As for your error handling, try-catch-finally. This isn't tested code. Let me know if you run into any issues, documentation on try-catch and other statements here or here
public static void main(String[] args) {
while (String sn == null)
try {
String sn = JX1.getText();
} catch (Exception ex) {
System.out.println("Exception thrown!");
} finally {
if (sn != null) {
System.out.println("Closing PrintWriter");
sn.close();
} else {
System.out.println("PrintWriter not open");
}
}

Get system brightness event in windows

Can somebody will guide me how to get brightness changes event using vc++ in windows system?
or I need to get brightness slider value whenever it will change.
Any help will be very appreciated.
Thanks in advance.
A late answer but since I have been looking for the same thing. Although it is true that controlling brightness is not a Windows task but sometimes a driver's task and could also be related directly to ACPI calls, we can still get some information from Windows about its changes by implementing WMI Events. In particular, you will need to implement WmiMonitorBrightnessEvent which will give you the information you need whenever Windows receives an event of brightness change. The sample code below is a direct conversion to C++/CLI of the C# code in #RRUZ answer here where he made use of WmiMonitorBrightnessEvent.
EventWatcherAsync.h
#pragma once
using namespace System;
using namespace System::Management;
ref class EventWatcherAsync
{
public:
void WmiEventHandler(Object^ sender, EventArrivedEventArgs^ e);
EventWatcherAsync();
};
EventWatcherAsync.cpp
#include "stdafx.h"
#include "EventWatcherAsync.h"
void EventWatcherAsync::WmiEventHandler(Object^ sender, EventArrivedEventArgs^ e)
{
Console::WriteLine("Active : " + e->NewEvent->Properties["Active"]->Value->ToString());
Console::WriteLine("Brightness : " + e->NewEvent->Properties["Brightness"]->Value->ToString());
Console::WriteLine("InstanceName : " + e->NewEvent->Properties["InstanceName"]->Value->ToString());
}
EventWatcherAsync::EventWatcherAsync()
{
try
{
System::String^ ComputerName = "localhost";
System::String^ WmiQuery;
ManagementEventWatcher^ Watcher;
ManagementScope^ Scope;
if (ComputerName != "localhost")
{
ConnectionOptions^ Conn = gcnew ConnectionOptions();
Conn->Username = "";
Conn->Password = "";
Conn->Authority = "ntlmdomain:DOMAIN";
Scope = gcnew ManagementScope(String::Format("\\\\{0}\\root\\WMI", ComputerName), Conn);
}
else
Scope = gcnew ManagementScope(String::Format("\\\\{0}\\root\\WMI", ComputerName));
Scope->Connect();
WmiQuery = "Select * From WmiMonitorBrightnessEvent";
Watcher = gcnew ManagementEventWatcher(Scope, gcnew EventQuery(WmiQuery));
Watcher->EventArrived += gcnew EventArrivedEventHandler(this, &EventWatcherAsync::WmiEventHandler);
Watcher->Start();
Console::Read();
Watcher->Stop();
}
catch (Exception^ e)
{
Console::WriteLine("Exception {0} Trace {1}", e->Message, e->StackTrace);
}
}
Main.cpp
#include "stdafx.h"
#include "EventWatcherAsync.h"
using namespace System;
int main(array<System::String ^> ^args)
{
Console::WriteLine("Listening {0}", "WmiMonitorBrightnessEvent");
Console::WriteLine("Press Enter to exit");
EventWatcherAsync^ eventWatcher = gcnew EventWatcherAsync();
Console::Read();
return 0;
}