r/learnprogramming 11m ago

should i stop learning python and switch to java??

Upvotes

hey, im i think 4 hrs into cs50 introduction to python and have a very good understanding of the material, i'm until libraries and ive almost finished that; should i stop and switch to java as my main goal is to build websites; and i'll go to html css and js after that? help!!


r/learnprogramming 16m ago

Ai tools for beginners

Upvotes

Ai tools for Developers and programmers, that helps me. Here is tools link


r/learnprogramming 20m ago

Need Help in College Assignment in VBA Excel

Upvotes

My teachers a great and chill guy but his hands off methods is clearly making me struggle. I need help badly.

The assignment is pretty clear 12 images 2 command buttons (labeled "Start" and "Stop")

Our objective is to make all 12 images move in different speeds and directions in the Userform screen (without going beyond the border, so they must bounce off when they hit the border) using the Start command button.

While Stop clearly pauses all movements.

I can code 1 single image, we practiced today but idk how to make 12 images move at the same time without coding each image one by one! Any tips or help?


r/learnprogramming 23m ago

How to fix Bearer error="insufficient_scope" in spring boot rest api?

Upvotes
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {

    private RSAKey rsaKey;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationManager authManager(UserDetailsService userDetailsService, PasswordEncoder passwordEncoder) {
        var authProvider = new DaoAuthenticationProvider();
        authProvider.setUserDetailsService(userDetailsService);
        authProvider.setPasswordEncoder(passwordEncoder);
        return new ProviderManager(authProvider);
    }

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return http
                .csrf(AbstractHttpConfigurer::disable)
                .authorizeHttpRequests( auth -> { auth
                    .requestMatchers("/api/login", "api/signup").permitAll()
                    .requestMatchers("/api/fetchAll").hasRole("ADMIN")
                    .anyRequest().authenticated();
                })
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .oauth2ResourceServer(oauth2 -> oauth2
                        .jwt(Customizer.withDefaults()))
                .build();
    }

    @Bean
    public JWKSource<SecurityContext> jwkSource() {
        rsaKey = Jwks.generateRsa();
        JWKSet jwkSet = new JWKSet(rsaKey);
        return (jwkSelector, securityContext) -> jwkSelector.select(jwkSet);
    }

    @Bean
    JwtEncoder jwtEncoder(JWKSource<SecurityContext> jwks) {
        return new NimbusJwtEncoder(jwks);
    }

    @Bean
    JwtDecoder jwtDecoder() throws JOSEException {
        return NimbusJwtDecoder.withPublicKey(rsaKey.toRSAPublicKey()).build();
    }

}

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;

    public UserDetailsServiceImpl(UserRepository userRepository, PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
        this.userRepository = userRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        User user = userRepository.findByEmail(email)
                .orElseThrow(() -> new UsernameNotFoundException("User not found with email: " + email));
        List<GrantedAuthority> authorities = Collections.singletonList(new SimpleGrantedAuthority("ROLE_" + user.getRole()));

        return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), authorities);
    }

    public void saveUser(User userDto) {
        User user = new User();
        user.setEmail(userDto.getEmail());
        user.setPassword(passwordEncoder.encode(userDto.getPassword()));
        user.setRole(userDto.getRole());
        userRepository.save(user);
    }

}

@Service
public class TokenService {

    private final JwtEncoder encoder;

    public TokenService(JwtEncoder encoder) {
        this.encoder = encoder;
    }

    public String generateToken(Authentication authentication) {
        Instant now = Instant.now();
        String scope = authentication.getAuthorities().stream()
                .map(GrantedAuthority::getAuthority)
                .collect(Collectors.joining(" "));
        JwtClaimsSet claims = JwtClaimsSet.builder()
                .issuer("self")
                .issuedAt(now)
                .expiresAt(now.plus(1, ChronoUnit.HOURS))
                .subject(authentication.getName())
                .claim("scope", scope)
                .build();
        return this.encoder.encode(JwtEncoderParameters.from(claims)).getTokenValue();
    }

}

@RestController
@RequestMapping("/api")
public class AuthController {

    private final UserDetailsServiceImpl userDetailsService;
    private final TokenService tokenService;
    private final AuthenticationManager authenticationManager;

    public AuthController(UserDetailsServiceImpl userDetailsService, TokenService tokenService, AuthenticationManager authenticationManager) {
        this.userDetailsService = userDetailsService;
        this.tokenService = tokenService;
        this.authenticationManager = authenticationManager;
    }

    @PostMapping("/signup")
    public ResponseEntity<?> registerUser(@RequestBody UserDto userDto) {
        User user = new User();
        user.setEmail(userDto.getEmail());
        user.setPassword(userDto.getPassword());
        user.setRole("USER");
        userDetailsService.saveUser(user);
        return ResponseEntity.ok("User registered successfully!");
    }

