elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Únete al Grupo Steam elhacker.NET


  Mostrar Mensajes
Páginas: 1 [2] 3 4
11  Seguridad Informática / Hacking / Re: Saltarse Firewall en: 26 Diciembre 2023, 17:56 pm
Te recomendaría probar las siguientes configuraciones y luego me comentas los resultados:

1. Escaneo SYN Agresivo:

Código
  1. sudo nmap -sS -T4 -f -v <host_ip>

Este comando realiza un escaneo SYN, enviando paquetes de sincronización para obtener una respuesta ACK del otro extremo. Utiliza un manejo del tiempo agresivo, fragmentación de paquetes y un modo verbose, tal como te sugirió @D3s0rd3n.

2. Ataque por Fragmentación de Paquetes:

Código
  1. sudo nmap --mtu 8 -v <host_ip>

En este caso, también se realiza un ataque por fragmentación de paquetes, pero enviando paquetes más pequeños que un paquete completo. En este escenario, se envían paquetes de 8 bytes.

3. Enmascaramiento de Puerto:

Código
  1. sudo nmap -g 80 -v <host_ip>

Aquí se le indica a nmap que enmascare el puerto, haciéndolo parecer como si estuviera utilizando el puerto 80 (HTTP), un puerto de uso común.

4. Generación de Señuelos para Evadir Bloqueo:

Código
  1. sudo nmap -D RND:12 <host_ip>

Se solicita a nmap que genere 12 señuelos aleatorios con el objetivo de evadir posibles bloqueos de tu dirección IP por parte del IDS/firewall.

5. Manipulación de Longitud de Datos:

Código
  1. sudo nmap --data-length 5 <host_ip>

En este caso, se acumula un número aleatorio de bytes de datos en la mayoría de los paquetes, sin seguir un protocolo específico. Esto ayuda a evaluar cómo el firewall y el otro extremo gestionan estos datos.

6. Envío de Checksum Incorrecto:

Código
  1. sudo nmap --badsum <host_ip>

Este comando envía a propósito un checksum erróneo para observar la reacción del IDS/Firewall. El checksum es un código de redundancia generado por la suma de todos los bytes y un polinomio generador.

Además, puedes explorar la creación de paquetes personalizados utilizando herramientas como NetScanTools. Al final se resume en probar distintas cosas hasta que suene la flauta (quizás).  :-\
12  Programación / Scripting / Re: Git Update Manager en Batch en: 26 Diciembre 2023, 16:58 pm
¡Hola a todos!

Solo quería informarles de que he actualizado el código de mi script Git Update Manager. La versión 0.2 (publicada el 2023-12-26) ahora incluye manejo de secciones para la configuración de proyectos. Los usuarios pueden editar directamente el archivo de configuración y pasar el nombre del proyecto como parámetro al llamar al script.

* Configuración del fichero gitmgr_config.ini:

     Para cada proyecto, utiliza una sección [NombreProyecto].
     Cierra cada sección con [/NombreProyecto].

    
Código:
    [MiProyecto]
    projectDirFrom=C:\Ruta\Del\Proyecto\Desde
    projectDirTo=C:\Ruta\Del\Proyecto\A
    repo_uri=https://github.com/usuario/proyecto.git
    [/MiProyecto]
    

Ejemplos de Uso:

* Imprimir Nombres de Proyectos:
Código:
gitmgr -f

* Crear Nueva Sección de Proyecto:
Código:
gitmgr -c


* Actualización de un Proyecto Específico:
Código:
gitmgr MiProyecto

Espero que encuentren útil esta actualización y que los ejemplos de uso sean claros. Como siempre, estoy abierto a comentarios y sugerencias.

