How can I combine these classes

558fe5180e0e8fc922d31c23ef84d240

I have a web page that loads images with a modal, and at the same time is meant to inhibit image piracy by delivering a transparent overlay when a user attempts to make a screen copy of the image.
I have two php lines of image scripts which work OK independently, but when I attempt to combine them into one div, only script one will work. You can see that I've commented out the second image here (which delivers the transparent overlay) and the first image (which creates the modal) then works, and vice versa but I want to use them both at the same time. How can they be successfully combined?
It is unsuccessful if I do class="first second modal-target "

<style>
.modal-target {
    width: 390px;
    /* sets the width of the image */
    border-radius: 5px;
    cursor: pointer;
    transition: 0.3s;
}
</style>


<style>
.first {
    position: relative;
}

.second {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}
</style>

<div class="first">
<!-- the following line delivers some images and their title to the web page -->
    <img class="modal-target" src="<?php echo $file_source; ?>" &nbsp;&nbsp;&nbsp; alt="<?php echo $title; ?>" width="400">
 <!-- the following line prevents a user from copying the image from the webpage -->
<img class="second" src='../images/Copyright.gif' alt='This image is copyright'>
</div>
<!-- there are further scripts including some php and javascript related to the modal but as the modal works OK I haven't included them here -->

Display list of months, sorted in order of rainfall, highest to lowest

558fe5180e0e8fc922d31c23ef84d240

Hi everyone, was wondering if maybe someone could help me. I'm new to coding and have an assignment to do. The assignment is as follows:

Write a program that lets the user enter the total rainfall for each of 12 months into an array of doubles. The program should calculate and display the total rainfall for the year, the average monthly rainfall, and the months with the highest and lowest amounts.

The program should display a list of months, sorted in order of rainfall, from highest to lowest

Input Validation: Do not accept negative numbers for monthly rainfall figures.

Include the following functions
Calculate total rainfall
Calculate the average rainfall
Find the largest amount of rainfall
Find the smallest amount of rainfall
Sort the array of rainfall data
Display the sorted data.
Display Array

what I have so fa

#include <iostream>
#include <string>
#include <iomanip>
using namespace std;

// Months, double, things needed
   const int MONTHS = 12; //Number of elements
   string name[MONTHS] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
   int i = 0; //Loop index
   double rainFall[MONTHS];
   double total = 0, avg = 0, highRain = 0, lowRain = 0;
   string highMonth;
   string lowMonth;

   int main()
{

   for (int i = 0; i < MONTHS; i++)
   {
      //input total rainfall for each month
      cout << "Enter rainfall for " <<name[i] << ": " << endl;
      cin >> rainFall[i];
      // input validation -- negative inputs not allowed
      while (rainFall[i] < 0)
      {
         //notify user of the error
         cout << "invalid data (negative rainfall) -- retry" << endl;
         //get new input
         cin >> rainFall[i];
      }
      //total rainfall
      total += rainFall[i];
   }

   //average rainfall
   avg = total / 12;

// Max or most rainfall
   highRain = rainFall[0];
   highMonth = name[0];

   for (int i = 1; i < MONTHS; i++)
   {
      if (rainFall[i] > highRain)
      {
         highMonth = name[i];
         highRain = rainFall[i];
      }
   }

//least or less rainfall
   lowRain = rainFall[0];
   lowMonth = name[0];

   for (int i = 1; i < MONTHS; i++)
   { 
      if (rainFall[i] < lowRain)
      {
         lowMonth = name[i];
         lowRain = rainFall[i];
      }
   }
// Display calculations --> average and total rainfall, most and least rainfall
   cout << "\n"; 
   cout << "Total rainfall: " << total << endl;
   cout << "Average: " << avg << endl;
   cout << "Most rainfall in " << highMonth << " with an amount of " << highRain << endl;
   cout << "Least rainfall in " << lowMonth << " with an amount of " << lowRain << endl;
  cout << "\n"; 

// Display a list of months, sorted in order of rainfall, from high to low
  for (i = 0; i < MONTHS; i++) {
      cout << name[i] << " " << rainFall[i] << endl;
   }

   return 0;
}

I was wondering if anyone knew how to go about sorting it? I just cant seem to wrap my head about it.
Thank you in advance!

“41% of all code on GitHub right now is AI generated.”

558fe5180e0e8fc922d31c23ef84d240

This just in from an AI researcher.

Given the impact GenAI has had, it's been odd to see how unwelcome discussions about GenAI are here and other places.
Then again, it is an existential threat to new and old programmers that don't add these new tools to their repertoire or skill set.

Also, AI/ML has created no end of angst in Hollywood. Last month a company that makes audiobooks reduced its workforce because the AI tool to make audiobooks costs 20USD a month. Everyday voice actors at this point are going to have a rough time going forward except for the big names.

I have stories about the use of AI/ML/GenAI in the circles I run. All use has resulted in higher productivity. Which is good for the company, not so much everyone else.

How do I use RGBA in pygame.draw

558fe5180e0e8fc922d31c23ef84d240

I am trying to make a drawing board in pygame but I want to be able to change the opacity using RGBA but it doesn't seem to be working, my code below:

import pygame as pg
import sys, os
from pygame.locals import *
pg.init()
draw = 0
color = 0
thick = 30
sav = 0
c = 0
r = 0
g = 0
b = 0
a = 255
l = 0
n = 0
z = 0
i9 = 1
circle = []
long = 0
drawing_name = ''
load_name = ''
th = False
fill = r,g,b,a
WHITE = 255,255,255
file = 0
surf = pg.image.load('dot.png') 
surf.fill((r,g,b))   
color_ = pg.cursors.Cursor((20,20), surf)
pg.mouse.set_cursor(color_)
screen = pg.display.set_mode((1440,900),pg.FULLSCREEN)
pg.display.set_caption('Drawing board')
screen.fill(WHITE)
#pg.mouse.set_visible(False)
font1 = pg.font.SysFont('Chalkduster', 50)
font2 = pg.font.SysFont('Chalkduster', 25)
text1 = font1.render('What do you want to name your artwork:', True, (0, 0, 0))
textRect1 = text1.get_rect()
textRect1.center = (700, 500)
text2 = font1.render(drawing_name, True, (0, 0, 0))
textRect2 = text2.get_rect()
textRect2.center = (700, 500)
text3 = font1.render('Too Long!', True, (0, 0, 0))
textRect3 = text3.get_rect()
textRect3.center = (700, 700)
text4 = font1.render('What do artwork do you want to load:', True, (0, 0, 0))
textRect4 = text4.get_rect()
textRect4.center = (700, 500)
text5 = font1.render(load_name, True, (0, 0, 0))
textRect5 = text5.get_rect()
textRect5.center = (700, 600)
text6 = font2.render('Not a drawing!', True, (0, 0, 0))
textRect6 = text6.get_rect()
textRect6.center = (700, 700)
line_pos_lst = []
def save():
    global sav
    sav += 1
    screen.blit(text1, textRect1)