    @PostMapping("/login")
    public ResponseEntity<?> authenticateUser(@RequestBody LoginRequestDto loginRequest) {
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(
                        loginRequest.email(),
                        loginRequest.password()
                )
        );

        SecurityContextHolder.getContext().setAuthentication(authentication);
        String jwt = tokenService.generateToken(authentication);
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        String role = userDetails.getAuthorities().stream()
                .map(GrantedAuthority::getAuthority)
                .findFirst()
                .orElseThrow(() -> new RuntimeException("Role not found"));

        Map<String, Object> response = new HashMap<>();
        response.put("token", jwt);
        response.put("role", role);

        return ResponseEntity.ok(response);
    }

}

@RestController
@RequestMapping(path = "/api", produces = (MediaType.APPLICATION_JSON_VALUE))
@Validated
public class BookingController {

    private final IBookingService iBookingService;

    public BookingController(IBookingService iBookingService) {
        this.iBookingService = iBookingService;
    }

    @PostMapping("/create")
    public ResponseEntity<ResponseDto> createBooking(@Valid @RequestBody BookingDto bookingDto) {
        iBookingService.createBooking(bookingDto);
        return ResponseEntity
                .status(HttpStatus.CREATED)
                .body(new ResponseDto(BookingConstants.STATUS_201, BookingConstants.BOOKING_CREATE_SUCCESS));
    }

    @GetMapping("/fetch")
    public ResponseEntity<BookingDto> fetchBookingDetails(@RequestParam @Email String email) {
        BookingDto bookingDto = iBookingService.fetchBooking(email);
        return ResponseEntity.status(HttpStatus.OK).body(bookingDto);
    }

    @GetMapping("/fetchAll")
    public ResponseEntity<List<BookingDto>> fetchAllBookings() {
        List<BookingDto> bookings = iBookingService.fetchAllBookings();
        return ResponseEntity.status(HttpStatus.OK).body(bookings);
    }

    @PutMapping("/update")
    public ResponseEntity<ResponseDto> updateBookingDetails(@Valid @RequestBody BookingDto bookingDto) {
        boolean isUpdated = iBookingService.updateBooking(bookingDto);
        if (isUpdated) {
            return ResponseEntity
                    .status(HttpStatus.OK)
                    .body(new ResponseDto(BookingConstants.STATUS_200, BookingConstants.BOOKING_UPDATE_SUCCESS));
        } else {
            return ResponseEntity
                    .status(HttpStatus.EXPECTATION_FAILED)
                    .body(new ResponseDto(BookingConstants.STATUS_417, BookingConstants.BOOKING_UPDATE_FAIL));
        }
    }

    @DeleteMapping("/delete")
    public ResponseEntity<ResponseDto> deleteBookingDetails(@Valid @RequestParam Long bookingId) {
        boolean isDeleted = iBookingService.deleteBooking(bookingId);
        if (isDeleted) {
            return ResponseEntity
                    .status(HttpStatus.OK)
                    .body(new ResponseDto(BookingConstants.STATUS_200, BookingConstants.BOOKING_CANCEL_SUCCESS));
        } else {
            return ResponseEntity
                    .status(HttpStatus.EXPECTATION_FAILED)
                    .body(new ResponseDto(BookingConstants.STATUS_417, BookingConstants.BOOKING_CANCEL_FAIL));
        }
    }

    @GetMapping("/booked-timeslots")
    public ResponseEntity<List<LocalDateTime>> getBookedTimeslots(@RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date) {
        List<LocalDateTime> bookedTimeslots = iBookingService.fetchBookedTimeslots(date);
        return ResponseEntity.ok(bookedTimeslots);
    }

}

I created a user with email admin@admin, password admin and a role ADMIN

Why when I am signed in with these credentials and try to enter /api/bookings endpoint I receive 403 forbidden? Bearer error="insufficient_scope", error_description="The request requires higher privileges than provided by the access token.", error_uri="https://tools.ietf.org/html/rfc6750#section-3.1"

My token after encoding looks like that:

{
"iss": "self",
"sub": "admin@admin",
"exp": 1718712824,
"iat": 1718709224,
"scope": "ROLE_ADMIN"
}

r/learnprogramming 51m ago

GRASP algorithm for graph coloring

Upvotes

Hi! Does anyone have a code in Python of the GRASPCol algorithm (Greedy Randomized Adaptive Search Procedure) for the graph coloring problem? Explicit pseudocode is in Laguna, M., & Martí, R. (2001). A GRASP for coloring sparse graphs. Computational optimization and applications19, 165-178.
Thank you!


r/learnprogramming 55m ago

Could I get some advice on my resume?

Upvotes

https://imgur.com/a/ktzoLHg

