/r/AskProgramming

Photograph via snooOG

Ask questions about programming.

AskProgramming

All questions related to programming welcome. Wonder how things work? Have a bug you can't figure out? Just read about something on the news and need more insights? We got you covered! (probably)

Do

  1. Ask questions and start discussions
  2. Keep things civil and support each other
  3. Give your threads descriptive titles
  4. Include relevant information when asking for help
  5. Stay on topic in your posts and replies

Don't

  1. Post off-topic material
  2. Troll or flamebait, insult others, or act in bad faith
  3. Self-promote
  4. Ask others to do your work for you
  5. Ask for help in illegal or unethical activities
  6. Repost the same question within 24 hours
  7. Post AI-generated answers

You can find out more about our (preliminary) rules in this wiki article. If you have any suggestions please feel free to contact the mod team.

Have a nice time, and remember to always be excellent to each other :)

/r/AskProgramming

151,011 Subscribers

2

Need Help with Recursive Method Not Printing Negative Numbers in Number Pattern

Hi everyone,

I'm working on a recursive method to print a number pattern, but I'm running into an issue where negative numbers are not being printed. The problem happens when I try to subtract a positive integer repeatedly until a negative value is reached and then add it back until the original value is reached again.

Here’s what I’m trying to achieve:

Given two positive integers as input:

  • The first integer (num) is the starting point.
  • The second integer (step) is the value to subtract and later add back.

I want the method to:

  • Subtract the second integer repeatedly from the first integer until a negative value is reached.
  • Then, once the negative value is reached, it should add the second integer back until the first integer is reached again.

For example:

  • If the input is 12 and 3, the expected output should be: 12 9 6 3 0 -3 0 3 6 9 12

The problem is that the negative numbers aren't being printed properly in my current code.