while True:
    print(a)
    fill = r,g,b,[a]
    surf = pg.Surface((thick+20, thick+20))
    surf.fill((r,g,b))
    color_ = pg.cursors.Cursor((20,20), surf)
    pg.mouse.set_cursor(color_)
    for event in pg.event.get():
        if event.type == pg.QUIT:
            running = False
            pg.quit()
            sys.exit()
        if event.type == pg.KEYDOWN:
            if event.key == pg.K_SPACE:
                if sav % 2 == 0:
                    screen.fill(WHITE)
            if event.key == pg.K_TAB:
                if sav % 2 == 0:
                    draw += 1
                    pg.mouse.set_visible(True)
            if event.key == pg.K_p:
                if sav % 2 == 0:
                    r = 255
                    g = 255
                    b = 255
                    a = 255
                    color += 1
            if event.key == pg.K_0:
                if sav % 2 == 0:
                    thick = 5
            if event.key == pg.K_1:
                if sav % 2 == 0:
                    thick = 10
            if event.key == pg.K_2:
                if sav % 2 == 0:
                    thick = 20
            if event.key == pg.K_3:
                if sav % 2 == 0:
                    thick = 30
            if event.key == pg.K_4:
                if sav % 2 == 0:
                    thick = 40
            if event.key == pg.K_5:
                if sav % 2 == 0:
                    thick = 50
            if event.key == pg.K_q:
                if sav % 2 == 0:
                    color1 = [r,g,b,a]
            if event.key == pg.K_w:
                if sav % 2 == 0:
                    color2 = [r,g,b,a]
            if event.key == pg.K_e:
                if sav % 2 == 0:
                    color3 = [r,g,b,a]
            if event.key == pg.K_a:
                if sav % 2 == 0:
                    r = color1[0]
                    g = color1[1]
                    b = color1[2]
                    a = color1[3]
            if event.key == pg.K_s:
                if sav % 2 == 0:
                    r = color2[0]
                    g = color2[1]
                    b = color2[2]
                    a = color2[3]
            if event.key == pg.K_d:
                if sav % 2 == 0:
                    r = color3[0]
                    g = color3[1]
                    b = color3[2]
                    a = color3[3]
            if event.key == pg.K_m:
                if sav % 2 == 0:
                    screen.fill(fill)
            if event.key == pg.K_c:
                if sav % 2 == 0:
                    r = 0
                    g = 0
                    b = 0
                    a = 255
            if event.key == pg.K_r:
                if sav % 2 == 0:
                    r += 10
            if event.key == pg.K_g:
                if sav % 2 == 0:
                    g += 10
            if event.key == pg.K_b:
                if sav % 2 == 0:
                    b += 10
            if event.key == pg.K_PLUS:
                if sav % 2 == 0:
                    a += 10
            if event.key == pg.K_MINUS:
                if sav % 2 == 0:
                    a -= 10
            if event.key == pg.K_F4:
                pg.image.save(screen, 'temp' + str(i9) + '.png')
                save()
                a += 1
                std = True
                while std:
                    pg.draw.rect(screen, (255,255,255), Rect(100, 400, 1240, 400))
                    text2 = font1.render(drawing_name, True, (0, 0, 0))
                    textRect2 = text2.get_rect()
                    textRect2.topleft = (300,600)
                    screen.blit(text2, textRect2)
                    save()
                    if len(drawing_name) == 30:
                        screen.blit(text3, textRect3)
                        long = 1
                    else:
                        long = 0
                    for event in pg.event.get():
                        if event.type == KEYDOWN:
                            if event.key == pg.K_BACKSPACE:
                                drawing_name = drawing_name[:-1]
                            elif event.key == pg.K_RETURN:
                                a9 = pg.image.load('temp' + str(i9) + '.png')
                                screen.blit(a9,(0,0))
                                pg.image.save(screen, 'drawing_' + drawing_name + ".png")
                                drawing_name = ''
                                std = False
                            else:
                                if long == 0:
                                    if event.unicode == ' ':
                                        drawing_name += '_'
                                    else:
                                        drawing_name += event.unicode
                    pg.display.update()
                sav += 1
                screen.fill((255,255,255))
                continue
            if event.key == pg.K_F6:
                screen.blit(text4, textRect4)
                sav += 1
                th = True
                while th:
                    pg.draw.rect(screen, (255,255,255), Rect(100, 400, 1240, 400))
                    screen.blit(text4, textRect4)
                    screen.blit(text5, textRect5)
                    text5 = font1.render(load_name, True, (0, 0, 0))
                    textRect5 = text5.get_rect()
                    textRect5.center = (700, 600)
                    if len(load_name) == 30:
                        screen.blit(text3, textRect3)
                        long = 1
                    else:
                        long = 0
                    if file == 1:
                        screen.blit(text6, textRect6)
                    if os.path.isfile('drawing_' + load_name + '.png') == True:
                        file = 0
                    for event in pg.event.get():
                        if event.type == KEYDOWN:
                            if event.key == pg.K_BACKSPACE:
                                load_name = load_name[:-1]
                            elif event.key == pg.K_RETURN:
                                if os.path.isfile('drawing_' + load_name + '.png') == True:
                                    z0 = pg.image.load('drawing_' + load_name + '.png')
                                    screen.blit(z0,(0,0))
                                    load_name = ''
                                    th = False
                                else:
                                    file = 1 
                            else:
                                if long == 0:
                                    if event.unicode == ' ':
                                        load_name += '_'
                                    else:
                                        load_name += event.unicode
                    pg.display.update()
                continue
            if event.key == pg.K_F9:
                if sav % 2 == 0:
                    pg.mouse.set_visible(True)
                    c += 1
                    circle.append(pg.mouse.get_pos())
                    if len(circle) == 2:
                        x1,y1 = circle[0]
                        x2,y2 = circle[1]
                        radius = ((x1 - x2)**2 + (y1 - y2)**2)**0.5
                        pg.draw.circle(screen, (r,g,b,a),[x1, y1], radius, thick+20)
                        circle.clear()
            if event.key == pg.K_l:
                if sav % 2 == 0:
                    pg.mouse.set_cursor(pg.SYSTEM_CURSOR_CROSSHAIR)
                    pg.mouse.set_visible(True)
                    c += 1
                    l += 1
            if event.key == pg.K_ESCAPE:
                pg.quit()
                sys.exit()
        if event.type == pg.MOUSEBUTTONDOWN:
            if sav % 2 == 0:
                line_pos_lst.append(pg.mouse.get_pos())
                n += 1
                l += 1
                if len(line_pos_lst) == 2:
                    pg.draw.line(screen, (r,g,b,a), line_pos_lst[0], line_pos_lst[1], width=thick+20 )
                    print(line_pos_lst[0],line_pos_lst[1])
                    n += 1
                    line_pos_lst.clear()
    if draw % 2 == 0:
        if c % 2 == 0:
            if color % 2 != 1:
                pg.mouse.set_visible(False)
                r %= 255
                g %= 255
                b %= 255
                a %= 255
            x,y = pg.mouse.get_pos()
            pg.draw.circle(screen, (r,g,b,a),[x, y], thick, 0)
    pg.display.update()

Can you help me?

Regex to match word one or more times in a string

558fe5180e0e8fc922d31c23ef84d240

I'm really bad with regex. For the purposes of URI rewriting, I'm trying to figure out how to match a word one or more times in a string.

For example, I want to do something like:

string/string/string/foo/bar => foo/bar
string/string/bazbat => bazbat

Currently I have:

^string/(.*)$ => $1

and that works, but I want to make string/ work for one or more times, not just once.

id list1 open for random

558fe5180e0e8fc922d31c23ef84d240

Hi, I'm Arcon.

I have a problem when saving records, it saves a record and when it saves another it overlaps the first record
when reading records with its id it does not read it to me correctly

