How to send enter as an input in console application - cmd

I want to create a console application and want to send command prompt commands
but I dont know how to send enter in it
Module Module1
Sub Main()
Console.ForegroundColor = ConsoleColor.Green
Console.Write("tree")
End Sub
End Module

If you don't use Enter as the termination of input. How do you alert the console that you finish your input?
Suppose that you press X to terminate the input.
You can use do while loop runs to listen what you press (including the Enter to break line) until you press X. Something like:
public static string CustomReadline()
{
string s = "";
ConsoleKeyInfo keyinfo;
do
{
keyinfo = Console.ReadKey();
if (keyinfo.Key == ConsoleKey.Enter)
{
Console.WriteLine();
}
s += keyinfo.KeyChar.ToString();
}
while (keyinfo.Key != ConsoleKey.X);
return s;
}
and you call the method to receive the input
static void Main(string[] args)
{
var s = CustomReadline();
}

Related

How can I make title screen?

I am trying to make title screen when i press a button. It goes when i press the button game stops
with Time.timeScale = 0f; and I am trying to do is when I click button time stops and two buttons shows up for quit and resume and I am trying to do when I press the button it sets show = true; in script for Menu button. This work but when I type script for button "resume" witch is:
private void Awake()
{
gameObject.SetActive(false);
}
private void Update()
{
show();
}
private void show ()
{
if (show = true)
{
gameObject.SetActive(true);
}
}
But there is an Error: Cannot assign to show because it is a method group.
I don't know what this mean and how I can repair my code.
it would be great if you made bool
here some example of your code
public bool show;
private void Awake()
{
gameObject.SetActive(false);
}
private void Start()
{
show = false;
gameObject.SetActive(false);
}
private void gameobject()
{
if (show = true)
{
gameObject.SetActive(true);
}
else(show = false){
gameobject.SetActive(false);
}
}
Deleted show() and replaced update() with Start()
Useful information about bool
https://docs.unity3d.com/ScriptReference/30_search.html?q=bool
source: unity documentary

OpenTK Integers Stop Changing Values after Window Open

