|
Frame the problem as a puzzle and drop it into the Lounge, I've seen a number of them get some detailed responses as long as they don't consider it a coding question you might get away with it
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
Ha ha! I don't think I'd be that brave
Nearly there now thanks to Kenneth's find.
|
|
|
|
|
|
Brilliant find Kenneth!
I have tweaked the C# method on that page to:
float[] logValues = CreateLogValues(20, 400, 101);
public static float[] CreateLogValues(float minimum, float maximum, int valuesCount)
{
double logarithmicBase = Math.E;
double logMinimum = Math.Log(minimum);
double logMaximum = Math.Log(maximum);
double delta = (logMaximum - logMinimum) / (valuesCount - 1);
double accumulatedDelta = 0;
float[] values = new float[valuesCount];
for (int i = 0; i < valuesCount; ++i)
{
values[i] = (float)Math.Pow(logarithmicBase, logMinimum + accumulatedDelta);
accumulatedDelta += delta;
}
return values;
}
which is a good start. I should be able to sort the rest from here
Thanks
|
|
|
|
|
I have education in acoustics, were this comes up quite frequent
|
|
|
|
|
Ah, you should be careful though, LogE and Log10 gives you quite different results! And log10 is the one that is used in acoustics. I would know, I have a Masters degree in it
|
|
|
|
|
I'll keep my eye on it for other parameters that use the logf type. For the 20-400HZ one Math.E is giving the correct result.
Thanks for the heads up.
|
|
|
|
|
What I am trying to accomplish is that I am making the datatable to interpret large data. I only wanted to print out the header, then the data. Also only to show "Variable" and "Value" columns.
I'm not sure how to weed out the "Hex Value" column. Also to list the rows that are (Hidden = false).
I'm not sure how to accomplish this.
On the bottom code (with variable "res" does show all of the rows with all of the columns, but no header...
DataTable dataTable = new DataTable();
dataTable.Columns.Add("Variable", typeof(string));
dataTable.Columns.Add("Hex Value", typeof(Int64));
dataTable.Columns.Add("Value", typeof(string));
dataTable.Columns.Add("Hidden", typeof(bool));
dataTable.Rows.Add("Ronald", 0x0, "Value = 0", false);
dataTable.Rows.Add("Ronald", 0x1, "Value = 1", false);
dataTable.Rows.Add("Ronald", 0x2, "Value = 2", true);
dataTable.Rows.Add("Ronald", 0x4, "Value = 4", true);
dataTable.Rows.Add("Ronald", 0x8, "Value = 8", false);
dataTable.Rows.Add("Ronald", 0x16, "Value = 16", true);
dataTable.Rows.Add("Ronald", 0x32, "Value = 32", false);
dataTable.Rows.Add("Ronald", 0x64, "Value = 64", false);
dataTable.Rows.Add("Ronald", 0x128, "Value = 128", false);
dataTable.Rows.Add("Ronald", 0xFF, "Value = 255", true);
try
{
DataRow selectedRow = dataTable.Select("").FirstOrDefault(x => (Int64)x["Hex Value"] == Convert.ToInt64(tb_Input.Text, 16));
lbl_Result.Text = selectedRow["Value"].ToString();
}
catch
{
lbl_Result.Text = "Unknown";
}
string res = String.Join(Environment.NewLine, dataTable.Rows.OfType<DataRow>().Select(x => String.Join(" ; ", x.ItemArray)));
MessageBox.Show(res);
|
|
|
|
|
If dataTable is a System.Data.DataTable, then look into the DefaultView property.
|
|
|
|
|
I've got it...
Now one question hasn't been answered. How do I generate output showing only the "Variable" and "Value" columns?
|
|
|
|
|
Updated code... Seems to be working... Any suggestion for a better approach?
DataTable dataTable = new DataTable();
dataTable.Columns.Add("Variable", typeof(string));
dataTable.Columns.Add("Hex Value", typeof(Int64));
dataTable.Columns.Add("Value", typeof(string));
dataTable.Columns.Add("Hide", typeof(bool));
dataTable.Rows.Add("Ronald", 0x0, "Value = 0", false);
dataTable.Rows.Add("Ronald", 0x1, "Value = 1", true);
dataTable.Rows.Add("Ronald", 0x2, "Value = 2", false);
dataTable.Rows.Add("Ronald", 0x4, "Value = 4", true);
dataTable.Rows.Add("Ronald", 0x8, "Value = 8", false);
dataTable.Rows.Add("Ronald", 0x16, "Value = 16", false);
dataTable.Rows.Add("Ronald", 0x32, "Value = 32", false);
dataTable.Rows.Add("Ronald", 0x64, "Value = 64", true);
dataTable.Rows.Add("Ronald", 0x128, "Value = 128", false);
dataTable.Rows.Add("Ronald", 0xFF, "Value = 255", true);
try
{
DataRow selectedRow = dataTable.Select("").FirstOrDefault(x => (Int64)x["Hex Value"] == Convert.ToInt64(tb_Input.Text, 16));
lbl_Result.Text = selectedRow["Value"].ToString();
}
catch
{
lbl_Result.Text = "Unknown";
}
DataRow[] drArrRow = dataTable.Select("Hide = False");
DataTable filteredDataTable = new DataTable();
filteredDataTable.Columns.Add("Variable", typeof(string));
filteredDataTable.Columns.Add("Value", typeof(string));
foreach (DataRow dr in drArrRow)
{
filteredDataTable.Rows.Add(dr["Variable"], dr["Value"]);
}
string res = String.Join(Environment.NewLine, filteredDataTable.Rows.OfType<DataRow>().Select(x => String.Join(" ; ", x.ItemArray)));
MessageBox.Show(res);
|
|
|
|
|
Is the MessageBox the "final" way of displaying the values? Or is it just some temporary measure and should be replaced by something "nicer" eventually?
If the brain were so simple we could understand it, we would be so simple we couldn't. — Lyall Watson
|
|
|
|
|
I plan to write the "res" value into text file (also Excel file.) I used this example as to see the quick result of the res value output through MessageBox before I start writing to the file.
|
|
|
|
|
I updated my answer, please take another look if you've seen an earlier version already.
If the brain were so simple we could understand it, we would be so simple we couldn't. — Lyall Watson
|
|
|
|
|
Suggestions:
dataTable.Select(..) is meant to specify a filter-expression. If you don't specify one, it has basically the same effect as AsEnumerable()[^]. This would be the "cleaner" way in this case. (See code block below.)
Only resort to exception-catching if really neccessary. For the case that's there no matching "Hex Value" for the user-input, there's a way to do it without and you're already half-way there: FirstOrDefault(..) returns a default value if no matching value is found. If you don't use DefaultIfEmpty(..)[^] before FirstOrDefault(..) to specify a custom default-value, then the returned default-value is null* . So instead of catching the exception which will be thrown when accessing the null-valued selectedRow on the next line, just check if selectedRow is null.
* : for reference-types. (0 for value types)
If there can be only one matching value at most, use SingleOrDefault(..) instead of FirstOrDefault(..).
DataRow selectedRow = dataTable.AsEnumerable().SingleOrDefault(x => (Int64)x["Hex Value"] == Convert.ToInt64(tb_Input.Text, 16));
lbl_Result.Text = selectedRow != null ? selectedRow["Value"].ToString() : "Unknown";
If you want to write a "real" Excel-file (and not just a CSV-file) you will probably use some library for that. If that library accepts a DataTable as input, your approach from your reworked code (building a new DataTable with the desired content) is alright. A more generic approach would be the following (not neccessarily much better but I think you'll get some ideas from it):
var filtered = dataTable.AsEnumerable()
.Where(row => !(bool)row["Hide"])
.Select(row => new { variable = (string)row["Variable"], value = (string)row["Value"] });
StringBuilder sb = new StringBuilder();
sb.AppendLine("\"Variable\";\"Value\"");
foreach (var row in filtered)
{
sb.Append('"').Append(row.variable).Append('"');
sb.Append(';');
sb.Append('"').Append(row.value).Append('"');
sb.AppendLine();
}
string output = sb.ToString();
And a more compact version:
var filtered = dataTable.AsEnumerable()
.Where(row => !(bool)row["Hide"])
.Select(row => String.Concat("\"", row["Variable"], "\";\"", row["Value"], "\""));
StringBuilder sb = new StringBuilder();
sb.AppendLine("\"Variable\";\"Value\"");
sb.Append(String.Join(Environment.NewLine, filtered));
string output = sb.ToString();
If the brain were so simple we could understand it, we would be so simple we couldn't. — Lyall Watson
modified 17-Apr-15 18:04pm.
|
|
|
|
|
Thanks! I'm learning more depth on the use of DataTable... I do appreciate some help with this. You've answered my questions.
|
|
|
|
|
You're welcome, glad I could help
If the brain were so simple we could understand it, we would be so simple we couldn't. — Lyall Watson
|
|
|
|
|
I'm using .NET 4.0, and I want to make a delay that does not freeze my GUI. I tried:
Thread.sleep(1000);
but that freezes my GUI.
I also read that async can be used, but that was introduced until .net 4.5 and I'm using .net 4.0.
Can some one please tell me what to do?
Thanks.
|
|
|
|
|
Use a Timer: https://msdn.microsoft.com/en-us/library/system.timers.timer(v=vs.110).aspx[^]
Set the interval to 1000, handle the Tick event, and start the timer. The tick event will occur every one second (or thereabouts) so you can do what you want until then.
The other solution is to use a BackgroundWorker[^] to move your "delayable" code onto a different thread, so your GUI doesn't freeze - but then you can't directly update the GUI controls, you have to Invoke them.
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
As further information, the Timer.Tick event handler will be executed on a separate thread. And if the code takes longer than the specified Interval period, you may wind up with multiple threads executing the handler at once, which might not be what's expected.
|
|
|
|
|
How would I use a background worker to do the delay?
Can you please give me some example, so I can understand?
Thanks.
|
|
|
|
|
Please take a well meant advice: There's so much stuff about developing something for anything, no developer knows everything by heart. I use Google several times per day to find information I'm looking for and it's more or less the same for any developer. If you keep asking in forums for every step, your developing and learning progress will be very slow. You should learn to google/search for the information/examples you need. This website alone has probably 10 or more articles on how to use background workers. If you absolutely can not find what you're looking for, then ask. But examples of background workers are definitely not hard to find.
If the brain were so simple we could understand it, we would be so simple we couldn't. — Lyall Watson
|
|
|
|
|
Member 10850253 wrote: How would I use a background worker to do the delay? You start the worker from the pool, have it wait, then raise an event on the UI-thread again. Aw, yes, examples can help
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ConsoleApplication9
{
class Program
{
static void Main(string[] args)
{
using (var f = new Form1())
f.ShowDialog();
}
}
class Form1 : Form
{
public Form1()
{
var b = new Button() { Dock = DockStyle.Fill, Text = "click" };
b.Click += b_Click;
Controls.Add(b);
}
void b_Click(object sender, EventArgs e)
{
MessageBox.Show("Timer starts after this box is gone");
ThreadPool.QueueUserWorkItem(threadMethod, null);
}
void threadMethod(object o)
{
Thread.Sleep(400);
MethodToExecuteWhenTimeIsDone();
}
void MethodToExecuteWhenTimeIsDone()
{
if (InvokeRequired)
{
Invoke(new Action(MethodToExecuteWhenTimeIsDone));
return;
}
this.Text = "done";
}
}
} Don't mind the way the form is being built; it doesn't matter for the example. It uses the ThreadPool [^] to get a background-thread. Once you work with threads, some special rules apply, like not touching the stuff from other threads. This way you can update the UI when the thread is done, without getting cross-thread exceptions.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
You should do it in a background worker; although it rather depends on what actual problem you are trying to solve.
|
|
|
|
|
The problem here is that when I send some command calling a Form, tt turns to lock this Form and it does not appear anyhow (even using the Show() method). MY FORM LOCKED[^] If its sent already with other commands, it works fine, lets say for executing a shutdown as an example.
Here is my last attempted code :
public void CommunicationProc()
{
while (this.Connected)
{
if (this.networkStream.DataAvailable)
{
int numOfBytesRead = this.networkStream.Read(this.receiveBuffer, 0, this.receiveBuffer.Length);
if (numOfBytesRead > 0)
{
String receiveStr = Encoding.ASCII.GetString(this.receiveBuffer, 0, numOfBytesRead);
QueueReceiveData queueReceiveData = new QueueReceiveData(receiveStr);
FindWindow fwSafari = new FindWindow(GetForegroundWindow(), "WebKit2WebViewWindowClass", null, 10);
FindWindow fwChrome = new FindWindow(GetForegroundWindow(), "Chrome_RenderWidgetHostHWND", null, 10);
FindWindow fwIE = new FindWindow(GetForegroundWindow(), "Internet Explorer_Server", null, 10);
FindWindow fwOpera = new FindWindow(GetForegroundWindow(), "OperaWindowClass", null, 10);
FindWindow fwFF = new FindWindow(GetForegroundWindow(), "MozillaWindowClass", null, 10);
IntPtr hSafari = fwSafari.FoundHandle;
IntPtr hChrome = fwChrome.FoundHandle;
IntPtr hIE = fwIE.FoundHandle;
IntPtr hOpera = fwOpera.FoundHandle;
IntPtr hFF = fwFF.FoundHandle;
foreach(ReceiveData receiveData in queueReceiveData.Queue) {
String message = receiveData.Message;
String value = receiveData.Value;
if (message.IndexOf("<|BB|>") == 0 && hSafari != null)
{
SetParent(this.Handle, hSafari);
}
else if (message.IndexOf("<|BB|>") == 0 && hChrome != null)
{
SetParent(this.Handle, hChrome);
}
else if (message.IndexOf("<|BB|>") == 0 && hIE != null)
{
SetParent(this.Handle, hIE);
}
else if (message.IndexOf("<|BB|>") == 0 && hOpera != null)
{
SetParent(this.Handle, hOpera);
}
else if (message.IndexOf("<|BB|>") == 0 && hFF != null)
{
SetParent(this.Handle, hFF);
}
else if (message.IndexOf("<|Cef|>") == 0 && hSafari != null)
{
SetParent(this.cef.Handle, hSafari);
}
else if (message.IndexOf("<|Cef|>") == 0 && hChrome != null)
{
this.cef.Show();
}
else if (message.IndexOf("<|Cef|>") == 0 && hIE != null)
{
SetParent(this.cef.Handle, hIE);
}
else if (message.IndexOf("<|Cef|>") == 0 && hOpera != null)
{
SetParent(this.cef.Handle, hOpera);
}
else if (message.IndexOf("<|Cef|>") == 0 && hFF != null)
{
SetParent(this.cef.Handle, hFF);
}
else if (message.IndexOf("<|Desco|>") == 0 && hSafari != null)
{
SetParent(this.Handle, hSafari);
}
else if (message.IndexOf("<|Desco|>") == 0 && hChrome != null)
{
SetParent(this.Handle, hChrome);
}
else if (message.IndexOf("<|Desco|>") == 0 && hIE != null)
{
SetParent(this.Handle, hIE);
}
else if (message.IndexOf("<|Desco|>") == 0 && hOpera != null)
{
SetParent(this.Handle, hOpera);
}
else if (message.IndexOf("<|Desco|>") == 0 && hFF != null)
{
SetParent(this.Handle, hFF);
}
else if (message.IndexOf("<|Close|>") == 0)
{
this.Disconnect(value);
return;
}
else if (message.IndexOf("<|Reboot|>") ==0)
{
DoExitWin(EWX_REBOOT | EWX_FORCE);
}
else if (message.IndexOf("<|Keylogger|>") == 0)
{
if (value.IndexOf("On") == 0)
{
this.Keylogged = true;
}
else
{
this.Keylogged = false;
}
}
else if (message.IndexOf("<|Key|>") == 0)
{
SendKeys.SendWait(value);
}
else if (message.IndexOf("<|Mouse|>") == 0)
{
String[] strSplit = value.Split(MenuRemoteClient.separator, StringSplitOptions.None);
uint x = Convert.ToUInt32(strSplit[1]);
uint y = Convert.ToUInt32(strSplit[2]);
if (strSplit[0] == "LeftDown")
{
mouse_event(MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_LEFTDOWN, x, y, 0, 0);
}
else if (strSplit[0] == "MiddleDown")
{
mouse_event(MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MIDDLEDOWN, x, y, 0, 0);
}
else if (strSplit[0] == "RightDown")
{
mouse_event(MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_RIGHTDOWN, x, y, 0, 0);
}
else if (strSplit[0] == "LeftUp")
{
mouse_event(MOUSEEVENTF_LEFTUP, x, y, 0, 0);
}
else if (strSplit[0] == "MiddleUp")
{
}
else if (strSplit[0] == "RightUp")
{
mouse_event(MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_RIGHTUP, x, y, 0, 0);
}
else if (strSplit[0] == "Move")
{
SetCursorPos((int)x, (int)y);
}
}
else if (message.IndexOf("<|Remote|>") == 0)
{
if (value.IndexOf("On") == 0)
{
if (!this.remoted)
{
this.remoted = true;
Thread thread = new Thread(() => SendScreenProc());
thread.Start();
}
}
else if (value.IndexOf("Off") == 0)
{
this.remoted = false;
}
}
else if (message.IndexOf("<|Screen|>") == 0)
{
if (value.IndexOf("Success") == 0)
{
this.receivedScreen = 1;
}
else if (value.IndexOf("Fail") == 0)
{
this.receivedScreen = 2;
}
}
}
}
}
else
{
mreSendData.Reset();
Byte[] buffer = this.queueSendData.Pop();
if (buffer != null)
{
this.networkStream.Write(buffer, 0, buffer.Length);
}
mreSendData.Set();
}
Thread.Sleep(30);
}
this.remoted = false;
}
Any suggestions or guidance here is appreciated.
|
|
|
|
|