thank you

How do I get a button to do what it is supposed to do?

558fe5180e0e8fc922d31c23ef84d240

The button in question is supposed to calculate the cost of a car rental, from inputs for how many months, how many weeks and how many days.
This is the entire code at the moment:

import tkinter as tk
from datetime import *


# Create a tkinter window
window = tk.Tk()
window.title("Car Rental Service")
window.resizable(True, True)

# Define global variables
rental_cost = 0
rental_duration = 0

def submit_form():
    name = name_entry.get()


# Define functions
def calculate_cost():
      # Extract numeric values from label text
    rental_days_text = rental_label_days.cget('text')
    rental_days = 0
    if any(c.isdigit() for c in rental_days_text):
        rental_days = int(''.join(filter(str.isdigit, rental_days_text)))

    rental_weeks_text = rental_label_weeks.cget('text')
    rental_weeks = 0
    if any(c.isdigit() for c in rental_weeks_text):
        rental_weeks = int(''.join(filter(str.isdigit, rental_weeks_text)))

    rental_months_text = rental_label_months.cget('text')
    rental_months = 0
    if any(c.isdigit() for c in rental_months_text):
        rental_months = int(''.join(filter(str.isdigit, rental_months_text)))

    global rental_cost
    # Calculate rental cost based on duration
    if rental_days >= 1:
        rental_cost = 30 * rental_days
    elif rental_weeks >= 1:
        rental_cost = 95 * rental_weeks
    elif rental_months >= 1:
        rental_cost = 270 * rental_months

    # Add VAT to rental cost
    rental_cost = ((rental_days * 36) + (rental_weeks * 114) + (rental_months * 324)) * 1.2
    # Update the cost label
    cost_label.config(text="Total cost: " + str(round(rental_cost, 2)))

def rent_car():
    # Get customer details
    name = name_entry.get()
    dob = dob_entry.get()
    nationality = nationality_entry.get()
    licence_duration = licence_entry.get()
    # Display rental details
    rental_label.config(text="Thank you, " + name + ". You have rented a " + category_var.get() + " car for " + str(rental_duration) + " " + duration_var.get_name() + ".")
    # Disable form fields
    name_entry.config(state="disabled")
    dob_entry.config(state="disabled")
    nationality_entry.config(state="disabled")
    licence_entry.config(state="disabled")
    category_small.config(state="disabled")
    category_medium.config(state="disabled")
    category_large.config(state="disabled")
    one_day.config(state="disabled")
    one_week.config(state="disabled")
    one_month.config(state="disabled")
    # Enable the checkout button
    checkout_button.config(state="normal")

def validate_age():
    dob = dob_entry.get()
    age = calculate_age(dob)
    if age < 24:
        tk.Label(text="You must be aged 24 or over to complete this rental form.")
        submit_button.config(state="disabled")
    else:
        tk.Label(text="")
        submit_button.config(state="normal")

def checkout():
    # Display checkout message
    checkout_label.config(text="Thank you for your custom. You have been charged " + str(round(rental_cost, 2)) + ".")

def calculate_age(dob):
    # Calculate age from date of birth
    # Assuming dob is in the format "dd/mm/yyyy"
    dob_list = dob.split("/")
    dob_day = int(dob_list[0])
    dob_month = int(dob_list[1])
    dob_year = int(dob_list[2])
    today = date.today()
    age = today.year - dob_year - ((today.month, today.day) < (dob_month, dob_day))
    return age

small_car_img = tk.PhotoImage(file="small-car (1).gif")
medium_car_img = tk.PhotoImage(file="mid-size-car.gif")
large_car_img = tk.PhotoImage(file="large-car (1).gif")

def update_image():
    if category_var.get() == "Small":
        image_label.config(image=small_car_img)
    elif category_var.get() == "Medium":
        image_label.config(image=medium_car_img)
    elif category_var.get() == "Large":
        image_label.config(image=large_car_img)

# Create form fields
name_label = tk.Label(window, text="Name:")
name_label.pack()
name_entry = tk.Entry(window)
name_entry.pack()

dob_label = tk.Label(window, text="Date of birth (dd/mm/yyyy):")
dob_label.pack()
dob_entry = tk.Entry(window)
dob_entry.pack()

validate_age_button = tk.Button(window, text="Validate Age", command=validate_age)
validate_age_button.pack()

nationality_label = tk.Label(window, text="Nationality:")
nationality_label.pack()
nationality_entry = tk.Entry(window)
nationality_entry.pack()

licence_label = tk.Label(window, text="How long have you held your licence for? (years):")
licence_label.pack()
licence_entry = tk.Entry(window)
licence_entry.pack()

label = tk.Label(window, text="Select a car category:")
label.pack()

category_var = tk.StringVar()
small_button = tk.Radiobutton(window, text="Small", variable=category_var, value="Small")
medium_button = tk.Radiobutton(window, text="Medium", variable=category_var, value="Medium")
large_button = tk.Radiobutton(window, text="Large", variable=category_var, value="Large")

