Whiteboy
Whiteboy
CC#
Created by Whiteboy on 4/24/2024 in #help
✅ Executing bash script in docker container with Docket.DotNet in ASP.NET website
No description
121 replies
CC#
Created by Whiteboy on 3/19/2024 in #help
Read process RAM usage in real time from docker container using c#
So i have web app in asp.net that user Docker.dotnet to run some things in docker containers and i need to read memory of some process inside the container. How can i do it? it has to be in real time tho
2 replies
CC#
Created by Whiteboy on 2/8/2024 in #help
✅ Submit form just once, disabling the button breaks form submition
So i need to submit form just once and the submitions takes about 3-5s, how can i prevent user from spamming the button (it creates huge load on server if he spams 100cps) if i wrote simple JS to disable the button after clicking it doesn't submit the form
<form method="post" asp-page-handler="SubmitCode" asp-route-assignmentId="@Model.Assignment.AssignmentId">
<div align="center">
<textarea id="UserCode" name="UserCode" class="form-control" style="resize: vertical; width: 98%;" rows="20" placeholder="Enter your code here"></textarea>
</div>
<div style="margin-right: 1%; margin-bottom: 1%; margin-top: 1%" align="right">
<button id="SubmitCode" type="submit" name="action" value="SubmitCode" class="btn btn-primary" disabled>Submit</button>
</div>
</form>
<form method="post" asp-page-handler="SubmitCode" asp-route-assignmentId="@Model.Assignment.AssignmentId">
<div align="center">
<textarea id="UserCode" name="UserCode" class="form-control" style="resize: vertical; width: 98%;" rows="20" placeholder="Enter your code here"></textarea>
</div>
<div style="margin-right: 1%; margin-bottom: 1%; margin-top: 1%" align="right">
<button id="SubmitCode" type="submit" name="action" value="SubmitCode" class="btn btn-primary" disabled>Submit</button>
</div>
</form>
5 replies
CC#
Created by Whiteboy on 1/30/2024 in #help
✅ MySQL with Entity Framework, getting null of entity all time
public class UserAssignmentDate
{
[ForeignKey("UserId")]
public int UserId { get; set; }

[ForeignKey("AssignmentId")]
public int AssignmentId { get; set; }

public DateTimeOffset AssignmentTime { get; set; }
public DateTimeOffset DeadLineDateTime { get; set; }
public DateTimeOffset LastUploadDateTime { get; set; }
public TimeSpan TimeToNextUpload { get; set; }

// Navigation properties
public User User { get; set; }
public Assignment Assignment { get; set; }
}
public class UserAssignmentDate
{
[ForeignKey("UserId")]
public int UserId { get; set; }

[ForeignKey("AssignmentId")]
public int AssignmentId { get; set; }

public DateTimeOffset AssignmentTime { get; set; }
public DateTimeOffset DeadLineDateTime { get; set; }
public DateTimeOffset LastUploadDateTime { get; set; }
public TimeSpan TimeToNextUpload { get; set; }

// Navigation properties
public User User { get; set; }
public Assignment Assignment { get; set; }
}
var userAssignmentDate = await dbContext.UserAssignmentDates
.FirstOrDefaultAsync(userAssignmentDate => userAssignmentDate.UserId == UserId && userAssignmentDate.AssignmentId == assignmentId);
var userAssignmentDate = await dbContext.UserAssignmentDates
.FirstOrDefaultAsync(userAssignmentDate => userAssignmentDate.UserId == UserId && userAssignmentDate.AssignmentId == assignmentId);
foreach (int userId in userIds)
{
var userAssignmentDate = new UserAssignmentDate
{
UserId = userId,
AssignmentId = assignmentId,
AssignmentTime = assignmentTime,
LastUploadDateTime = DateTimeOffset.MinValue,
};

dbContext.UserAssignmentDates.Add(userAssignmentDate);
}

await dbContext.SaveChangesAsync();
foreach (int userId in userIds)
{
var userAssignmentDate = new UserAssignmentDate
{
UserId = userId,
AssignmentId = assignmentId,
AssignmentTime = assignmentTime,
LastUploadDateTime = DateTimeOffset.MinValue,
};

dbContext.UserAssignmentDates.Add(userAssignmentDate);
}

