I want to write english transcription in console.
In debugger I have this səˈdʒest
but in console I have s??d?est.
How to resolve this problem ? Thanks!
Up
Client for getting transcription
class TranslationFormattedResult
{
public string Transcription { get; set; }
public List<string> TranslatedWordList = new List<string>();
}
class TranslatorClient
{
private TranslationServiceSoapClient _client = new TranslationServiceSoapClient("TranslationServiceSoap");
public async Task<TranslationFormattedResult> GetTranslationAsync(string word)
{
var result = await _client.GetTranslationAsync("er", "General",
word,
lang: "ru",
limit: 3000,
useAutoDetect: true,
key: "",
ts: "MainSite",
tid: "");
var translationResult = new TranslationFormattedResult {Transcription = await GetTranscriptionAsync(result)};
return translationResult;
}
private async Task<string> GetTranscriptionAsync(TranslationResult result)
{
var task = new Task<string>(() =>
{
string pr = null;
string pattern = "\\[.+\\]";
var match = Regex.Match(result.result, pattern);
if(match.Success)
{
pr = match.Value.Trim('[', ']');
}
return pr;
});
task.Start();
return await task;
}
}
And main method
class Program
{
static void Main(string[] args)
{
//this works
var client = new TranslatorClient();
var ts = client.GetTranslationAsync("suggest")
.ContinueWith(r =>
{
var transcription = r.Result.Transcription;
Console.OutputEncoding = Encoding.Unicode;
Console.WriteLine(transcription);
Console.WriteLine("press any key");
Console.ReadKey();
}
);
ts.Wait();
}
}
You should:
set the OutputEncoding to Unicode: Console.OutputEncoding = Encoding.Unicode;
run your program
right click on the console window
in the properties window change the console font and set it to Consolas.
class Program {
static void Main( string[ ] args ) {
Console.OutputEncoding = Encoding.Unicode;
Console.WriteLine( "səˈdʒest" );
}
}
The result in the console is:
Is this Russian?
If so, try running chcp 866 at the command line.
Refer to this
http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/chcp.mspx?mfr=true
This answer also suggests a specific (or at least, different) font may need to be selected (not sure if this applies to Russian or not) Unicode characters in Windows command line - how?
Related
I'm testing C# console application cli tool (System.CommandLine) & I have this code:
using System.CommandLine.NamingConventionBinder;
using System.CommandLine;
internal class Program
{
private static async Task Main (string[] args)
{
var rootCommand = new RootCommand { };
var getCommand = new Command ("get")
{
new Option<string> (
"me",
description: "Gets the name of a takeep & shows its text.")
};
var setCommand = new Command ("set")
{
new Option<string> (
"the",
description: "Sets a takeep by name & text.")
};
getCommand.Handler = CommandHandler.Create<string> ((me) =>
{
Console.WriteLine ($"Build Version: {me}");
});
setCommand.Handler = CommandHandler.Create<string> ((set) =>
{
Console.WriteLine ($"Build Version: {set}");
});
rootCommand.Add (getCommand);
rootCommand.Add (setCommand);
await rootCommand.InvokeAsync (args);
}
}
When I call the command, this way:
.\takeep.cli.exe get me 'Name'
Is there a way to remove that "me", but keep its functionality (I mean, other commands also work)? Thanks for your help 💐
I'm attempting to create a simple C# application which can accept input on StdIn and process that with Ghostscript to create a PDF, eventually I'd like to do other things with the output PDF, but for now just creating the PDF is enough.
I was thinking of running the Ghostscript .exe with a Process, but then I found Ghostscript.NET, the thing I'm struggling with is how to pass the data received on StdIn to the Ghostscript.NET Processor.
using (GhostscriptProcessor ghostscript = new GhostscriptProcessor(gvi))
{
List<string> switches = new List<string>();
switches.Add("-sDEVICE=pdfwrite");
switches.Add("-r300");
switches.Add("-dBATCH");
switches.Add("-dNOPAUSE");
switches.Add("-dSAFER");
switches.Add("-dNOPROMPT");
switches.Add("-sPAPERSIZE=a4");
switches.Add("-sOutputFile = \"" + filename + "\"");
switches.Add("-c");
switches.Add(".setpdfwrite");
switches.Add(#"-f");
switches.Add("-");
ghostscript.Process(switches.ToArray(), new ConsoleStdIO(true, true, true));
}
This was from the GitHub repo, but I'm not sure if it's what I need or not:
public class ConsoleStdIO : Ghostscript.NET.GhostscriptStdIO
{
public ConsoleStdIO(bool handleStdIn, bool handleStdOut, bool handleStdErr) : base(handleStdIn, handleStdOut, handleStdErr) { }
public override void StdIn(out string input, int count)
{
char[] userInput = new char[count];
Console.In.ReadBlock(userInput, 0, count);
input = new string(userInput);
}
public override void StdOut(string output)
{
Console.Write(output);
}
public override void StdError(string error)
{
Console.Write(error);
}
}
public static string[] PStoPDFArguments(string fileName) =>
new string[]
{
"-dBATCH",
"-dNOPAUSE",
"-sDEVICE=pdfwrite",
"-sPAPERSIZE=a4",
"-dPDFSETTINGS=/prepress",
$"-sOutputFile=\"{fileName}\"",
"-"
};
//...
public override void StdIn(out string input, int count)
{
var buffer = new char[count];
Console.In.ReadBlock(buffer, 0, count);
input = buffer[0] == '\0'
? null
: new string(buffer);
}
//...
I'm attempting to write a simple keylogger that will check typed words against a blacklist and fire a screenshot when a word is triggered. This is because we have a new PREVENT agenda that we have to use in UK schools to capture any possible extremist views.
I've been looking at the Keylogger API from https://github.com/fabriciorissetto/KeystrokeAPI
I'm using the following code as a test but i'm trying to add the characters to a string so i can then fire a comparison with a word list when the user presses the spacebar. The trouble i'm having is that i cannot convert character into a string. Is it possible do this so i can append it to another string a whilst waiting for a spacebar key?
class Program
{
static void Main(string[] args)
{
using (var api = new KeystrokeAPI())
{
api.CreateKeyboardHook((character) => { Console.Write(character); });
Application.Run();
}
}
}
This is what i have so far, the error i get is on the if statement converting character to a string.
static void Main(string[] args)
{
string line = "";
using (var api = new KeystrokeAPI())
{
api.CreateKeyboardHook((character) => {
line += character.ToString();
if (character.ToString() = "space")
{
Console.Write("Spacebar Hit");
}
Console.Write(character.KeyCode);
});
Application.Run();
}
}
Edit.
I rewrote this.
Captures both spaces and enter commands
static void Main(string[] args)
{
string line = string.Empty;
using (var api = new KeystrokeAPI())
{
api.CreateKeyboardHook((character) => {
if (character.KeyCode.ToString() == "Space" || character.KeyCode.ToString() == "Return")
{
if(BannedWordsCheck(line))
{
Console.WriteLine("Banned Word Typed: " + line);
}
line = string.Empty;
}
else
{
line += character.KeyCode.ToString();
}
});
Application.Run();
}
}
static bool BannedWordsCheck(string word)
{
if(word.ToLower().Contains("terror"))
{
return true;
}
else
{
return false;
}
}
The error you are receiving in your code is due to the following line
if (character.ToString() = "space")
You are attempting to assign the string literal "space" to character.ToString(), I also have this error in my comment which I can't edit anymore.
Here's a snippet that will check the key code against an enum instead of a string, it will then call the HandleComparison method if Space was pressed, and then clear out the StringBuilder
The only issue I found here is that pressing Shift will prefix the string with <shift>, so some additional logic will have to be applied for action keys, but this is a base to get you started with a working code sample.
I hope this helps.
class Program
{
private static StringBuilder builder;
static void Main(string[] args)
{
using (var api = new KeystrokeAPI())
{
builder = new StringBuilder();
api.CreateKeyboardHook(HandleKeyPress);
Application.Run();
}
}
private static void HandleKeyPress(KeyPressed obj)
{
// To be more reliable, lets use the KeyCode enum instead
if (obj.KeyCode == KeyCode.Space)
{
// Spacebar was pressed, let's check the word and flush the StringBuilder
HandleComparison(builder.ToString());
builder.Clear();
return;
}
// Space wasn't pressed, let's add the word to the StringBuilder
builder.Append(obj);
}
// Handle comparison logic here, I.E check word if exists on blacklist
private static void HandleComparison(string compareString)
{
Console.WriteLine(compareString);
}
}
Could you use the StringBuilder as a buffer?
something like this
var buffer = new StringBuilder();
using (var api = new KeystrokeAPI())
{
api.CreateKeyboardHook((character) => {
if (character.ToString() == " ")
{
//check the word
CallSomeMethodToCheckWord(buffer.ToString());
//reset the buffer
buffer = new StringBuilder();
}
else
{
//ToString returns special characters in it, so you could append here and parse later, or parse here.
buffer.Append(character.ToString());
}
});
Application.Run();
}
I have followed the instructions here: https://github.com/sharwell/antlr4cs/wiki and here: http://www.antlr.org/wiki/display/ANTLR4/Getting+Started+with+ANTLR+v4
I have morphed my grammar from the opening example but it works with the Java tools (antlr4.bat and grun.bat) but not with my console app as configured by the sharwell wiki.
Java (inside a folder with only the Hello.g4 file):
antlr4 Hello.g4
javac *.java
grun Hello prog -gui
I then type "hello world" then Return then "^Z" then Return
The gui pops up an matches my grammar correctly
C# (only difference is the #parser and #lexer directives are not used in the Java version)
Hello.g4:
grammar MetaMeta;
#parser::members
{
protected const int EOF = Eof;
}
#lexer::members
{
protected const int EOF = Eof;
protected const int HIDDEN = Hidden;
}
prog : stmt NL* EOF;
stmt : hello eos;
hello : HELLO ID;
eos : ';' | NL;
HELLO : 'hello';
ID : [a-z]+;
NL : '\r'? '\n';
WS : [ \t]+ -> skip;
Program.cs:
private static void Main(string[] args)
{
(new Program()).Run();
}
public void Run()
{
var text = "hello world\n";
try
{
Console.WriteLine("START");
RunParser(text);
Console.Write("DONE. Hit RETURN to exit: ");
}
catch (Exception ex)
{
Console.WriteLine("ERROR: " + ex);
Console.Write("Hit RETURN to exit: ");
}
Console.ReadLine();
}
private void RunParser(string text)
{
var input = new AntlrInputStream(text);
var lexer = new MetaMetaLexer(input);
var tokens = new CommonTokenStream(lexer);
var parser = new MetaMetaParser(tokens);
var context = parser.prog();
var visitor = new MyVisitor();
visitor.VisitProg(context);
}
When running the program I get the following:
START
HelloVisitor VisitProg
Visit Symbol=<EOF>
DONE. Hit RETURN to exit:
My visitor is the same as the code example on the cs wiki. Thanks for any help. ;)
Scott
If you would have included your visitor code here, you would have received an answer much faster.
The visitor you are using does not override AbstractParseTreeVisitor<Result>.VisitTerminal(ITerminalNode). Therefore, the default implementation of this method is used each time a terminal node is reached, which simply returns DefaultResult() (which by default is just default(Result)).
The modified visitor code is as follows:
public class MyVisitor : AbstractParseTreeVisitor<object>
{
public override object VisitTerminal(ITerminalNode node)
{
var text = node.Symbol.Text;
if (text == "\n")
text = #"\n";
Console.WriteLine(" Visit Symbol={0}", text);
return base.VisitTerminal(node);
}
}
And the modified calling code is as follows:
private void RunParser(string text)
{
var input = new AntlrInputStream(text);
var lexer = new MetaMetaLexer(input);
var tokens = new CommonTokenStream(lexer);
var parser = new MetaMetaParser(tokens);
var context = parser.prog();
var visitor = new MyVisitor();
visitor.Visit(context); //changed to just Visit
}
I added this for completeness, but awarded the correct answer to Sam above.
Thanks,
Scott
I'm exploring MSMQ services, and I wrote a simple console client-server application that sends each of the client's keystrokes to the server. Whenever hit a control character (DEL, ESC, INS, etc) the server understandably throws an error. However, whenever I type a space character, the server receives the packet but doesn't throw an error and doesn't display the space.
Server:
namespace QIM
{
class Program
{
const string QUEUE = #".\Private$\qim";
static MessageQueue _mq;
static readonly object _mqLock = new object();
static XmlSerializer xs;
static void Main(string[] args)
{
lock (_mqLock)
{
if (!MessageQueue.Exists(QUEUE))
_mq = MessageQueue.Create(QUEUE);
else
_mq = new MessageQueue(QUEUE);
}
xs = new XmlSerializer(typeof(string));
_mq.BeginReceive(new TimeSpan(0, 1, 0), new object(), OnReceive);
while (Console.ReadKey().Key != ConsoleKey.Escape) { }
}
static void OnReceive(IAsyncResult result)
{
Message msg;
lock (_mqLock)
{
try
{
msg = _mq.EndReceive(result);
Console.Write(".");
Console.Write(xs.Deserialize(msg.BodyStream));
}
catch (Exception ex)
{
Console.Write(ex);
}
}
_mq.BeginReceive(new TimeSpan(0, 1, 0), new object(), OnReceive);
}
}
}
Client:
namespace QIM_Client
{
class Program
{
const string QUEUE = #".\Private$\qim";
static MessageQueue _mq;
static void Main(string[] args)
{
if (!MessageQueue.Exists(QUEUE))
_mq = MessageQueue.Create(QUEUE);
else
_mq = new MessageQueue(QUEUE);
ConsoleKeyInfo key = new ConsoleKeyInfo();
while (key.Key != ConsoleKey.Escape)
{
key = Console.ReadKey();
_mq.Send(key.KeyChar.ToString());
}
}
}
}
Client Input:
Testing, Testing...
Server Output:
.T.e.s.t.i.n.g.,..T.e.s.t.i.n.g......
You'll notice that the space character sends a message, but the character isn't displayed.
Your issue is not with MSMQ, it's with the XmlSerializer class. See:
var key = Console.ReadKey();
XmlSerializer s = new XmlSerializer(typeof(string));
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
s.Serialize(ms, key.KeyChar.ToString());
ms.Position = 0;
var foo = (string)s.Deserialize(ms);
}
If you type a space in the console, you'll see that key.KeyChar.ToString() yields " ", but foo is equal to "". Because of the default implementation of XmlReader, the XmlSerializer class considers a string of only whitespace to be empty; if the string contains any other characters, both leading and trailing spaces are preserved. The whitespace does get serialized, but deserializing it turns it into an empty string.
Use this instead:
Console.Write(
s.Deserialize(System.Xml.XmlReader.Create(msg.BodyStream,
new System.Xml.XmlReaderSettings()
{
IgnoreWhitespace = false
})));
The answer from #Adam is right. The easiest solution is to use BinaryMessageFormatter (it will result in slightly smaller messages anyway).
After you initialize the message queue objects in both the client and the server, set the formatter explicitly:
_mq.Formatter = new BinaryMessageFormatter();
Then in the server, don't try to mess with BodyStream directly. Instead just use Body (which will have already been deserialized by the formatter):
Console.Write(".");
Console.Write(msg.Body);