I need to Have Integers that change in the Background while the GameWindow is Open in OpenTK i tested Some Things and It Totaly didn't work, after this code:
GameWindow polyWindow = new GameWindow(1024, 768);
polyWindow.Run(200);
the Folowwing Code:
if (Gamesets.Polygon.Playfield.timer == 2)
{
polyWindow.Close();
}
Does Not Execute, its Just a Basic Timer that Closes the Window after 2
Seconds, The Code for That is Here:
public static int timer;
public static int ms_timer;
public static void playfield()
{
while (true)
{
ms_timer = + ms_timer + 1;
System.Threading.Thread.Sleep(10);
Console.WriteLine(timer + "S"+ms_timer + "MS");
if (ms_timer == 100) { timer = timer + 1; ms_timer = 0; }
if (timer == 10)
{
}
and it Does Not Work after the GameWindow is Shown
Any code written after the GameWindow.Run() statement will not be executed until after the window has been closed. So the code checking if the time is equal to 2 will not run until polywindow.close() has already been executed or you manualy close the window.
Alternatively what you could do, is check the timer from within the Opentk window in the Update or Render methods and execute the Close() method there.
For example:
protected override void OnUpdateFrame(FrameEventArgs e)
{
base.OnUpdateFrame(e);
if (Gamesets.Polygon.Playfield.timer == 2)
{
Close();
}
}

Console.ReadLine() passed to C# event

I'm learning RX and would like to use Console.ReadLine as a source for observable sequences.
I know that I can create "IEnumerable" using "yield return", but for my concrete use case I've decided to create a C# event, so that potentially many observers will be able to share the same keyboard input.
Here is my code:
class Program
{
private delegate void OnNewInputLineHandler(string line);
private static event OnNewInputLineHandler OnNewInputLineEvent = _ => {};
static void Main(string[] args)
{
Task.Run((Action) GetInput);
var input = ConsoleInput();
input.Subscribe(s=>Console.WriteLine("1: " + s));
Thread.Sleep(30000);
}
private static void GetInput()
{
while (true)
OnNewInputLineEvent(Console.ReadLine());
}
private static IObservable<string> ConsoleInput()
{
return Observable.Create<string>(
(IObserver<string> observer) =>
{
OnNewInputLineHandler h = observer.OnNext;
OnNewInputLineEvent += h;
return Disposable.Create(() => { OnNewInputLineEvent -= h; });
});
}
}
My problem - when I run the GetInput method as it is shown above, the very first input line is not sent to the sequence (but it is sent to the event handler).
However, if I replace it with the following version, everything works as expected:
private static void GetInput()
{
while (true)
{
var s = Console.ReadLine();
OnNewInputLineEvent(s);
}
}
Could someone shed some light on why this might happen?
You're trying to make life difficult for yourself. There is almost always a way to make things simple with Rx. It's just a matter of learning to think more functionally rather than procedurally.
This is all you need:
class Program
{
static void Main(string[] args)
{
var subscription = ConsoleInput().Subscribe(s => Console.WriteLine("1: " + s));
Thread.Sleep(30000);
subscription.Dispose();
}
private static IObservable<string> ConsoleInput()
{
return
Observable
.FromAsync(() => Console.In.ReadLineAsync())
.Repeat()
.Publish()
.RefCount()
.SubscribeOn(Scheduler.Default);
}
}
This lets multiple subscribers share the one input through the .Publish().RefCount(). And the .SubscribeOn(Scheduler.Default) pushes the subscription out to a new thread - without it you block on a subscription.
If you move Task.Run((Action) GetInput); to after the subscription your code will work as desired. This is because in your original version, the first call of OnNewInputEvent(Console.ReadLine()) is run before you've hooked OnNewInputLineEvent to the observer.OnNext.

Listview from arrayadapter filled text file always one update behind

I have a listview that I want to update with information from a textfile (rollcall.txt). Each time rollcall.txt is updated I am calling rollcall() (code below). The data is updated correctly in the text file before rollcall() is called, I have checked. The problem I have is that the listview doesnt show the updated entry until the next time I call rollcall() (I.E it always appears to be one update step behind).
Where am I going wrong?
public void rollcall(){
String[] splitdata = null;
try{
File myFile = new File(Environment.getExternalStorageDirectory() + "/rollcall.txt");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
splitdata = aBuffer.split("`"); //recover the file and split it based on `
myReader.close();
}
catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.logbooklayout, splitdata);
lv1.setAdapter(adapter);
adapter.notifyDataSetChanged(); //called to ensure updated data is refreshed into listview without reload
EDIT: rollcall is called from this method:
public void onClick(View v) {
if (v==badd){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("ROLLCALL"); //Set Alert dialog title here
alert.setMessage("Enter data: "); //Message here
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//You will get as string input data in this variable.
// here we convert the input to a string and show in a toast.
add = input.getEditableText().toString();
try {
File myFile = new File(Environment.getExternalStorageDirectory() + "/rollcall.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile, true);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(add);
myOutWriter.append("`"); // ` used to split the file down later in lv section
myOutWriter.close();
fOut.close();
}
catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
} // End of onClick(DialogInterface dialog, int whichButton)
}); //End of alert.setPositiveButton
alert.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
dialog.cancel();
}
}); //End of alert.setNegativeButton
AlertDialog alertDialog = alert.create();
alertDialog.show();
rollcall();
}//end badd
}
Thanks for the help, I am new to using arrayadapters.
Andy
Short answer to your question is everything in UI thread is asynchronous and unless you somehow manage to freeze/lock the whole application you can't make the rest of your UI wait for your alert to grab the input. So long before you press "OK" button in your alert, your rollcall() method is being called from your onClick() function and whatever is inside your .txt file is being read/displayed on your UI, right behind your alert dialog hanging on for you to press one of the buttons, asynchronously.
Maybe the fastest solution to what you want to achieve is to call your rollcall() function somewhere else, after you confirm that your adapter's feeding data has actually been changed. If you must call it from within onClick() function, without questioning your reasons to do so, you should call it inside the try{} block, right after you close the output stream.
Like this:
try {
File myFile = new File(Environment
.getExternalStorageDirectory() + "/rollcall.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile, true);
OutputStreamWriter myOutWriter = new OutputStreamWriter(
fOut);
myOutWriter.append(add);
myOutWriter.append("`"); // ` used to split the
// file down later
// in lv section
myOutWriter.close();
fOut.close();
rollcall();
}
The reason this "works" is you already declared the listener for your "OK" button and whenever you press it, whatever inside your EditText input will be written on file. In order to make it work as before I think you need superhuman skills to write some text on alert dialog and click on button before rollcall() function is called in the same scope.
Obviously the better way to do update the list view is to be able to use adapter.notifyDataSetChanged() but I believe you should call it somewhere else than where you write on your file and in that case your adapter must be declared outside the scope of rollcall() function.
Anyways in order to show how it all goes on I created a simple(rather ugly) android application and put some logs on where the mysterious stuff is happening:
public class MainActivity extends Activity {
private ListView lv1;
private Button refreshButton;
ArrayAdapter<String> adapter;
String[] splitdata;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
refreshButton = (Button) findViewById(R.id.refreshButton);
lv1 = (ListView) findViewById(R.id.someTextViewId);
refreshButton.setOnClickListener(myButtonhandler);
splitdata = null;
}
View.OnClickListener myButtonhandler = new View.OnClickListener() {
public void onClick(View v) {
Log.d("main", "la noliy");
someFunction();
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void someFunction() {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("ROLLCALL"); // Set Alert dialog title here
alert.setMessage("Enter data: "); // Message here
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// You will get as string input data in this
// variable.
// here we convert the input to a string and show in
// a toast.
String add = input.getEditableText().toString();
try {
File myFile = new File(Environment
.getExternalStorageDirectory() + "/rollcall.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile, true);
OutputStreamWriter myOutWriter = new OutputStreamWriter(
fOut);
myOutWriter.append(add);
myOutWriter.append("`"); // ` used to split the
// file down later
// in lv section
myOutWriter.close();
fOut.close();
if (splitdata.length > 0) {
rollcall(new String("call from inside"));
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
} // End of onClick(DialogInterface dialog, int
// whichButton)
}); // End of alert.setPositiveButton
alert.setNegativeButton("CANCEL",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
dialog.cancel();
}
}); // End of alert.setNegativeButton
AlertDialog alertDialog = alert.create();
alertDialog.show();
Log.d("someFunction", "before rollcall");
Log.d("someFunction", "location: "
+ Environment.getExternalStorageDirectory().getAbsolutePath());
rollcall(new String("call from outside"));
Log.d("someFunction", "after rollcall");
}// end badd
public void rollcall(String message) {
Log.d("rollcall", message);
try {
File myFile = new File(Environment.getExternalStorageDirectory()
+ "/rollcall.txt");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(new InputStreamReader(
fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
splitdata = aBuffer.split("`"); // recover the file and split it
// based on `
myReader.close();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT)
.show();
}
int length = splitdata.length;
for (int i = 0; i < length; i++) {
Log.d("rollcall", splitdata[i]);
}
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, splitdata);
lv1.setAdapter(adapter);
}
}
I put a button and an onClickListener to it. The first time you press the button everything is called, listview is updated and your dialog is hanging on your screen for either of the buttons to be pressed:
And you will see a log like this:
07-26 04:09:20.802: D/someFunction(11273): before rollcall
07-26 04:09:20.802: D/someFunction(11273): location: /mnt/sdcard
07-26 04:09:20.802: D/rollcall(11273): call from outside
07-26 04:09:20.802: D/rollcall(11273): some data
07-26 04:09:20.802: D/rollcall(11273): some other data
07-26 04:09:20.812: D/someFunction(11273): after rollcall
You can see that rollcall() has been called from outside and not inside of your try/catch block since there is also another call from there to rollcall(). But when you press the button your try/catch block will do it's job inside your onClick() function and rollcall() will be called afterwards. Hence your listview wil be updated with new data you just entered in the dialog:
Here is the final part of log right after you press "OK" you can see that rollcall() is being called and it can read the new data:
07-26 04:09:46.347: D/rollcall(11273): call from inside
07-26 04:09:46.357: D/rollcall(11273): some data
07-26 04:09:46.357: D/rollcall(11273): some other data
07-26 04:09:46.357: D/rollcall(11273): new data
Finally, I'm sure there are a lot of ugliness in this whole approach to your problem. Bottom line is you need to know that everything happening in the UI thread is asynchronous and no one is waiting for you to enter data inside your dialog in that onClick() function. You should update your listview somewhere else with a more elegant approach in case your application throws an exception for example around that try/catch block. At least maybe you should add a finally{} block at the end of it and update your listview in there even though the try part fails. Hope this answered your question:)
PS. For those who want to try this at home, remember to provide a TextView id from your layout.xml file to the findViewById() function to get the ListView reference in your code, not an actual ListView id. Yeah, I know...
call adapter.notifyDataSetChanged() everytime you update your adapter, then listview will automatically be updated
I suggest you run rollcall as an asychronous task for 2 reasons. First, it will not stop your UI when rollcall() is running.
Second, you will be able to call onPostExecute(Object o) wher you can call `adapter.notifyDataSetChanged(); '

How could I choose one particular file to load with loadStrings

The title is explicit enough, I want to let the user choose the text file he want to open.
I do not know if there is an explorer or an input field already implemented on processing.
Any help would be great.
Use selectInput. From the Processing reference:
Opens a platform-specific file chooser dialog to select a file for input. After the selection is made, the selected File will be passed to the 'callback' function. If the dialog is closed or canceled, null will be sent to the function, so that the program is not waiting for additional input. The callback is necessary because of how threading works.
I've modified the example sketch they provide in the reference to include loading the file with the loadStrings method.
String[] txtFile;
void setup() {
selectInput("Select a file to process:", "fileSelected");
}
void fileSelected(File selection) {
if (selection == null) {
println("Window was closed or the user hit cancel.");
} else {
String filepath = selection.getAbsolutePath();
println("User selected " + filepath);
// load file here
txtFile = loadStrings(filepath);
}
}
There is no Implemented method, but you could could make a buffer and monitor key presses like so:
String[] File;
String keybuffer = "";
Char TriggerKey = Something;
void setup(){
//do whatever here
}
void draw(){
//Optional, to show the current buffer
background(255);
text(keybuffer,100,100);
}
void keyPressed(){
if(keyCode >= 'a' && keyCode <= 'z'){
keybuffer = keybuffer + key;
}
if(key == TriggerKey){
File = loadStrings(keybuffer + ".txt");
}
}
when triggerkey is pressed, it loads the file

Resources