image_label = tk.Label(window)
image_label.pack()

small_button.pack()
medium_button.pack()
large_button.pack()

small_button.config(command=update_image)
medium_button.config(command=update_image)
large_button.config(command=update_image)

rental_label_months = tk.Label(window, text="How many months do you plan on renting the car for?:")
rental_label_months.pack()
rental_label_months_entry = tk.Entry(window)
rental_label_months_entry.pack()

rental_label_weeks = tk.Label(window, text="How many weeks do you plan on renting the car for?:")
rental_label_weeks.pack()
rental_label_weeks_entry = tk.Entry(window)
rental_label_weeks_entry.pack()

rental_label_days = tk.Label(window, text="How many days do you plan on renting the car for?:")
rental_label_days.pack()
rental_label_days_entry = tk.Entry(window)
rental_label_days_entry.pack()

cost_label = tk.Label(window, text="Your Total Cost Is: ")
cost_label.pack()
print(cost_label)
cost_label.config(text="Total cost: " + str(round(rental_cost, 2)))

rental_cost_button = tk.Button(window, text="Calculate Cost", command=calculate_cost)
rental_cost_button.pack()

submit_button = tk.Button(window, text="Submit Form", command=submit_form)
submit_button.pack()

window.mainloop()

Side nav menu with accordion sub-items

558fe5180e0e8fc922d31c23ef84d240

I've searched, but can't even find what to call this. Any links or code would help a ton. I want 8 main items to appear from a side-menu with 4 sub-items branching out to their right when clicked. As any sub-item is clicked, I'd like for 4 items below that to appear in an accordion-style fashion. The entire thing should never get any larger than 8x2.

Does this make sense? What am I looking for here? Thanks for any help you're able to provide.

How to make separate functions to get the mean and standard deviation?

558fe5180e0e8fc922d31c23ef84d240

H! I need to calculate the mean of the coverages of two types of particles that could be trapped on a square surface. They are particle #1 and particle #2. Such averages are taken after certain number of steps, for example, every 10 Monte Carlo steps, and considering a number of iterations.

The coverages mentioned before are defined as (number of particles trapped in the surface)/(number of total cells).

For illustrative purposes, the following are the steps that my simulation follows:

  1. Start with the random collision of a particle on a square lattice.

  2. We chose particle #1 with a given probability Y and particle #2 with probability 1 Y. ("Y is determined by the mole fraction of the particle #1 in the gas phase").

  3. If the chosen particle is particle #1, we choose a site on the lattice at random. If that site is full the trial ends. Otherwise, particle #1 is trapped.

  4. If the chosen particle is particle #2, we choose a site on the lattice at random. If that site is full the trial ends. Otherwise, particle #2 is trapped.

This is the code I have so far:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>

//define the dimensions of the grid
#define MAX_X 4
#define MAX_Y 4
//define the iterations 
#define ITERATIONS (MAX_Y*MAX_X)
#define Y 0.55
FILE *data;

//define the states of a cell in grid`
typedef enum  { S_EMPTY, P1_OCCUPIED, P2_OCCUPIED, S_NONE } gstate;

// help generate random coordinate of the grid
int gridrnd(int max)
{
    return (rand() % max);
}


// generates random coordinates of the grid
int generate_coords(int* j, int* i ) 
{
    if (!i || !j)
        return 1;

    *i = gridrnd(MAX_X);
    *j = gridrnd(MAX_Y);

   // printf("(%d,%d)\n\n", *j, *i);
    return 0;
}

//function to initialize the grid as empty
void grid_init(gstate grid[MAX_Y][MAX_X])
{
    for (int j = 0; j < MAX_Y; j++) {
        for (int i = 0; i < MAX_X; i++) {
            grid[j][i] = S_EMPTY;
        }
    }
}




