Posts by Lacobus • 13,510 points
596 posts
-
1
votes2
answers69
viewsA: Error when user provides file name
You can use the function isprint() of the standard library ctype.h to test whether a character is printable. The function fgets() does not remove the \n of the end of string read, and fopen() will…
-
5
votes2
answers4327
viewsA: How to compare the value of a variable to a string in the shell script
1) Single block: if [ "$V1" == "sim" ]; then echo "Sim!" fi In a row: [ "$V1" == "sim" ] && echo "Sim!" 2) Block if/else: if [ "$V1" == "sim" ]; then echo "Sim!" else echo "Nao!" fi In a…
-
3
votes1
answer34
viewsA: Bytearray disk size
You can use the native function len() to calculate the size in bytes of a bytearray, look at you: with open("img.png", "rb") as imageFile: f = imageFile.read() b = bytearray(f) print(len(b)) Exit:…
-
1
votes1
answer506
viewsA: Password when executing postgresql command
To create a new usuario/role in the PostgreSQL, you need the command CREATE ROLE, for example: CREATE ROLE adempiere LOGIN NOSUPERUSER INHERIT CREATEDB CREATEROLE; To create a new usuário/role…
-
1
votes3
answers1041
viewsA: Sort sequence of numbers from a TXT file
Assuming that your input file (arquivo.txt) be something like: 9 8 7 6 5 4 3 2 1 5 3 1 9 7 5 9 8 1 3 4 5 8 3 0 1 0 0 1 2 3 3 2 1 10 11 12 6 3 8 15 20 1 4 2 9 You can implement a function capable of…
-
3
votes2
answers257
viewsA: Mystery Square
You do not mention in the question anything about the sum of the columns, according to Wikipedia the definition of a Quadrado Mágico is: Magic Square is a square table equal to intersection of…
-
5
votes3
answers6645
viewsA: Union of two vectors in C
No tie is needed for to solve your problem! You can use the function memcpy() of the standard library string.h to unite the two vectors into a third vector, see only: int a[5] = { 1, 2, 3, 4, 5 };…
-
0
votes1
answer45
viewsA: Doubt in the use of the to_string function
Increase the accuracy of NumReal replacing its type of: float NumReal; To: double NumReal;
-
2
votes1
answer186
viewsA: Problem splitting a String array into C
Its function DivideString() can be implemented in a much simpler way, see: #include <ctype.h> #include <string.h> void DivideString( const char * txt, char * m1, char * m2 ) { int tam =…
-
2
votes2
answers253
viewsA: copy an entire txt file to a c++ string
You can create an instance of std::string from a std::ifstream, look at you: #include <iostream> #include <string> #include <fstream> #include <streambuf> using namespace…
-
2
votes2
answers109
viewsA: How to average N numbers greater than 6
You can implement a function capable of calculating the arithmetic mean of an integer vector using only elements that have a value below the set limit, see only: double media( int v[], int tam, int…
-
1
votes2
answers109
viewsA: Find and Replace in bash
You can implement a script in gawk to process your files, for example: BEGIN{ } { if( FNR == NR ) { a[FNR] = $0; next; } print (a[FNR] == $0) ? a[FNR] : $0; } END{ } Or, in a line: $ awk…
-
8
votes1
answer388
viewsA: How to work with more than one Python replacement using Replace?
In Python 3, the primitive type str provides interface for this. You can create a translation table using static method str.maketrans() and then perform the replacement operation using the method…
-
1
votes1
answer107
viewsA: Get size of a two-dimensional matrix
It is not possible to determine how much memory was allocated from the pointer only. sizeof(p) is not able to determine at runtime the size of the previously allocated memory block. sizeof(p)…
-
1
votes1
answer447
viewsA: How to copy files preserving their metadata?
shutil.copy2() is perfectly capable of copying the metadata containing the date and time of the last file modification: shutil.copy2( src, dst, * , follow_symlinks=True ) Identical to copy() except…
-
1
votes2
answers120
viewsA: How to format strings and store them in a dynamic vector
The function snprintf() of the standard library stdio.h is able to calculate the size needed to accommodate the formatted string. The secret is to pass a buffer NULL, sized 0, causing snprintf()…
-
1
votes1
answer125
viewsA: Read text file and store fields in variables
Assuming your data structure is something like: struct veiculo_s { char * lote; char * placa; char * uf; char * renavam; char * chassi; char * motor; char * ano; char * marca_modelo; char *…
-
4
votes4
answers2189
viewsA: Sum of primes in a range in C
First, you will need a routine capable of determining whether a number is prime: int eh_primo( unsigned int n ) { unsigned int i = 0; if( n <= 1 ) return 0; if( (n % 2 == 0) && (n > 2)…
-
3
votes5
answers286
viewsA: Regex to capture dimensions of a product with unit of measure
You can use the following expression: [^0-9,.] That is able to replace anything other than numeric digits, semicolons: In a function: import re def findDimensions(text): s = re.sub('[^0-9,.]', ' ',…
-
0
votes1
answer96
viewsA: Pointers with argc and argv
char * argv[] is a pointer vector of the type char *. Therefore, when accessing one of the elements of this vector through argv[i], you will have a pointer char *. The function atoi() takes as…
-
2
votes2
answers2641
viewsA: Find lower vector value recursively
You can implement a function that takes an integer vector and its respective size and returns the smallest finding value within this vector, see only: int menor( int vec[], int tam ) { if( tam == 1…
-
0
votes2
answers1303
viewsA: How to validate an email in c
How about using the function sscanf() of the standard library stdio.h ? #include <stdio.h> int validar_email( const char * email ) { char usuario[256], site[256], dominio[256]; if( sscanf(…
-
0
votes2
answers444
viewsA: How do I assign the last value of an array to a variable?
The function len() returns the amount of elements contained in a list. In Python, the first element of a list has index 0, while the last element has an index len() - 1. idx_ultimo = len(tensao) - 1…
-
2
votes1
answer103
viewsA: How to audit records by saving changes in JSON
This field of audit log is certainly of the type hstore. You can use the function hstore_to_json() to convert a field of the type hstore for JSON, look at you: SELECT hstore_to_json('"id"=>"2",…
-
0
votes1
answer291
viewsA: Create an Oracle Agent/Job for Postgresql
In Postgres, you can write a stored Procedure using the language PL/Python able to connect in a bank Oracle, enabling the exchange of data, see only: CREATE FUNCTION oracle_foobar() RETURNS SETOF…
-
0
votes2
answers56
viewsA: If block is not well located, how to solve?
It seems to me that your intention is to make yours if is outside the scope of the function. Your block if must be identified at the same level as def, look at you: import socket s =…
-
2
votes1
answer237
viewsA: Find a sub-string in the first column of a csv file
Assuming that your file .CSV input be something like (entrada.csv): 2018;ALPHA;3.1415 2018;BETA;1.4142 2007;GAMMA;1.7320 2018;DELTA;2.7182 2007;EPSILON;2.2543 Follows the program in Python able to…
-
2
votes1
answer146
viewsA: How do I recover the current date of a Mysql database in Arduino?
The MySQL has a date and time call manipulation function UNIX_TIMESTAMP(), which in turn is able to return the date and time of the database represented by the amount of seconds that have passed…
-
1
votes1
answer40
viewsA: C++: Elements just below the constructor call of a class
The class attributes _first and _n are being initialized with the value 0. The attribute _elements, it is a std::vector and is being built with initial size n, through one of its non-standard…
-
0
votes3
answers1369
viewsA: Calculate the sum and mean of a numerical sequence
Follows the solution: # Geracao da sequencia contendo 12 valores seq = list(range(3, 27, 2)) # Extrai valores da sequencia iniciados com '3' a = [ n for n in seq if str(n)[0] == '3' ] # Calcula soma…
-
3
votes2
answers136
viewsA: What is the difference between memcpy and snprintf
Both functions have very distinct purposes and are not equivalent. One is not able to replace the other without an additional implementation. The purpose of the function snprintf() is to format…
-
0
votes2
answers47
viewsA: Problem when replacing strings
You can implement a function capable of replacing all occurrences within a string, see only: #include <string> using namespace std; void substituir( string& str, const string& de,…
-
1
votes2
answers872
viewsA: How to know how many numbers in one list are repeated in others?
You can convert both lists to one set to then use the intersection operator (&) to calculate the amount of elements in common between them: A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] B = [1, 2, 3, 5,…
-
1
votes2
answers110
viewsA: transform sql with subquery into query in Entity
You don’t need a subquery to solve this problem, a LEFT JOIN combined with a SUM() can help you, look at that: SELECT Colaborador.Id, Colaborador.Nome, SUM( CASE WHEN Pedidos.Id IS NULL THEN 0 ELSE…
-
1
votes3
answers416
viewsA: How to Insert in a non-zero position in an empty list?
You can write a function capable of filling the empty 'spaces' if the list does not have the proper size using a default value, see only: def insert_at_pos( lst, pos, val, default=None ): if(…
-
0
votes1
answer276
viewsA: How to modularize the following code C
Follows a streamlined and modularized code capable of solving your problem: Foobar. h: #ifndef __FOOBAR_H__ #define __FOOBAR_H__ #define ERR_DIA_BISSEXTO_INVALIDO (-4) #define ERR_DIA_INVALIDO (-3)…
-
1
votes1
answer999
viewsA: LEFT OUTER JOIN
Maybe you don’t need any kind of JOIN to make this comparative count, look at this: SELECT codmunic, ene_ine, count(loc) as energia_ine FROM tabela GROUP BY codmunic, ene_ine ORDER BY codmunic,…
-
3
votes2
answers584
viewsA: How to stop a loop at a certain time?
Your logic is correct, you are only making a big mess by manipulating the date/time object by converting it to string in order to make the time comparison! This conversion is not necessary, the…
-
3
votes2
answers1039
viewsA: Geometric Progression in python
Assuming that a geometric progression be something like: In Python this could be calculated as follows: a = 2 r = 5 tam = 10 pg = [ a * r ** (n - 1) for n in range(1, tam + 1) ] print( pg ) Exit:…
-
0
votes2
answers55
viewsA: Find the index in a value-based array of dictionaries
The same value may be contained in several elements of your list of dictionaries. A solution would be to assemble a list containing the index of each element/dictionary in which the value was found,…
-
1
votes3
answers56
viewsA: Mass collection of information from files
You can use a script awk to solve your problem (script.awk): BEGIN { OFS = ","; FS = " -- "; print "ctime,atime,mtime,crtime" } { for( i = 0; i < 4; i++ ){ split( $(i+2), a, " 0x" ); b[i] = a[1];…
-
1
votes1
answer202
viewsA: How to update column for each SELECT in a given table?
Unfortunately (or fortunately), in PostgreSQL there are no TRIGGERS of the kind AFTER SELECT. However, you can solve your problem by "encapsulating" your table in a stored Procedure written in…
-
1
votes2
answers1389
viewsA: Fetch a value within an array of dictionaries
You can calculate the amount of times the word sim appears inside your list of dictionaries, see only: palavra1 = {'palavra': 'sim', 'positivo': 0} palavra2 = {'palavra': 'não', 'positivo': 0}…
-
0
votes1
answer2857
viewsA: Calculate arithmetic mean of a vector
Solution #1: Using sum() and len() vetor = [ 1, 3, 5, 7, 9, 2, 4, 6, 8, 0 ] print( sum(vetor) / float(len(vetor)) ) Solution #2: Using lambda vetor = [ 1, 3, 5, 7, 9, 2, 4, 6, 8, 0 ] print(…
-
1
votes1
answer149
viewsA: Select the two highest values of a vector and add them up?
You can sort your vector downwards using the method sort() and passing the argument reverse=True. Once ordered down, you can use the function sum() to add only the first two elements of the vector,…
-
2
votes3
answers902
viewsA: RETURN THE SUM OF MAXIMUM 3 SQL VALUES
You can create a function PL/PgSQL to perform this calculation, see only: CREATE OR REPLACE FUNCTION fc_obter_top3() RETURNS TABLE ( RECIPIENT VARCHAR(200), AMOUNT BIGINT ) AS $$ DECLARE rec RECORD;…
-
1
votes2
answers697
viewsA: How to add list values?
You can use the function sum(), look at you: lst = [['ALABAMA', 'Abbeville', 2645, 11, 63], ['ALABAMA', 'Adamsville', 4481, 19, 321], ['ALABAMA', 'Addison', 744, 1, 25], ['ALABAMA', 'Alabaster',…
-
1
votes1
answer263
viewsA: How to change a string name
To replace all the strings contained in a string, you can implement something like: #include <string.h> #include <stdio.h> int strrepstr( char * dst, const char * src, const char *…
-
1
votes2
answers59
viewsA: Problems with array type?
In PostgreSQL you can do something like: CREATE TABLE tb_cores ( id INTEGER NOT NULL PRIMARY KEY, nome TEXT NOT NULL ); INSERT INTO tb_cores ( id, nome ) VALUES ( 1, 'PRETO' ); INSERT INTO tb_cores…
-
3
votes1
answer1282
viewsA: See the best-selling product
Translating the tables Produto and venda_Produto from its model to PgSQL: CREATE TABLE Produto ( idproduto INTEGER NOT NULL, nome VARCHAR(60) NOT NULL, PRIMARY KEY ( idproduto ) ); CREATE TABLE…