Posts by Victor Stafusa • 63,338 points
1,321 posts
-
5
votes1
answer72
viewsA: How to force the user to pass a type to a generic class?
You have to declare the method func as generic if you want it to work for any UnitType and with generic types (Quantity<T>). However, if you want to use a specific type, you only use the…
-
1
votes1
answer93
viewsA: Use if with matrices
First I’ll reformat your code to make it very visible. I’ll take the part where you put the if because I was wrong: #include "stdio.h" int main(void) { float MatOriginal[3][5], MatFinal[3][5]; //…
-
5
votes2
answers97
viewsA: Is it correct to program returning exceptions to the expected event?
Exceptions serve to signal that something has failed. Exceptions checked (checked), that is to say, Exception and their subclasses that are not RuntimeException, serve to signal things that must be…
-
0
votes3
answers71
viewsA: Algebraic System - Python
Look, one approach to solving this problem is to think with classes, objects and methods. You have an object, which is an array. This matrix can have methods for obtaining a value, changing a value,…
-
2
votes1
answer134
viewsA: Problems with a date validation function in C
The parameter valor of function validaData is passed by value. So when you do scanf("%d", &valor);, you will change only the value of the local variable valor, but this will not alter the…
canswered Victor Stafusa 63,338 -
2
votes1
answer46
viewsA: Error in C Stack implementation
Try this: #include<stdio.h> #include<stdlib.h> typedef char Item_Pilha; typedef struct Pilha { int max; int topo; Item_Pilha *item; } Pilha; Pilha *criar_pilha(int m) { Pilha *p = (Pilha…
canswered Victor Stafusa 63,338 -
4
votes1
answer42
viewsA: In Java Swing, should I extend Jpanel and top-level containers like Jframe?
Prefer to use composition rather than inheritance if possible. This way, you could create classes that contain several types fields JPanel, JButton, JRadioButton, etc. and use them. If you really…
-
1
votes2
answers351
viewsA: Python Playsound is not playing an audio
For me, it worked perfectly: from gtts import gTTS import playsound import os def falar(texto): sintese = gTTS(texto, lang='pt', slow=False) arq = os.path.join(os.getcwd(), 'fala.mp3')…
pythonanswered Victor Stafusa 63,338 -
2
votes1
answer64
viewsA: Reduce running time in Python simulation
That operation: s = s[:j] + '1' + s[j+1:] This is something very slow. Basically it creates a whole new list by copying all the elements one by one and just swapping one of them in the middle. If…
-
3
votes1
answer379
viewsA: Format numbers correctly in Java
The cause of the problem Your problem is further down. For example, look at this: public class Main { public static void main(String[] args) { double a = 10000999999999999999100.69d; double b =…
-
3
votes2
answers693
viewsA: How to generate a range from A to B-1 in Python?
The answer is for x in range(2, numero):. The first number in range is the first value that is considered to be inside it. The second number is the first that is considered to be outside. Then,…
pythonanswered Victor Stafusa 63,338 -
0
votes1
answer36
viewsA: I tried debugging for a long time, but I can’t correctly omit consecutive repeat characters
I rewrote your show like this: #include <stdio.h> #include <stdlib.h> #include <string.h> void elimina_seguidos_repetidos(char *dst, const char *src) { char ultimo = 0; int i = 0,…
-
2
votes2
answers286
viewsA: Remove characters that are before another
I suggest you use a StringBuilder. You copy in it the characters one by one, but when you find one #, you delete the last. public class Main { public static void main(String[] args) {…
-
1
votes1
answer56
viewsA: buffered Reader server while(in.read() != -1)
The problem is that when you give the in.read(), you consume a character of the line to be read and store it nowhere, and therefore it ends up being lost. The solution would be to do the following:…
-
5
votes1
answer45
viewsA: Create a range within a for in range() loop?
There are several ways to do this. The most obvious is this: for x in range(2, numero): fazer_alguma_coisa() fazer_outra_coisa() If you want to skip some number within the range, you can do this:…
pythonanswered Victor Stafusa 63,338 -
0
votes1
answer210
viewsA: Thread Pool for multiplication of arrays in java
Try this: package com.example.matrixmult; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList;…
-
1
votes1
answer254
viewsA: algorithm that finds prime numbers in an interval
Typo: if(cont % n == 0); primo++; The problem is the semicolon at the end of the if that shouldn’t be there. Ah, and as an observation, the variable primo you should actually call yourself…
canswered Victor Stafusa 63,338 -
2
votes2
answers96
viewsA: Python loop requesting data reentry
Change the function name vetor for something that makes clear the intention to read user data and store the results in a variable, ensuring that this function is called once and only once. For…
-
5
votes2
answers171
viewsA: Besides structures like "for", "while", "goto" or recursion, is there any other way to repeat something in the programming?
Some mechanisms different from those cited: Corollaries. It is also possible to do with creating subprocesses, where a process starts a copy of itself. Some computer viruses/worms do this. Once or…
-
2
votes2
answers159
viewsA: I would like to know all the combinations of 5 numbers between 0 and 100 that add up to 100
Traverse a of 0 until 100. Traverse b of 0 until 100 - a. Traverse c of 0 until 100 - a - b. Traverse d of 0 until 100 - a - b - c. e = 100 - a - b - c - d.…
pythonanswered Victor Stafusa 63,338 -
1
votes1
answer37
viewsA: Nullpointerexception when trying to log into the system inside netbeans
Look at this: } catch (Exception e) { //a linha abaixo serve de apoio para esclarecer o erro //System.out.println(e); return null; } That one return null; is a very, very, very bad idea! In addition…
-
0
votes2
answers31
viewsA: Error in condition return
The correct condition is as follows: if (mes >= 1 && mes <= 12 && dia >= 1 && dia <= 31 && ano >= 1) { printf("\nEssa data eh valida!"); } else {…
-
0
votes1
answer144
viewsA: Square and cube of the same variable in C
I see you’re using pointers, but in the wrong way. One possibility would be to use a function like this: void quadrado_cubo(int valor, int *quadrado, int *cubo) { *quadrado = valor * valor; *cubo =…
canswered Victor Stafusa 63,338 -
5
votes4
answers422
viewsA: What is the best way to convert an int array to String in Java?
Here’s a code that can help you: import java.util.stream.IntStream; public class Main { public static void main(String[] args) { int[] array = {1, 2, 3, 4, 5}; String resposta =…
javaanswered Victor Stafusa 63,338 -
5
votes1
answer59
viewsA: How to deal encapsulated a field that is a list of immutable elements?
From the point of view of encapsulation, I normally consider that the best approach is the following: public class SuaClasse { // Embora AlgumaCoisa seja imutável, a lista em si é mutável. private…
-
4
votes1
answer182
viewsA: Algorithm O(n log n) to identify contiguous intervals given a range list
The Java code I’ve built is as follows: import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * @author Victor Williams Stafusa da Silva */ public class Main { public…
-
2
votes2
answers94
viewsA: How to name the keys of a dictionary from a list (array)?
Suppose you have the following: dados = {"batata": [1, 2, 3], "abacaxi": [4, 5, 6]} And then you do it: names = ['macaco', 'gato'] dados.keys() = names Which of these would be the result? dados =…
-
2
votes4
answers333
viewsA: Bring only the values of the Python keys
Try this: def AlunoeNota(lista, nome): print('Aluno da FHO ' + nome + '- SI' ) for disciplina in lista: print(disciplina['nota']) disciplina1 = {'nome': 'Python', 'sigla': 'F0D4', 'periodo':…
pythonanswered Victor Stafusa 63,338 -
3
votes1
answer99
viewsA: Java Arraylist Equals - Do not allow element duplicity in Arraylist
First, we see this: public class Emprestimo { private ArrayList<Emprestimo> emprestimo = new ArrayList(); // ... Mais código aqui ... } This makes no sense. It means that a Emprestimo has a…
javaanswered Victor Stafusa 63,338 -
2
votes2
answers598
viewsA: Error in @Onetomany mapping with JPA and Hibernate
When the relationship is bidirectional, you should connect the two sides of the relationship explicitly: private Sale nova(SaleDto saleDto, BindingResult result) throws ParseException { SaleItem…
-
2
votes1
answer325
viewsA: Power Building Exercise in C
In the variable s, you should be multiplying x and not x*x. Besides, it shouldn’t be adding up anything (that + s). Here is your revised program. It also works for negative whole powers: #include…
canswered Victor Stafusa 63,338 -
1
votes2
answers158
viewsA: How to reduce the amount of Elif
I would try to move the code that is in common across all branches of if out of it (either before or after). Put all these ifs in a part function also helps. def criar_setor(lista): if "SAME" in…
pythonanswered Victor Stafusa 63,338 -
1
votes2
answers558
viewsA: Java Calculator Problem Using Switch Case
You don’t need to pass result/z as a parameter. You want to read the value of escolha before the switch. And not after. Think about switch as if it were a sequence of ifs. What did you put in…
javaanswered Victor Stafusa 63,338 -
0
votes4
answers353
viewsA: Doubt with error - comparisons against strings
The code can be simplified in this way: function podeSeAposentar(idade, sexo, anosTrabalhados) { return anosTrabalhados >= 40 && idade >= (sexo === 'F' ? 60 : 65); } If he keeps…
javascriptanswered Victor Stafusa 63,338 -
1
votes1
answer42
viewsA: Java array changing itself
Instead: int[][] newSon = new int[coordenadasX.length/2][2]; newSon = individuo[0].ordemIndividuos; Do it: int[][] original = individuo[0].ordemIndividuos; int[][] newSon = new…
-
4
votes1
answer58
viewsA: String concatenation behavior in C
Because the C compiler glues/concatenates literals of consecutive strings. For example: #include<stdio.h> int main() { const char *hw = "" "Hello" " " "World" "!" "!" "!"; printf("%s", hw); }…
-
7
votes5
answers1841
viewsA: Why are there so many programming languages?
Among the different reasons we have: Technological evolution. What was invented yesterday may no longer serve today. Today’s need may be different from yesterday’s need. This is one of the reasons…
language-independentanswered Victor Stafusa 63,338 -
2
votes2
answers61
viewsA: Random generation
Basically, you add the length of the intervals and then spread the number in the given intervals. For example, the range of 10 to 15 has 6 numbers (counting the 10 and the 15) and the 20 to 25 has…
-
5
votes1
answer116
viewsA: How to find the intersection between a line and a mathematical function?
You can use the bisection method. You’re basically trying to find the root of this equation: y = |x| - cos(3x) - (mx + b) The root of this equation is where its two lines meet. Like Vector2 works…
-
1
votes1
answer51
viewsA: Vector pointer with dynamic allocation in C
This will create an array with 6 integer pointers. int *valor[6]; The positions of this array are numbered from 0 to 5. But here, you assign something to position 6, outside the array: valor[6] =…
-
1
votes1
answer206
viewsA: Parking Stack
The indentation of your code is a mess. Reindenting your code, you get into it: package estacionamento; import java.util.Scanner; public class Estacionamento { public static void main(String[] args)…
javaanswered Victor Stafusa 63,338 -
4
votes1
answer64
viewsA: How does the creation of a proxy work under the table?
So, like, underneath the covers, Java creates this object? Note that the newProxyInstance receives as first parameter a ClassLoader and as a second, an array of interfaces. What it will do is create…
-
11
votes1
answer118
viewsA: What are "bridge" methods in Java?
What is a bridge method? How to create bridge methods? Why bridge methods have emerged in the history of Java? What problems they solve? These problems were from the Java language or related to some…
-
4
votes2
answers710
viewsA: Select "maximum" elements given a certain criterion in a "stream"
Why don’t you use the method Method.isBridge() to help you? Here comes the MCVE: import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.stream.Stream; public class…
-
2
votes3
answers74
viewsA: Displaying message of no number read and accepting different types of input
Your problem is that maior is returning a list instead of a single element. And then, just function imprimir test by None. def maior(colecao): if len(colecao) == 0: return None if len(colecao) == 1:…
-
3
votes2
answers85
viewsA: Performance testing, how to reduce running time
The fastest way is the one that pushes the complexity of building the list for the compiler or for initialization of the program so that it only needs to be built once. Look at this: import timeit…
pythonanswered Victor Stafusa 63,338 -
1
votes1
answer139
viewsA: Exception in thread "main" java.awt.Illegalcomponentstateexception: The frame is Decorated
Let’s see the description of setUndecorated: Disables or Enables decorations for this frame. This method can only be called while the frame is not displayable. To make this frame Decorated, it must…
-
2
votes3
answers95
viewsA: Issue in question Python String/File Manipulation
The while True is infinite and with each iteration, it opens the file and reads its first line. It would only stop if the first line was blank because of the break. I don’t think that’s what you…
-
1
votes1
answer169
viewsA: How to sort my Java list alphabetically?
Try this: @GET @Path("/tipos-debitos") @Produces(MediaType.APPLICATION_JSON) @Permission(grupo = {Grupo.ADMINISTRADOR}) public Response listarDebitosMultas() { final TipoDebitoMultaTO to = new…
-
3
votes1
answer892
viewsA: How to create new routes dynamically python/flask
Before the if request.method == 'POST': is unnecessary, it would be enough to remove the GET from the above and hence no longer needs the if. I think you can do it like this: def pega_dados():…