int main(){
    data=fopen("data.txt","w");
    int i = 0, j = 0;
    gstate grid[MAX_Y][MAX_X];
    double particle1 = 0, particle2 = 0; // counters for the number of particle1 and particle2
    double availcells = MAX_X * MAX_Y; //first we initialize with all the cells of the matrix available
    double fullcells = 0;
    int rounds = 0;
    double N = 1.0*sizeof(grid)/sizeof(grid[0][0]); //number of the total sites in the matrix
    float r;
    double cover1 = 0.0, cover2 = 0.0, sumacov = 0.0;
    double average1 = 0.0, average2 = 0.0; //we define the average of the coverages of particle 1 and particle 2 
    double num_1[MCSTEPS*ITERATIONS];
    double num_2[MCSTEPS*ITERATIONS];
    double sum1 = 0.0, sum2 = 0.0; //sum of the coverages of both particle 1 and 2. useful to calculate the average of the coverages
    double MCSTEPS = 5;

    srand((unsigned)time(0));

    // Initialize grid to be S_EMPTY
    grid_init(grid);

sum1=0.0;
sum2=0.0;

    for(int time = 0; time < MCSTEPS; time++ ) {
        for(int iter = 0; iter < ITERATIONS; iter++){
            //LOCATE AN ENTRY OF THE MATRIX RANDOMLY
            generate_coords(&j, &i);

            //EVALUATE THE CHOOSEN SITE
            switch (grid[j][i])
            {
                        case S_EMPTY:
                            //printf("IT'S S_EMPTY, LET'S FILL IT WITH A PARTICLE. FIRST LET'S GENERATE TO DECIDE IFIT WILL BE TRAPPED\n\n");

                            r = rand()/(float)RAND_MAX;

                            if(r <= Y){//The particle #1 is chosen         
                              //printf("r = %lf is less than Y = %lf. We choose the particle #1\n\n", r, Y);
                                grid[j][i] = P1_OCCUPIED;
                                particle1++;
                                availcells--;
                                fullcells++;
                            }
                            else{//The particle #2 is chosen
                              //printf("r = %lf is greater than Y = %lf. We choose the particle #2\n\n", r, Y);
                                grid[j][i] = P2_OCCUPIED;
                                particle2++;
                                availcells--;
                                fullcells++;                
                            }  
                            break;

                        case P1_OCCUPIED:
                            //printf("IT'S OCCUPIED WITH THE PARTICLE #1. PLEASE, GENERATE ANOTHER SITE ON THE SURFACE\n\n");
                            break;

                        case P2_OCCUPIED:
                            //printf("IT'S OCCUPIED WITH THE PARTICLE #2. PLEASE, GENERATE ANOTHER SITE ON THE SURFACE\n\n");
                            break;

                        }  

            cover1 = particle1/N;
            cover2 = particle2/N;

            num_1[time] += cover1;
            num_2[time] += cover2;

            sum_1 += num_1[time];
            sum_2 += num_2[time];
        }    
    }  

    average1 = sum_1/(MCSTEPS*ITERATIONS);
    average2 = sum_2/(MCSTEPS*ITERATIONS);

    printf("The process took %d rounds\n\n", rounds);
    printf("#particle1 = %d\n\n", particle1);//total of particle1 adsorbed
    printf("#particle2 = %d\n\n", particle2);//total of particle2 adsorbed
    printf("#availcells = %d\n\n",availcells);
    printf("#fullcells = %d\n\n",fullcells); 
    return 0;
}

I would like to calculate the mean and standard deviation of such coverages in separate functions since I will to add more interactions between the particles later on and to do not have parts of my code "spread out".my

The problem is that I'm not sure how to write properly those functions due to the content that I already have inside the for loops.

Note that such averages and standard deviations should be calculated at the end of my loops.

Collision in VB.Net

558fe5180e0e8fc922d31c23ef84d240

I'm trying to make the picturebox collide with the others.
I tried to do several things but they don't work.
I spoke to my teacher and he said I should do something like this:

PictureBox1.Left + PictureBox1.Width >= PictureBox2.Left And
         PictureBox1.Top + PictureBox1.Height >= PictureBox2.Top And
         PictureBox1.Top <= PictureBox2.Top + PictureBox2.Height And
         PictureBox1.Left <= PictureBox2.Left + PictureBox2.Width

But it didn't work either, not if it was because I didn't set the variables right or if I didn't put it in the right place.

This is The full code:

Imports System.Math
Imports System.Security.Policy

