- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
string log;
...
try
{
Logger.SaveLog(fullPath, log);
}
catch (Exception ex)
{
Logger.SaveLog(fullPath, ex.ToString());
}
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+141
string log;
...
try
{
Logger.SaveLog(fullPath, log);
}
catch (Exception ex)
{
Logger.SaveLog(fullPath, ex.ToString());
}
Senior developer...
+142
public void AllocateMemory(ref int[] segmentSizeProcess)
{
int[] difference;
int j = 0;
int tempo = 0;
for (int i = 0; i < segmentSizeProcess.Count(); i++)
{
difference = new int[memory.Count]; // храним разность размера блока памяти и требуемого размера для процесса
for (int count = 0; count < memory.Count; count++)
{
difference[count] = -2; // предварительно инициализируем
}
for (int count_memory=0; count_memory<memory.Count();
count_memory++)
{
if (memory[count_memory].size - segmentSizeProcess[i] >= 0) // если равно 0, значит
// сегмент полностью распределён
{
if (!memory[count_memory].isAllocate)
{ difference[count_memory] = memory[count_memory].size - segmentSizeProcess[i]; }
else
{ difference[count_memory] = -1; } // если сегмент занят -
// то он недоступен
}
}
tempo = GetMinDifference(ref difference); // получаем индекс минимальной разности
// если результат "-", значит секторы заняты, выходим из цикла
if (difference[tempo] >= 0)
{
memory.ElementAt(tempo).isAllocate = true; // процесс занял сегмент
if (difference[tempo] > 0) // если остаётся фрагмент памяти
{
CreateDifferenceSegment(difference[tempo]); // создаем новый сегмент, равный
// наименьшей разности памяти сегмента и памяти для процесса
}
memory[tempo].size = segmentSizeProcess[i]; // распределяем память
}
else
{
break;
}
}
}
Примерная реализация алгоритма best-fit
+142
public class Generator
{
private Random R = new Random();
public Generator()
{
}
public int GetNumber(int left, int right)
{
return R.Next(left, right);
}
}
Полезный класс
+143
System.String origString;
System.Int32 index;
System.Console.WriteLine("Введите строку: ");
origString = System.Console.ReadLine();
System.Int32 length = 0;
for (int i = 0; i < origString.Length; i++)
length++;
System.Console.WriteLine("Какую букву вычесть?: ");
index = System.Console.Read() - 49;
System.Char[] newString = new System.Char[origString.Length];
for (int i = 0; i < length; i++)
{
if (i != index && index != i && i != null && index != null)
{
newString[i] = origString[i];
}
if (i == index && index == i && i != null && index != null)
{
newString[i] = Convert.ToChar(7);
}
}
System.Console.Write("Результат: ");
length = 0;
for (int i = 0; i < newString.Length; i++)
length++;
for(int i = 0; i < length; i++)
System.Console.Write(newString[i]);
System.Console.ReadLine();
System.Console.ReadLine();
Ответ на вопрос на toster.ru
Как сделать это на c#?
Вычеркните i-ю букву заданной строки
https://toster.ru/q/222727
+142
var leftDate = GetAll().Select(i => i.SaveDateTime).OrderBy(i => i).FirstOrDefault();
var rigthDate = GetAll().Select(i => i.SaveDateTime).OrderByDescending(i => i).FirstOrDefault();
// 1e7 - количество тактов в секунде (а в итоге: проверка разницы в неделю)
while (rigthDate.Ticks - leftDate.Ticks > 1e7 * 60 * 60 * 24 * 7)
{
....................................
}
с точностью до тика.
+142
using (new MPI.Environment(ref args))
{
//Эта программа для MPI. Внешний алгоритм
System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
stopwatch.Start();
Intracommunicator world = Communicator.world;
if (world.Rank == 0)
{
RightRectangleSubDomain(horror, world);
LeftRingSubdomain(dolor, world);
world.Barrier();
SendArthas(dolor, world);
RecvKelthuzad(kelthuzad, world);
}
if (world.Rank == 1)
{
LeftRectangleSubDomain(pavor, world);
RightRingSubdomain(tristicia, world);
world.Barrier();
SendKelthuzad(tristicia, world);
RecvArthas(arthas, world);
}
stopwatch.Stop();
Console.WriteLine("Elapsed time: {0}", stopwatch.ElapsedMilliseconds);
}
Очень сильно напугала лабораторная, что отразилось на названиях переменных. Да и сам файл был назван MPITenebris.
+142
return optionsBackButtonCommand ?? ((Func<RelayCommand>)(() =>
optionsBackButtonCommand = new RelayCommand(param =>
RandomMethod() )))();
Сам придумал. "Изящно" обошел использование if.
+144
string q = DateTime.Now.ToString().Substring(3, 3);
string w = DateTime.Now.ToString().Substring(0, 2);
string e = DateTime.Now.ToString().Substring(5, DateTime.Now.ToString().Length - 5);
string dsasd = q + w + e;
CrmDateTimeProperty _new_date_fitst_update_rstatus = new CrmDateTimeProperty();
_new_date_fitst_update_rstatus.Name = "new_date_first_update_rstatus";
_new_date_fitst_update_rstatus.Value = new CrmDateTime();
_new_date_fitst_update_rstatus.Value.Value = dsasd;
dynamicEntity.Properties.Add(_new_date_fitst_update_rstatus);
Попался проект на фрилансе. Попросили исправить ошибки. Начал исправлять и вот такое.
+142
// ...
Action updatingLoadedItemsList = null;
foreach (Item loadedItem in loadedItems)
if (loadedItem.Id == currentItem.Id)
updatingLoadedItemsList = () => loadedItems.RemoveAt(loadedItems.IndexOf(loadedItem));
if(updatingLoadedItemsList != null)
updatingLoadedItemsList.Invoke();
// ...
+141
private List<string> urls = new List<string>();
private int urls_index = -1;
private ProgressBar pb = new ProgressBar()
{
Width = 291,
Height = 26,
Maximum = 100,
Minimum = 0,
Location = new Point(12, 41)
};
public Object SyncIndex = new Object();
public void DownLoad(object index)
{
int indexwhile = (int) index;
while (work)
{
int localIndex;
lock (SyncIndex)
{
urls_index++;
localIndex = urls_index;
}
WebClient webClient = new WebClient();
try
{
webClient.DownloadFile(new Uri(urls[localIndex]), "img/" + localIndex + ".jpg");
webClient.DownloadProgressChanged += (s, a) => Invoke(new Action(() => {progressBars[indexwhile].Value = a.ProgressPercentage;}));
}
catch (Exception exception)
{
Invoke(new Action(() =>
{
listBox2.Items.Add("Ошибка" + listBox1.Items[localIndex]);
}));
DownLoad(index);
}
Invoke(new Action(() =>
{
listBox1.Items[localIndex] = "Загружен" + listBox1.Items[localIndex];
label1.Text = urls.Count.ToString();
richTextBox1.Text += localIndex + @".jpg Загружен" + Environment.NewLine;
}));
Thread.Sleep(500);
}
}
private void button2_Click(object sender, EventArgs e)
{
work = true;
Thread[] threads = new Thread[30];
for (int i = 0; i < 20; i++)
{
int mnoj = i + 1;
progressBars[i] = new ProgressBar()
{
Width = 291,
Height = 26,
Maximum = 100,
Minimum = 0,
Location = new Point(12, 41)
};
progressBars[i].Location = new Point(12, 41 * mnoj);
Controls.Add(progressBars[i]);
threads[i] = new Thread(DownLoad);
threads[i].IsBackground = true;
threads[i].Start(i);
}
}
И все в одной форме..