Código
  1. @echo off
  2. setlocal enabledelayedexpansion
  3.  
  4. set "insideSection="
  5. set "sectionFound="
  6. set "configFile=gitmgr_config.ini"
  7.  
  8. REM Batch Script for Git Project Update
  9. REM Author: profinet
  10. REM Date: 2023-12-26
  11. REM Version: 0.2
  12.  
  13. REM Description:
  14. REM This batch script is designed to automate the process of updating Git projects.
  15. REM It includes functionality for handling multiple projects, cleaning the destination directory,
  16. REM extracting the latest backup, and pushing changes to the remote repository.
  17. REM The script is intended to streamline the update process and reduce manual intervention.
  18.  
  19. REM Author's Note:
  20. REM The script was created by profinet on the specified date. For any inquiries or suggestions, please contact the author.
  21.  
  22. REM Version History:
  23. REM - Version 0.1 (2023-11-20): Initial release of the script.
  24. REM   This version includes basic functionality for updating Git projects and serves as the foundation for future enhancements.
  25.  
  26. REM - Version 0.2 (2023-12-26): Added section handling for project configuration.
  27. REM   Users can now directly edit a configuration file and pass the project name as a parameter when calling the script.
  28.  
  29. REM Call printProjectNames
  30. @if "%1"=="-f" (
  31.    call :printProjectNames
  32.    exit /b
  33. )
  34.  
  35. REM Call createSection
  36. @if "%1"=="-c" (
  37.    call :createSection
  38.    exit /b
  39. )
  40.  
  41. REM Display help section
  42. @if "%1"=="-h" (
  43.    call :displayHelp
  44.    exit /b
  45. )
  46.  
  47. :initCheck
  48. REM Check for provided input
  49. if "%~1"=="" (
  50.    echo ERROR: No parameters provided...
  51.    call :displayHelp
  52.    exit /b
  53. )
  54.  
  55. REM Check for dependencies
  56. set "gitFolder=%ProgramFiles%\Git"
  57. if not exist "%gitFolder%" (
  58.    set "gitFolder=%ProgramFiles(x86)%\Git"
  59.    if not exist "%gitFolder%" (
  60.        echo:
  61.        echo ERROR: Git is not installed in the default location. Exiting...
  62.        call :endPoint
  63.        exit /b
  64.    )
  65. )
  66.  
  67. :configFile
  68. REM Read the configuration from the file
  69. if not exist %configFile% (
  70.    echo:
  71.    echo ERROR: Config file is not found. Exiting...
  72.    call :endPoint
  73.    exit /b
  74. )
  75.  
  76. set "projectSection=%~1"
  77. for /f "tokens=*" %%a in ('type "%configFile%"') do (
  78.    set "line=%%a"
  79.    if "!line!" equ "[%projectSection%]" (
  80.        set "insideSection=1"
  81.        set "sectionFound=1"
  82.    ) else if "!line!" equ "[/!projectSection!]" (
  83.        set "insideSection="
  84.    )
  85.    if defined insideSection (
  86.        REM Extract variables within section
  87.        for /f "tokens=1,* delims==" %%b in ("!line!") do (
  88.            set "varName=%%b"
  89.            set "varValue=%%c"
  90.            set "!varName!=!varValue!"
  91.        )
  92.    )
  93. )
  94.  
  95. REM Check if the section was found
  96. if not defined sectionFound (
  97.    echo:
  98.    echo ERROR: Project section "%projectSection%" not found in the configuration file.
  99.    echo Exiting...
  100.    call :endPoint
  101.    exit /b
  102. )
  103.  
  104. :verifyConfig
  105. REM Display configuration information for user verification
  106. echo:
  107. echo Please verify the configuration information:
  108. echo:
  109. echo   Project: %projectSection%
  110. echo   Project Directory From: !projectDirFrom!
  111. echo   Project Directory To: !projectDirTo!
  112. echo   Repository URI: !repo_uri!
  113. echo:
  114.  
  115. REM Prompt user for confirmation
  116. set /p "confirm=Is the configuration correct? (Y/N): "
  117. if /i "%confirm%" neq "Y" (
  118.    echo:
  119.    echo Exiting...
  120.    call :endPoint
  121.    exit /b
  122. )
  123.  
  124. :doWork
  125. REM Create environment variable to use git commands
  126. set "PATH=%PATH%;%gitFolder%\cmd"
  127.  
  128. REM Look up the latest backups
  129. cd "%projectDirFrom%"
  130. for %%i in (*.zip) do (
  131.    set "currentFile=%%i"
  132.    if "!currentFile!" gtr "!latestFile!" (
  133.        set "latestFile=!currentFile!"
  134.    )
  135. )
  136.  
  137. REM Get date and time to rename the new branch
  138. set "current_date=!date:/=-!!time::=-!"
  139. set "dt=%DATE:~6,4%_%DATE:~3,2%_%DATE:~0,2%__%TIME:~0,2%_%TIME:~3,2%_%TIME:~6,2%"
  140. set "dt=%dt: =0%"
  141.  
  142. cd /d "%projectDirTo%"
  143.  
  144. REM Delete all files (excluding .git) in the destination directory
  145. for %%i in (*) do (
  146.    if /i not "%%i"=="%projectDirTo%\%projectFolder%\.git" (
  147.        del "%%i"
  148.    )
  149. )
  150.  
  151. REM Delete all subdirectories (excluding .git) in the destination directory
  152. for /d %%i in (*) do (
  153.    if /i not "%%i"=="%projectDirTo%\%projectFolder%\.git" (
  154.        rmdir /s /q "%%i"
  155.    )
  156. )
  157.  
  158. REM Extract the latest zip file to the destination directory
  159. powershell -command Expand-Archive -Path '%projectDirFrom%\!latestFile!' -DestinationPath '%projectDirTo%\' -Force
  160.  
  161. REM Set up Git and push the changes
  162. git remote add origin %repo_uri%
  163. git checkout -b %dt%
  164. cd %projectFolder%
  165. git add --all
  166. git commit -m "Update %dt%"
  167. git push -u origin %dt%
  168.  
  169. call :endPoint
  170. exit /b
  171.  
  172. :printProjectNames
  173. REM Print project names from configuration file
  174. echo:
  175. echo Project Names defined in the configuration file:
  176. echo:
  177. for /f "tokens=1 delims=[]" %%a in ('findstr /r "\[*\]" "%configFile%"') do (
  178.    echo   %%a
  179. )
  180.  
  181. call :endPoint
  182. exit /b
  183.  
  184. :createSection
  185. REM Create a new section in the configuration file
  186. echo:
  187. set /p "newSection=Enter the name of the new project section >> "
  188.  
  189. REM Check if the section already exists
  190. findstr /r "\[%newSection%\]" "%configFile%" >nul
  191. if !errorlevel! equ 0 (
  192.    echo.
  193.    echo ERROR: Project section "%newSection%" already exists in the configuration file.
  194.    echo Exiting...
  195.    exit /b
  196. )
  197.  
  198. REM Prompt user for new project configuration
  199. set /p "projectDirFrom=Enter project directory from >> "
  200. set /p "projectDirTo=Enter project directory to >>  "
  201. set /p "repo_uri=Enter repository URI >> "
  202.  
  203. REM Write the new section to the configuration file
  204. echo:
  205. echo( >>"%configFile%"
  206. echo [%newSection%]>>"%configFile%"
  207. echo projectDirFrom=!projectDirFrom!>>"%configFile%"
  208. echo projectDirTo=!projectDirTo!>>"%configFile%"
  209. echo repo_uri=!repo_uri!>>"%configFile%"
  210. echo [/%newSection%]>>"%configFile%"
  211. echo:
  212. echo New project section "%newSection%" added to the configuration file.
  213. echo:
  214.  
  215. call :endPoint
  216. exit /b
  217.  
  218. :displayHelp
  219. echo:
  220. echo Git Project Update Script - Help
  221. echo:
  222. echo Usage:
  223. echo   project_update.bat [OPTIONS] PROJECT_NAME
  224. echo:
  225. echo Options:
  226. echo   -f         Print project names defined in the configuration file.
  227. echo   -c         Create a new project section in the configuration file.
  228. echo   -h         Display this help section.
  229. echo:
  230. echo Example:
  231. echo   project_update.bat -f
  232. echo   project_update.bat -c
  233. echo   project_update.bat MyProject
  234. echo:
  235. echo For more information, refer to the script documentation.
  236. echo:
  237.  
  238. :endPoint
  239. endlocal
  240. exit /b
  241.  
13  Programación / Scripting / Re: Git Update Manager en Batch en: 21 Diciembre 2023, 19:16 pm
¡Hola! ¡Agradezco mucho tu comentario!

Estoy de acuerdo en que sería beneficioso hacer el script más flexible, permitiendo la carga de configuración directamente desde un archivo .config. Sin embargo, la razón detrás de su diseño actual fue la intención de involucrar al usuario, brindándole la oportunidad de sumergirse en el código y adaptarlo a sus propias necesidades. Esta aproximación tiene un componente didáctico, ¡y además, puede resultar divertido! :xD

Adicionalmente, parte de la motivación para crear el script de esta manera fue la necesidad de automatizar la gestión de versiones en mi trabajo. Aunque el código puede ser considerado "guarro", encontré satisfacción en su funcionalidad y decidí compartirlo aquí.

Tengo planes de lanzar una actualización con las sugerencias que me has proporcionado. ¡Estoy esperando el momento adecuado, quizás cuando tenga un poco de tiempo libre en el trabajo y nadie esté mirando! En mi ordenador personal, utilizo Parrot OS. :D
14  Media / Diseño Gráfico / Re: En memoria de CPH en: 21 Diciembre 2023, 18:58 pm
¡Acabas de catapultarme de vuelta a mi adolescencia! Aunque no me destacaba como usuario en PortalHacker y pasé desapercibido, indudablemente ese foro ha dejado una marca significativa en mi vida.

En realidad, parte de la razón por la que me registré en este foro es devolver a la comunidad el "favor" que recibí en su momento (y que lamentablemente, CPH ya no existe). Ahora, como una persona más experimentada y versada en mis áreas de conocimiento, estoy aquí para compartir mi experiencia, en contraste con aquel jovenzuelo que apenas podía escribir correctamente y aspiraba a ser un juanker.
15  Programación / Programación C/C++ / Revelando el Intrigante Arte de la Ruleta: Desentrañando el Hack de la Cadena de Markov en: 18 Diciembre 2023, 18:37 pm
Saludos a la comunidad apasionada de la ruleta. Hoy, me complace compartir con ustedes un fascinante enfoque que ha capturado la atención de los entusiastas del juego y los amantes de las estrategias ingeniosas: el hack de la cadena de Markov en la ruleta. ¿Qué sucede cuando la probabilidad se encuentra con la emoción del juego? La respuesta yace en la asombrosa intersección entre la teoría de la cadena de Markov y la rueda giratoria del destino.

Antes de sumergirnos en los detalles, tomémonos un momento para apreciar la magia que impulsa este hack. La cadena de Markov, conocida por su capacidad para modelar sistemas estocásticos, se convierte en una aliada inesperada en el universo impredecible de la ruleta. ¿Será esta la clave para desbloquear patrones ocultos en la ruleta? Descubramos juntos si este hack es un truco astuto o una revelación genuina.

LA CADENA DE MARKOV

Una cadena de Markov es un modelo matemático que describe una secuencia de eventos donde la probabilidad de que ocurra un evento particular depende solo del evento inmediatamente anterior. Es decir, en una cadena de Markov, el futuro solo está condicionado por el presente, y no retiene información sobre el pasado más allá del último estado.

Matemáticamente, la propiedad de Markov se expresa de la siguiente manera:


portal foto

En palabras simples, esta fórmula indica que la probabilidad de pasar al estado s en el próximo paso, dado el estado actual st, no depende de la secuencia completa de estados anteriores, sino solo del estado actual.

LA MATRIZ DE TRANSICIÓN

La matriz de transición, P, es una matriz que representa las probabilidades de transición entre los estados de una cadena de Markov. En una cadena con n estados, P es una matriz n×n, y Pij​ representa la probabilidad de pasar del estado i al estado j.

portal foto

CÁLCULO DEL VECTOR DE ESTADOS

Si tenemos un vector de probabilidades inicial vt​ en el paso t, la actualización del vector de probabilidades al paso t+1 se realiza multiplicando el vector por la matriz de transición P.


portal foto

EL CÓDIGO!

Código
  1. /* ROULETTE MARKOV CHAIN SIMULATION by profinet
  2.  
  3.  In the ethereal realm of Markov chains, we delve into the enchanting world
  4.  of probabilities governing the game of Roulette. Before we unveil the magic
  5.  woven by this C program, let's unravel the mathematical essence of a Markov chain.
  6.  
  7.  MARKOV CHAIN:
  8.  
  9.  A Markov chain is a stochastic model that describes a sequence of events where
  10.  the probability of transitioning to any particular state depends solely on the
  11.  current state and time elapsed, not on the sequence of events that preceded it.
  12.  This memoryless property is known as the Markov property.
  13.  
  14.  - State Space: Sets A, B, C, and D represent the states in our Roulette Markov
  15.  chain. Each state corresponds to a range of numbers on the Roulette wheel.
  16.  
  17.  - Transition Probabilities: The heart of the Markov chain lies in the probabilities
  18.  of transitioning from one state to another. These probabilities form a transition
  19.  matrix, where each element signifies the likelihood of moving between states.
  20.  
  21.  - Transition Matrix: A square matrix where rows and columns correspond to states,
  22.  and each entry represents the probability of transitioning from one state to another.
  23.  In our Roulette context, this matrix captures the dynamics of the game over spins.
  24.  
  25.  - Markov Property: The future state of the system depends only on its current state,
  26.  adhering to the Markov property. The dynamics of the system are memoryless,
  27.  simplifying the modeling of random processes.
  28.  
  29.  Now, armed with the knowledge of Markov chains, let's witness the magic of
  30.  probabilities and state transitions as we simulate the dance of fate on the
  31.  Roulette wheel with this enchanting C program.
  32.  
  33.  INITIAL STATE VECTOR CALCULATION:
  34.  
  35.  Before embarking on our magical journey through the Roulette Markov chain,
  36.  let's decipher the incantation that conjures the initial state vector, v0.
  37.  
  38.  The mystical probabilities for each zone are as follows:
  39.  - Zone A: 1/37 = 0.02702702702
  40.  - Zone B [1-12]: 1/37 * 12 = 0.32432432432
  41.  - Zone C [13-24]: 1/37 * 12 = 0.32432432432
  42.  - Zone D [25-36]: 1/37 * 12 = 0.32432432432
  43.  
  44.  Therefore, the initial state vector v0 is crafted with these probabilities:
  45.  v0 = { 0.02702702702, 0.32432432432, 0.32432432432, 0.32432432432 }
  46.  
  47.  This vector sets the stage for our journey, representing the initial likelihood
  48.  of finding ourselves in each enchanted zone after the first spin of the Roulette wheel.
  49.  
  50.  Now, let the magic unfold as we traverse the Markov chain, weaving the threads
  51.  of destiny and revealing the ever-shifting cosmic energies within the enchanted lands.
  52.  
  53.  THE DARK SPIRIT SCRIPT:
  54.  
  55.  Legend has it that sets A, B, C, and D correspond to specific ranges of numbers
  56.  on the Roulette wheel. Zone A encompasses the single number 0, while zones B, C,
  57.  and D represent ranges [1-12], [13-24], and [25-36], respectively.
  58.  
  59.  Then, the script unfolds as follows:
  60.  
  61.  1. A sample array of mystical symbols is presented, representing the outcome
  62.  of a Roulette game.
  63.  
  64.  2. The `countSpecificTransitions` function takes the mystical sample array and
  65.  counts transitions between sets A, B, C, and D. The ancient spirits are
  66.  summoned to calculate the probabilities of weaving the threads of destiny
  67.  from one set to another.
  68.  
  69.  3. The calculated probabilities are then used to build a powerful transition
  70.  matrix with the `buildTransitionMatrix` function. Each element of the matrix
  71.  represents the likelihood of moving from one enchanted zone to another.
  72.  
  73.  4. The transition matrix is unveiled to mortal eyes through the `printMatrix`
  74.  function, revealing the hidden patterns and cosmic energies.
  75.  
  76.  5. A mystical ritual is performed with the `multiplyMatrixVector` function,
  77.  combining the powers of the sacred matrix and a humble vector. The result is
  78.  a new vector that holds the secrets of transformation, representing the
  79.  probabilities of ending up in each enchanted zone after a Roulette spin.
  80.  
  81.  May the ancient spirits guide you through the script, and may the probabilities
  82.  revealed here bring fortune and wisdom to those who seek the mystical insights
  83.  of the Roulette wheel.
  84.  
  85.  Best of luck on your magical journey! */
  86.  
  87. #include <math.h>
  88. #include <time.h>
  89. #include <stdio.h>
  90. #include <stdlib.h>
  91. #include <stdbool.h>
  92.  
  93. /**
  94.  * @brief Count specific transitions in the sample and calculate transition probabilities.
  95.  *
  96.  * This magical function takes a mystical sample array and counts the transitions between
  97.  * enchanted sets A, B, C, and D. It then summons the ancient spirits to calculate the
  98.  * probabilities of weaving the threads of destiny from one set to another.
  99.  *
  100.  * @param sample The magical sample array containing mystical symbols.
  101.  * @param size The size of the sample array (the length of your magical journey).
  102.  * @param counters The counters representing the cosmic energies of transitions.
  103.  * @param probabilities The probabilities of weaving the threads of destiny between sets.
  104.  */
  105. static void countSpecificTransitions(int sample[], int size, int *counters,
  106. double *probabilities) {
  107. int i, j, k;
  108.  
  109. // Define the sets
  110. int sets[][12] = { { 0 },                                       // A
  111. { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 },     // B
  112. { 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 }, // C
  113. { 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36 }   // D
  114. };
  115.  
  116. // Wipe off counters
  117. for (i = 0; i < 16; i++) {
  118. counters[i] = 0;
  119. probabilities[i] = 0.0;
  120. }
  121.  
  122. // Let's go on a magical journey through the sample array
  123. for (i = 0; i < size - 1; i++) {
  124. int currentSet = -1;
  125. int nextSet = -1;
  126.  
  127. // Seeking the meaning of life in the current set
  128. for (j = 0; j < 4; j++) {
  129. for (k = 0; k < 12; k++) {
  130. /* If our sample number aligns
  131. * with the mystical symbols in the current set */
  132. if (sample[i] == sets[j][k]) {
  133. // We've found it!
  134. currentSet = j;
  135. break;
  136. }
  137. }
  138. /* If we've already found the meaning of life
  139. * there's no need to keep searching */
  140. if (currentSet != -1) {
  141. break;
  142. }
  143. }
  144.  
  145. // Gazing into the crystal ball to find the next set
  146. for (j = 0; j < 4; j++) {
  147. for (k = 0; k < 12; k++) {
  148. if (sample[i + 1] == sets[j][k]) {
  149. nextSet = j;
  150. break;
  151. }
  152. }
  153. if (nextSet != -1) {
  154. break;
  155. }
  156. }
  157.  
  158. // Summoning the ancient spirits to increment the counters
  159. if (currentSet != -1 && nextSet != -1) {
  160. /* We're not just incrementing counters;
  161. * we're weaving the threads of destiny! */
  162. counters[currentSet * 4 + nextSet]++;
  163. }
  164. }
  165.  
  166. // Let's do some magic math
  167. int totalTransitions = size - 1;
  168. for (i = 0; i < 16; i++) {
  169. probabilities[i] = (double) counters[i] / totalTransitions;
  170. }
  171. }
  172.  
  173. /**
  174.  * @brief Build the transition matrix using mystical probabilities.
  175.  *
  176.  * This function takes a set of magical probabilities and weaves them into a powerful
  177.  * transition matrix. Each element of the matrix represents the likelihood of moving
  178.  * from one enchanted zone to another.
  179.  *
  180.  * @param matrix The matrix that will be imbued with magical probabilities.
  181.  * @param probabilities The mystical probabilities, carefully chosen by sorcery.
  182.  */
  183. static void buildTransitionMatrix(double matrix[4][4], double *probabilities) {
  184. /* Fill the matrix with the provided probabilities
  185. * creating a tapestry of transitions */
  186. for (int i = 0; i < 4; i++) {
  187. for (int j = 0; j < 4; j++) {
  188. matrix[i][j] = probabilities[i * 4 + j];
  189. }
  190. }
  191. }
  192.  
  193. /**
  194.  * @brief Normalizes a matrix and tries to make it feel like it fits in.
  195.  *
  196.  * This function takes a matrix and makes each row behave, by subtracting a bit from each element.
  197.  * Think of it as matrix therapy - we're helping them get along better with their row-mates.
  198.  *
  199.  * @param N The size of the matrix.
  200.  * @param matrix The matrix to normalize.
  201.  */
  202. static void normalizeMatrix(int N, double matrix[N][N]) {
  203.    for (int i = 0; i < N; i++) {
  204.        double rowSum = 0.0;
  205.  
  206.        /* Finding the sum of the row
  207.          * - because everyone needs to know their worth! */
  208.        for (int j = 0; j < N; j++) {
  209.            rowSum += matrix[i][j];
  210.        }
  211.  
  212.        /* Subtracting (rowSum - 1) / N from every value in this row
  213.          * - just a little adjustment therapy */
  214.        for (int j = 0; j < N; j++) {
  215.            matrix[i][j] -= (rowSum - 1) / N;
  216.        }
  217.    }
  218. }
  219.  
  220. /**
  221.  * @brief Checks if a matrix is living its best stochastic life.
  222.  *
  223.  * This function takes a matrix and interrogates its rows to see if they're all adding up to 1.
  224.  * It's like a reality show for matrices - if they're not pulling their weight, they're out!
  225.  *
  226.  * @param N The size of the matrix.
  227.  * @param matrix The matrix to investigate.
  228.  * @return Returns true if the matrix is living the stochastic dream, false otherwise.
  229.  */
  230. static bool isStochasticMatrix(int N, double matrix[N][N]) {
  231.    for (int i = 0; i < N; i++) {
  232.        double rowSum = 0.0;
  233.  
  234.        /* Calculating the sum of the current row
  235.          * - because each row is a unique individual */
  236.        for (int j = 0; j < N; j++) {
  237.            rowSum += matrix[i][j];
  238.        }
  239.  
  240.        /* Checking if the sum is approximately equal to 1
  241.          * - because a row that adds up to 1 is a happy row! */
  242.        if (fabs(rowSum - 1.0) > 1e-6) {
  243.            return false;
  244.        }
  245.    }
  246.  
  247.    // The matrix is living its best life!
  248.    return true;
  249. }
  250.  
  251. /**
  252.  * @brief Cast a spell to reveal the mystical matrix.
  253.  *
  254.  * This function is a magical incantation that unleashes the enchanted matrix
  255.  * into the mortal realm. It gracefully prints the ethereal values with precision,
  256.  * allowing mere mortals to catch a glimpse of the hidden patterns.
  257.  *
  258.  * @param matrix The mystical matrix to be unveiled.
  259.  */
  260. static void printMatrix(double matrix[4][4]) {
  261. for (int i = 0; i < 4; i++) {
  262. for (int j = 0; j < 4; j++) {
  263. // Reveal the magical values with four decimal places
  264. printf("%.4f ", matrix[i][j]);
  265. }
  266. // Move to the next line, as the magic unfolds row by row
  267. printf("\n");
  268. }
  269. }
  270.  
  271. /**
  272.  * @brief Unleash the magic of matrix-vector multiplication.
  273.  *
  274.  * This function is a mystical ritual that combines the powers of a sacred matrix
  275.  * and a humble vector. It gracefully performs the multiplication, weaving the
  276.  * threads of destiny to produce a new vector that holds the secrets of transformation.
  277.  *
  278.  * @param matrix The sacred matrix, carefully crafted by the wizards of computation.
  279.  * @param inputVector The humble vector offering itself to the magic of multiplication.
  280.  * @param resultVector The newborn vector, now imbued with the enchanted transformation.
  281.  */
  282. static void multiplyMatrixVector(double matrix[4][4], double *inputVector,
  283. double *resultVector) {
  284. for (int i = 0; i < 4; i++) {
  285. // Prepare the newborn vector, clearing any remnants of previous enchantments
  286. resultVector[i] = 0.0;
  287. for (int j = 0; j < 4; j++) {
  288. // Unleash the magic: combine the powers of matrix and vector
  289. resultVector[i] += matrix[i][j] * inputVector[j];
  290. }
  291. }
  292. }
  293.  
  294. /**
  295.  * @brief Normalizes a vector and makes its elements feel like they're on a diet.
  296.  *
  297.  * This magical function takes a vector on a sumptuous feast and says, "Enough is enough!"
  298.  * It calculates the sum of the elements, scolds them for overindulgence, and puts them on
  299.  * a strict diet by dividing each element by the sum. Now, the vector is light, fit, and ready
  300.  * for the runway – or any mathematical adventure!
  301.  *
  302.  * @param vector The vector to be normalized, because even vectors need to watch their weight.
  303.  * @param size The size of the vector – because size matters, especially in the world of vectors.
  304.  */
  305. void normalizeVector(double *vector, int size) {
  306.    double sum = 0.0;
  307.  
  308.    // Calculate the sum of the elements – a grand feast awaits!
  309.    for (int i = 0; i < size; i++) {
  310.        sum += vector[i];
  311.    }
  312.  
  313.    // Normalize by dividing each element by the sum of the elements
  314.    for (int i = 0; i < size; i++) {
  315.        vector[i] /= sum;
  316.    }
  317. }
  318.  
  319.  
  320. /**
  321.  * @brief Generates a random list of numbers to keep life exciting.
  322.  *
  323.  * This function is your go-to party planner for creating a list that's as unpredictable as life itself.
  324.  * It seeds the random number generator with the current time, ensuring a unique and lively mix every time.
  325.  *
  326.  * @param list The list to be filled with random numbers.
  327.  * @param size The size of the list - because size matters, especially in random number lists.
  328.  */
  329. static void generateRandomList(int *list, int size) {
  330.    // Let's throw a dice and see where the randomness takes us!
  331.    srand((unsigned int) time(NULL));
  332.  
  333.    // Generating random numbers and filling the list with excitement
  334.    for (int i = 0; i < size; i++) {
  335.       /* Generating a random number between 0 and 36
  336.         * - because variety is the spice of life! */
  337.     list[i] = rand() % 37;
  338.    }
  339. }
  340.  
  341. /**
  342.  * @brief Embark on a magical journey through the enchanted realms of sets A, B, C, and D.
  343.  *
  344.  * This mystical main function leads a daring expedition into the unseen world of transitions
  345.  * and probabilities. A sample array of mystical symbols is presented to the ancient wizards
  346.  * who count specific transitions, unveil the secrets of probability, and build a powerful
  347.  * transition matrix. The enchanted matrix is then used to transform an initial state vector
  348.  * into a new state, revealing the ever-shifting cosmic energies within the enchanted lands.
  349.  *
  350.  * @return The triumphant return code, signifying the successful completion of the magical journey.
  351.  */
  352. int main() {
  353.    // Sample array
  354.    int initialData[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 };
  355.    int size = (int)sizeof(initialData) / sizeof(initialData[0]);
  356.  
  357.    // Declare and allocate memory for the sample array
  358.    int *sample = (int *)malloc(size * sizeof(int));
  359.  
  360.    // Check if memory allocation was successful
  361.    if (sample == NULL) {
  362.        fprintf(stderr, "Memory allocation failed :(\n");
  363.        return 1; // Return an error code
  364.    }
  365.  
  366.    // Initialize sample array with default values
  367.    for (int i = 0; i < size; i++) {
  368.        sample[i] = i;
  369.    }
  370.  
  371.    // Initialize counters and probabilities
  372.    int counters[16];
  373.    double probabilities[16];
  374.  
  375.    int i = 0;
  376.    int winningBet = 0;
  377.  
  378.    do {
  379.        // Count specific transitions
  380.        countSpecificTransitions(sample, size, counters, probabilities);
  381.  
  382.        // Print the results
  383.        printf("\n");
  384.        for (i = 0; i < 16; i++) {
  385.            char currentSet = (char)('A' + i / 4);
  386.            char nextSet = (char)('A' + i % 4);
  387.  
  388.            printf("Transition %c->%c: %d, Probability: %.4f\n", currentSet, nextSet, counters[i], probabilities[i]);
  389.        }
  390.  
  391.        // Build the transition matrix
  392.        double transitionMatrix[4][4];
  393.        buildTransitionMatrix(transitionMatrix, probabilities);
  394.        if (!isStochasticMatrix(4, transitionMatrix)) {
  395.            normalizeMatrix(4, transitionMatrix);
  396.        }
  397.  
  398.        // Print the transition matrix
  399.        printf("\nTransition Matrix:\n");
  400.        printMatrix(transitionMatrix);
  401.  
  402.        // Build the new state vector
  403.        double initialState[4] = {0.02702702702, 0.32432432432, 0.32432432432, 0.32432432432};
  404.        double newState[4];
  405.        multiplyMatrixVector(transitionMatrix, initialState, newState);
  406.  
  407.        // Normalize the new state vector
  408.        normalizeVector(newState, 4);
  409.  
  410.        // Print the new state vector with corresponding zones and intervals
  411.        printf("\nNew state vector:\n");
  412.        for (i = 0; i < 4; i++) {
  413.            char zoneLabel;
  414.            const char *intervalDescription;
  415.  
  416.            // Determine the zone label and interval description
  417.            switch (i) {
  418.            case 0:
  419.                zoneLabel = 'A';
  420.                intervalDescription = "Only 0 ";
  421.                break;
  422.            case 1:
  423.                zoneLabel = 'B';
  424.                intervalDescription = "[1-12] ";
  425.                break;
  426.            case 2:
  427.                zoneLabel = 'C';
  428.                intervalDescription = "[13-24]";
  429.                break;
  430.            case 3:
  431.                zoneLabel = 'D';
  432.                intervalDescription = "[25-36]";
  433.                break;
  434.            default:
  435.                // Handle an unexpected index (this should not happen)
  436.                zoneLabel = '?';
  437.                intervalDescription = "Unknown Interval";
  438.                break;
  439.            }
  440.  
  441.            // Print the probability along with zone and interval information
  442.            printf("Zone %c %s -> %.3f%%\n", zoneLabel, intervalDescription, (double)newState[i] * 100);
  443.        }
  444.  
  445.        printf("\nEnter a new winningBet (or any non-integer to exit): ");
  446.        if (scanf("%d", &winningBet) != 1) {
  447.            break;
  448.        }
  449.  
  450.        // Update the sample array with the new winningBet
  451.        // (For simplicity, just add the winningBet to the end of the array
  452.        sample = realloc(sample, (size + 1) * sizeof(int));
  453.        if (sample == NULL) {
  454.            fprintf(stderr, "Memory reallocation failed :(\n");
  455.            return 1; // Return an error code
  456.        }
  457.        sample[size] = winningBet;
  458.        size++;
  459.  
  460.    } while (1);
  461.  
  462.    // Free the allocated memory
  463.    free(sample);
  464.  
  465.    // The triumphant return code!
  466.    return 0;
  467. }
  468.  



portal foto
16  Foros Generales / Dudas Generales / Re: Automatizando puerta.... Algo falla.... en: 29 Noviembre 2023, 08:48 am
En tu esquema, estás empleando el bloque B003 para establecer un ciclo infinito. Para iniciar el ciclo cuando lo desees, es necesario conectar la salida del bloque Set/Reset a la entrada de B002 mediante una puerta NOT en serie.
17  Programación / .NET (C#, VB.NET, ASP) / Re: Recibir dos tramas por RS232 diferentes. en: 29 Noviembre 2023, 08:35 am
He cometido varios descuidos al escribir ese código, al parecer.  :-\

Me complace que hayas logrado resolverlos y que el código ahora funcione correctamente, espero que te sea útil como ejemplo.

Además, es importante que incluyas los demás caracteres en el mismo arreglo de separadores para procesar todas las tramas. También te recomiendo separar la lógica de la interfaz de usuario de la lógica de gestión del puerto serie mediante la creación de clases distintas.
18  Programación / .NET (C#, VB.NET, ASP) / Re: Recibir dos tramas por RS232 diferentes. en: 28 Noviembre 2023, 10:15 am
Ah sí, tuve un descuido al copiar y pegar directamente la lógica para editar los labels. Mis disculpas por eso.

En cuanto a la afirmación de que "no hace nada", me parece extraño. Al menos debería arrojar un error al configurar el puerto o indicar "puerto cerrado" al presionar uno de los dos botones.

En tu código, sería útil almacenar el tipo de solicitud realizada ("B" o "X72") en dos variables booleanas para procesar la trama en la función correspondiente. Puedes aprovechar el mismo manejador de eventos para recibir ambos tipos de tramas y luego pasar el array de cadenas (string[]) a la función apropiada.
19  Foros Generales / Foro Libre / Re: ¿qué sucederá? en: 24 Noviembre 2023, 16:17 pm
En muchos casos, la resistencia de un material es el esfuerzo en un punto de ruptura de un material bajo carga. Ahora bien, consideremos una moneda estándar, puramente de latón, con diámetro 20 mm y grosor 1.5 mm (que obviamos para simplificar el cálculo).

Primero calculemos el área transveral de la moneda: At = d^2 x pi /4 = 0.314mm2

Dado que la resistencia a la tracción del latón oscila entre los 300-600 MPa, consideremos su valor más alto.

La fuerza que debes hacer para romper la moneda se define como:

F = E x St

F = 600 MPa x 0.314 mm2 = 188.4N

Así que puedes poner estos cálculos en práctica poniendo la moneda encima de la vía de un tren, y puede pasar: a) se rompe, b) se deforma, c) descarrila el tren.
20  Foros Generales / Dudas Generales / Re: Automatizando puerta.... Algo falla.... en: 24 Noviembre 2023, 15:08 pm
Discúlpame, ese circuito es erróneo (también lo escribí a mano sin poder simularlo).  :-\
Prueba el siguiente, acabo de simularlo.

Páginas: 1 [2] 3 4
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines