|
|
Message Closed
modified 9-May-17 6:10am.
|
|
|
|
|
Can any one suggest a better way to identify the redundant code in a class using c# code.
For Example:
Method1() body had some other method calls
Method2() body had few more other method calls including the methods in Method1().
In this case i have to identify that the method1() had the redundant code. I need to comment that.
Suggest me the best answer.
|
|
|
|
|
The only way to be sure is to understand exactly what the code is doing. There may be good logical reasons why some code is duplicated in a program.
|
|
|
|
|
Application has the legacy code.I want to remove that code.Can you suggest the better approach
|
|
|
|
|
How better? There is no automatic method of deciding what code to remove.
|
|
|
|
|
WinDiff - Wikipedia
"(I) am amazed to see myself here rather than there ... now rather than then".
― Blaise Pascal
|
|
|
|
|
Below is a program that selects the coefficients and corresponds to the result. After that sorting is performed for the statement.
Initially the program calculated the coefficient from 10%.
I tried to change the accuracy by 2%. The result turned out to be bad - the time for selecting the coefficients was greatly increased.
The question is:
Can other methods be used to speed up the finding of the result. And how fast can the program work?
Maybe someone already faced a similar problem?
Below is the code of the program
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Flerov.PortfolioOptimizer
{
class Program
{
[STAThread]
static void Main(string[] args)
{
var dlg = new OpenFileDialog();
if (dlg.ShowDialog() != DialogResult.OK)
return;
var input = File.ReadAllLines(dlg.FileName).Skip(2).Select(line =>
{
var res = line.Split(';');
var date = DateTime.ParseExact(res[0], "dd.MM.yyyy", (IFormatProvider)CultureInfo.InvariantCulture);
var data = res.Skip(1).Select(decimal.Parse).ToArray();
return new Tuple<DateTime, decimal[]>(date, data);
}).ToArray();
var count = input.First().Item2.Length;
var allKkoefs = new List<decimal>();
for (decimal i = 0; i <= 1; i += 0.02m)
{
allKkoefs.Add(i);
}
var listResult = new List<Tuple<decimal[], decimal>>();
var permutation = allKkoefs.Permutations(count).Select(p => p.ToArray()).Where(p => p.Sum() == 1).ToArray();
foreach (var k in permutation)
{
var koefs = k.ToArray();
var sum = input.Select(p => p.Item2.Zip(koefs, (arg1, arg2) => arg1*arg2).Sum()).ToArray();
var avg = sum.Average();
var std = sum.StandardDeviation(avg);
if (std == 0) std = 1;
var res = (decimal) (avg/std);
listResult.Add(new Tuple<decimal[], decimal>(koefs, res));
}
var best = listResult.OrderByDescending(p => p.Item2).Take(30).ToArray();
var header = "value;";
for (int i = 1; i <= count; i++)
{
header += "koef" + i + ";";
}
File.WriteAllLines(dlg.FileName + ".result.csv", new[]{header});
File.AppendAllLines(dlg.FileName + ".result.csv", best.Select(i => string.Format("{0};{1}", i.Item2,
i.Item1.Aggregate("", (s, arg2) => s+arg2+";"))));
}
}
static class Helper
{
public static decimal StandardDeviation(this ICollection<decimal> num, decimal? avg)
{
if (num.Count == 1)
return num.First();
if (avg == null)
avg = num.Average();
var sumOfSqrs = num.Sum(t => Math.Pow((double)(t - avg.Value), 2));
var n = num.Count;
return (decimal)Math.Sqrt(sumOfSqrs / (n - 1));
}
public static IEnumerable<IEnumerable<T>> Permutations<T>(this IEnumerable<T> pool, int selectionSize)
{
var idxs = new int[selectionSize];
var pl = pool.ToArray();
var length = pl.Length;
do
{
yield return GetItems(pl, idxs, selectionSize);
GetNextPermutation(idxs, selectionSize, length);
} while (idxs[0] < length);
}
private static void GetNextPermutation(IList<int> idxs, int selectionSize, int poolSize)
{
var position = selectionSize - 1;
idxs[position]++;
while (idxs[position] == poolSize && position > 0)
{
idxs[position - 1]++;
for (var i = position; i < selectionSize; i++)
idxs[i] = 0;
position--;
}
}
private static IEnumerable<T> GetItems<T>(IList<T> items, IList<int> idxs, int length)
{
for (var i = 0; i < length; i++)
yield return items[idxs[i]];
}
}
}
|
|
|
|
|
This program here plays a small question game over the network, it's multi-threading and is of course based on a server and a client. It's written in C# using windows forms for the client and just console for the server.
I have a problem when the client writes to the server when the user press on enter. On line 70 I try to write to the server but it seems that the connection is somehow closed before I do so because I get the following error:
System.IOEndOfStreamException: Unable to read beyond the end of the stream.
at System.IO.BinaryReader.ReadByte()
at System.IO.BinaryReader.7BitEncodedInt()
at System.IO.BinaryReader.ReadString()
at question_game_client.Form1.RunCLient() in somepath:line 112
When I press enter in the textbox it's supposed to write to the server and it does but it does it twice and the client crashes with the error above.
Client:
using System;
using System;
using System.Windows.Forms;
using System.Threading;
using System.Net.Sockets;
using System.IO;
namespace question_game_client
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private NetworkStream output;
private BinaryWriter writer;
private BinaryReader reader;
private Thread readThread;
private string message = "";
private void Form1_Load(object sender, EventArgs e)
{
readThread = new Thread(new ThreadStart(RunClient));
readThread.Start();
}
private void Form1_FormClosing(object sender,
FormClosingEventArgs e)
{
}
private delegate void DisplayDelegate(string message);
private void DisplayMessage(string message)
{
if (displayTextBox.InvokeRequired)
{
Invoke(new DisplayDelegate(DisplayMessage),
new object[] { message });
}
else
displayTextBox.Text += message;
}
private delegate void DisableInputDelegate(bool value);
private void inputTextBox_KeyDown(object sender, KeyEventArgs e)
{
try
{
if (e.KeyCode == Keys.Enter && inputTextBox.ReadOnly == false)
{
writer.Write(inputTextBox.Text);
inputTextBox.Clear();
}
}
catch (SocketException)
{
displayTextBox.Text += "\nError writing object";
}
}
public void RunClient()
{
TcpClient client;
try
{
client = new TcpClient();
client.Connect("127.0.0.1", 8190);
output = client.GetStream();
writer = new BinaryWriter(output);
reader = new BinaryReader(output);
do
{
try
{
DisplayMessage("\r\n" + message);
message = reader.ReadString();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
} while (message != "SERVER>>> TERMINATE");
writer.Close();
reader.Close();
output.Close();
client.Close();
}
catch (Exception error)
{
MessageBox.Show(error.ToString(), "Connection Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void inputTextBox_TextChanged(object sender, EventArgs e)
{
}
}
}
Server:
using System;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Collections.Generic;
using System.IO;
namespace question_game_server
{
class Program
{
private Socket connection;
private int port = 8190;
private Random rand = new Random();
string message = null;
string answer = null;
static void Main(string[] args)
{
new Program().Run();
}
void Run()
{
new Thread(RunServer).Start();
getquestions();
}
public void RunServer()
{
Thread readThread;
bool done = false;
TcpListener listener;
try
{
listener = new TcpListener(IPAddress.Any, port);
listener.Start();
Console.WriteLine("Waiting for connection ...");
while (!done)
{
connection = listener.AcceptSocket();
readThread = new Thread(GetMessages);
readThread.Start();
}
}
catch (Exception)
{
Console.WriteLine("Port " + port + " may be busy. Try another.");
}
}
public string getquestions()
{
int countquestions;
int random_question_val;
try
{
using (StreamReader sr = new StreamReader("questions_and_answers.txt"))
{
String line = sr.ReadToEnd();
string[] questions_and_answers = line.Split(';');
countquestions = questions_and_answers.Length-1;
random_question_val = rand.Next(0, (countquestions));
Console.WriteLine(random_question_val);
string[] question_and_answer = questions_and_answers[random_question_val].Split(':');
Console.WriteLine("Answer:"+question_and_answer[1]);
answer = question_and_answer[1];
sr.Close();
return question_and_answer[0];
}
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
return null;
}
}
public void GetMessages()
{
Socket socket = connection;
NetworkStream socketStream = null;
BinaryWriter writer = null;
BinaryReader reader = null;
try
{
socketStream = new NetworkStream(socket);
reader = new BinaryReader(socketStream);
writer = new BinaryWriter(socketStream);
Console.WriteLine("Connection successful.\n");
writer.Write(getquestions());
message = reader.ReadString();
Console.WriteLine(message);
if (answer == message)
{
writer.Write("Correct Answer!");
Console.WriteLine(message);
}
if (answer != message && message != null)
{
Console.WriteLine(message);
writer.Write("Wrong Answer!");
}
}
catch (Exception error)
{
Console.WriteLine(error.ToString());
}
finally
{
reader.Close();
writer.Close();
socketStream.Close();
socket.Close();
}
Console.ReadKey();
}
}
}
I guess it has a very simple explanation, I just can't see it. The only thing I know that this happens when I try to write to the server and the program is complaining about some reading issues. So what's wrong?
[edit]Code block added - OriginalGriff[/edit]
modified 8-May-17 3:38am.
|
|
|
|
|
Edit your post and put the code between code tags, like so: (This preserves the formatting.) Also, just include the portion of the code that is giving the problem. Nobody is going to wade through tons of code.
if (answer != message && message != null)
{
Console.WriteLine(message);
writer.Write("Wrong Answer!");
}
The difficult we do right away...
...the impossible takes slightly longer.
|
|
|
|
|
I converted you code to code block, as Richard suggested - but I'm not looking at that lot of uncommented code trying to work out what you might have done or why!
Help us to help you: edit your post and show us just the relevant code fragments, tell us which line it occurs on, and explain what you have tried to find and find the problem. Remember, we can't run your code here under the same circumstances you do as we have no idea what you are doing - so you need to give us the relevant info (without being lazy and dumping everything on us).
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Hi
I have
selling point
i want Create Dynamic buttons win app c#
with my table Items database sql server2008 R2
and Get value GUID win I click in buttons
|
|
|
|
|
And what have you tried to do to achieve that?
|
|
|
|
|
Share what you have tried and what issue you are facing on this...
modified 20-Sep-20 21:01pm.
|
|
|
|
|
How I can put selling buttons in my interface to put in them my materials
private void DisplayData5()
{
con.Open();
DataTable dt5 = new DataTable();
adapt = new SqlDataAdapter("select * from MER where GUID = '" + listBox1.SelectedValue.ToString() + "' order by NUBER ", con);
adapt.Fill(dt5);
listBox2.DataSource = dt5;
listBox2.DisplayMember = "NAME";
listBox2.ValueMember = "GUID1";
con.Close();
}
// insert materials
private void listBox2_MouseClick(object sender, MouseEventArgs e)
{
try
{
con.Open();
SqlCommand cmd3 = new SqlCommand(" insert into SellingPoint (GUID, MONY,MONY1,NAME,NUBER,COUNT) select GUID1,MONY,MONY1,NAME,'" + txt_Number.Text + "', '" + textBox2.Text + "' from MER where GUID1 = '" + listBox2.SelectedValue + "' ", con);
cmd3.ExecuteNonQuery();
con.Close();
sum();
textBox7.Text = textBox4.Text;
DisplayData();
number();
textBox2.Text = "1";
}
catch
{
MessageBox.Show("77");
con.Close();
}
}
|
|
|
|
|
|
1- Write a class Counter include a method preincrement() that increments a
private variable count and a method predecrement() that decrements a data member count but only using prefix notation. Using inheritance, add the ability to use postfix notation for both incrementing and decrementing. In the main method call all the methods from the object of child class
modified 6-May-17 17:57pm.
|
|
|
|
|
First you do some research into prefix notation, what a weird concept!
The you start writing the code for the classes required to meet your homework requirement.
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
Do you know what prefix notation is? Do you know what postfix notation is? Do you know what inheritance is? Combine these to get your answer.
This space for rent
|
|
|
|
|
gentle reader: please recall this forum is also intended to be a C# language discussion forum. Yes, it may have evolved into a kind of parallel QA forum, but, I hope it is still a place for some exchanges around language features, and issues.
I'd guess most of us have noticed at some time there's no lexical qualifier for Types 'short or 'byte, like there are for 'long, 'double, etc. ... and wondered why ... even looked for a "why" ... perhaps come across Eric Lippert's standard why-no-feature rationale: "... because no one ever designed, implemented, tested and shipped that feature. More specifically: why should there be?"
Big-deal: you gotta cast, or specify Type, and these are compile-time operations:
var brain = (short) 3;
short damage = 222; However, today, while exploring 'BitVector32, I came across this:
> ? ((short)1) << 2
4
> ? ((short)1) << 2 is short
false
> ? ((short)1) << 2 is int
true
> ? ((long)1) << 2
4
> ? ((long)1) << 2 is long
true
> ? ((long)1) << 2 is int
false
> ? ((uint)1) << 2
4
> ? ((uint)1) << 2 is uint
true
> ? ((uint)1) << 2 is int
false
> I conclude bit-shifts cast a 'short to an 'int": ergo they are not short-shifted. Of course, I would never dare think the language designers were short-sighted !
fyi: the largest possible 'BitVector32.Section size is 0x7FFF (15 bits).
«When I consider my brief span of life, swallowed up in an eternity before and after, the little space I fill, and even can see, engulfed in the infinite immensity of spaces of which I am ignorant, and which know me not, I am frightened, and am astonished at being here rather than there; for there is no reason why here rather than there, now rather than then.» Blaise Pascal
|
|
|
|
|
Quote: I conclude bit-shifts cast a 'short to an 'int" What does this (I'm not very firm in C# and can't test it here):
? ((short)1) << ((short)2) is short When this is true it might not be the bit-shift but the common rule that the largest operand type defines the result type.
Or are short operations always executed as int and converted to short afterwards when requested?
|
|
|
|
|
There is an implicit conversion going on in your shift code. To achieve a short result, you would have to do the following:
(short)(1 << 2) To test which part of the operation is causing the conversion, you can use the following
((short)1) << ((short)2) is short; This will return false, telling us that the << operator is returning the int.
This space for rent
|
|
|
|
|
I conclude bit-shifts cast a 'short to an 'int"
That is true. It also applies to all other arithmetic and bitwise operators. It happens because there are no pre-defined operators for them, for example the list of pre-defined left shift operators is, according to ECMA 364:
Quote: int operator <<(int x, int count);
uint operator <<(uint x, int count);
long operator <<(long x, int count);
ulong operator <<(ulong x, int count);
(note also that all shift counts are int )
Since an implicit conversion exists from short to int , you can still write someShort << k and it will pick the first overload and insert an implicit conversion.
As for why, I suspect this is a case of "because C does it and there was not enough reason to change it". Personally I don't like it, I would have preferred the extra overloads to exist, I find that most of the time when I work with a narrow type it is either widened immediately upon loading it (which without this implicit conversion could still use the implicit conversion that happens when assigning it to a temporary variable) or it has to stay narrow forever (which would become a lot less messy by changing it from C-style to "all the overloads").
A commonly cited non-reason is that, supposedly, "processors are optimized for their word size". But they aren't really, and "word size" is a badly defined can of worms to begin with. Even for "problematic cases" such as 16bit arithmetic on x86, x64, MIPS and a bunch of others, it would be completely trivial for the compiler to do the math in 32bit as much as possible and only insert the bare minimum of operations required to keep the range down to 16bits. Most operations don't propagate information from the msb down to the lsb, so you can work with "crap in the higher bits" without it affecting anything until one of the exceptions to the rule is encountered (division, right shift, comparison, function call).
As a bonus for "future work", keeping calculations narrow would make it easier to auto-vectorize effectively. The amount of parallelism is SIMDwidth / elementsize so the element size should be as small as possible. Not that the .NET JIT compiler does much auto-vectorization, but it could, and with the auto-widening semantics as they are it takes extra analysis to narrow everything back down again and keep the parallelism up. Even ahead-of-time compilers are still pretty bad at that, often taking the simple route of vectorizing the code extremely literally, including all useless widening and subsequent narrowing.
modified 5-May-17 9:16am.
|
|
|
|
|
Thanks, Harold; that's just the type of informative response I was hoping for !
It intrigues me why the BitVector32.Section designers made the c'tor size parameter a signed short, limiting you to 0x7FFF: there is no barrier to using the entire 32 bits; for example:
BitVector32.Section s0 = BitVector32.CreateSection(0xFF);
BitVector32.Section s1 = BitVector32. CreateSection(0xFF, s0);
BitVector32.Section s2 = BitVector32.CreateSection(0xFF, s1);
BitVector32.Section s3 = BitVector32.CreateSection(0xFF, s2);
BitVector32 BvValue = new BitVector32();
BvValue[s0] = 0xFFFF;
BvValue[s1] = 0xFFFF;
BvValue[s2] = 0xFFFF;
BvValue[s3] = 0xFFFF;
«When I consider my brief span of life, swallowed up in an eternity before and after, the little space I fill, and even can see, engulfed in the infinite immensity of spaces of which I am ignorant, and which know me not, I am frightened, and am astonished at being here rather than there; for there is no reason why here rather than there, now rather than then.» Blaise Pascal
|
|
|
|
|
Well, I don't know that one. It does make the Section type a nicely round 4 bytes instead of something slightly bigger that would be padded to 8.. that doesn't sound like sufficient motivation but it's the only thing I can think of.
Frankly I find most of the design of BitVector32 strange and generally more painful than manipulating bits manually, it seems to me more like an attempt to make bitfields "more objecty" than a legitimately useful tool, but I'm biased because I work with bits so much.
|
|
|
|
|