await dbContext.SaveChangesAsync();
and userAssignmentDate returns null all time when UserId and AssignmentId are good values
26 replies
CC#
Created by Whiteboy on 1/24/2024 in #help
✅ EF with MySQL getting double/triple time values ?!
So i assign task to user and set the assignTime to DateTime.Now so i should be able to get remaining time right?
var userTaskAssignment = dbContext.UserTaskAssignments.FirstOrDefault(assignment => assignment.TaskId == taskId && assignment.UserId == UserId);
if (userTaskAssignment != null)
{
RemainingTime = userTaskAssignment.TimeToCompleteTask - DateTime.Now;
RemainingHours = RemainingTime.TotalHours;
RemainingMinutes = RemainingTime.TotalMinutes;
RemainingSeconds = RemainingTime.TotalSeconds;
}
var userTaskAssignment = dbContext.UserTaskAssignments.FirstOrDefault(assignment => assignment.TaskId == taskId && assignment.UserId == UserId);
if (userTaskAssignment != null)
{
RemainingTime = userTaskAssignment.TimeToCompleteTask - DateTime.Now;
RemainingHours = RemainingTime.TotalHours;
RemainingMinutes = RemainingTime.TotalMinutes;
RemainingSeconds = RemainingTime.TotalSeconds;
}
private async Task<Task?> AssignTaskToUserIds(List<int> userIds, int taskId, TimeSpan taskLifespan)
{
DateTime assignmentTime = DateTime.Now;

foreach (int userId in userIds)
{
UserTaskAssignment userTaskAssignment = new UserTaskAssignment
{
UserId = userId,
TaskId = taskId,
AssignmentTime = assignmentTime,
};

dbContext.UserTaskAssignments.Add(userTaskAssignment);
}

await dbContext.SaveChangesAsync();

var assignedTasks = dbContext.UserTaskAssignments
.Where(uta => userIds.Contains(uta.UserId) && uta.TaskId == taskId)
.ToList();

foreach (var assignment in assignedTasks)
{
assignment.TimeToCompleteTask = assignment.AssignmentTime.Add(taskLifespan);
}

await dbContext.SaveChangesAsync();

PageHelper.SetTempDataSuccessMessage("Task assigned successfully", TempData);
return null;
}
private async Task<Task?> AssignTaskToUserIds(List<int> userIds, int taskId, TimeSpan taskLifespan)
{
DateTime assignmentTime = DateTime.Now;

foreach (int userId in userIds)
{
UserTaskAssignment userTaskAssignment = new UserTaskAssignment
{
UserId = userId,
TaskId = taskId,
AssignmentTime = assignmentTime,
};

dbContext.UserTaskAssignments.Add(userTaskAssignment);
}

await dbContext.SaveChangesAsync();

var assignedTasks = dbContext.UserTaskAssignments
.Where(uta => userIds.Contains(uta.UserId) && uta.TaskId == taskId)
.ToList();

foreach (var assignment in assignedTasks)
{
assignment.TimeToCompleteTask = assignment.AssignmentTime.Add(taskLifespan);
}

await dbContext.SaveChangesAsync();

PageHelper.SetTempDataSuccessMessage("Task assigned successfully", TempData);
return null;
}
For some reason when i set TimeToCompleteTask = 1h and i go to user i get 3h to complete task orr 1h 59min?
47 replies
CC#
Created by Whiteboy on 1/24/2024 in #help
✅ ASP.NET Fetch request to MySQL
So i want to chcek if typed login exisits in db but i get all time error 404
Error checking login existence: Error: HTTP error! Status: 404
at 3:176:31
(anonymous) @ 3:191
Promise.catch (async)
checkLoginExists @ 3:190
checkLogins @ 3:202
(anonymous) @ 3:208
Error checking login existence: Error: HTTP error! Status: 404
at 3:176:31
(anonymous) @ 3:191
Promise.catch (async)
checkLoginExists @ 3:190
checkLogins @ 3:202
(anonymous) @ 3:208
function checkLoginExists(login) {
fetch(`/AssignTask/{taskId}?handler=CheckLoginExists&login=${login}`, { method: 'GET' })
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.then(data => {
const loginErrorMessage = document.getElementById('loginErrorMessage');

if (!data.exists) {
loginErrorMessage.textContent = `User with login '${login}' not found in the database.`;
} else {
loginErrorMessage.textContent = ''; // Clear the error message
enableAssignButton();
}
})
.catch(error => {
console.error('Error checking login existence:', error);
// Handle the error, e.g., display a generic error message
});
}