Public Class Form1
    Dim CoordX As Single
    Dim CoordY As Single
    Dim Velocity As Double = 0
    Dim Angle As Double
    Dim Time As Double = 0
    Dim Gravity As Double = 9.8
    Dim moving As Boolean = False
    Dim mousePosX As Integer
    Dim mousePosY As Integer
    Dim X As Integer = 80
    Dim Y As Integer = 250
    Dim picturebox1 As New PictureBox
    Dim Timer1 As New Timer
    Dim Timer2 As New Timer
    Dim Tracking As New RichTextBox
    Dim Angle2 As Single
    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Time += 0.1
        'formula da trajetoria para o x e o y
        CoordX = Velocity * Time * Cos(Angle)
        CoordY = (Velocity * Time * Sin(Angle)) - ((Gravity / 2) * Time * Time)
        picturebox1.Invalidate() 'desenhar a bola 

        picturebox1.Top += 0.1
        If picturebox1.Bounds.IntersectsWith(PictureBox3.Bounds) Then
        End If
    End Sub
    Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim deltaY As Integer = 250 - mousePosY
        Dim deltaX As Integer = mousePosX - 86
        Dim temp As Single
        temp = Math.Atan2(deltaY, deltaX) * 180 / Math.PI
        If Not temp >= 0 Then
            temp += 360
        End If
        Angle2 = temp
        'mostar as cordenadas - mas para isso funconar  preciso criar uma label na public class
        'Tracking.Text = " Ball Coord_X: " & CoordX & vbNewLine & " Ball Coord_Y: " & CoordY & vbNewLine _
        ' & " Gravity: 9.8" & vbNewLine & " Velocity: " & Velocity & vbNewLine & " Angle: " & Angle2
        Tracking.Text = "Pontos:"
    End Sub
    Private Sub PictureBox1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
        ' verificar se a bola est em movimento ou a saltar
        If Timer1.Enabled = True Then
            moving = False
        Else
            'reiniciar
            CoordX = 0
            CoordY = 0
            Time = 0
            Velocity = 0
            X = mousePosX - 8
            Y = mousePosY - 8
            moving = True
        End If
    End Sub
    Private Sub PictureBox1_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
        If Timer1.Enabled = False Then
            moving = False
            X = mousePosX - 8
            Y = mousePosY - 8
            Timer1.Interval = 10
            FindAngle()
            Timer1.Start()
            'label.Visible = False - isto s  valido no caso de mostrar-mos os dados na label
        End If
    End Sub
    Public Sub FindAngle()
        'obter 2 angulos x
        ' (250,80) est no meio 
        Dim deltaY As Integer = 250 - mousePosY
        Dim deltaX As Integer = mousePosX - 86
        Dim temp As Single
        temp = Math.Atan2(deltaY, deltaX) * 180 / Math.PI
        'Tirar numeros negativos
        If Not temp >= 0 Then
            temp += 360
        End If
        'angulo inverso
        'se a bola tiver em 225, entao vai ser lanado num angulo de 45
        If temp + 180 > 360 Then
            temp += 180
        Else
            temp -= 180
        End If
        'degrees to radians
        temp = temp * PI / 180
        Angle = temp
    End Sub
    Private Sub PictureBox1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
        'Mover a bola
        If moving = True Then
            mousePosX = e.X
            mousePosY = e.Y
            picturebox1.Invalidate()
        End If
    End Sub
    Private Sub PictureBox1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs)
        If moving = True Then
            ' regras
            If mousePosX - 8 < 120 And mousePosX - 8 > 10 Then
                e.Graphics.FillEllipse(Brushes.OrangeRed, mousePosX - 8, mousePosY - 8, 16, 16)
            Else
                If mousePosX - 8 > 120 Then
                    e.Graphics.FillEllipse(Brushes.OrangeRed, 118, mousePosY - 8, 16, 16)
                    mousePosX = 118
                Else
                    e.Graphics.FillEllipse(Brushes.OrangeRed, 12, mousePosY - 8, 16, 16)
                    mousePosX = 12
                End If
            End If
            'da velociade ao calcular a distancia que esta se encontra do  centro
            'quando mais for a distncia maior  a fora
            Dim xx As Integer
            Dim yy As Integer

            If mousePosX > 80 Then
                xx = mousePosX - 80
            Else
                xx = 80 - mousePosX
            End If

            If mousePosY > 250 Then
                yy = mousePosY - 250
            Else
                yy = 250 - mousePosY
            End If

            If yy > xx Then
                Velocity = yy
            Else
                Velocity = xx
            End If

        Else
            'single - para desenhar melhor 
            e.Graphics.FillEllipse(Brushes.Navy, X + CoordX, Y - CoordY, 16, 16)
        End If
        If Y - CoordY > 315 Then
            Timer1.Stop()
            Time = 0
            X = X + CoordX
            Y = Y - CoordY
            ' a velocidade tem de diminuir enquanto a bola tocar no cho 
            Velocity -= 5
            If Velocity < 1 Then
                Timer1.Stop()
                Velocity = 0
                e.Graphics.FillEllipse(Brushes.OrangeRed, 80, 250, 16, 16)
            Else
                Timer1.Start()
            End If

        End If
        e.Graphics.FillEllipse(Brushes.White, 82, 254, 8, 8)
    End Sub
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.BackColor = Color.Black
        Me.Size = New Size(900, 370)
        Me.FormBorderStyle = Windows.Forms.FormBorderStyle.FixedToolWindow
        picturebox1.Location = New Point(0, 0)
        picturebox1.Size = New Size(900, 390)
        picturebox1.BackColor = Color.Transparent
        picturebox1.Name = "picturebox1"
        Tracking.Location = New Point(750, 12)
        Tracking.Size = New Size(200, 106)
        Tracking.BackColor = Color.Black
        Tracking.Cursor = Cursors.Default
        Tracking.BorderStyle = BorderStyle.None
        Tracking.ReadOnly = True
        Tracking.ForeColor = Color.GreenYellow
        Me.Controls.Add(picturebox1)
        Me.Controls.Add(Tracking)
        Tracking.BringToFront()
        AddHandler picturebox1.Paint, AddressOf PictureBox1_Paint
        AddHandler picturebox1.MouseMove, AddressOf PictureBox1_MouseMove
        AddHandler picturebox1.MouseUp, AddressOf PictureBox1_MouseUp
        AddHandler picturebox1.MouseDown, AddressOf PictureBox1_MouseDown
        AddHandler Timer1.Tick, AddressOf Timer1_Tick
        AddHandler Timer2.Tick, AddressOf Timer2_Tick
        Timer2.Start()
    End Sub
    End Class