Here’s the code I’ve written so far (I'll post it below), but the negative numbers are missing. I’d really appreciate any help or suggestions to fix this!

Thanks in advance!

import java.util.Scanner;

public class NumberPattern {
   public static void printNumPattern(int num1, int num2) {
      System.out.print(num1 + " ");
      
      if (num1 <= 0) {
         return;
      }
      
      printNumPattern(num1 - num2, num2);
      System.out.print(num1 + " ");
   }
  
   public static void main(String[] args) {
      Scanner scnr = new Scanner(System.in);
      int num1;
      int num2;
      
      num1 = scnr.nextInt();
      num2 = scnr.nextInt();
      printNumPattern(num1, num2);
   }
}
1 Comment
2024/11/10
21:26 UTC

2

Issues with acoustic model in Pocketsphinx

I'm trying to access the Catalan acoustic model in pocket sphinx. I used the following code but I'm getting an error saying that the folder 'acoustic-model' doesn't contain an mdef file. It does. I've checked and rechecked, so I'm not sure if I just downloaded the files incorrectly??? I'm fairly new to machine learning, so I'm sorry if I sound like I have no idea what I'm talking about.

from pocketsphinx import Pocketsphinx

# Specify the paths to acoustic model, language model, and dictionary

config = {

'hmm': 'Operation BlabberMouth/acoustic-model', # Path to the Catalan acoustic model folder

'lm': 'Operation BlabberMouth/language-model.lm.bin', # Path to the Catalan language model

'dict': 'Operation BlabberMouth/pronunciation-dictionary.dict' # Path to the Catalan dictionary

}

# Initialize the Pocketsphinx decoder with the Catalan configuration

ps = Pocketsphinx(**config)

# Decode an audio file in Catalan

ps.decode(audio_file='0011.wav')

# Print the decoded text in Catalan

print("Decoded Text:", ps.hypothesis())

0 Comments
2024/11/10
20:49 UTC

1

Hello, I do not know if this is the place for this, but, how much would a programmer charge for creating a secure login system for health/patient information?

basically we are creating a website in Brazil and we would need to have a login system, that is secure because of the sort of information related (health, exams etc), so that each client will have a different page with their own information.

how much would this cost normally?

6 Comments
2024/11/10
18:36 UTC

5

Help! My neural network isn't learning

For the weekend, I thought it would be fun to implement backpropagation in rust without looking at any examples or tutorials, but over the last few hours, I've been descending into madness. I think that my math is correct, as my equations match those on wikipedia. The code, however, is not and I can't understand why. When training for XOR it will get stuck on a high loss for 95% of the runs. But for the other 5%, it converges very quickly (probably by pure luck of good initial parameters).

I have played with different learning rates and tried adding a decay rate, without any succes.

If there's anyone who could look at my code and tell me what I'm doing wrong, I will be very grateful.

github

2 Comments
2024/11/10
18:00 UTC

0

Is it possible for compilled programming languages to have named parameters?

Is it possible for compilled programming languages to have named parameters? For example in PHP...

function str_contains(string $haystack, string $needle): bool {}

str_contains('FooBar', 'Foo');

str_contains(needle: 'Foo', haystack: 'FooBar');

Can this even exist in languages like C, C#, C++, Go, Rust? Or is this not possible for conpilled languages since compilled languages require all paramters to be filled out and there cannot be any optional parameters in a compilled language?

11 Comments
2024/11/10
17:59 UTC

0

How can I learn to program again?

I am a CS student and I am about to graduate. However I use a lot of AI and lost a lot of the basics for certain data structures. I want to get better in order to pass a technical interview, I still use AI to explain the questions to me but I still feel it is not enough. I understand to practice and practice but is there a study method to give to a student to learn in depth about a programming language as well accomplish their goal to solve leetcode on their own? Is that a good way to re-learn to practice for a technical interview?

4 Comments
2024/11/10
17:37 UTC

5

Technology

i want to make a vox cosplay using a lcd screen from this guy(https://www.ebay.com/itm/266486913144?toolid=10050&customid=9e12597eab131caf0cfb3fdbb71948bf) and a raspberry pi as a microphone to detect decibel levels as to create a image that swaps back and forth as a illusion of the mouth moving how would i program that or is there a better way?

4 Comments
2024/11/10
16:16 UTC

4

Design patterns where do I find the basic knowledge of it

Hi All

I am attempting to start my first kind of a real app, so I am still in the middle of the learning roadmap that I am following, I have not reached DataBase yet but I am familiar with saving data on files and working with them so :

I need a bit of knowledge about Design Patterns so the transition from saving data on a file system to a DataBase system later on would be easier, so I could have this project on my professional CV later on.

I have a general idea about the Interfaces I wanted in this project and a general idea about how the (class and inheritance) map would look like, but I don't have any real knowledge about Design Patterns I just needed them at this stage.

3 Comments
2024/11/10
14:25 UTC

2

not generating .uf2 file

Hi I'm trying to run Tetris on my pi pico but when I try to use cmake it almost never works and never generates a .uf2 file here's the error -- The C compiler identification is GNU 14.2.0 -- The CXX compiler identification is GNU 14.2.0 -- Detecting C compiler ABI info -- Detecting C compiler ABI info - done -- Check for working C compiler: C:/msys64/mingw64/bin/cc.exe - skipped -- Detecting C compile features -- Detecting C compile features - done -- Detecting CXX compiler ABI info -- Detecting CXX compiler ABI info - done -- Check for working CXX compiler: C:/msys64/mingw64/bin/c++.exe - skipped -- Detecting CXX compile features -- Detecting CXX compile features - done Using PICO_SDK_PATH from environment ('C:\pico\pico-sdk') PICO_SDK_PATH is C:/pico/pico-sdk Defaulting platform (PICO_PLATFORM) to 'rp2040' since not specified. Defaulting target board (PICO_BOARD) to 'pico' since not specified. Using board configuration from C:/pico/pico-sdk/src/boards/include/boards/pico.h Pico Platform (PICO_PLATFORM) is 'rp2040'. -- Defaulting build type to 'Release' since not specified. Defaulting compiler (PICO_COMPILER) to 'pico_arm_cortex_m0plus_gcc' since not specified. Configuring toolchain based on PICO_COMPILER 'pico_arm_cortex_m0plus_gcc' -- The ASM compiler identification is GNU -- Found assembler: C:/msys64/mingw64/bin/cc.exe Build type is Release CMake Warning at C:/pico/pico-sdk/tools/Findpicotool.cmake:28 (message): No installed picotool with version 2.0.0 found - building from source

It is recommended to build and install picotool separately, or to set PICOTOOL_FETCH_FROM_GIT_PATH to a common directory for all your SDK projects Call Stack (most recent call first): C:/pico/pico-sdk/tools/CMakeLists.txt:138 (find_package) C:/pico/pico-sdk/src/cmake/on_device.cmake:33 (pico_init_picotool) C:/pico/pico-sdk/src/rp2040/boot_stage2/CMakeLists.txt:57 (pico_add_dis_output) C:/pico/pico-sdk/src/rp2040/boot_stage2/CMakeLists.txt:101 (pico_define_boot_stage2)

Downloading Picotool CMake Warning (dev) at C:/msys64/mingw64/share/cmake/Modules/FetchContent.cmake:1953 (message): Calling FetchContent_Populate(picotool) is deprecated, call FetchContent_MakeAvailable(picotool) instead. Policy CMP0169 can be set to OLD to allow FetchContent_Populate(picotool) to be called directly for now, but the ability to call it with declared details will be removed completely in a future version. Call Stack (most recent call first): C:/pico/pico-sdk/tools/Findpicotool.cmake:46 (FetchContent_Populate) C:/pico/pico-sdk/tools/CMakeLists.txt:138 (find_package) C:/pico/pico-sdk/src/cmake/on_device.cmake:33 (pico_init_picotool) C:/pico/pico-sdk/src/rp2040/boot_stage2/CMakeLists.txt:57 (pico_add_dis_output) C:/pico/pico-sdk/src/rp2040/boot_stage2/CMakeLists.txt:101 (pico_define_boot_stage2) This warning is for project developers. Use -Wno-dev to suppress it.

-- Found Python3: C:/Users/mav/AppData/Local/Programs/Python/Python313/python.exe (found version "3.13.0") found components: Interpreter TinyUSB available at C:/pico/pico-sdk/lib/tinyusb/src/portable/raspberrypi/rp2040; enabling build support for USB. BTstack available at C:/pico/pico-sdk/lib/btstack cyw43-driver available at C:/pico/pico-sdk/lib/cyw43-driver lwIP available at C:/pico/pico-sdk/lib/lwip mbedtls available at C:/pico/pico-sdk/lib/mbedtls -- Configuring done (8.7s) CMake Error: Error required internal CMake variable not set, cmake may not be built correctly. Missing variable is: CMAKE_ASM_COMPILE_OBJECT -- Generating done (0.2s) CMake Generate step failed. Build files cannot be regenerated correctly

1 Comment
2024/11/10
11:46 UTC

4

I don't know where to go

Hi,

I learned C++ but only the basic of basics but I don't know where to go from there some people told me problem solving and other's told me build projects, yet when i watched youtube for a roadmap the video told me like API and Frameworks and stiff I don't know either of these things please some guidance

2 Comments
2024/11/10
11:35 UTC

4

Backend and API languages to use

I am currently planning a hobby project and am still deciding on a language for backend and API development. I will be using Postgresql for the database, and planning a website and an Android app which will communicate with the backend.

I've worked with Node Express before and thought to do same but with TypeScript. In the end I know it doesn't matter much but was thinking maybe learning something else than what I'm using for my job everyday and was wondering what you guys find as an enjoyably language to use for projects as such, or something that would be interesting to learn to use.

14 Comments
2024/11/10
11:30 UTC

8

What is the status of Mojo (Programming Language)

I am curious about the status of Mojo Language, the supposed superset of python. I was very interested in it was it was making all the noise about performance and the how it will transform the AI space, but couldn't really make time to learn it.

These days I have some time to spare and was considering getting into it, but I have a few questions below.

  1. Is it ready yet?
  2. Is it worth learning it now?
  3. What type of projects can you use it for?
  4. Are there good open source projects that are using Mojo right now?
  5. How does it compare to the already existing python tools that focus on performance like Numba, Cython and the others?
8 Comments
2024/11/10
11:07 UTC

2

New MacBook - Python installation

Hi everyone!

I've bought a new Macbook and will continue learning python with it. I have installed python through homebrew and am wondering if the installation I have now is correct.

When I type “which python3” in the terminal I get:

/opt/homebrew/bin/python3

Which I think is correct (must be homebrew's and not the system's version here?)

When I type “where python3” I get the following:

/opt/homebrew/bin/python3

/opt/homebrew/bin/python3

/usr/bin/python3

I find it a bit strange that the path to homebrew appears twice, but is this because maybe there are two versions of python 3 there? Or did I do something wrong?

I'm asking all this because I want the installation to be correct and as clean as possible, since I'm not going to install packages from pip in global, but in virtual environment per project.

Thanks!

19 Comments
2024/11/10
08:43 UTC

0

Use of ChatGPT

Hey everyone, I just want everyone's opinion.

Is it fine if I use ChatGPT to "give me explanation" rather than "giving an answer" when it comes to studying and going hands on in programming and machine learning?\

I have this dilemma of using AI like Google Gemini and ChatGPT to help me study programming and machine learning (concepts, terms, foundations, and the likes) but I read somewhere online where the traditional way is better or going hands on without AI.

I've also used Google Gemini and ChatGPT to give me suggestions to improve certain code. I'd use it's suggestions but customize it to suit my code and make sure it works

I want to know your opinion and do you also have the same dilemma as me?

11 Comments
2024/11/10
06:02 UTC

0

Which programing languages have best support for TIMTOWTDI

TIMTOWTDI stands for 'there is more than one way to do it'. Which languages make this a priority.

From the top of my head I can think of perl or maybe even scala, and as for not allowing it python and go comes to mind.

34 Comments
2024/11/10
01:25 UTC

1

Pls I need help with this

I need help with a college project in which I don't know how to write the code in Python.

I only did the logic for the points, I don't know how to do the average, if someone throws a cross it would help me a lot. The results must be independent and deterministic

I need to create the following model for a particular team, where I obtain the match data through a fixture.csv (structured: home, away, date) and the other data from averages.csv (structured: #,Team, 22,23,24,Pts,PJ,Avg)
My approach is the following:
Decision variables:
-Pac,i= points that team i obtains in the remaining games.
-Vij = 1 if team i wins the match with team j, 0 otherwise.
-Eij = 1 if team i ties with team j, 0 otherwise.

Objective function:
- Max_Points: sum of the first date of team i to the last date of i of Pac,i
Restrictions:
-One result per match: Vij+Eij+Dij=1
- Accumulated points Pac,i = Sum of j (first date of team i) until the last date of i, of (3Vij + Eij) that is, 3 points for victory and one for a draw (if they lose or win)
- A restriction is that both this target team is always one of the last 2 on the list.

The idea is that this is done by one team at a time, that is, to have a for loop at the end that repeats this process and gives me the minimum amount of points that the team needs to avoid relegation.

I leave the teacher's instructions:

In Argentine soccer nothing lasts forever, and the rules change all the time. The Chiqui
 Tapia has decided that relegations this season will be a reality, and they caught fire
 the alarms of all the clubs.
 The conditions will be the following:
 ● Relegation by Annual Table: The two teams with the fewest points in the annual table at
 finish the last date of the tournament they will be automatically relegated.
 ● Relegation by Averages: The two teams with the lowest average points,
 contemplating the last two seasons played and adding the current one to the moment
 upon completion, they will automatically descend. If a team is already relegated by table
 annually, the next team in the average table will take its place.
 The objective of the work is to determine the minimum number of points that each team needs
 to guarantee their permanence in the category, without depending on the results of others
 teams. That is, how many points must my team score to, even in the worst scenario
 possible, ensure salvation. Is my equipment safe now?
 To solve this, they will have to develop a mixed integer linear programming model that
 Analyze this situation for each team.
 The following attachments are included:
 ● averages.csv: A position table that includes both seasons
 previous and the current one in progress.
 ● fixture.csv: A CSV file containing the remaining matches to be played.
0 Comments
2024/11/09
23:13 UTC

0

Duda UML

Perdón por escribir en español, no he repasado mi inglés bien como para redactar de manera clara mi duda.

Tengo que realizar un modelo UML para la propuesta de un proyecto que realice, tengo dos problemas principalmente.

  1. No puedo usar la herramienta que tengo para modelar (StarUML)

  2. Se como hacerlo, pero quisiera consultar ante ustedes si hay una manera de expandir aún más mi modelamiento, es decir expandir más su contenido o también modelarlo mejor (Es sobre una app de reciclaje que permite la obtención de puntos por cantidad de material reciclado a cambio de objetos IRL)

Muchas gracias por detenerse a leerme, perdón si no está en inglés.

0 Comments
2024/11/09
22:59 UTC

3

Common naming conventions for JavaScript and PHP?

I understand that that is not official standard on how to name variable and constants for JavaScript and PHP. However is it common to do the following for both languages...

  • All variables, functions and non-primitive constants (objects, arrays) use camelCase names
  • All primitive constants use SCREAMING_SNAKE_CASE names

This seems to make sense for readability and seems to be common standard for both of these programming languages.

8 Comments
2024/11/09
20:24 UTC

2

Optimising greedy algo to search for matching lines across files

currently I have this below code:

from collections import defaultdict
import re

# Parameters
X_percent = 0.93  # Desired coverage percentage (e.g., 93%)
lambda_penalty = 500  # Adjusted penalty
max_attack_time = 3600  # Maximum allowed execution time per attack in seconds
max_total_time = 20 * 3600  # Maximum total execution time in seconds (15 hours)
min_new_plains = 10  # Minimum number of new plains an attack must cover
max_plain_weight = 5  # Maximum weight assigned to any plain
set_a_directory = '/root/setA/'  # Directory containing Set A files
file_b_path = '/root/h.txt'  # Path to File B

# Step 1: Read File B and assign unique IDs to plains
plain_to_id = {}
id_to_plain = {}
with open(file_b_path, 'r') as f:
    for line in f:
        plain = line.strip()
        if plain not in plain_to_id:
            plain_id = len(plain_to_id)
            plain_to_id[plain] = plain_id
            id_to_plain[plain_id] = plain

total_plains = len(plain_to_id)
print(f"Total number of plains in File B: {total_plains}")

# Step 2: Process Set A files and build data structures
attack_info = []
plain_to_attacks = defaultdict(set)  # Maps plain ID to set of attack indices

# Regular expression to extract time from file name
time_pattern = re.compile(r'^(\d+)_')

# Iterate over each file in Set A
for file_name in os.listdir(set_a_directory):
    file_path = os.path.join(set_a_directory, file_name)
    
    # Extract execution time from file name
    time_match = time_pattern.match(file_name)
    if not time_match:
        continue  # Skip files that don't match the pattern
    execution_time = int(time_match.group(1))
    
    if execution_time > max_attack_time:
        continue  # Exclude attacks over the maximum allowed time
    
    with open(file_path, 'r') as f:
        lines = f.readlines()
        if not lines:
            continue  # Skip empty files
        attack_command = lines[0].strip()
        plains_covered = set()
        
        for line in lines[1:]:
            parts = line.strip().split(':')
            if not parts:
                continue
            plain = parts[0].strip()
            if plain in plain_to_id:
                plain_id = plain_to_id[plain]
                plains_covered.add(plain_id)
                plain_to_attacks[plain_id].add(len(attack_info))  # Index of this attack
        
        attack_info.append({
            'command': attack_command,
            'time': execution_time,
            'plains': plains_covered,
            'index': len(attack_info)
        })

num_attacks = len(attack_info)
print(f"Total number of attacks in Set A after filtering: {num_attacks}")

# Step 3: Compute the number of attacks covering each plain (f_p)
plain_cover_count = {}
for plain_id in plain_to_id.values():
    cover_count = len(plain_to_attacks[plain_id])
    plain_cover_count[plain_id] = cover_count

# Step 4: Assign weights to plains with a maximum weight
plain_weights = {}
for plain_id, f_p in plain_cover_count.items():
    if f_p > 0:
        plain_weights[plain_id] = min(1.0 / f_p, max_plain_weight)
    else:
        plain_weights[plain_id] = max_plain_weight

# Step 5: Implement the weighted greedy algorithm with adjusted efficiency
total_plains_needed = int(total_plains * X_percent)
print(f"Number of plains needed for {X_percent*100}% coverage: {total_plains_needed}")

covered_plains = set()
selected_attacks = []
remaining_attacks = set(range(num_attacks))
total_execution_time = 0

while len(covered_plains) < total_plains_needed and remaining_attacks:
    best_efficiency = -1
    best_attack = None

    for i in remaining_attacks:
        attack = attack_info[i]
        new_plains = attack['plains'] - covered_plains
        if len(new_plains) < min_new_plains:
            continue  # Skip attacks that cover too few new plains
        # Calculate W_i (sum of weights of new plains)
        W_i = sum(plain_weights[p] for p in new_plains)
        # Adjusted Efficiency E_i
        efficiency = (W_i * len(new_plains)) / (attack['time'] + lambda_penalty)
        if efficiency > best_efficiency:
            best_efficiency = efficiency
            best_attack = i

    if best_attack is None:
        print("No further attacks can improve coverage.")
        break

    # Check if adding this attack exceeds the maximum total execution time
    if total_execution_time + attack_info[best_attack]['time'] > max_total_time:
        print("Reached maximum total execution time limit.")
        break

    # Select the attack with the highest adjusted efficiency
    selected_attacks.append(best_attack)
    covered_plains.update(attack_info[best_attack]['plains'])
    remaining_attacks.remove(best_attack)
    total_execution_time += attack_info[best_attack]['time']

    # Optional: Print progress
    coverage_percentage = (len(covered_plains) / total_plains) * 100
    print(f"Selected attack {best_attack}: Coverage {coverage_percentage:.2f}%, "
          f"Total Time: {total_execution_time / 3600:.2f} hours")

# Step 6: Output the results
print("\nSelected Attacks:")
for idx in selected_attacks:
    attack = attack_info[idx]
    print(f"Attack Index: {idx}")
    print(f"Command: {attack['command']}")
    print(f"Time: {attack['time']} seconds")
    print(f"Plains Covered: {len(attack['plains'])}")
    print("-----------------------------")

final_coverage = (len(covered_plains) / total_plains) * 100
print(f"Final Coverage: {final_coverage:.2f}%")
print(f"Total Execution Time: {total_execution_time / 3600:.2f} hours")
print(f"Total Attacks Selected: {len(selected_attacks)}")

I have a directory of files, we will call this Set A files. Each file has a runtime as the file name follow by _Randstring.txt, The first line in each file is a command/attack and the rest of the lines are 2 columns seperated by ":" that are produced by that command/attack(the result of another program), the left side is what we can call plains, the right side can be ignored. I have another file seperate we can call file B. This has 121k lines of plains. My goal with this python program is to find commands/attack chains thats files plains match a certain percentage of plains in file B in the shortest time possible. The plains in Set A files have a lot of overlap and I have 3600 files with a total of 250million lines, so time/computation is an issue hence the greedy algo. Currently my python code isn't producing the best results, its choosing too many attack chains and too high run time(ints from file names). Is there any way I can make this better so the attack chain it chooses is more "optimal", I don't mind waiting a few hours and have 192core 256gb PC. Thanks

0 Comments
2024/11/09
20:01 UTC

0

C/C++ are officially dead: Are they still worth learning though?

According to the article below, the US government wants us to stop using c/c++

What do you think?

Are they still worth learning though for a solid foundation in systems programming?

https://www.theregister.com/2024/11/08/the_us_government_wants_developers/

18 Comments
2024/11/09
19:53 UTC

3

Non Cohesive pdf image extraction as Cohesive

Is there a way, in python to extract an image from pdf cohesively. Since sometimes a pdf might have an image that is actually formed from many cutouts. These cutouts are extracted instead of one whole image for my problem.

0 Comments
2024/11/09
19:39 UTC

46

Why have modern programming languages reversed variable declarations?

So in the old days a variable declarations would put the type before the name, such as in the C family:

int num = 29;

But recently I've noticed a trend among modern programming languages where they put the type after the name, such as in Zig

var num : i32 = 29;

But this also appears in Swift, Rust, Odin, Jai, GoLang, TypeScript, and Kotlin to name a few.

This is a bit baffling to me because the older syntax style seems to be clearly better:

  • The old syntax is less verbose, the new style requires you type "var" or "let" which isn't necessary in the old syntax.

  • The new style encourages the use of "auto". The variables in the new camp let you do var num = GetCalc(); and the type will be deduced. There is nothing wrong with type deduction per se, but in this example it's clear that it makes the code less clear. I now have to dive into GetCalc() to see what type num is. It's always better to be explicit in your code, this was one of the main motivations behind TypeScript. The old style encourages an explicit type, but allows auto if it's necessary.

  • The old style is more readable because variable declaration and assignment are ordered in the same way. Suppose you have a long type name, and declare a variable: MyVeryLongClassNameForMyProgram value = kDefaultValue;, then later we do value = kSpecialValue;. It's easy to see that value is kDefaultValue to start with, but then gets assigned kSpecialValue. Using the new style it's var value : MyVeryLongClassNameForMyProgram = kDefaultValue; then value = kSpecialValue;. The declaration is less readable because the key thing, the variable name, is buried in the middle of the expression.

I will grant that TypeScript makes sense since it's based off JavaScript, so they didn't have a choice. But am I the only one annoyed by this trend in new programming languages? It's mostly a small issue but it never made sense to me.

53 Comments
2024/11/09
19:06 UTC

0

What languages are best suitable for remote development?

I want to code on the phone when I have time so what languages are most suitable to mobile version of vscode or terminal and do some code changes etc.

Should I go with interpreted or compiled?

11 Comments
2024/11/09
18:12 UTC

0

How to figure out how to decrypt weird symbols in my file?

This is part of the text btw:

ꄏ⠍âCX ë âKX ë  á ”åâ 0å  á3ÿ/áTO⠍â8X ë â@X ë  á ”åâ 0å  á3ÿ/á ”åå  á1ÿ/á Uã8  ‘1ÿ/DЍâð€½è÷r br Buffer is NULL  -ép@-éxŸå†ßMâ P ã  ãàâØY ë(å Pã ÞV ë @ áÜV ë åŠ/â0å  áå3ÿ/á PãG P ã(å å0 ‘å ã2ÿ/áÍåÿ ã (å å0 ‘å  ã2ÿ/áÍå(å  ã å0‘偍â3ÿ/á @°á+

ÌŸå€/ ãà â®Y 댍⠍åµV ë ` á³V ë åHå  á1ÿ/á  á ââ—W ë âçW ëâ €à,å  á§W ë  ã å âºOâ¿W ë âÛW ë âÙW ë  á ”åâ 0å  á3ÿ/á ”åå  á1ÿ/á Uã( ‘1ÿ/†ßâp ½èðäzq åp Trace: tick=%10d  -éðA-éxŸåŠßMâ  ãà„âpY ëyV ë @ á åHå  á1ÿ/á P á ”å‰/â0å  á¸å3ÿ/á$å å0 ‘å ã2ÿ/áÍåÿ ã $å å0 ‘å  ã2ÿ/áÍå$å  ã å0‘儍â3ÿ/á @°á/

 áú ãÇY ëp á  áá ãÃY ë` á<  ãÀY 뀠á á<  ã¼Y ë ` áœ Ÿå á¸Y ë  á â0 áˆâpå €å*W ë‘â å âxW ëâ €à@å â8W ë  ã å âoW ë  á ”åâ 0å  á3ÿ/á ”åå  á1ÿ/á$å å‘å1ÿ/áŠßâð½èðäíq €î6 %02d:%02d:%02d:%03d-- ðM-ép áHŸåŠßMâ € á  ãà„âY ëV ë @ á V ë å‰/â0å  áTå3ÿ/á$å å0 ‘å ã2ÿ/áÍåÿ ã $å å0 ‘å  ã2ÿ/áÍå$å  ã å0‘儍â3ÿ/á  °á'

¦ Wã@â° á¦p ƒ` ã Wã Ú Wá` ± P ã ê Ø焏â

THERE IS: plain text included, its a smart watch game, and parts of other files are Chinese.

This is the smart watch:

Phyulls Smart Watch for Kids with 24 Games Alarm Clock, Touchscreen, Calendaring Camera Music Player Time Display Video & Audio Recording, Toys for 3-12 Years Old Boys

9 Comments
2024/11/09
17:14 UTC

0

2024 pure maths grad looking to get into the tech industry.

so i am a bsc(hon.) maths grad. i have always had interest in programming was good at python and sql. Now i am learning MERN stack and trying for internships but hardly getting any response, while most of my peers and seniors from clg are learning data analysis or working as an intern as DA. This makes me question my choice whether i coming from maths background try DA instead of development. As i have heard on the internet that people with few yoe as Data analyst earn as high as developers ( 20-30Lpa). which should i go for to get employed asap and learn along with job. (within 5 to 6 months )

1 Comment
2024/11/09
15:43 UTC

3

Anime Fighting Game Style Code Editor with Effects and Sounds – Saw It on Instagram Reel, Can’t Find

I saw an Instagram reel showcasing a code editor with animation and sound effects in an anime or fighting-game style (like Dragon Ball fights). Each letter I typed triggered effects and sounds, and even the cursor movements had these effects, making it feel like a battle scene. The caption mentioned something like 'code editor like Dragon Ball fight,' with a GitHub download link, but I lost the video. Does anyone know where I can find this editor or something similar to this?

2 Comments
2024/11/09
15:06 UTC

3

Stuck in 3D rotation hell. Trying to snap a face to the forward direction.

Here's a clip: https://www.reddit.com/user/Introscopia/comments/1gnb6wv/3d_rotation_hell/

basically I'm spinning the dice. whichever is the forward-most face, that's what you rolled, right? but I want to then snap the face to be exactly facing forwards. This code seems to work about half the time.

D is the dice struct. T is its transform, expressed as a basis triplet.

// grab the resulting face normal in world-space
D->snap_normal = xform_v3d( D->T, D->mesh->tris[v].normal );
v3d_normalize(&(D->snap_normal));
...
// dice has stopped rolling
if( v3d_dot( D->rotvel, D->rotvel ) < 0.00001 ){ 
    D->state = 2;
    static const vec3d FWD = (vec3d){ 0, 0, -1 }; 
    D->snap_axis = v3d_cross( D->snap_normal, FWD ); 
    v3d_normalize( &(D->snap_axis) ); 
    double sign = 1;//( v3d_dot(D->snap_axis, D->snap_normal) > 0 )? 1.0 : -1.0;
    D->snap_total_angle = sign * acos( v3d_dot(D->snap_normal, FWD) );
    D->snap_T_origin = D->T;
    D->snap_timer = 0;
}
...
if( D->state == 2 ){ // SNAPPING

    float t = smooth_step( D->snap_timer / 32.0 );

    double step = D->snap_total_angle * t;
    D->T = D->snap_T_origin;
    rodrigues_rotate_Transform( &(D->T), D->snap_axis, step );

    D->snap_timer += 1;
    
    if ( D->snap_timer >= 32 ){
        D->state = 0;
        D->T = D->snap_T_origin;
        rodrigues_rotate_Transform( &(D->T), D->snap_axis, D->snap_total_angle );
    }
}

When I left off I was thinking that maybe the trick would be to flip the sign of the angle, cause I noticed that setting it negative yielded basically the same results. But I can't figure out what the test is for deciding the direction of rotation... something something right-hand rule?

Any insight is appreciated. Oh and is this the best sub to be asking this? I feel like it's almost more of a math question, but I feel like a math sub won't like to see a big wall of code...

6 Comments
2024/11/09
14:38 UTC

2

Missing logic in rotated array problem.

Can anyone explain where I am missing the logic for finding the pivot in a sorted then rotated array in the below function?

static int pivot(int[] arr){
    int start = 0, end = arr.length - 1;
    while (start < end){
        int mid = start + (end - start) / 2;
        if (arr[mid] <= arr[start]) {
            end = mid - 1;
        } else {
            start = mid;
        }
    }
    return start; //return end or return mid
}
8 Comments
2024/11/09
12:48 UTC

2

In OOP, in the context of using separate objects for persistence vs. business: should the technical/unique ID be passed onto the business model as well?

Suppose a database architecture that uses surrogate keys, so each entity has its unique ID generated by a database sequence. This is regardless of the business unicity on specific field(s). Suppose that your code works with a persistence framework and its associated objects, but the business logic will manipulate another set of objects, so there is a mapping between the two models every time you fetch or persist objects.

Would you include the persistence ID (the PK) in the business models? For the purpose of facilitating fetching other nested (or parent) objects, for example, otherwise you'd have to join tables every time your business needs to fetch related objects.

2 Comments
2024/11/09
12:25 UTC

6

Studied pure math at college, can I become a software developer?

So the title is petty much self explanatory, I've had some experience with programming before (mainly python and java) but not really with frontend/backend/web development. I know the math and logic behind code (some of it) and also have my fair understanding of algorithms and even automatons, is it really possible for me to become a software engineer/developer? My brother (younger than me) studied computer engineering (not finished) but he got interested in programming outside school and now works as a software developer, he has inspired and encouraged me to learn more coding skills and apply for jobs. Any recommendations? It's seems fun to me and I think I can make a career out of it, also, I'll admit, there's good money on it and that's kinda another reason I wanna become a developer.

63 Comments
2024/11/09
08:57 UTC

Back To Top