function checkLogins(logins) {
let loginLines = logins.split("\n");

for (let i = 0; i < loginLines.length; i++) {
let login = loginLines[i].trim();
if (login !== "") {
checkLoginExists(login);
}
}
}
function checkLoginExists(login) {
fetch(`/AssignTask/{taskId}?handler=CheckLoginExists&login=${login}`, { method: 'GET' })
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.then(data => {
const loginErrorMessage = document.getElementById('loginErrorMessage');

if (!data.exists) {
loginErrorMessage.textContent = `User with login '${login}' not found in the database.`;
} else {
loginErrorMessage.textContent = ''; // Clear the error message
enableAssignButton();
}
})
.catch(error => {
console.error('Error checking login existence:', error);
// Handle the error, e.g., display a generic error message
});
}

function checkLogins(logins) {
let loginLines = logins.split("\n");

for (let i = 0; i < loginLines.length; i++) {
let login = loginLines[i].trim();
if (login !== "") {
checkLoginExists(login);
}
}
}
16 replies
CC#
Created by Whiteboy on 12/30/2023 in #help
ASP.NET file data not being saved in page
So i need to upload user list from .xslx file and displa yit in a table for adjustments, then send send the users to mySQL db, the problem i have is that after i upload file and try to send ti db the "ExtractedData" returns null
27 replies
CC#
Created by Whiteboy on 12/4/2023 in #help
ASP.NET HTTP ERROR 401 after deleting cookies
So i need to login users using authorization prompt and just get their logins, but when i tried to make a logout and cleared cookie data on site to try logging in with other account it stopped working (I get http error 401) Edit: I tested with other browser and the login works just file but i remain logged in even after not saving credentials and reopening the page. How do i fix it?
public class IndexModel : PageModel
{
public string Username { get; private set; }

public IActionResult OnGet()
{
string authHeader = Request.Headers["Authorization"];

if (!string.IsNullOrEmpty(authHeader) && authHeader.StartsWith("Basic "))
{
string base64Credentials = authHeader.Substring("Basic ".Length).Trim();
string credentials = Encoding.UTF8.GetString(Convert.FromBase64String(base64Credentials));

string[] parts = credentials.Split(':');
Username = parts[0];

return Page();
}

// If no valid authentication header, return a challenge response to prompt for credentials
Response.Headers["WWW-Authenticate"] = "Basic realm=\"My Realm\"";
return new UnauthorizedResult();
}
}
public class IndexModel : PageModel
{
public string Username { get; private set; }

public IActionResult OnGet()
{
string authHeader = Request.Headers["Authorization"];

if (!string.IsNullOrEmpty(authHeader) && authHeader.StartsWith("Basic "))
{
string base64Credentials = authHeader.Substring("Basic ".Length).Trim();
string credentials = Encoding.UTF8.GetString(Convert.FromBase64String(base64Credentials));

string[] parts = credentials.Split(':');
Username = parts[0];

return Page();
}

// If no valid authentication header, return a challenge response to prompt for credentials
Response.Headers["WWW-Authenticate"] = "Basic realm=\"My Realm\"";
return new UnauthorizedResult();
}
}
8 replies
CC#
Created by Whiteboy on 11/28/2023 in #help
Testing Coding Plagiarisms C# CPP Java
So im making a website in ASP.NET that creates tests for coding questions and need to test plagiarized inputs, i've made a good one for c# but i still need one for Java and CPP and couldn't manage to do so for a while. Can you reccomend any lib or something i can use for other languages? Mostly to tokenize the code. I've also tried using ANTLR4 but i couldn't figure it much. My work so far: https://github.com/Whiteboy92/TestPlagiarismCA
19 replies
CC#
Created by Whiteboy on 11/3/2023 in #help
❔ ✅ Coding Test Website in ASP.NET
No description
97 replies
CC#
Created by Whiteboy on 7/2/2023 in #help
Timer not working
So i want a simple timer for my WPF app so i can run a Update each second but it sends an update every 2-3s instead how do i fix it?
private void StartUpdateLoop()
{
updateTimer = new Timer(Update, null, TimeSpan.Zero, TimeSpan.FromSeconds(1));
}
private void StartUpdateLoop()
{
updateTimer = new Timer(Update, null, TimeSpan.Zero, TimeSpan.FromSeconds(1));
}
public MainWindow()
{
InitializeComponent();
StartUpdateLoop();
}
public MainWindow()
{
InitializeComponent();
StartUpdateLoop();
}
private void Update(object? state)
{
elapsedTime++;
if (elapsedTime % 3 == 0)
{
IncreaseCurrentMoney(power1Output);
}
if (elapsedTime % 9 == 0)
{
IncreaseCurrentMoney(power2Output);
}
if (elapsedTime % 27 == 0)
{
IncreaseCurrentMoney(power3Output);
}
if (elapsedTime % 81 == 0)
{
IncreaseCurrentMoney(power4Output);
}
if (elapsedTime % 273 == 0)
{
IncreaseCurrentMoney(power5Output);
}
}