Can someone help me make this work?

558fe5180e0e8fc922d31c23ef84d240

My program worked earlier this year before Windows 10 put and update and suddenly it doesn't work anymore. I have a separate laptop that didn't get the update and it works perfectly. Can someone please tell me what I need to do to get it to work? Ive tried everything I could think of and nothing works.

                    string[] music = Directory.GetFiles(@"C:\Users\Robert\Documents\C# stuff\Skynet\Skynet\bin\Debug\Music file", "*.mp3");// this is the original path

                    WMPLib.IWMPPlaylist Classicalplaylist = mplayer.playlistCollection.newPlaylist("classicalplaylist");
                    foreach (string file in music)
                    {
                        WMPLib.IWMPMedia media = mplayer.newMedia(file);
                        Classicalplaylist.appendItem(media);
                    }
                    mplayer.currentPlaylist = Classicalplaylist;

Print photos from Windows98 to HP8025 Laser resolution problem

558fe5180e0e8fc922d31c23ef84d240

I am trying to print out photos from an old Windows98 computer (Dell Inspiron 2400) to a brand new HP8025e Laser printer. Our store has been operating a photo booth on this computer so I don't think I can port it to a newer version of Windows.

We had been using an old HP2200 Business Jet which did the job and had native support under W98, but that finally broke and could not obtain another.

Three questions:

  1. "Properties" under W98 only offers 300dpi, I need better resolution
  2. I did set the printer console to 'photo paper', but when I print the photo on photo paper, it just comes out very overdone and smeary, as if it's using 10 times too much ink. W98 properties doesn't offer a 'photo paper' option
  3. The photos printed somewhat smaller on the old HP (maybe 2 1/2" by 2") whereas they print larger (maybe 4 x 3) on the new 8025, and I need them smaller so all 4 fit in a line on a 3 1/2 x 11 strip of photo paper.

I don't know if this is insoluble (HP support just told me there was no support for W98) but I thought I'd give it a try.

How to vectorize and speed-up double for-loop for pandas dataframe when doi

558fe5180e0e8fc922d31c23ef84d240

I have the following dataframe:

d_test = {
    'name' : ['South Beach', 'Dog', 'Bird', 'Ant', 'Big Dog', 'Beach', 'Dear', 'Cat', 'Fish', 'Dry Fish'],
    'cluster_number' : [1, 2, 3, 3, 2, 1, 4, 2, 2, 2]
}
df_test = pd.DataFrame(d_test)

I want to identify similar names in name column if those names belong to one cluster number and create unique id for them. For example South Beach and Beach belong to cluster number 1 and their similarity score is pretty high. So we associate it with unique id, say 1. Next cluster is number 2 and three entities from name column belong to this cluster: Dog, Big Dog, Cat, 'Fish' and 'Dry Fish'. Dog and Big Dog have high similarity score and their unique id will be, say 2. For Cat unique id will be, say 3. Finally for 'Fish' and 'Dry Fish' unique id will be, say 4. And so on.

I created a code for the logic above:

# pip install thefuzz
from thefuzz import fuzz

df_test = df_test.sort_values(['cluster_number', 'name'])
df_test.reset_index(drop=True, inplace=True)

df_test['id'] = 0

i = 1
for index, row in df_test.iterrows():
    row_ = row
    index_ = index

    while index_ < len(df_test) and df_test.loc[index, 'cluster_number'] == df_test.loc[index_, 'cluster_number'] and df_test.loc[index_, 'id'] == 0:
        if row['name'] == df_test.loc[index_, 'name'] or fuzz.ratio(row['name'], df_test.loc[index_, 'name']) > 50:
            df_test.loc[index_,'id'] = i
            is_i_used = True
        index_ += 1

    if is_i_used == True:
        i += 1
        is_i_used = False

Code generates expected result:

    name         cluster_number  id
0   Beach               1        1
1   South Beach         1        1
2   Big Dog             2        2
3   Cat                 2        3
4   Dog                 2        2
5   Dry Fish            2        4
6   Fish                2        4
7   Ant                 3        5
8   Bird                3        6
9   Dear                4        7

Computation runs for 210 seconds for dataframe with 1 million rows where in average each cluster has about 10 rows and max cluster size is about 200 rows. I am trying to understand how to vectorize the code.

Also thefuzz module has process function and it allows to process data at once:

from thefuzz import process
out = process.extract("Beach", df_test['name'], limit=len(df_test))

But I don't see if it can help with speeding up the code.

designing a flipflop

558fe5180e0e8fc922d31c23ef84d240

Design a three-bit counter using T-FFs. The counter has one input X. The counter counts odd numbers (1, 3, 5, 7) if X = 0 and counts even numbers (0, 2, 4, 6) if X = 1. If X = 1 and the current number is odd, the counter will go to the next even number. likewise, if X = 0 and the current number is even, the counter will go to the next odd.
**wanting to make have I did good so far ;-; been struggling a lot, next step is just drawing if I wasn't mistaken""

current_state.png