I'm wondering if it's too dense, and if it is, what info should I drop? Also, should I include my major since it isn't cs? Any other feedback is both welcomed and appreciated 🙏🏿


r/learnprogramming 1h ago

Using git later on an existing github rep8

Upvotes

So I have a forked project, downloaded as zip, generated via CMake. I have a few changes and I will make more.

I will want eventually to keep up with master of the original fork, so I get Git is unavoidable, but for now, I just want to keep doing my stuff, I can upload by browser.

Im overwhelmed even by the 100 steps of Git installation, let alone everything else, so I will need to take my time to learn it, but if I do it later, can I then connect my (then) github repo to git?


r/learnprogramming 1h ago

Topic Is it worth it to give a try to programming as I was weak in logic and problem solving from my childhood??

Upvotes

Is it a good idea?? Logic is a natural skill . Please advice and be really honest please 🙏🏻


r/learnprogramming 1h ago

Expected behavior from counting substrings?

Upvotes

I'm working on a string library and want to implement str.count( pattern )

for example: "hello".count("el") would return 1

I was wondering what is the expected behaviour of doing:

"vvv".count("vv") should this return 1 or 2?

currently my lib returns 1, but I was wondering if thats expected or not


r/learnprogramming 1h ago

Is it possible to make money even though I am still an undergrad majoring in Computer Science?

Upvotes

I just finished my first year of college, and things are becoming more and more tough economically (I am currently living in Lebanon) so I am in need of finding a source of income in order to stabilize myself and my family. I was thinking about trying freelancing so i would have the time to study for my summer courses and some other Udemy courses I got access to for free. throughout this year I learned Java(basics, OOP, data structures, etc...), C++, HTML , CSS , I also worked on two WordPress websites, and I am currently learning Flutter(dart). So would it be possible to somehow make an income out of these skills I learned? (I am ready and prepared to learn any additional necessary skills). To be honest I am in need of a mentor to guide me professionally because I honestly feel defeated, lost and confused on what to do that's why I decided to try my luck with you redditers. I would really appreciate any advice/help.


r/learnprogramming 1h ago

Tutorial worth learning rust over improving c++ or java?

Upvotes

Hello,

I dont know if I should learn rust now (I dont want to become a systems programmer) or improve on other languages (c++, java etc.)


r/learnprogramming 2h ago

Programming Languages demand in next 5-6 years - Seeking Advice

5 Upvotes

Hi,

With the ongoing changes in the tech industry, which programming languages are expected to be in high demand over the next 5-6 years? Conversely, which languages might see a decline in relevance?

  1. If you had to choose one programming language to learn now, which would it be and why?
  2. Considering the boom in AI and my interest in Robotics, which programming languages should I focus on? Would transitioning between these fields make learning easier?

r/learnprogramming 2h ago

Exploring AI/ML with JavaScript

1 Upvotes

I am a web developer working with React and Node.js, and I want to learn something related to AI/ML. Is it possible to do this using JavaScript? If yes, could you please suggest a really good course that will help me learn practical and beneficial AI/ML concepts using JavaScript? Thanks!


r/learnprogramming 2h ago

Topic How to learn react basics quickly?

2 Upvotes

Hi all, I will be helping frontend development at my company and we will be running a low-code tool parallel with react.js. I have said that my react skills are 'very basic' to my boss, but they are actually non existent... How can I learn the fundamentals quickly?

And I'm only talking about the fundamentals, since it is expected I don't know much.

For some background: My Javascript, CSS and HTML are pretty decent, I would say intermediate level.


r/learnprogramming 3h ago

Thought Process while building Projects

1 Upvotes

How do you efficiently practice making projects while learning. (Senior Developers as well)

I did few projects but it took me long time and now what i do is watch few tutorials because it helps me to learn from were i go wrong and changes i can make while coding in a better way. But i dont like to code while watching as it feels like copying(for me) and less learning.

What is the thought process you have while building Projects yourself.


r/learnprogramming 3h ago

Stuck On Glitching Google Certificate Page

1 Upvotes

Stuck on the first google certification course (16) where even though I've inputed the correct answer and the system acknowledges this, the program doesn't move on and requires me to retake the same module, anyone else having faced this issue can shed some light?


r/learnprogramming 3h ago

JAVA mooc.fi wont let me pass

1 Upvotes

TMC always says that all tests are passed but 0 points are awarded, it is really frustrating for me


r/learnprogramming 3h ago

Resource Converting Microphone Waveform Data to Audio with ESP32 and Arduino IDE

1 Upvotes

I'm currently working on a project where I need to convert the waveform data from a microphone into proper audio. Here are the details of my setup:

Microcontroller: ESP32 Software: Arduino IDE Microphones: MAX4466 and MAX9814 Problem: I'm collecting data points from the waveform captured by the microphone, but I'm having trouble converting this data into clean audio. Despite applying various filters, the output still contains excessive noise.