private void IncreaseCurrentMoney(double amount)
{
lock (this)
{
currentMoney += amount;
LbCurrentMoney.Content = $"{currentMoney}$";
}
}
private void Update(object? state)
{
elapsedTime++;
if (elapsedTime % 3 == 0)
{
IncreaseCurrentMoney(power1Output);
}
if (elapsedTime % 9 == 0)
{
IncreaseCurrentMoney(power2Output);
}
if (elapsedTime % 27 == 0)
{
IncreaseCurrentMoney(power3Output);
}
if (elapsedTime % 81 == 0)
{
IncreaseCurrentMoney(power4Output);
}
if (elapsedTime % 273 == 0)
{
IncreaseCurrentMoney(power5Output);
}
}

private void IncreaseCurrentMoney(double amount)
{
lock (this)
{
currentMoney += amount;
LbCurrentMoney.Content = $"{currentMoney}$";
}
}
25 replies
CC#
Created by Whiteboy on 6/15/2023 in #help
❔ Fast Fourier Transform. I need to make app displaying image and result like ImageJ
10 replies
CC#
Created by Whiteboy on 4/18/2023 in #help
❔ Check pixel intensity along a line in image
so i made this funcion that should do it but i get this weird error
private void DrawProfileLane()
{
// load image and convert to grayscale
Image<Bgr, byte> image = new Image<Bgr, byte>("path/to/image.jpg");
Image<Gray, byte> grayImage = image.Convert<Gray, byte>();

// check that both points are defined
if (_firstPoint == null || _secondPoint == null)
{
return;
}

// define line between two points
Point firstPoint = _firstPoint.Value;
Point secondPoint = _secondPoint.Value;
LineSegment2D line = new LineSegment2D(firstPoint, secondPoint);
float dx = line.Direction.X;
float dy = line.Direction.Y;
double length = line.Length;

// get pixel intensity values along the line using a parallel for loop
int[] intensities = new int[(int)length];
Parallel.For(0, (int)length, i =>
{
Point pointOnLine = new Point((int)(firstPoint.X + i * dx / length), (int)(firstPoint.Y + i * dy / length));
intensities[i] = grayImage.Data[(int) pointOnLine.Y, (int) pointOnLine.X, 0];
});

// create plot and add data
double[] intensitiesDouble = intensities.Select(x => (double)x).ToArray();
WpfPlot plot = new WpfPlot();
plot.Plot.AddSignal(intensitiesDouble);

// create and show window
ProfileLaneWindow profileLaneWindow = new ProfileLaneWindow
{
Title = $"Profile Lane Plot of {Title}",
ProfileLanePlot = plot,
};
profileLaneWindow.Show();
}
private void DrawProfileLane()
{
// load image and convert to grayscale
Image<Bgr, byte> image = new Image<Bgr, byte>("path/to/image.jpg");
Image<Gray, byte> grayImage = image.Convert<Gray, byte>();

// check that both points are defined
if (_firstPoint == null || _secondPoint == null)
{
return;
}

// define line between two points
Point firstPoint = _firstPoint.Value;
Point secondPoint = _secondPoint.Value;
LineSegment2D line = new LineSegment2D(firstPoint, secondPoint);
float dx = line.Direction.X;
float dy = line.Direction.Y;
double length = line.Length;

// get pixel intensity values along the line using a parallel for loop
int[] intensities = new int[(int)length];
Parallel.For(0, (int)length, i =>
{
Point pointOnLine = new Point((int)(firstPoint.X + i * dx / length), (int)(firstPoint.Y + i * dy / length));
intensities[i] = grayImage.Data[(int) pointOnLine.Y, (int) pointOnLine.X, 0];
});

// create plot and add data
double[] intensitiesDouble = intensities.Select(x => (double)x).ToArray();
WpfPlot plot = new WpfPlot();
plot.Plot.AddSignal(intensitiesDouble);

// create and show window
ProfileLaneWindow profileLaneWindow = new ProfileLaneWindow
{
Title = $"Profile Lane Plot of {Title}",
ProfileLanePlot = plot,
};
profileLaneWindow.Show();
}
Argument type 'System.Windows.Point' is not assignable to parameter type 'System.Drawing.Point' here:
LineSegment2D line = new LineSegment2D(firstPoint, secondPoint);
LineSegment2D line = new LineSegment2D(firstPoint, secondPoint);
at "firstPoint"
3 replies
CC#
Created by Whiteboy on 3/23/2023 in #help
✅ Process image using Emgu.CV, WPF app .NET 7.0
So i have to check if the image i upload is in Grayscale or not and based on it make further progress here is how i upload image:
private void BtnOpenNewFile_Click(object sender, RoutedEventArgs e)
{
var openFileDialog = new OpenFileDialog
{
Filter = "Image Files (*.bmp;*.jpg;*.jpeg;*.gif;*.png)|*.bmp;*.jpg;*.jpeg;*.gif;*.png"
};

if (openFileDialog.ShowDialog() == true)
{
Mat image = new Mat(openFileDialog.FileName, ImreadModes.Color);
string fileName = Path.GetFileNameWithoutExtension(openFileDialog.FileName);

ImageWindow imageWindow = new ImageWindow();

if (image.Height > 1000 || image.Width > 1000)
{
imageWindow.Height = 1000;
imageWindow.Width = 1000;
}
else
{
imageWindow.Height = image.Height + 200;
imageWindow.Width = image.Width + 50;
}

imageWindow.Title = fileName;
imageWindow.ImgMainImage.Source = image.ToBitmapSource();
imageWindow.Show();
}
}
private void BtnOpenNewFile_Click(object sender, RoutedEventArgs e)
{
var openFileDialog = new OpenFileDialog
{
Filter = "Image Files (*.bmp;*.jpg;*.jpeg;*.gif;*.png)|*.bmp;*.jpg;*.jpeg;*.gif;*.png"
};

if (openFileDialog.ShowDialog() == true)
{
Mat image = new Mat(openFileDialog.FileName, ImreadModes.Color);
string fileName = Path.GetFileNameWithoutExtension(openFileDialog.FileName);

ImageWindow imageWindow = new ImageWindow();

if (image.Height > 1000 || image.Width > 1000)
{
imageWindow.Height = 1000;
imageWindow.Width = 1000;
}
else
{
imageWindow.Height = image.Height + 200;
imageWindow.Width = image.Width + 50;
}

imageWindow.Title = fileName;
imageWindow.ImgMainImage.Source = image.ToBitmapSource();
imageWindow.Show();
}
}
and here is how i try to convert it but no matter if i upload gray image or not it says the image is already in grayscale, (i checked using ImageJ)
20 replies
CC#
Created by Whiteboy on 10/28/2022 in #help
Counting Sort, display the array
I need to display the array which counted how many each numbers there are like in the screen
7 replies
CC#
Created by Whiteboy on 10/15/2022 in #help
Hi, I have simple golf game in Unity and the ball keeps hitting invisible objects [Answered]
well not every time, but i don't know where they come from. When i paused the game and checked scene there was nothing sus
11 replies
CC#
Created by Whiteboy on 10/12/2022 in #help
Unity 2 golf, ball doesn't stop rolling and... [Answered]
6 replies
CC#
Created by Whiteboy on 9/3/2022 in #help
Enable button from another Form [Answered]
there is -Main menu then 3 subforms to main menu -A, B, C I want to enable Main Menu button when i click a button in form A or B or C and the code that moves user through forms
private void OpenChildForm(Form childForm, object btnSender)
{
if (btnSender is null)
{
throw new ArgumentNullException(nameof(btnSender));
}

_activeForm?.Close();

_activeForm = childForm;
childForm.TopLevel = false;
childForm.FormBorderStyle = FormBorderStyle.None;
childForm.Dock = DockStyle.Fill;
this.panelDesktop.Controls.Add(childForm);
this.panelDesktop.Tag = childForm;
childForm.BringToFront();
childForm.Show();
}
private void OpenChildForm(Form childForm, object btnSender)
{
if (btnSender is null)
{
throw new ArgumentNullException(nameof(btnSender));
}

_activeForm?.Close();

_activeForm = childForm;
childForm.TopLevel = false;
childForm.FormBorderStyle = FormBorderStyle.None;
childForm.Dock = DockStyle.Fill;
this.panelDesktop.Controls.Add(childForm);
this.panelDesktop.Tag = childForm;
childForm.BringToFront();
childForm.Show();
}
195 replies
CC#
Created by Whiteboy on 9/2/2022 in #help
Why all my randoms are the same? [Answered]
so there is the code and the outputs why are they the same and how to change it?
46 replies
CC#
Created by Whiteboy on 9/1/2022 in #help
Thread.Sleep(int32) not working? Send Help [Answered]
private void BtnUpgrade_Click(object sender, EventArgs e)
{
if (IsEqScroll == false && IsEqAmulet == false)
{
var random = new Random();
var num = random.Next(1, 1000);
if(num < 1000/(1+ SharedClass.UpgradeLvlValue.UpgradeLevel*1.69))
{
lbUpgradeOutput.BackColor = Color.FromArgb(46, 51, 73);
Thread.Sleep(250);
SharedClass.UpgradeLvlValue.UpgradeLevel++;
lbUpgradeOutput.Text = "Upgrade succeed";
lbUpgradeOutput.BackColor = Color.Green;
UpgradeLvl.Text = "+ " + SharedClass.UpgradeLvlValue.UpgradeLevel.ToString();
}
else
{
lbUpgradeOutput.BackColor = Color.FromArgb(46, 51, 73);
Thread.Sleep(250);
lbUpgradeOutput.Text = "Upgrade failed";
lbUpgradeOutput.BackColor = Color.Red;
}
}
}
private void BtnUpgrade_Click(object sender, EventArgs e)
{
if (IsEqScroll == false && IsEqAmulet == false)
{
var random = new Random();
var num = random.Next(1, 1000);
if(num < 1000/(1+ SharedClass.UpgradeLvlValue.UpgradeLevel*1.69))
{
lbUpgradeOutput.BackColor = Color.FromArgb(46, 51, 73);
Thread.Sleep(250);
SharedClass.UpgradeLvlValue.UpgradeLevel++;
lbUpgradeOutput.Text = "Upgrade succeed";
lbUpgradeOutput.BackColor = Color.Green;
UpgradeLvl.Text = "+ " + SharedClass.UpgradeLvlValue.UpgradeLevel.ToString();
}
else
{
lbUpgradeOutput.BackColor = Color.FromArgb(46, 51, 73);
Thread.Sleep(250);
lbUpgradeOutput.Text = "Upgrade failed";
lbUpgradeOutput.BackColor = Color.Red;
}
}
}
So it goes like this - the basic color - 1st click on the button assigned - color goes green (succeeded) - 2nd click - color stays green (success again) When it should flash for 0.25 to the basic color then go green I want to make something aka flashy event for the label with text "upgrade succeeded/failed" so when you get 2x upgrade in a row you get that little visual information that it actually tried the upgrading instead of the color being green all time What am i missing?
18 replies