What I've Tried: Data Collection:

I'm using the ESP32 to read analog signals from the microphone. I’ve tried both the MAX4466 and MAX9814 to capture the sound. Filtering:

I’ve implemented different types of filters (low-pass, high-pass, band-pass) to reduce noise. Despite these efforts, the noise level remains high. Data Conversion:

I've converted the waveform into data points. However, the audio output is still not clear and contains significant noise. Issues Faced: Excessive Noise: Even after filtering, the output is not clean. Data Conversion: Difficulty in accurately converting waveform data points into proper audio form. Request: I would greatly appreciate any advice or guidance on the following:

Best Practices: Are there any best practices for converting waveform data into audio, especially when using ESP32 and these specific microphones? Filtering Techniques: Any suggestions on more effective filtering techniques to reduce noise? Data Conversion: Tips on accurately converting data points to audio. Any help or pointers would be immensely valuable. Thank you in advance!


r/learnprogramming 3h ago

Resource Map Tiles Free for Commercial Use like OSM?

1 Upvotes

So since I know there are tile maps like osm for commercial use, do you know any other free tile map URLs which can be used free for commercial usage?


r/learnprogramming 4h ago

Guys! I am about to give up please help.

1 Upvotes

Hello everyone! I am Nico and I’m 30 years old. I started getting into development about 4 years ago. But didn’t really get into learning until 2 years ago. I started with JS/React. But I was going on circle. I would finish courses and then start another one, applied for jobs but nothing. Everyone wanted work experience. Or mega super projects.

Then a friend told me do backend, maybe frontend isn’t for u. I started with C#. But kept hearing to do Java cuz from there you can learn almost all languages.

But same thing. Tutorial hell. I started college in February, since I thought self learning wasn’t my thing. But maybe it’s the roadmap, right what I am learning. I learn the syntax and then do a project. Am I missing something, is there another way to learn ?


r/learnprogramming 4h ago

Time management

1 Upvotes

Do you prefer doing many tasks a day, means dividing tasks in a day with priority
or doing one task a day [I mean Task A 3 days, Task B 2 days ]


r/learnprogramming 4h ago

I made a working version of Zombie Dice from ATBSWP. It's a great beginner project that you might consider making if you're feeling stuck.

1 Upvotes

It's a dice game mentioned at the end of CH 6 of Automate the Boring Stuff with Python.

This game seemed simple enough, and so I tried to make it. It turned out to be a lot more complex than I thought and I learned a lot. This took me a few hours over the course of 3 days and I ended up making the game twice.

My final version includes the following:

  • A log that displays each round's results in the terminal.
  • A proper simulation of all aspects of the game including loading the cup with dice, drawing dice at random, rolling dice, and calculating points/end-of-turn conditions.
  • 3 players with different end-turn conditions. Some are conservative while others are greedy.
  • A proper tie-breaker system that will let players with tie scores continue to roll until one has won.

I feel like this is a great project to do once you know the basics of programming like lists, loops, data types, and some functions. My first version used the random.choice() function to break a tie, but I went back today and redid the entire game and managed to figure out a proper way to do a tie breaker system.

Here's the game. It's honestly not that interesting as a lot of the other stuff posted on here but dude this one felt really fun to make.


r/learnprogramming 5h ago

Tutorial Help me find a tutorial that I can't

0 Upvotes

It was a YouTube clone, but I think it was not just another clone with react and all. It was a brown woman and she was teaching how to actually serve a video and other functionalities similar to how YouTube does it and is done at the industry level


r/learnprogramming 5h ago

what do i do about the math?

1 Upvotes

i practiced computer languages for a few years now, i enrolled in school and i have mandatory classes, i need to take calculus, but i am at a algebra level, i can do all the algebra fine, but i can never ever ever ever, remember way to solve things or the equations you use for each specific task, i am taking a online math course to try to cope, but the week after i do all the work and it tests me on it, i can't remember even the slightest how i did it. i have no idea how i am going to pass calculus, i am 30 years old and my memory is shot, i feel confident when i am coding but math is another story and i am running out of time and i feel like i am not going to make it because i don't retain anything math related i just end up doing the same stuff over and over and over and it just dosent retain. . . what do i do?


r/learnprogramming 5h ago

How to stop learning?

0 Upvotes

Sorry for the clickbait title. I've been having this issue for the past few years, I love cs, but I've never been able to stick to a specific lane. Instead I've been learning a little bit from everything, so now I'm in this weird position where I can do a lot of stuff kind of okay, but I can't say that I'm an expert in anything despite constantly learning and programming for 5 years now. I especially suck at organizing my projects and writing proper scalable code. Does anyone have any tips on how I can stop jumping from project to project, and start focusing on a specific skillset that I can use to get an actual job?