Snippets Collections
Unfortunately our team is not trained to support websites built with Next.js which is a custom javascript framework.  so we cannot complete integrations on web apps like this, they have to be client integrations.  You can provide the help docs to guide them.
1. Instalar Apache2 (si no está instalado)
bash
# Ubuntu/Debian
sudo apt update
sudo apt install apache2

# CentOS/RHEL/Fedora
sudo dnf install httpd
2. Estructura de archivos importantes
Configuración principal: /etc/apache2/apache2.conf

Sites disponibles: /etc/apache2/sites-available/

Sites activos: /etc/apache2/sites-enabled/

Document root por defecto: /var/www/html/

3. Crear un Virtual Host
Paso 1: Crear el directorio del sitio
bash
sudo mkdir -p /var/www/misitio.local/public_html
sudo mkdir -p /var/www/misitio.local/logs
Paso 2: Crear archivo de prueba
bash
sudo nano /var/www/misitio.local/public_html/index.html
Contenido del archivo:

html
<!DOCTYPE html>
<html>
<head>
    <title>Mi Sitio Local</title>
</head>
<body>
    <h1>¡Bienvenido a misitio.local!</h1>
    <p>Este es un virtual host de prueba.</p>
</body>
</html>
Paso 3: Configurar permisos
bash
sudo chown -R $USER:$USER /var/www/misitio.local/public_html
sudo chmod -R 755 /var/www
4. Crear archivo de Virtual Host
bash
sudo nano /etc/apache2/sites-available/misitio.local.conf
Contenido del archivo:

apache
<VirtualHost *:80>
    # Dirección de email del administrador (opcional)
    ServerAdmin webmaster@misitio.local
    
    # Directorio raíz del sitio
    DocumentRoot /var/www/misitio.local/public_html
    
    # Dominio del sitio
    ServerName misitio.local
    ServerAlias www.misitio.local
    
    # Archivos de log
    ErrorLog /var/www/misitio.local/logs/error.log
    CustomLog /var/www/misitio.local/logs/access.log combined
    
    # Configuraciones adicionales
    <Directory /var/www/misitio.local/public_html>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>
5. Activar el Virtual Host
bash
# Activar el sitio
sudo a2ensite misitio.local.conf

# Desactivar sitio por defecto (opcional)
sudo a2dissite 000-default.conf

# Recargar Apache
sudo systemctl reload apache2
6. Configurar el archivo hosts
bash
sudo nano /etc/hosts
Agregar esta línea:

text
127.0.0.1   misitio.local www.misitio.local
7. Verificar la configuración
bash
# Verificar sintaxis de Apache
sudo apache2ctl configtest

# Reiniciar Apache
sudo systemctl restart apache2
8. Probar el sitio
Abre tu navegador y visita: http://misitio.local

Configuración adicional útil
Para HTTPS (opcional)
bash
# Habilitar módulo SSL
sudo a2enmod ssl

# Crear certificado auto-firmado
sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
    -keyout /etc/ssl/private/misitio.local.key \
    -out /etc/ssl/certs/misitio.local.crt
Virtual Host con HTTPS
apache
<VirtualHost *:443>
    ServerName misitio.local
    DocumentRoot /var/www/misitio.local/public_html
    
    SSLEngine on
    SSLCertificateFile /etc/ssl/certs/misitio.local.crt
    SSLCertificateKeyFile /etc/ssl/private/misitio.local.key
</VirtualHost>
Comandos útiles
bash
# Ver sitios activos
sudo apache2ctl -S

# Ver módulos activos
sudo apache2ctl -M

# Reiniciar Apache
sudo systemctl restart apache2

# Ver estado de Apache
sudo systemctl status apache2
¡Listo! Ahora tienes un dominio local funcionando con Apache2. Puedes repetir estos pasos para crear tantos virtual hosts como necesites.

para laravel

Te explico cómo configurar un Virtual Host para Laravel en Apache2:

1. Estructura de directorios de Laravel
En Laravel, el document root debe apuntar a la carpeta public:

text
/var/www/tu-proyecto-laravel/
├── app/
├── bootstrap/
├── config/
├── database/
├── public/     ← Esta es la carpeta raíz para Apache
├── resources/
├── routes/
├── storage/
└── vendor/
2. Crear el Virtual Host para Laravel
bash
sudo nano /etc/apache2/sites-available/laravel.local.conf
Contenido del archivo:

apache
<VirtualHost *:80>
    ServerName laravel.local
    ServerAlias www.laravel.local
    DocumentRoot /var/www/tu-proyecto-laravel/public
    ServerAdmin admin@laravel.local

    <Directory /var/www/tu-proyecto-laravel/public>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
        FallbackResource /index.php
    </Directory>

    # Configuración específica para Laravel
    <Directory /var/www/tu-proyecto-laravel>
        Options FollowSymLinks
        AllowOverride None
        Require all denied
    </Directory>

    # Logs
    ErrorLog /var/log/apache2/laravel_error.log
    CustomLog /var/log/apache2/laravel_access.log combined

    # Headers para mejor seguridad y performance
    Header always set X-Content-Type-Options nosniff
    Header always set X-Frame-Options DENY
    Header always set X-XSS-Protection "1; mode=block"
</VirtualHost>
3. Configuración alternativa más específica para Laravel
apache
<VirtualHost *:80>
    ServerName laravel.local
    DocumentRoot /var/www/tu-proyecto-laravel/public

    <Directory /var/www/tu-proyecto-laravel/public>
        # Habilitar rewrite module
        RewriteEngine On

        # Redirect Trailing Slashes If Not A Folder...
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_URI} (.+)/$
        RewriteRule ^ %1 [L,R=301]

        # Handle Front Controller...
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^ index.php [L]

        # Configuraciones de seguridad y permisos
        Options -Indexes +FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    # Configuración para carpeta storage (importante para Laravel)
    Alias /storage /var/www/tu-proyecto-laravel/storage/app/public
    <Directory /var/www/tu-proyecto-laravel/storage/app/public>
        Options -Indexes +FollowSymLinks
        AllowOverride None
        Require all granted
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/laravel_error.log
    CustomLog ${APACHE_LOG_DIR}/laravel_access.log combined
</VirtualHost>
4. Configurar permisos de Laravel
bash
# Navegar al directorio del proyecto
cd /var/www/tu-proyecto-laravel

# Permisos para storage y cache
sudo chown -R $USER:www-data /var/www/tu-proyecto-laravel
sudo find /var/www/tu-proyecto-laravel -type f -exec chmod 664 {} \;
sudo find /var/www/tu-proyecto-laravel -type d -exec chmod 775 {} \;

# Permisos específicos para storage y bootstrap/cache
sudo chgrp -R www-data storage bootstrap/cache
sudo chmod -R ug+rwx storage bootstrap/cache

# Permisos para el usuario www-data (Apache)
sudo chown -R www-data:www-data storage bootstrap/cache
5. Activar el sitio y módulos necesarios
bash
# Activar módulos necesarios
sudo a2enmod rewrite
sudo a2enmod headers

# Activar el sitio de Laravel
sudo a2ensite laravel.local.conf

# Desactivar sitio por defecto (opcional)
sudo a2dissite 000-default.conf

# Recargar configuración
sudo systemctl reload apache2
6. Configurar el archivo hosts
bash
sudo nano /etc/hosts
Agregar:

text
127.0.0.1    laravel.local
7. Configurar .env y aplicación Laravel
bash
# Copiar archivo de entorno
cp .env.example .env

# Generar key de la aplicación
php artisan key:generate

# Configurar cache y rutas
php artisan config:cache
php artisan route:cache
8. Virtual Host para entorno de producción
apache
<VirtualHost *:80>
    ServerName tudominio.com
    ServerAlias www.tudominio.com
    DocumentRoot /var/www/tu-proyecto-laravel/public

    <Directory /var/www/tu-proyecto-laravel/public>
        AllowOverride All
        Options +FollowSymLinks -Indexes
        Require all granted

        RewriteEngine On
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^ index.php [L]
    </Directory>

    # Configuración de logs
    ErrorLog /var/log/apache2/laravel_error.log
    CustomLog /var/log/apache2/laravel_access.log combined

    # Configuración de performance
    EnableSendfile on
    Timeout 300
</VirtualHost>
9. Comandos de verificación
bash
# Verificar sintaxis de Apache
sudo apache2ctl configtest

# Ver permisos
ls -la /var/www/tu-proyecto-laravel/storage/
ls -la /var/www/tu-proyecto-laravel/bootstrap/cache/

# Ver logs en tiempo real
sudo tail -f /var/log/apache2/laravel_error.log
10. Solución de problemas comunes
Error: "No input file specified"
apache
# En el Virtual Host, agregar:
<IfModule mod_php7.c>
    php_admin_value open_basedir "/var/www/tu-proyecto-laravel/:/tmp/:/proc/"
</IfModule>
Error de permisos:
bash
sudo chcon -R -t httpd_sys_rw_content_t /var/www/tu-proyecto-laravel/storage
sudo chcon -R -t httpd_sys_rw_content_t /var/www/tu-proyecto-laravel/bootstrap/cache
Para habilitar mod_rewrite:
bash
sudo a2enmod rewrite
sudo systemctl restart apache2
¡Con esta configuración tu aplicación Laravel debería funcionar correctamente! Recuerda que el punto más importante es que el DocumentRoot apunte a la carpeta public de tu proyecto Laravel.

name: cool_et
services:
  hoarder-chrome:
    cpu_shares: 90
    command: []
    deploy:
      resources:
        limits:
          memory: 1024M
    image: seleniarm/standalone-chromium:latest
    labels:
      icon: https://icon.casaos.io/main/all/hoarder-web.png
    platform: linux/arm64
    restart: unless-stopped
    ports: []
    volumes: []
    devices: []
    cap_add: []
    environment: []
    network_mode: bridge
    privileged: false
    container_name: ""
    hostname: ""
  hoarder-meilisearch:
    cpu_shares: 90
    command: []
    deploy:
      resources:
        limits:
          memory: 3797M
    environment:
      - HOARDER_VERSION=latest
      - MEILI_MASTER_KEY=aqxYm5UWCphGhkAu5fBcSJAPbSzeoiC2X
      - MEILI_NO_ANALYTICS=true
      - NEXTAUTH_SECRET=qxo0NvLCphGhkAu5fBcS1B0MxCeoig8G
      - NEXTAUTH_URL=http://localhost:3088
    image: getmeili/meilisearch:v1.6
    labels:
      icon: https://icon.casaos.io/main/all/hoarder-web.png
    platform: linux/arm64
    restart: unless-stopped
    volumes:
      - type: bind
        source: /DATA/AppData/karakeep/meili
        target: /meili_data
    ports: []
    devices: []
    cap_add: []
    network_mode: bridge
    privileged: false
    container_name: ""
    hostname: ""
  web:
    cpu_shares: 90
    command: []
    deploy:
      resources:
        limits:
          memory: 2048M
    environment:
      - BROWSER_WEB_URL=http://hoarder-chrome:9222
      - DATA_DIR=/data
      - HOARDER_VERSION=latest
      - MEILI_ADDR=http://hoarder-meilisearch:7700
      - MEILI_MASTER_KEY=aqxYm5UWCphGhkAu5fBcSJAPbSzeoiC2X
      - NEXTAUTH_SECRET=qxo0NvLCphGhkAu5fBcS1B0MxCeoig8G
      - NEXTAUTH_URL=http://localhost:3088
      - OPENAI_API_KEY=
    image: ghcr.io/karakeep-app/karakeep:latest
    labels:
      icon: https://icon.casaos.io/main/all/hoarder-web.png
    platform: linux/arm64
    ports:
      - target: 3000
        published: "3088"
        protocol: tcp
    restart: unless-stopped
    volumes:
      - type: bind
        source: /DATA/Documents/Hoarder
        target: /data
    devices: []
    cap_add: []
    network_mode: bridge
    privileged: false
    container_name: ""
    hostname: ""
x-casaos:
  author: self
  category: self
  hostname: 10.0.0.6
  icon: https://icon.casaos.io/main/all/hoarder-web.png
  index: /
  is_uncontrolled: false
  port_map: "3088"
  scheme: http
  store_app_id: cool_et
  title:
    custom: Karakeep
add_filter(
    'wpcp_max_input_bar_value',
    function ( $value ) {
        return 4000;
    }
);
como lo integro con vscode
Para integrar Pieces for Developers con Visual Studio Code, debes instalar la extensión oficial de Pieces desde el marketplace de VS Code. Con esto, podrás acceder a tu Pieces Drive y a las funcionalidades del Copilot de Pieces directamente desde tu editor. 
Requisitos previos
Asegúrate de que la aplicación de escritorio de Pieces y PiecesOS estén instalados y en ejecución. En Linux, el servicio de PiecesOS debe estar funcionando en segundo plano. 
Pasos para integrar Pieces con VS Code
1. Abre el gestor de extensiones de VS Code
Inicia Visual Studio Code.
Haz clic en el ícono de extensiones en la barra de actividades de la izquierda (o usa el atajo Ctrl+Shift+X). 
2. Busca la extensión de Pieces
En el campo de búsqueda del gestor de extensiones, escribe Pieces for VS Code.
La extensión oficial de Pieces debería aparecer en los resultados de la búsqueda. 
3. Instala la extensión
Haz clic en el botón Install en la extensión Pieces for VS Code.
Después de la instalación, es posible que se te pida reiniciar VS Code para que los cambios surtan efecto. 
4. Empieza a usar Pieces en VS Code
Una vez que la extensión esté instalada y PiecesOS esté en funcionamiento, verás las opciones de Pieces dentro de tu entorno de VS Code. 
Guardar fragmentos de código: Selecciona un bloque de código, haz clic derecho y elige Pieces > Save Selection to Pieces. Pieces guardará el fragmento en tu Drive y le añadirá metadatos generados por IA para que sea fácil de encontrar más tarde.
Buscar fragmentos: Accede a la búsqueda de Pieces desde la paleta de comandos (Ctrl+Shift+P y busca Pieces: Search Pieces) o desde el menú contextual. Podrás buscar en tu repositorio personal de materiales.
Usar el Copilot de Pieces: Al igual que la búsqueda, puedes interactuar con el Copilot de Pieces. Para acciones contextuales, selecciona un fragmento de código, haz clic derecho y elige una de las opciones del menú de Pieces, como Explain Selection with Copilot o Comment Selection with Copilot.
Paso 1: Habilitar Snap en Linux Mint
Abre la terminal.
Ejecuta los siguientes comandos para instalar snapd y asegurarte de que los paquetes de Snap funcionan correctamente en tu sistema:
sh
sudo rm /etc/apt/preferences.d/nosnap.pref
sudo apt update
sudo apt install snapd
Usa el código con precaución.

Reinicia tu sistema o sal y vuelve a iniciar sesión para asegurarte de que la configuración de Snap se haya aplicado correctamente. 
Paso 2: Instalar PiecesOS y Pieces for Developers
La aplicación Pieces tiene dos componentes principales:
PiecesOS: El servicio en segundo plano que gestiona la IA y la lógica de la aplicación.
Pieces for Developers: La aplicación de escritorio que interactúa con PiecesOS. 
Sigue estos pasos en la terminal para instalarlos:
Instala PiecesOS:
sh
sudo snap install pieces-os
Usa el código con precaución.

Habilita el control de procesos:
sh
sudo snap connect pieces-os:process-control :process-control
Usa el código con precaución.

Instala la aplicación de escritorio Pieces for Developers:
sh
sudo snap install pieces-for-developers
Usa el código con precaución.

Paso 3: Lanzar la aplicación
Una vez completada la instalación, puedes abrir Pieces de dos maneras:
Desde la terminal, escribiendo:
sh
pieces-for-developers
ods output FailurePlot=EP_visit_plot;
Proc LifeTest Data=analysis timelist=90 180 365 730 1865 3285 
                            plots=survival(/*CB*/ failure nocensor test);
   Strata Sex_text;
   Time tt_EP*tt_EP_event(0);
run;

Data EP_visit_plot;
   Set EP_visit_plot; *reduce size*;
   if missing(_1_SURVIVAL_) and Time > 0 then delete;
run;

Proc SGPlot Data=EP_visit_plot;
   Step y=_1_SURVIVAL_  x=Time / group=stratum;
   refline 90 180 365 730 1865 3285 / axis=x;
   xaxis values=(0 90 180 365 730 1865 3285) min=0;
   yaxis max=1;
run;
quit;
<style>
  .down, .up {
    --column-height: 500px;
    --image-height: 200px;
    --row-gap: 10px;
    --num-images: 5;

    height: var(--column-height);
    overflow: hidden;
    position: relative;
    -webkit-mask-image: linear-gradient(to bottom, rgba(0, 0, 0, 0) 0%, black 20%, black 80%, rgba(0, 0, 0, 0) 100%);
  }

  .scroll-container {
    display: flex;
    flex-direction: column;
  }

  .up .scroll-container {
    animation: imagescrolling 15s linear infinite alternate;
    animation-delay: -0.1s; /* Offset to ensure it starts halfway through the cycle */
  }

  .down .scroll-container {
    animation: imagescrolling2 15s linear infinite alternate;
  }

  .scroll-container img {
    height: var(--image-height);
    width: 100%;
    margin-bottom: var(--row-gap);
    padding: 0;
    object-fit: cover;
  }

  @keyframes imagescrolling {
    0% {
      transform: translateY(0);
    }
    100% {
      transform: translateY(calc(
        -1 * (((var(--image-height) + var(--row-gap)) * var(--num-images)) - var(--column-height))
      ));
    }
  }

  @keyframes imagescrolling2 {
    0% {
      transform: translateY(calc(
        -1 * (((var(--image-height) + var(--row-gap)) * var(--num-images)) - var(--column-height))
      ));
    }
    100% {
      transform: translateY(0);
    }
  }
</style>
laravel:
composer create-project laravel/laravel nombre-proyecto
yii2:
composer create-project --prefer-dist yiisoft/yii2-app-basic basic
composer create-project --prefer-dist yiisoft/yii2-app-advanced yii-application

yii3
composer create-project yiisoft/app nombre-del-proyecto

stos comandos instalan las versiones estables más recientes y las crean listas para usar. Si se desea la última versión de desarrollo, se puede añadir la opción --stability=dev, aunque no es recomendado para producción.

La opción --stability=dev se coloca directamente en el comando de Composer al momento de crear el proyecto con create-project. Sirve para indicar que deseas instalar la versión de desarrollo (inestable) de un paquete en lugar de la versión estable por defecto.
Cómo y dónde colocar --stability=dev

Ejemplo para Yii2 Basic con la versión de desarrollo:

composer create-project --prefer-dist --stability=dev yiisoft/yii2-app-basic basic
Ejemplo para Yii2 Advanced con la versión de desarrollo:

composer create-project --prefer-dist --stability=dev yiisoft/yii2-app-advanced yii-application
Ejemplo para Yii3 con la versión de desarrollo:

composer create-project --stability=dev yiisoft/app nombre-del-proyecto
Detalles importantes
--stability=dev va después de create-project y antes del nombre del paquete o justo junto con la opción --prefer-dist.

Esta opción indica a Composer que acepte versiones con estabilidad "dev" (desarrollo), que pueden incluir cambios recientes no testeados para producción.

Si utilizas esta opción, es posible que debas también agregar --prefer-source para que Composer use el código fuente en lugar de los paquetes comprimidos.
var $sticky = $(".sticky-column").stickit({				
  scope: StickScope.Parent,				
  top: 20,
  screenMinWidth: 980
});	

$sticky.bind('stickit:end', function () {
  $('.sticky-column').addClass('bottom-0');
});
$sticky.bind('stickit:stick', function () {
  $('.sticky-column').removeClass('bottom-0');
});

https://github.com/emn178/jquery-stickit
public static function Lista()
    {
        $s = \yii\helpers\ArrayHelper::map(Transportes::find()->orderBy('id_transporte')->all(), 'id_transporte', 'desc_transporte');
        return ($s) ? $s : [];
    }
public void reverseString(char[] s) {
  char[] fixedS = s.clone();

  for (int i = 0; i < s.length; i++) {
    s[i] = fixedS[(fixedS.length - 1) - i];
  }
}
public int singleNumber(int[] nums) {
  Arrays.sort(nums);

  for (int i = 0; i < (nums.length - 1); i++) {

    if ((i == 0 && nums[i + 1] != nums[i])
        || (nums[i + 1] != nums[i] && nums[i] != nums[i - 1])){
      return nums[i];
    }
  }
  return nums[nums.length - 1];
}
tablas a:
-- Table: public.tipobuques

-- DROP TABLE IF EXISTS public.tipobuques;

CREATE TABLE IF NOT EXISTS public.tipobuques
(
    id_tipo integer NOT NULL DEFAULT nextval('tipo_buques_id_tipo_seq'::regclass),
    desc_tipo character varying COLLATE pg_catalog."default",
    otros_datos character varying(255) COLLATE pg_catalog."default",
    CONSTRAINT tipo_buques_pkey PRIMARY KEY (id_tipo)
)

TABLESPACE pg_default;

ALTER TABLE IF EXISTS public.tipobuques
    OWNER to postgres;

tabla b:
-- Table: public.transportes

-- DROP TABLE IF EXISTS public.transportes;

CREATE TABLE IF NOT EXISTS public.transportes
(
    id_transporte integer NOT NULL DEFAULT nextval('transportes_id_transporte_seq'::regclass),
    nombre_transporte character varying(255) COLLATE pg_catalog."default" NOT NULL,
    id_buquescarga integer,
    id_tipo integer[],
    id_nacionalidad integer,
    otros_datos character varying(255) COLLATE pg_catalog."default",
    CONSTRAINT transportes_pkey PRIMARY KEY (id_transporte)
)

TABLESPACE pg_default;

ALTER TABLE IF EXISTS public.transportes
    OWNER to postgres;

<div class="col-xs-4" id='id_transporte' style="display:none;">
                <?= $form->field($model, 'id_transporte')
                    ->dropDownList(
                        ArrayHelper::map(
                            Transportes::find()->all(),
                            'id_transporte',
                            'nombre_transporte'
                        ),
                        [
                            'prompt' => 'Seleccione Transporte',
                            'id' => 'id-transporte'
                        ]
                    ); ?>
            </div>

            <div class="col-xs-4" id='id_tipo' style="display:none;">
                <?= $form->field($model, 'id_tipo')->widget(\kartik\depdrop\DepDrop::classname(), [
                    'options' => ['id' => 'id-tipo'],
                    'pluginOptions' => [
                        'depends' => ['id-transporte'],
                        'placeholder' => 'Seleccione Tipo de Buque',
                        'url' => \yii\helpers\Url::to(['transportes/listartipos'])
                    ],
                ]); ?>
            </div>
functionController:
public function actionListartipos()
{
    \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    
    $out = [];
    
    if (isset($_POST['depdrop_parents'])) {
        $id_transporte = $_POST['depdrop_parents'][0];
        
        if (!empty($id_transporte)) {
            // Buscar el transporte seleccionado
            $transporte = \app\models\Transportes::findOne($id_transporte);
            
            if ($transporte && !empty($transporte->id_tipo)) {
                // Convertir el array PostgreSQL a un array de PHP
                $ids_tipos = $transporte->id_tipo;
                
                // Si es una cadena (formato PostgreSQL array), convertir a array
                if (is_string($ids_tipos)) {
                    // Remover llaves y convertir a array
                    $ids_tipos = trim($ids_tipos, '{}');
                    $ids_tipos = $ids_tipos ? explode(',', $ids_tipos) : [];
                }
                
                if (!empty($ids_tipos)) {
                    // Buscar los tipos de buques correspondientes a los IDs en el array
                    $out = \app\models\Tipobuques::find()
                        ->where(['id_tipo' => $ids_tipos])
                        ->select(['id_tipo as id', 'desc_tipo as name'])
                        ->asArray()
                        ->all();
                }
            }
        }
    }
    
    return ['output' => $out, 'selected' => ''];
}
use kartik\select2\Select2;

<?= $form->field($model, 'id_tipo')->widget(Select2::classname(), [
    'data' => ArrayHelper::map(Tipobuques::find()->all(), 'id_tipo', 'desc_tipo'),
    'options' => [
        'multiple' => true,
        'placeholder' => 'Seleccione Tipos de Buque...'
    ],
]); ?>
  
index:
[
  'attribute' => 'id_tipo',
  'label' => 'Tipos de Buques',
  'value' => function ($model) {
    // Usar el método de debug seguro
    return $model->getTiposBuquesNombres();
  },
  'format' => 'raw',
],
view:
[
  'attribute' => 'id_tipo',
  'label' => 'Tipos de Buques',
  'value' => function ($model) {
    // Usar el método de debug seguro
    return $model->getTiposBuquesNombres();
  },
    'format' => 'raw',
      ],
public boolean containsDuplicate(int[] nums) {

  Set<Integer> set = new HashSet<>();

  for (int num : nums) {
    if (!set.add(num)) {
      return true;
    }
  }
  return false;
}
public void rotate(int[]nums, int k) {
  int n = nums.length;
  int[] newNums = new int[n];
  k = k % n;// k is number of rotations
  
  for(int i = 0; i < n; i++) {
    newNums[(i + k) % n] = nums[i];
  }
  
  for(int i = 0; i < n; i++){
    nums[1] = newNums[i];
  }
}
.wcgs-grid-template.wcgs-grid-height-auto.grid.wcgs-grid-template > *:only-child {
  grid-column: 1 / -1;
}
 
document.addEventListener("DOMContentLoaded", function() {
        var mediaQuery = window.matchMedia("(min-width: 641px)");
 
        function handleChange(e) {
            if (e.matches) {
                var el = document.querySelector(".fusion-no-medium-visibility.fusion-no-large-visibility #wpgs-gallery");
                if (el) {
                    el.remove();
                }
            }
        }
 
        // Run once
        handleChange(mediaQuery);
 
        // Run when screen crosses 641px breakpoint
        mediaQuery.addEventListener("change", handleChange);
});
DO $$
BEGIN
   IF NOT EXISTS (
      SELECT 1 
      FROM pg_class c
      JOIN pg_namespace n ON n.oid = c.relnamespace
      WHERE c.relname = 'carrier_id_seq'
        AND n.nspname = 'lookup'
   ) THEN
      CREATE SEQUENCE lookup.carrier_id_seq OWNED BY lookup.carrier.id;
   END IF;
END$$;

-- Make id use sequence
ALTER TABLE lookup.carrier ALTER COLUMN id SET DEFAULT nextval('lookup.carrier_id_seq');

-- Reset sequence based on max(id) from lookup.carrier
SELECT setval(
   'lookup.carrier_id_seq',
   (SELECT COALESCE(MAX(id), 0) + 1 FROM lookup.carrier),
   false
);




-- Create a sequence if not exists
DO $$
BEGIN
   IF NOT EXISTS (SELECT 1 FROM pg_class WHERE relname = 'carrier_id_seq') THEN
      CREATE SEQUENCE carrier_id_seq OWNED BY carrier.id;
   END IF;
END$$;

-- Make id use sequence
ALTER TABLE carrier ALTER COLUMN id SET DEFAULT nextval('carrier_id_seq');


SELECT setval('carrier_id_seq', (SELECT COALESCE(MAX(id), 0) + 1 FROM carrier), false);
# Commands to add  Jar file to postgres
nano ~/.bashrc

# Add PostgreSQL JDBC JAR to Spark
export SPARK_CLASSPATH=$SPARK_CLASSPATH:/home/youruser/jars/postgresql-42.7.3.jar
export PYSPARK_SUBMIT_ARGS="--jars /home/youruser/jars/postgresql-42.7.3.jar pyspark-shell"

source ~/.bashrc

# Restart your terminal or Jupyter Notebook server to apply the changes.
// import 'package:flutter/material.dart';

// class GamingPage extends StatelessWidget {
//   const GamingPage({super.key});

//   @override
//   Widget build(BuildContext context) {
//     final games = [
//       {"title": "چرخونه شانس", "icon": Icons.casino},
//       {"title": "جعبه جایزه", "icon": Icons.card_giftcard},
//       {"title": "چیستان", "icon": Icons.quiz},
//       {"title": "حدس کلمه", "icon": Icons.spellcheck},
//       {"title": "بازی حافظه", "icon": Icons.memory},
//       {"title": "پازل", "icon": Icons.extension},
//     ];

//     return Directionality(
//       textDirection: TextDirection.rtl,
//       child: Scaffold(
//         body: CustomScrollView(
//           slivers: [
//             // 🔹 هدر بزرگ که کوچیک میشه
//             SliverAppBar(
//               expandedHeight: 200,
//               pinned: true,
//               floating: false,
//               flexibleSpace: FlexibleSpaceBar(
//                 title: const Text("🎮 بازی‌ها"),
//                 background: Container(
//                   decoration: const BoxDecoration(
//                     gradient: LinearGradient(
//                       colors: [Color(0xFF6A11CB), Color(0xFF2575FC)],
//                       begin: Alignment.topRight,
//                       end: Alignment.bottomLeft,
//                     ),
//                   ),
//                   child: Center(
//                     child: Icon(
//                       Icons.videogame_asset,
//                       size: 80,
//                       color: Colors.white.withOpacity(0.8),
//                     ),
//                   ),
//                 ),
//               ),
//             ),

//             // 🔹 Grid بازی‌ها
//             SliverPadding(
//               padding: const EdgeInsets.all(16),
//               sliver: SliverGrid(
//                 gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
//                   crossAxisCount: 2, // دو ستون
//                   mainAxisSpacing: 16,
//                   crossAxisSpacing: 16,
//                   childAspectRatio: 1, // مربعی
//                 ),
//                 delegate: SliverChildBuilderDelegate(
//                   (context, index) {
//                     final game = games[index];
//                     return _gameCard(
//                       context,
//                       game["title"] as String,
//                       game["icon"] as IconData,
//                     );
//                   },
//                   childCount: games.length,
//                 ),
//               ),
//             ),
//           ],
//         ),
//       ),
//     );
//   }

//   Widget _gameCard(BuildContext context, String title, IconData icon) {
//     return InkWell(
//       onTap: () {
//         ScaffoldMessenger.of(context).showSnackBar(
//           SnackBar(content: Text("شروع بازی: $title")),
//         );
//       },
//       child: Card(
//         shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
//         elevation: 4,
//         child: Column(
//           mainAxisAlignment: MainAxisAlignment.center,
//           children: [
//             Icon(icon, size: 50, color: Colors.deepPurple),
//             const SizedBox(height: 12),
//             Text(
//               title,
//               style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
//             ),
//           ],
//         ),
//       ),
//     );
//   }
// }

/**
 * !عالی
 * 
 * 
 */
// import 'package:flutter/material.dart';

// class GamingPage extends StatelessWidget {
//   const GamingPage({super.key});

//   @override
//   Widget build(BuildContext context) {
//     final games = [
//       {"title": "چرخونه شانس", "icon": Icons.casino},
//       {"title": "جعبه جایزه", "icon": Icons.card_giftcard},
//       {"title": "چیستان", "icon": Icons.quiz},
//       {"title": "حدس کلمه", "icon": Icons.spellcheck},
//       {"title": "بازی حافظه", "icon": Icons.memory},
//       {"title": "پازل", "icon": Icons.extension},
//     ];

//     return Directionality(
//       textDirection: TextDirection.rtl,
//       child: Scaffold(
//         body: CustomScrollView(
//           slivers: [
//             // 🔹 هدر تصویری
//             SliverAppBar(
//               expandedHeight: 220,
//               pinned: true,
//               flexibleSpace: FlexibleSpaceBar(
//                 title: const Text("🎮 بازی‌ها"),
//                 centerTitle: true,
//                 background: Image.asset(
//                   "assets/gaming_banner.jpg", // عکس بنر بزرگ
//                   fit: BoxFit.cover,
//                 ),
//               ),
//             ),

//             // 🔹 Grid بازی‌ها
//             SliverPadding(
//               padding: const EdgeInsets.all(16),
//               sliver: SliverGrid(
//                 gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
//                   crossAxisCount: 2, // دو ستون
//                   mainAxisSpacing: 16,
//                   crossAxisSpacing: 16,
//                   childAspectRatio: 1, // مربعی دقیق
//                 ),
//                 delegate: SliverChildBuilderDelegate(
//                   (context, index) {
//                     final game = games[index];
//                     return _gameCard(
//                       context,
//                       game["title"] as String,
//                       game["icon"] as IconData,
//                     );
//                   },
//                   childCount: games.length,
//                 ),
//               ),
//             ),
//           ],
//         ),
//       ),
//     );
//   }

//   Widget _gameCard(BuildContext context, String title, IconData icon) {
//     return InkWell(
//       onTap: () {
//         ScaffoldMessenger.of(context).showSnackBar(
//           SnackBar(content: Text("شروع بازی: $title")),
//         );
//       },
//       child: Card(
//         shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
//         elevation: 4,
//         child: Column(
//           mainAxisAlignment: MainAxisAlignment.center,
//           children: [
//             Icon(icon, size: 50, color: Colors.deepPurple),
//             const SizedBox(height: 12),
//             Text(
//               title,
//               style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
//             ),
//           ],
//         ),
//       ),
//     );
//   }
// }
import 'package:flutter/material.dart';
import 'package:lottery_app/games/memory_page.dart';

class GamingPage extends StatelessWidget {
  const GamingPage({super.key});

  @override
  Widget build(BuildContext context) {
    final games = [
      {"title": "بازی حافظه", "icon": Icons.memory},
      {"title": "تاس شانس", "icon": Icons.casino},
      {"title": "جعبه جایزه", "icon": Icons.card_giftcard},
      {"title": "چیستان", "icon": Icons.quiz},
      // {"title": "حدس کلمه", "icon": Icons.spellcheck},
      // {"title": "بازی حافظه", "icon": Icons.memory},
      // {"title": "پازل", "icon": Icons.extension},
      // {"title": "پازل", "icon": Icons.extension},
      // {"title": "پازل", "icon": Icons.extension},
    ];

    return Directionality(
      textDirection: TextDirection.rtl,
      child: Scaffold(
        body: CustomScrollView(
          slivers: [
            // 🔹 SliverAppBar با Parallax و Rounded Bottom
            SliverAppBar(
              expandedHeight: 260,
              pinned: true,
              stretch: true,
              //snap: false,
              backgroundColor: const Color.fromARGB(235, 0, 0, 0),
              flexibleSpace: FlexibleSpaceBar(
                title: const Text(
                  "🎮 بازی‌ها",
                  style: TextStyle(
                    color: Colors.white,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                centerTitle: true,
                stretchModes: const [
                  StretchMode.zoomBackground,
                  StretchMode.fadeTitle,
                ],
                background: Stack(
                  fit: StackFit.expand,
                  children: [
                    // تصویر پس‌زمینه
                    ClipRRect(
                      borderRadius: const BorderRadius.only(
                        bottomLeft: Radius.circular(30),
                        bottomRight: Radius.circular(30),
                      ),
                      child: Image.asset(
                        "assets/gaming_banner.jpg",
                        fit: BoxFit.cover,
                      ),
                    ),
                    // Overlay Gradient
                    Container(
                      decoration: BoxDecoration(
                        borderRadius: const BorderRadius.only(
                          bottomLeft: Radius.circular(30),
                          bottomRight: Radius.circular(30),
                        ),
                        gradient: LinearGradient(
                          colors: [
                            Colors.black.withOpacity(0.4),
                            Colors.transparent,
                          ],
                          begin: Alignment.bottomCenter,
                          end: Alignment.topCenter,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),

            // 🔹 Grid بازی‌ها
            SliverPadding(
              padding: const EdgeInsets.all(16),
              sliver: SliverGrid(
                gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  mainAxisSpacing: 16,
                  crossAxisSpacing: 16,
                  childAspectRatio: 1, // مربع دقیق
                ),
                delegate: SliverChildBuilderDelegate((context, index) {
                  final game = games[index];
                  return _gameCard(
                    context,
                    game["title"] as String,
                    game["icon"] as IconData,
                  );
                }, childCount: games.length),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _gameCard(BuildContext context, String title, IconData icon) {
    return InkWell(
      onTap: () {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text("شروع بازی: $title")));
      },
      child: Card(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
        elevation: 4,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(icon, size: 50, color: Colors.deepPurple),
            const SizedBox(height: 12),
            Text(
              title,
              style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
            ),
          ],
        ),
      ),
    );
  }
}
// import 'package:flutter/material.dart';

// class GamingPage extends StatelessWidget {
//   const GamingPage({super.key});

//   @override
//   Widget build(BuildContext context) {
//     final games = [
//       {"title": "چرخونه شانس", "icon": Icons.casino},
//       {"title": "جعبه جایزه", "icon": Icons.card_giftcard},
//       {"title": "چیستان", "icon": Icons.quiz},
//       {"title": "حدس کلمه", "icon": Icons.spellcheck},
//       {"title": "بازی حافظه", "icon": Icons.memory},
//       {"title": "پازل", "icon": Icons.extension},
//     ];

//     return Directionality(
//       textDirection: TextDirection.rtl,
//       child: Scaffold(
//         body: CustomScrollView(
//           slivers: [
//             // 🔹 هدر بزرگ که کوچیک میشه
//             SliverAppBar(
//               expandedHeight: 200,
//               pinned: true,
//               floating: false,
//               flexibleSpace: FlexibleSpaceBar(
//                 title: const Text("🎮 بازی‌ها"),
//                 background: Container(
//                   decoration: const BoxDecoration(
//                     gradient: LinearGradient(
//                       colors: [Color(0xFF6A11CB), Color(0xFF2575FC)],
//                       begin: Alignment.topRight,
//                       end: Alignment.bottomLeft,
//                     ),
//                   ),
//                   child: Center(
//                     child: Icon(
//                       Icons.videogame_asset,
//                       size: 80,
//                       color: Colors.white.withOpacity(0.8),
//                     ),
//                   ),
//                 ),
//               ),
//             ),

//             // 🔹 Grid بازی‌ها
//             SliverPadding(
//               padding: const EdgeInsets.all(16),
//               sliver: SliverGrid(
//                 gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
//                   crossAxisCount: 2, // دو ستون
//                   mainAxisSpacing: 16,
//                   crossAxisSpacing: 16,
//                   childAspectRatio: 1, // مربعی
//                 ),
//                 delegate: SliverChildBuilderDelegate(
//                   (context, index) {
//                     final game = games[index];
//                     return _gameCard(
//                       context,
//                       game["title"] as String,
//                       game["icon"] as IconData,
//                     );
//                   },
//                   childCount: games.length,
//                 ),
//               ),
//             ),
//           ],
//         ),
//       ),
//     );
//   }

//   Widget _gameCard(BuildContext context, String title, IconData icon) {
//     return InkWell(
//       onTap: () {
//         ScaffoldMessenger.of(context).showSnackBar(
//           SnackBar(content: Text("شروع بازی: $title")),
//         );
//       },
//       child: Card(
//         shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
//         elevation: 4,
//         child: Column(
//           mainAxisAlignment: MainAxisAlignment.center,
//           children: [
//             Icon(icon, size: 50, color: Colors.deepPurple),
//             const SizedBox(height: 12),
//             Text(
//               title,
//               style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
//             ),
//           ],
//         ),
//       ),
//     );
//   }
// }

/**
 * !عالی
 * 
 * 
 */
// import 'package:flutter/material.dart';

// class GamingPage extends StatelessWidget {
//   const GamingPage({super.key});

//   @override
//   Widget build(BuildContext context) {
//     final games = [
//       {"title": "چرخونه شانس", "icon": Icons.casino},
//       {"title": "جعبه جایزه", "icon": Icons.card_giftcard},
//       {"title": "چیستان", "icon": Icons.quiz},
//       {"title": "حدس کلمه", "icon": Icons.spellcheck},
//       {"title": "بازی حافظه", "icon": Icons.memory},
//       {"title": "پازل", "icon": Icons.extension},
//     ];

//     return Directionality(
//       textDirection: TextDirection.rtl,
//       child: Scaffold(
//         body: CustomScrollView(
//           slivers: [
//             // 🔹 هدر تصویری
//             SliverAppBar(
//               expandedHeight: 220,
//               pinned: true,
//               flexibleSpace: FlexibleSpaceBar(
//                 title: const Text("🎮 بازی‌ها"),
//                 centerTitle: true,
//                 background: Image.asset(
//                   "assets/gaming_banner.jpg", // عکس بنر بزرگ
//                   fit: BoxFit.cover,
//                 ),
//               ),
//             ),

//             // 🔹 Grid بازی‌ها
//             SliverPadding(
//               padding: const EdgeInsets.all(16),
//               sliver: SliverGrid(
//                 gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
//                   crossAxisCount: 2, // دو ستون
//                   mainAxisSpacing: 16,
//                   crossAxisSpacing: 16,
//                   childAspectRatio: 1, // مربعی دقیق
//                 ),
//                 delegate: SliverChildBuilderDelegate(
//                   (context, index) {
//                     final game = games[index];
//                     return _gameCard(
//                       context,
//                       game["title"] as String,
//                       game["icon"] as IconData,
//                     );
//                   },
//                   childCount: games.length,
//                 ),
//               ),
//             ),
//           ],
//         ),
//       ),
//     );
//   }

//   Widget _gameCard(BuildContext context, String title, IconData icon) {
//     return InkWell(
//       onTap: () {
//         ScaffoldMessenger.of(context).showSnackBar(
//           SnackBar(content: Text("شروع بازی: $title")),
//         );
//       },
//       child: Card(
//         shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
//         elevation: 4,
//         child: Column(
//           mainAxisAlignment: MainAxisAlignment.center,
//           children: [
//             Icon(icon, size: 50, color: Colors.deepPurple),
//             const SizedBox(height: 12),
//             Text(
//               title,
//               style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
//             ),
//           ],
//         ),
//       ),
//     );
//   }
// }
import 'package:flutter/material.dart';
import 'package:lottery_app/games/memory_page.dart';
import 'package:lottery_app/games/slotmachine_data.dart';
import 'package:lottery_app/games/time_game_page.dart';
import 'package:lottery_app/games/tuch_game_page.dart';

class GamingPage extends StatelessWidget {
  const GamingPage({super.key});

  @override
  Widget build(BuildContext context) {
    final games = [
      {"title": "بازی حافظه", "icon": Icons.memory},
      {"title": "ماشین شانس", "icon": Icons.casino},
      {"title": "بازی تایم", "icon": Icons.timer_off_outlined},
      {"title": "بازی تعداد کلیک", "icon": Icons.touch_app},
      // {"title": "حدس کلمه", "icon": Icons.spellcheck},
      // {"title": "بازی حافظه", "icon": Icons.memory},
      // {"title": "پازل", "icon": Icons.extension},
      // {"title": "پازل", "icon": Icons.extension},
      // {"title": "پازل", "icon": Icons.extension},
    ];

    return Directionality(
      textDirection: TextDirection.rtl,
      child: Scaffold(
        body: CustomScrollView(
          slivers: [
            // 🔹 SliverAppBar با Parallax و Rounded Bottom
            SliverAppBar(
              expandedHeight: 260,
              pinned: true,
              stretch: true,
              //snap: false,
              backgroundColor: const Color.fromARGB(235, 0, 0, 0),
              flexibleSpace: FlexibleSpaceBar(
                title: const Text(
                  "🎮 بازی‌ها",
                  style: TextStyle(
                    color: Colors.white,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                centerTitle: true,
                stretchModes: const [
                  StretchMode.zoomBackground,
                  StretchMode.fadeTitle,
                ],
                background: Stack(
                  fit: StackFit.expand,
                  children: [
                    // تصویر پس‌زمینه
                    ClipRRect(
                      borderRadius: const BorderRadius.only(
                        bottomLeft: Radius.circular(30),
                        bottomRight: Radius.circular(30),
                      ),
                      child: Image.asset(
                        "assets/gaming_banner.jpg",
                        fit: BoxFit.cover,
                      ),
                    ),
                    // Overlay Gradient
                    Container(
                      decoration: BoxDecoration(
                        borderRadius: const BorderRadius.only(
                          bottomLeft: Radius.circular(30),
                          bottomRight: Radius.circular(30),
                        ),
                        gradient: LinearGradient(
                          colors: [
                            Colors.black.withOpacity(0.4),
                            Colors.transparent,
                          ],
                          begin: Alignment.bottomCenter,
                          end: Alignment.topCenter,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),

            // 🔹 Grid بازی‌ها
            SliverPadding(
              padding: const EdgeInsets.all(16),
              sliver: SliverGrid(
                gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  mainAxisSpacing: 16,
                  crossAxisSpacing: 16,
                  childAspectRatio: 1, // مربع دقیق
                ),
                delegate: SliverChildBuilderDelegate((context, index) {
                  final game = games[index];
                  return _gameCard(
                    context,
                    game["title"] as String,
                    game["icon"] as IconData,
                  );
                }, childCount: games.length),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _gameCard(BuildContext context, String title, IconData icon) {
    return InkWell(
      onTap: () {
        Widget page;

        switch (title) {
          case "بازی حافظه":
            page = MemoryTilesApp(); // صفحه مخصوص شطرنج
            break;
          case "ماشین شانس":
            page = SlotMachineGame(); // صفحه مخصوص فوتبال
            break;
          case "بازی تایم":
            page = TimeGamePage(); // صفحه مخصوص پازل
            break;
          case "بازی تعداد کلیک":
            page = TouchGameApp(); // صفحه مخصوص پازل
            break;
          default:
            page = GamingPage(); // fallback در صورتی که اسم بازی ناشناخته باشه
        }

// رفتن به صفحه بعدی
Navigator.push(
  context,
  MaterialPageRoute(builder: (context) => page),
);
      },
      child: Card(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
        elevation: 4,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(icon, size: 50, color: Colors.deepPurple),
            const SizedBox(height: 12),
            Text(
              title,
              style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
            ),
          ],
        ),
      ),
    );
  }
}
#!/bin/bash
# Jobran Rodriguez

# Definir lista de personas (en orden) con 8 nombres
persons=("Juan" "Jobran" "Luis" "Jose" "Gabriel" "Jonathan" "Brian" "Robert")

# Detectar carpeta de escritorio válida
if [ -d "$HOME/Escritorio" ]; then
    DESKTOP_DIR="$HOME/Escritorio"
elif [ -d "$HOME/Desktop" ]; then
    DESKTOP_DIR="$HOME/Desktop"
else
    DESKTOP_DIR="$HOME/Escritorio"
    mkdir -p "$DESKTOP_DIR"
    echo "No se encontró carpeta de escritorio, se ha creado '$DESKTOP_DIR'."
fi

# Crear carpeta asignacion
A="$DESKTOP_DIR/asignacion"
mkdir -p "$A"

# Definir archivo de salida
OUTPUT_FILE="$A/asignacion_caja.txt"

echo "Hola! Este script te dirá qué días te toca buscar la caja de comida este mes."
read -p "Por favor, ingresa tu nombre: " name

# Validar mes
while true; do
    read -p "Ingresa el número del mes (1-12): " month
    if [[ "$month" =~ ^[0-9]+$ ]] && (( month >= 1 && month <= 12 )); then
        # Eliminar ceros a la izquierda para cálculos
        month=$((10#$month))
        # Formatear para mostrar
        month_fmt=$(printf "%02d" $month)
        break
    else
        echo "Error: Debes ingresar un número válido entre 1 y 12 para el mes."
    fi
done

# Validar año
while true; do
    read -p "Ingresa el año (ej. 2025): " year
    if [[ "$year" =~ ^[0-9]{4}$ ]] && (( year >= 1900 && year <= 3000 )); then
        break
    else
        echo "Error: Debes ingresar un año válido de 4 dígitos (por ejemplo, 2023)."
    fi
done

# Verificar nombre con mensaje específico
index=-1
for i in "${!persons[@]}"; do
    if [[ "${persons[$i],,}" == "${name,,}" ]]; then
        index=$i
        break
    fi
done

if [ $index -eq -1 ]; then
    echo "Error: Debes ingresar un nombre válido de las personas que trabajan en la oficina de sistemas y usan el servicio del comedor."
    echo "Nombres válidos: ${persons[*]}"
    exit 1
fi

# Fecha actual (sin ceros a la izquierda para comparaciones)
current_year=$(date +%Y)
current_month=$(date +%-m)
current_day=$(date +%-d)

# Determinar si mostrar asignación individual
show_individual=1
if (( year < current_year )) || { (( year == current_year )) && (( month < current_month )); }; then
    show_individual=0
fi

# Función para obtener días del mes
days_in_month() {
    local m=$1
    local y=$2
    
    case $m in
        1|3|5|7|8|10|12) echo 31 ;;
        4|6|9|11) echo 30 ;;
        2)
            if (( (y % 400 == 0) || ((y % 4 == 0) && (y % 100 != 0)) )); then
                echo 29
            else
                echo 28
            fi
            ;;
        *)
            echo 30
            ;;
    esac
}

total_days=$(days_in_month $month $year)

# Pre-calcular días laborales y asignaciones
declare -a laboral_days
declare -a asignacion_personas
declare -a day_names
laboral_count=0

for (( day=1; day<=total_days; day++ )); do
    # Formatear día con dos dígitos para fecha
    day_fmt=$(printf "%02d" $day)
    wd=$(date -d "$year-$month_fmt-$day_fmt" +%u 2>/dev/null)
    
    if [ $? -ne 0 ]; then
        echo "Error: Fecha inválida $year-$month_fmt-$day_fmt. Verifica el mes y año."
        exit 1
    fi
    
    if (( wd >= 1 && wd <= 5 )); then
        laboral_days[laboral_count]=$day
        assign_index=$(( laboral_count % ${#persons[@]} ))
        asignacion_personas[laboral_count]=${persons[$assign_index]}
        
        # Obtener nombre del día en español
        day_name=$(LC_TIME=es_ES.UTF-8 date -d "$year-$month_fmt-$day_fmt" +%A 2>/dev/null)
        day_names[laboral_count]=$day_name
        
        ((laboral_count++))
    fi
done

# Crear o sobreescribir archivo
echo "Asignación de búsqueda de caja para $month_fmt/$year" > "$OUTPUT_FILE"
echo "--------------------------------------------" >> "$OUTPUT_FILE"

assigned_days=()
current_week=""
week_started=0

# Mostrar asignación semanal por pantalla
echo
echo "📅 Asignación semanal de búsqueda de caja para $month_fmt/$year:"
echo "=========================================================="

for (( i=0; i<laboral_count; i++ )); do
    day=${laboral_days[i]}
    assigned_person=${asignacion_personas[i]}
    day_name=${day_names[i]}
    
    # Formatear día con dos dígitos
    day_fmt=$(printf "%02d" $day)
    fecha_es=$(LC_TIME=es_ES.UTF-8 date -d "$year-$month_fmt-$day_fmt" +"%A %d de %B de %Y" 2>/dev/null)
    
    if [ $? -ne 0 ]; then
        echo "Error: No se pudo obtener información de fecha para $year-$month_fmt-$day_fmt"
        continue
    fi
    
    # Determinar semana actual
    week_num=$(date -d "$year-$month_fmt-$day_fmt" +%U 2>/dev/null)
    
    # Verificar si la fecha ya pasó
    date_passed=0
    if (( year < current_year )) || \
       { (( year == current_year )) && (( month < current_month )); } || \
       { (( year == current_year )) && (( month == current_month )) && (( day < current_day )); }; then
        date_passed=1
    fi
    
    # Escribir en archivo (todas las fechas)
    echo "$fecha_es : $assigned_person" >> "$OUTPUT_FILE"
    
    # Mostrar solo asignación individual para el usuario si corresponde
    if [[ "${assigned_person,,}" == "${name,,}" && show_individual -eq 1 ]]; then
        assigned_days+=("$fecha_es")
    fi
    
    # Mostrar asignación semanal por pantalla (solo fechas futuras o actual)
    if [ $date_passed -eq 0 ]; then
        if [ "$current_week" != "$week_num" ]; then
            if [ $week_started -eq 1 ]; then
                echo "----------------------------------------------------"
            fi
            current_week=$week_num
            week_start_date=$(date -d "$year-$month_fmt-$day_fmt -$(( $(date -d "$year-$month_fmt-$day_fmt" +%u) - 1 )) days" +"%d/%m" 2>/dev/null)
            week_end_date=$(date -d "$year-$month_fmt-$day_fmt +$(( 7 - $(date -d "$year-$month_fmt-$day_fmt" +%u) )) days" +"%d/%m" 2>/dev/null)
            echo "📋 Semana del $week_start_date al $week_end_date:"
            week_started=1
        fi
        
        # Icono según el día de la semana
        case $day_name in
            lunes) icon="🔵" ;;
            martes) icon="🟢" ;;
            miércoles|miercoles) icon="🟡" ;;
            jueves) icon="🟠" ;;
            viernes) icon="🔴" ;;
            *) icon="📌" ;;
        esac
        
        # Resaltar si es el usuario actual
        if [[ "${assigned_person,,}" == "${name,,}" ]]; then
            echo "   $icon $day_name $day: 👤 **TÚ**"
        else
            echo "   $icon $day_name $day: $assigned_person"
        fi
    fi
done

if [ $week_started -eq 1 ]; then
    echo "=========================================================="
fi

# Mostrar resultados individuales al usuario
if (( show_individual == 1 )); then
    echo
    echo "¡Hola, $name! 🎉 Aquí están los días que te toca buscar la caja de comida este mes:"
    if [ ${#assigned_days[@]} -eq 0 ]; then
        echo "¡Nada esta vez! Pero recuerda estar listo para la próxima ronda. 😉"
    else
        for d in "${assigned_days[@]}"; do
            echo "  - $d"
        done
    fi
else
    echo
    echo "Tu asignación individual no se mostrará porque el mes seleccionado ($month_fmt/$year) ya pasó."
fi

echo
echo "Además, se ha creado o actualizado el archivo con la asignación completa en:"
echo "  $OUTPUT_FILE"
echo
echo "¡Gracias por colaborar con el equipo! 💪🍱"

exit 0
public int maxProfit(int[] prices) {
  int maxProfit = 0;

  for (int i = 1; i < prices.lentgh; i++) {
    if (prices[i] > prices[i -1]) {
      maxProfit += (prices[i] - prices[i -1]);
    }
  }
  return maxProfit;
}
 "require-dev": {
        "yiisoft/yii2-debug": "~2.1.0",
        "yiisoft/yii2-gii": "~2.1.0",
        "yiisoft/yii2-faker": "~2.0.0",
        "codeception/base": "^2.4.0",
        "phpunit/phpunit": "~6.5.5",
        "codeception/verify": "~1.0.0",
        "symfony/browser-kit": ">=2.7 <=4.2.4"
    },
      "config": {
        "process-timeout": 1800,
         "discard-changes": true,
	 "platform": {
      "php": "7.4.33"
	},
       "allow-plugins": {
            "yiisoft/yii2-composer": true
        }
    },
import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:provider/provider.dart';

/// Data model for the user's mission and simulated location.
class MissionData extends ChangeNotifier {
  final double _totalDistanceKm;
  double _currentDistanceKm;
  final double _userLatitude;
  final double _userLongitude;

  /// Initializes the mission with a total distance and a simulated user location.
  ///
  /// The initial current distance walked is 0.0.
  MissionData({
    required double totalDistanceKm,
    required double userLatitude,
    required double userLongitude,
    double initialDistanceKm = 0.0,
  })  : _totalDistanceKm = totalDistanceKm,
        _userLatitude = userLatitude,
        _userLongitude = userLongitude,
        _currentDistanceKm = initialDistanceKm {
    if (_totalDistanceKm <= 0) {
      throw ArgumentError('Total distance must be positive.');
    }
    if (_currentDistanceKm < 0) {
      throw ArgumentError('Initial distance cannot be negative.');
    }
    if (_currentDistanceKm > _totalDistanceKm) {
      _currentDistanceKm = _totalDistanceKm; // Cap initial distance at total
    }
  }

  /// The total distance required for the mission in kilometers.
  double get totalDistanceKm => _totalDistanceKm;

  /// The current distance walked by the user in kilometers.
  double get currentDistanceKm => _currentDistanceKm;

  /// The simulated geographical latitude of the user.
  double get userLatitude => _userLatitude;

  /// The simulated geographical longitude of the user.
  double get userLongitude => _userLongitude;

  /// The remaining distance to complete the mission in kilometers.
  double get remainingDistanceKm =>
      (_totalDistanceKm - _currentDistanceKm).clamp(0.0, _totalDistanceKm);

  /// The progress of the mission as a percentage (0.0 to 1.0).
  double get progressPercentage =>
      _currentDistanceKm / _totalDistanceKm.clamp(1.0, double.infinity);

  /// Adds a specified [distance] in kilometers to the current distance walked.
  ///
  /// The distance added must be positive. The current distance will not exceed
  /// the total mission distance.
  void addDistance(double distance) {
    if (distance <= 0) {
      throw ArgumentError('Distance to add must be positive.');
    }
    _currentDistanceKm = (_currentDistanceKm + distance).clamp(0.0, _totalDistanceKm);
    notifyListeners();
  }
}

/// The main application widget for displaying location and mission.
class LocationMissionApp extends StatelessWidget {
  const LocationMissionApp({super.key});

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<MissionData>(
      create: (context) => MissionData(
        totalDistanceKm: 100.0, // Mission: walk 100 kilometers
        userLatitude: 51.5, // Simulated London latitude
        userLongitude: -0.09, // Simulated London longitude
      ),
      builder: (context, child) {
        return MaterialApp(
          title: 'Mission Tracker',
          theme: ThemeData(
            primarySwatch: Colors.blue,
            visualDensity: VisualDensity.adaptivePlatformDensity,
          ),
          home: const MissionScreen(),
        );
      },
    );
  }
}

/// Displays the map with simulated user location and mission progress.
class MissionScreen extends StatefulWidget {
  const MissionScreen({super.key});

  @override
  State<MissionScreen> createState() => _MissionScreenState();
}

class _MissionScreenState extends State<MissionScreen> {
  final TextEditingController _distanceInputController = TextEditingController();
  final _formKey = GlobalKey<FormState>();

  @override
  void dispose() {
    _distanceInputController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Mission Progress'),
      ),
      body: Consumer<MissionData>(
        builder: (context, missionData, child) {
          return Column(
            children: <Widget>[
              Expanded(
                flex: 2,
                child: Card(
                  margin: const EdgeInsets.all(8.0),
                  clipBehavior: Clip.antiAlias,
                  child: Stack(
                    children: [
                      FlutterMap(
                        options: MapOptions(
                          initialCenter: LatLng(missionData.userLatitude, missionData.userLongitude),
                          initialZoom: 13.0,
                          interactionOptions: const InteractionOptions(
                            flags: InteractiveFlag.all & ~InteractiveFlag.rotate,
                          ),
                        ),
                        children: [
                          TileLayer(
                            urlTemplate: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
                            userAgentPackageName: 'com.example.app',
                          ),
                          MarkerLayer(
                            markers: [
                              Marker(
                                point: LatLng(missionData.userLatitude, missionData.userLongitude),
                                width: 80,
                                height: 80,
                                child: const Icon(
                                  Icons.location_on,
                                  color: Colors.red,
                                  size: 40.0,
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                      Positioned(
                        top: 8,
                        left: 8,
                        child: Container(
                          padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                          decoration: BoxDecoration(
                            color: Colors.black54,
                            borderRadius: BorderRadius.circular(4),
                          ),
                          child: const Text(
                            'Simulated Location',
                            style: TextStyle(color: Colors.white, fontSize: 12),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              Expanded(
                flex: 1,
                child: Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: <Widget>[
                      Text(
                        'Mission: Walk ${missionData.totalDistanceKm.toStringAsFixed(0)} km',
                        style: Theme.of(context).textTheme.headlineSmall,
                        textAlign: TextAlign.center,
                      ),
                      const SizedBox(height: 8.0),
                      Text(
                        'Progress: ${missionData.currentDistanceKm.toStringAsFixed(1)} km of ${missionData.totalDistanceKm.toStringAsFixed(0)} km',
                        style: Theme.of(context).textTheme.titleMedium,
                        textAlign: TextAlign.center,
                      ),
                      const SizedBox(height: 4.0),
                      LinearProgressIndicator(
                        value: missionData.progressPercentage,
                        minHeight: 10,
                        backgroundColor: Colors.grey[300],
                        valueColor: const AlwaysStoppedAnimation<Color>(Colors.green),
                      ),
                      const SizedBox(height: 8.0),
                      Text(
                        'Remaining: ${missionData.remainingDistanceKm.toStringAsFixed(1)} km',
                        style: Theme.of(context).textTheme.titleSmall,
                        textAlign: TextAlign.center,
                      ),
                      const Spacer(),
                      Form(
                        key: _formKey,
                        child: Row(
                          children: [
                            Expanded(
                              child: TextFormField(
                                controller: _distanceInputController,
                                keyboardType:
                                    const TextInputType.numberWithOptions(decimal: true),
                                decoration: InputDecoration(
                                  labelText: 'Add distance (km)',
                                  border: const OutlineInputBorder(),
                                  suffixText: 'km',
                                  errorStyle: TextStyle(
                                      color: Theme.of(context).colorScheme.error,
                                      fontSize: 10),
                                ),
                                validator: (String? value) {
                                  if (value == null || value.isEmpty) {
                                    return 'Please enter a distance';
                                  }
                                  final double? distance = double.tryParse(value);
                                  if (distance == null || distance <= 0) {
                                    return 'Enter a positive number';
                                  }
                                  return null;
                                },
                              ),
                            ),
                            const SizedBox(width: 8.0),
                            ElevatedButton(
                              onPressed: () {
                                if (_formKey.currentState!.validate()) {
                                  final double distanceToAdd =
                                      double.parse(_distanceInputController.text);
                                  missionData.addDistance(distanceToAdd);
                                  _distanceInputController.clear();
                                  FocusScope.of(context).unfocus(); // Dismiss keyboard
                                }
                              },
                              style: ElevatedButton.styleFrom(
                                padding: const EdgeInsets.symmetric(
                                    horizontal: 24, vertical: 16),
                              ),
                              child: const Text('Add Walk'),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          );
        },
      ),
    );
  }
}

void main() {
  runApp(const LocationMissionApp());
}
#Loading your work directory and RNASeq counts and filtering the counts

setwd("//files.wustl.edu/Shares/DOM/ONC/Hirbe_Lab/Diana/UBR5 KO RNASeq/analysis/HOM VS WT_2")
Counts <- read.csv("Counts.csv")
# Remove duplicate rows from Counts
Counts <- Counts[!duplicated(Counts[, 1]), ]
rownames(Counts) <- Counts[, 1]
Counts<- Counts [, -1]

# Calculate row means
row_means <- rowMeans(Counts)

# Order genes by row means in descending order
ordered_counts <- Counts[rev(order(row_means)), ]
#alternative code to the above is (ordered_counts <- Counts[order(row_means, decreasing = TRUE), ])
# Filter out rows with row means less than 10
filtered_counts <- ordered_counts[rowMeans(ordered_counts) >= 10, ]
#save filtered data frame
write.csv(filtered_counts, "filtered_counts.csv")

#prepare metadata telling R the conditions (columns) 
metadata <- data.frame( 
  
  sample_id = colnames(filtered_counts),  # Assuming you have loaded the filtered expression data 
  
  condition = c(rep("UBR5 WT", 3), rep("UBR5 HOM", 3)),  # Treatment conditions 
  
  replicate = c(1, 2, 3, 1, 2, 3)  # Sample replicates 
  
) 

metadata$condition <- factor(metadata$condition, levels = c("UBR5 WT", "UBR5 HOM"))

#Load DESEQ2 for normalization
library(DESeq2) 

#Use the DESeqDataSetFromMatrix function from DESeq2 to create a DESeqDataSet object
dds <- DESeqDataSetFromMatrix(countData = filtered_counts,
                              colData = metadata,
                              design = ~ condition)



#Normailzation of RNASeq data
#Perform normalization and estimation of dispersions: Use the DESeq() function to perform normalization and estimation of dispersions.

dds <- DESeq(dds)
results <- results(dds, alpha = 0.05)
DEGs <- subset(results, abs(log2FoldChange) > 1 & padj < 0.05)


#save the de_genes data frame
write.csv(DEGs, file = "DEG_HOM_VS_WT.csv",)
write.csv(results, file = "DeseqResults_HOM_VS_WT.csv",)



#Visualizing your differentially expressed genes

#create volcano plot
library(ggplot2)

# Add column to classify genes as DEG or not
results_df <- as.data.frame(results)
results_df$gene <- rownames(results_df)
results_df$threshold <- "Unchanged"
results_df$threshold[results_df$padj < 0.05 & abs(results_df$log2FoldChange) > 1] <- "DEG"


library(ggrepel)


# Volcano plot
ggplot(results_df, aes(x = log2FoldChange, y = -log10(padj), color = threshold)) +
  geom_point(alpha = 0.6, size = 1.5) +
  scale_color_manual(values = c("Unchanged" = "grey", "DEG" = "red")) +
  theme_minimal(base_size = 14) +
  labs(title = "Volcano Plot: HOM vs WT",
       x = "log2 Fold Change (HOM vs WT)",
       y = "-log10 Adjusted p-value",
       color = "Gene status") +
  geom_vline(xintercept = c(-1, 1), linetype = "dashed", color = "black") +
  geom_hline(yintercept = -log10(0.05), linetype = "dashed", color = "black")


# Select top 50 significant genes by padj
top100 <- results_df[order(results_df$padj), ][1:100, ]

# Volcano plot
ggplot(results_df, aes(x = log2FoldChange, y = -log10(padj), color = threshold)) +
  geom_point(alpha = 0.6, size = 1.5) +
  scale_color_manual(values = c("Unchanged" = "grey", "DEG" = "red")) +
  theme_minimal(base_size = 14) +
  labs(title = "Volcano Plot: HOM vs WT",
       x = "log2 Fold Change (HOM vs WT)",
       y = "-log10 Adjusted p-value",
       color = "Gene status") +
  geom_vline(xintercept = c(-1, 1), linetype = "dashed", color = "black") +
  geom_hline(yintercept = -log10(0.05), linetype = "dashed", color = "black") +
  geom_text_repel(data = top100,
                  aes(label = gene),
                  size = 3,
                  max.overlaps = Inf,
                  box.padding = 0.3,
                  point.padding = 0.2,
                  segment.color = "grey50")

write.csv(top100, file = "Top100_HOM_vs_WT.csv", row.names = FALSE)


#Querrying genes of interest i.e UBR5 substrates as determined form the papers you have read

# Define genes of interest
genes_of_interest <- c("Egfr", "Hsp90ab1", "Map2k2", "Cerk", "Pdgfra", "Tyk2", "Jak1",
                       "Yap1", "Taz", "Kdr", "Aurka", "Pten", "Csf1r","Ptch1", "Smo", "Gli2", "Gli3", "Wnt10a", "Rac2", "Rspo2", "Apc",
                       "Cd274", "Pdcd1", "Id1", "Id3", "Cdh1", "Cdc73", "Hrpt2","Csf1","Golph3", "Cdk1", "Acsl4", "Ptk2b", "Akt1", "Akt2", "Akt3", "Pik3ca", "Pik3c2a", "Pik3cb" , "Pik3c3", "Pik3c2b", "Pik3cd", "Atmin", "Cdkn1a", "Cdk9", "Rela", "Nfkb1", "Nfkb2", "Capza1", "Stat1", "Stat3", "Irf1", "Irf3")

# Subset DEGs for these genes (case-sensitive match!)
genes_subset <- results_df[rownames(results_df) %in% genes_of_interest, ]

# Save genes of interest with stats
write.csv(genes_subset, file = "GenesOfInterest_HOM_vs_WT.csv", row.names = TRUE)

ggplot(results_df, aes(x = log2FoldChange, y = -log10(padj), color = threshold)) +
  geom_point(alpha = 0.6, size = 1.5) +
  scale_color_manual(values = c("Unchanged" = "grey", "DEG" = "red")) +
  theme_minimal(base_size = 14) +
  labs(title = "Volcano Plot: HET vs WT",
       x = "log2 Fold Change (HET vs WT)",
       y = "-log10 Adjusted p-value",
       color = "Gene status") +
  geom_vline(xintercept = c(-1, 1), linetype = "dashed", color = "black") +
  geom_hline(yintercept = -log10(0.05), linetype = "dashed", color = "black") +
  geom_text_repel(
    data = genes_subset,
    aes(label = gene),
    color = "black",       # <-- force label text to black
    size = 3,
    max.overlaps = Inf,
    box.padding = 0.3,
    point.padding = 0.2,
    segment.color = "grey50"
  )


# Subset DEGs only
DEGs_df <- as.data.frame(DEGs)
DEGs_df$gene <- rownames(DEGs_df)

# Find overlap between DEGs and genes of interest
genes_subset <- DEGs_df[rownames(DEGs_df) %in% genes_of_interest, ]

# Save overlapping genes with stats
write.csv(genes_subset, file = "GenesOfInterest_DEGs_HOM_vs_WT.csv", row.names = TRUE)

# Volcano plot with labels ONLY for genes of interest that are DEGs
ggplot(results_df, aes(x = log2FoldChange, y = -log10(padj), color = threshold)) +
  geom_point(alpha = 0.6, size = 1.5) +
  scale_color_manual(values = c("Unchanged" = "grey", "DEG" = "red")) +
  theme_minimal(base_size = 14) +
  labs(title = "Volcano Plot: HET vs WT",
       x = "log2 Fold Change (HET vs WT)",
       y = "-log10 Adjusted p-value",
       color = "Gene status") +
  geom_vline(xintercept = c(-1, 1), linetype = "dashed", color = "black") +
  geom_hline(yintercept = -log10(0.05), linetype = "dashed", color = "black") +
  geom_text_repel(
    data = genes_subset,
    aes(label = gene),
    color = "black",       # labels in black
    size = 5,
    max.overlaps = Inf,
    box.padding = 0.3,
    point.padding = 0.2,
    segment.color = "grey50"
  )




#Running pathway enrichment analysis to determine pathways enriched following UBR5 KO

if (!requireNamespace("clusterProfiler", quietly = TRUE)) {
  BiocManager::install("clusterProfiler")
}
if (!requireNamespace("msigdbr", quietly = TRUE)) {
  install.packages("msigdbr")
}
library(clusterProfiler)
library(msigdbr)


# Convert results to dataframe
res_df <- as.data.frame(results)

# Remove NA log2FC
res_df <- res_df[!is.na(res_df$log2FoldChange), ]

# Create named vector: names = gene symbols, values = log2FC
gene_list <- res_df$log2FoldChange
names(gene_list) <- rownames(res_df)

# Sort decreasing for clusterProfiler
gene_list <- sort(gene_list, decreasing = TRUE)


# Mouse Hallmark gene sets
hallmark_sets <- msigdbr(species = "Mus musculus", category = "H")  # H = Hallmark

# Use as two-column dataframe: gs_name (pathway), gene_symbol
term2gene <- hallmark_sets[, c("gs_name", "gene_symbol")]

# Make sure your DESeq2 results have no NA log2FC
res_df <- as.data.frame(results)
res_df <- res_df[!is.na(res_df$log2FoldChange), ]

# Named vector: names = gene symbols, values = log2FC
gene_list <- res_df$log2FoldChange
names(gene_list) <- rownames(res_df)
gene_list <- sort(gene_list, decreasing = TRUE)


gsea_res <- GSEA(
  geneList = gene_list,
  TERM2GENE = term2gene,  # <- must be dataframe, not list
  pvalueCutoff = 0.1,
  verbose = FALSE
)

# View top pathways
head(as.data.frame(gsea_res))

# Save results
write.csv(as.data.frame(gsea_res), "GSEA_Hallmark_Mouse_HOM_vs_WT.csv", row.names = FALSE)

library(enrichplot)

# Convert GSEA results to dataframe
gsea_df <- as.data.frame(gsea_res)

# Suppose the top (and only) enriched pathway:
top_pathway <- gsea_df$ID[5]  # or use $Description if you prefer

# Classic GSEA plot for the top pathway
gseaplot2(
  gsea_res,
  geneSetID = top_pathway,   # pathway ID
  title = gsea_df$Description[5],  # nice descriptive title
  color = "red"
)
#PLOT HALLMARK PATHWAYS
library(ggplot2)

# Convert GSEA results to dataframe
gsea_df <- as.data.frame(gsea_res)

# Order pathways by NES (normalized enrichment score)
gsea_df <- gsea_df[order(gsea_df$NES, decreasing = TRUE), ]

# Plot ALL enriched pathways
ggplot(gsea_df, aes(x = reorder(Description, NES), y = NES, fill = -log10(p.adjust))) +
  geom_col() +
  coord_flip() +
  labs(
    title = "GSEA: All Enriched Hallmark Pathways",
    x = "Pathway",
    y = "Normalized Enrichment Score (NES)",
    fill = "-log10 adj p-value"
  ) +
  theme_minimal(base_size = 14)


#plot GSEA KEGG, GO, REACTOME --------------------------
# Prepare ranked gene list with Entrez IDs for GSEA
# --------------------------
library(clusterProfiler)
library(org.Mm.eg.db)
library(ReactomePA)

# Convert gene symbols to Entrez IDs
entrez_map <- bitr(names(gene_list), fromType="SYMBOL", toType="ENTREZID", OrgDb=org.Mm.eg.db)
gene_list_df <- merge(entrez_map, data.frame(log2FC = gene_list), by.x="SYMBOL", by.y="row.names")
gene_list_df <- gene_list_df[!duplicated(gene_list_df$ENTREZID), ]
gene_list_named <- gene_list_df$log2FC
names(gene_list_named) <- gene_list_df$ENTREZID

# Sort decreasing for GSEA
gene_list_named <- sort(gene_list_named, decreasing = TRUE)

# --------------------------
# 1) GSEA: KEGG Pathways
# --------------------------
gsea_kegg <- gseKEGG(
  geneList = gene_list_named,
  organism = "mmu",
  minGSSize = 10,
  pvalueCutoff = 0.1,
  verbose = TRUE
)

# Save KEGG GSEA results
write.csv(as.data.frame(gsea_kegg), "GSEA_KEGG_HOM_vs_WT.csv", row.names = FALSE)

# Top 30 KEGG pathways barplot
library(enrichplot)
library(ggplot2)

# Convert gseaResult to dataframe to see top pathways
gsea_df <- as.data.frame(gsea_kegg)

# Select top 30 pathways by NES or pvalue
top30 <- gsea_df[order(gsea_df$NES, decreasing = TRUE)[1:30], ]

# Ridgeplot (shows enrichment distribution for multiple pathways)
ridgeplot(gsea_kegg, showCategory = 30) +
  ggtitle("GSEA: KEGG Top 30 Pathways") +
  theme_minimal(base_size = 14)

# Optional: classic GSEA plot for the top pathway
top_pathway <- top30$ID[1]
gseaplot2(gsea_kegg, geneSetID = top_pathway,
          title = top30$Description[1], color = "red")


# --------------------------
# 2) GSEA: GO Biological Process (BP)
# --------------------------
gsea_go_bp <- gseGO(
  geneList = gene_list_named,
  OrgDb = org.Mm.eg.db,
  ont = "ALL",
  keyType = "ENTREZID",
  minGSSize = 10,
  maxGSSize = 500,
  pvalueCutoff = 0.1,
  verbose = TRUE
)

# Save GO BP GSEA results
write.csv(as.data.frame(gsea_go_bp), "GSEA_GO_BP_HOM_vs_WT.csv", row.names = FALSE)

# Top 30 GO BP pathways barplot
barplot(gsea_go_bp, showCategory = 30, title = "GSEA: GO BP Top 30 Pathways")

# --------------------------
# 3) GSEA: Reactome Pathways
# --------------------------
gsea_reactome <- gsePathway(
  geneList = gene_list_named,
  organism = "mouse",
  minGSSize = 10,
  pvalueCutoff = 0.1,
  verbose = TRUE
)

# Save Reactome GSEA results
write.csv(as.data.frame(gsea_reactome), "GSEA_Reactome_HOM_vs_WT.csv", row.names = FALSE)

# Top 30 Reactome pathways barplot
barplot(gsea_reactome, showCategory = 30, title = "GSEA: Reactome Top 30 Pathways")

# --------------------------


library(ggplot2)
library(dplyr)

# Convert GSEA Reactome results to dataframe
gsea_reactome_df <- as.data.frame(gsea_reactome)

# Select top 30 pathways by NES magnitude
top30_reactome <- gsea_reactome_df %>%
  arrange(desc(abs(NES))) %>%
  slice(1:30)

# Reorder for plotting (highest NES on top)
top30_reactome$Description <- factor(top30_reactome$Description, levels = rev(top30_reactome$Description))

# Plot barplot: NES on x-axis, pathways on y-axis, fill by -log10(padj)
ggplot(top30_reactome, aes(x = NES, y = Description, fill = -log10(p.adjust))) +
  geom_bar(stat = "identity") +
  scale_fill_gradient(low = "red", high = "darkred") +
  theme_minimal(base_size = 14) +
  labs(title = "GSEA: Top 30 Reactome Pathways",
       x = "Normalized Enrichment Score (NES)",
       y = "",
       fill = "-log10(adj.p)")



#Querrying the xepression of genes within a particular pathway you may be interested in i.e type I interferon signaling

ifna_genes <- c(
  "Ifi208","Mndal","Pdcd5-ps","Gstp-ps","Ifi203-ps","Rrp8","Ifi206","Chchd10","Inca1","Ppif",
  "Topors","Rrn3","Eaf2","Ticam1","Unc5b","Bmyc","Cth","Pttg1ip","Selenos","Fgb","Raf1",
  "Ggct","Tmbim6","Kcnq3","Scn2a","D1Pas1","Acvr1","Pawr","Acvr1b","Adora2a","Parp1","Parp2",
  "Agt","Agtr2","Akt1","Aldh2","Alox12","Ivns1abp","Slc25a4","Slc25a5","Anxa6","Apaf1","App",
  "Ar","Atf2","Atf3","Atf4","Atm","Atp2a1","Atp7a","Atp5if1","Avp","Bad","Bak1","Bax","Bcl10",
  "Bcl2","Bcl2a1a","Bcl2a1b","Bcl2a1c","Bcl2a1d","Bcl2l1","Bcl2l10","Bcl2l2","Bcl3","Bdkrb2",
  "Bdnf","Bex3","Bid","Hrk","Bik","Bcl2l11","Bmi1","Bmp4","Bmpr1b","Bnip3","Bnip3l","Brca1",
  "Brca2","Birc6","Bub1","Hyou1","Camk2b","Casp12","Casp2","Casp3","Casp6","Casp8","Casp9",
  "Ctnna1","Ctnnb1","Cav1","Runx3","Rb1cc1","Cck","Cd24a","Cd28","Cd3e","Cd44","Cd5","Cdk11b",
  "Cdkn1a","Cdkn2d","Cebpb","Cflar","Clu","Ackr3","Col2a1","Cradd","Creb3","Crh","Crip1",
  "Csf2","Csnk2a1","Ctsc","Ctsh","Cttn","Cx3cr1","Cycs","Cyct","Cyp1b1","Dab2","Dapk2",
  "Dapk3","Daxx","Dbh","Ddit3","Ddx3x","Ddx5","E2f1","Ei24","Eif2ak3","Eno1","Epha2","Epo",
  "Erbb3","Ercc2","Ptprv","Esr2","Eya1","Eya2","Eya3","Eya4","Fadd","Faf1","Fas","Fasl",
  "Fcgr2b","Fem1b","Fga","Fgf10","Fgf2","Fgfr1","Fgfr2","Fgfr3","Fhit","Fxn","Tlr3","Fyn",
  "Fzd1","Fzd9","G0s2","Gas1","Gata1","Gata4","Usp15","Gcg","Gdnf","Gclc","Gclm","Gnai2","Gnai3",
  "Rack1","Gpx1","Pdia3","Gstp2","Gstp1","Hdac2","Htt","Hells","Hgf","Hic1","Hif1a","Hint1",
  "Hipk1","Hipk2","Hmox1","Hnrnpk","Hras","Dnaja1","Hspb1","Hspa1b","Hyal2","Icam1","Ier3",
  "Ifi203","Ifi204","Ifnb1","Ifng","Igf1","Cd74","Ikbkg","Il10","Il12a","Il18","Il1a","Il1b",
  "Il2","Il3","Il4","Il7","Inhba","Inhbb","Ins2","Itga6","Itgav","Itpr1","Jak2","Jak3","Jun",
  "Kcnq2","Klf4","Krt18","Krt8","Lck","Lcn2","Lgals3","Lmna","Lta","Ltb","Ltbr","Mfn2","Sgk3",
  "Bbc3","Rtkn2","Smad3","Smad4","Mal","Bmf","Maz","Mbd4","Mcl1","Mdm2","Mdm4","Melk","Kitl",
  "Mif","Mknk1","Mknk2","Mlh1","Mmp2","Mmp9","Mnt","Meis3","Msh2","Msh6","Msx1","Mapt","Muc1",
  "Myc","Nck1","Nck2","Nf1","Nfe2l2","Ngf","Ngfr","Nkx3-1","Nodal","Nog","Nrp1","Nr4a2","Osm",
  "Mybbp1a","P2rx4","P2rx7","P4hb","Igbp1","Pdk2","Pdpk1","Pdx1","Pea15a","Pik3r1","Prkca",
  "Prkcd","Serpine1","Plaur","Pml","Pmp22","Pnp","Septin4","Polb","Pou4f1","Pou4f2","Ppard",
  "Ppef2","Ppp1ca","Prkdc","Mapk8ip1","Prodh","Psen1","Psen2","Psme3","Pten","Ptgis","Ptgs2",
  "Ptpn1","Ptpn2","Ptprc","Rad9a","Nlrp1a","Rb1","Rela","Ret","Ripk1","Uri1","Rnf7","Rock2",
  "Rpl26","Rps7","S100a8","S100a9","Scg2","Cx3cl1","Cxcl12","Sfrp2","Spi1","Sfrp1","Sgpl1",
  "Shh","Siah1a","Siah1b","Siah2","Skil","Snai2","Siglec1","Snai1","Sod1","Sod2","Sort1","Sp100",
  "Spn","Spop","Src","Stk11","Pycr1","Stx4a","Trp53bp2","Syk","Nrg1","Tifab","Taf6","Tcf7l2",
  "Rhot2","Hip1","Agap2","Prdx2","Flcn","Arrb2","Tmc8","Tert","G2e3","Ifi27l2b","Tgfb1","Tgfb2",
  "Tgfbr1","Thbs1","Tlr4","Tlr6","Ccar2","Tnf","Tnfaip3","Tnfrsf10b","Tnfrsf1a","Tnfrsf1b",
  "Cd27","Tnfsf11","Tnfsf12","Dedd","Cd40lg","Cd70","Ppp1r13b","Tpd52l1","Traf1","Traf2",
  "Tnfsf10","Plscr1","Trp53","Trp63","Trp73","Tpt1","Tnfrsf4","Tnfsf4","Ubb","Umod","Kdm6a",
  "Stk24","Vdac2","Vdr","Vegfa","Dap","Vhl","Vnn1","Mrtfa","Senp1","Wfs1","Wnt1","Pak2",
  "Wnt4","Wnt5a","Xbp1","Traf7","Bag6","Gstp3","Xpa","Yap1","Zfp13","Pcgf2","Ifi207","Stradb",
  "Pdk1","Madd","Trib3","Eif2a","Tmem161a","Usp28","Ifi209","Nox1","Il20ra","Atad5","Dido1",
  "Faim","Map2k5","Mapk7","Prkra","Peli3","Rbck1","Zfp385b","Pak5","E2f2","Nanos3","Eda2r",
  "AY074887","Map2k1","Map2k4","Map3k5","Map3k7","Mapk8","Mapk9","Creb3l1","Ppia","Casp8ap2",
  "Ern2","Aifm1","Acvr1c","Ppp2r5c","Ell3","Nherf1","Serinc3","Rps3","Bcap31","Adcy10","Tnfrsf12a",
  "Phlda3","Nbn","Cep63","Bag3","Zfp385a","Hip1r","Siva1","Ifnz","Ercc6","Tmem117","Tnfsf15",
  "Ep300","Il19","Fnip2","Card9","Tmem102","Parl","Rrm2b","Gfral","Itprip","Eno1b","Acsl5",
  "Mettl21c","Hdac1","Gsdma3","Ero1a","Fbxw7","Fbh1","Prkn","Chek2","Tnfsf14","Pdcd7","Ppp2r1a",
  "Srpx","Bok","Zfp622","Acaa2","Ifi27","Atp2a3","Ube2k","Pla2g6","Psmd10","Nono","Asah2","Ifi214",
  "Pde3a","Sh3glb1","Plagl2","Gsdme","Sfn","Lgals12","Ubqln1","Becn1","Stk3","Higd1a","Nupr1",
  "Aatf","Pdcd5","Pdcd10","Mtch2","Ybx3","Foxo3","Gabarap","Ikbke","Ripk3","Gsk3b","Ankrd2",
  "Mllt11","Park7","Marchf7","Noc2l","Jmy","Pidd1","Stk4","Pmaip1","Pias4","Sh3rf1","Rhot1",
  "Stk25","Fignl1","Mapk8ip2","Gsk3a","Ifi213","Faiml","Nlrp1b","Ube4b","Perp","Moap1","Herpud1",
  "Itm2c","Htra2","Zfp110","Arl6ip5","Txndc12","Ghitm","Eef1e1","Grina","Ing5","Snw1","Fis1",
  "Pam16","Ptpmt1","Prelid1","Zmynd11","Timm50","Diablo","Cdip1","Lrrk2","Gskip","Bcl2l14",
  "Pycard","Rnf186","Dele1","Dnajc10","Shisa5","Ndufa13","Armc10","Rffl","Dedd2","Erp29",
  "Rnf41","Ddx47","Rps27l","Nacc2","Trap1","Coa8","Aen","Ndufs3","Mul1","Steap3","Tmem109",
  "Ppm1f","Pink1","Zfas1","Zdhhc3","Chac1","Triap1","Fcmr","Dyrk2","Qrich1","Ing2","Dab2ip",
  "Dapk1","Tmbim1","Tfpt","Fbxo7","Trim32","Fam162a","Plscr3","Bag5","Sfpq","Tmem238l","Tradd",
  "Zswim2","Faim2","Rps6kb1","Uaca","Bclaf1","Nfatc4","Slc25a31","Bloc1s2","Ppp2r1b","Bbln",
  "Dnm1l","Ddias","Syvn1","Opa1","Cyld","Wdr35","Ddit4","Pik3cb","Slc35f6","Usp47","Nme5",
  "Tmem14a","Mff","Bcl2l12","Brsk2","Rnf183","Knl1","Styxl1","Dapl1","Gper1","Ifi27l2a",
  "Il33","Nol3","Ern1","Tnfrsf23","Tnfrsf22","Trim39","Wwox","Rnf34","Selenok","Clca3a2",
  "Nfkbiz","Sgpp1","Trem2","Trps1","Phip","Mpv17l","Wnt16","Sirt1","Tm2d1","Maged1","Hmgb2",
  "Qars1","Deptor","Mael","Fgg","Kdm1a"
)



# Get normalized counts from DESeq2
norm_counts <- counts(dds, normalized=TRUE)

# Subset for IFN-α response genes (keep only genes present in your dataset)
ifna_counts <- norm_counts[rownames(norm_counts) %in% ifna_genes, ]

# Optionally, z-score normalize each gene for heatmap visualization
ifna_counts_z <- t(scale(t(ifna_counts)))


# Create annotation for columns
ann_col <- data.frame(
  Condition = metadata$condition
)
rownames(ann_col) <- metadata$sample_id


library(pheatmap)

# Make sure columns are in your desired order
desired_order <- c("sample.WT_1", "sample.WT_2", "sample.WT_3",
                   "sample.neg.neg_1", "sample.neg.neg_2", "sample.neg.neg_3")
ifna_counts_z <- ifna_counts_z[, desired_order]

# Make sure annotation matches
ann_col <- ann_col[desired_order, , drop = FALSE]

# Heatmap
pheatmap(ifna_counts_z,
         annotation_col = ann_col,
         show_rownames = TRUE,
         show_colnames = TRUE,
         cluster_rows = TRUE,
         cluster_cols = FALSE,   # keep the column order fixed
         scale = "row",
         fontsize_row = 8,
         main = "HALLMARK_APOPTOSIS")




# Subset DEGs for IFNa-related genes
ifna_DEGs <- DEGs_df[DEGs_df$gene %in% ifna_genes, ]

# Save to CSV
write.csv(ifna_DEGs, "GOBP_APOPTOSIS_HOM_vs_WT DEG.csv", row.names = FALSE)
# Save subset expression to CSV
write.csv(as.data.frame(ifna_counts),
          file = "GOBP_APOPTOSIS_HOM VS WT.csv",
          row.names = TRUE)
# Quick check
print(ifna_DEGs)


library(ggplot2)
library(ggrepel)

ggplot(results_df, aes(x = log2FoldChange, y = -log10(padj), color = threshold)) +
  geom_point(alpha = 0.6, size = 1.5) +
  scale_color_manual(values = c("Unchanged" = "grey", "DEG" = "red")) +
  theme_minimal(base_size = 14) +
  labs(
    title = "HALLMARK_APOPTOSIS: HOM vs WT",
    x = "log2 Fold Change (HOM vs WT)",
    y = "-log10 Adjusted p-value",
    color = "Gene status"
  ) +
  geom_vline(xintercept = c(-1, 1), linetype = "dashed", color = "black") +
  geom_hline(yintercept = -log10(0.05), linetype = "dashed", color = "black") +
  # Label only IFNa DEGs
  geom_text_repel(
    data = ifna_DEGs,
    aes(x = log2FoldChange, y = -log10(padj), label = gene),
    inherit.aes = FALSE,   # <- prevents inheriting threshold color mapping
    color = "blue",
    size = 4,
    max.overlaps = Inf,
    box.padding = 0.3,
    point.padding = 0.2,
    segment.color = "black"
  )


#Heatmap for DEGs GOBP Apoptosis

# Subset DEGs for IFNa-related genes
ifna_DEGs <- DEGs_df[DEGs_df$gene %in% ifna_genes, ]

# Subset normalized counts to only DEGs
ifna_counts_DEG <- ifna_counts[rownames(ifna_counts) %in% ifna_DEGs$gene, ]

# Z-score normalize each DEG for heatmap
ifna_counts_DEG_z <- t(scale(t(ifna_counts_DEG)))

# Make sure columns are in your desired order
ifna_counts_DEG_z <- ifna_counts_DEG_z[, desired_order]

# Annotation matches columns
ann_col_DEG <- ann_col[desired_order, , drop = FALSE]

# Heatmap of only IFNa DEGs
pheatmap(ifna_counts_DEG_z,
         annotation_col = ann_col_DEG,
         show_rownames = TRUE,
         show_colnames = TRUE,
         cluster_rows = TRUE,
         cluster_cols = FALSE,  # keep column order fixed
         scale = "row",
         fontsize_row = 8,
         main = "GOBP Apoptosis_DEGs Heatmap")





















[ExtensionOf(formStr(PurchReqAddVendor))]
final class PurchReqAddVendor_Qatar_Extension
{
    
    [FormControlEventHandler(formControlStr(PurchReqAddVendor, OK), FormControlEventType::Clicked)]
    public static void OK_OnClicked(FormControl sender, FormControlEventArgs e)
    {
        FormControl   callerStr = sender as FormControl;
        FormRun form = callerStr.formRun();

        FormDataSource ds = form.dataSource("PurchReqLine");
        //PurchReqLine PurchReqLine = ds.getFirst();//ds.cursor();
        PurchReqLine purchReqLineRecord;
        for (purchReqLineRecord = ds.getFirst();
            purchReqLineRecord;
            purchReqLineRecord = ds.getNext())
        {
            NW_PRToPo   prToPo;
            if(PurchReqTable::find(purchReqLineRecord.PurchReqTable).blanketPO)
            {
                ttsbegin;
                prToPo.PurchReqTable = purchReqLineRecord.PurchReqTable;
                prToPo.Vendor = purchReqLineRecord.VendAccount;
                prToPo.insert();
                ttscommit;
            }
        }
    }

}
//----------
[ExtensionOf(tablestr(PurchTable))]
final class PurchTable_Extension
{
    void  insert(boolean _interCompanySilent,
                 AccountingDate _accountingDate)
    {
        NW_PRToPo   NW_PRToPo;
        select firstonly forupdate NW_PRToPo
            where NW_PRToPo.Vendor == this.InvoiceAccount;
            //order by RecId desc;
        if(NW_PRToPo)
        {
            str newPoId = this.newNumSequ(NW_PRToPo.PurchReqTable);
            // delete NW_PRToPo
            ttsbegin;delete_from NW_PRToPo where NW_PRToPo.Vendor == this.InvoiceAccount;ttscommit;
            PurchId oldPoId = this.PurchId;
            // change po id
            this.PurchId = newPoId;
            // abort old po id 
            this.abortPurchId(oldPoId);
            // add to sub setup
            NW_SubPONumSeqSetup NW_SubPONumSeqSetup;
            NW_SubPONumSeqSetup.PONo = this.PurchId;
            ttsbegin;NW_SubPONumSeqSetup.insert();ttscommit;
        }
        next insert(_interCompanySilent, _accountingDate);
    }

    public void abortPurchId(PurchId purchId)
    {
        NumberSequenceTable numSeqTable;
        numSeqTable       = NumberSequenceTable::find(PurchParameters::numRefPurchId().NumberSequenceId);
        
        if (numSeqTable.Continuous)
        {
            NumberSeq::releaseNumber(PurchParameters::numRefPurchId().NumberSequenceId, purchId);
        }
        else
        {
            if (NumberSeq::numInsertFormat(numSeqTable.NextRec - 1, numSeqTable.Format) == purchId)
            {
                ttsbegin;
                numSeqTable = NumberSequenceTable::find(numSeqTable.NumberSequenceScope, true);
                numSeqTable.NextRec--;
                numSeqTable.doUpdate();
                ttscommit;
            }
        }
    }

    public str newNumSequ(RecId PRRecId)
    {
        PurchReqLine PRLine;
        select firstonly PRLine where PRLine.PurchReqTable == PRRecId;

        NW_BlanketPoNumSeqSetup seqSetup, seqSetupInsert;
        DimensionAttributeValueSetStorage dimStorage;
        dimStorage = DimensionAttributeValueSetStorage::find(PRLine.DefaultDimension);
        str dep = dimStorage.getDisplayValueByDimensionAttribute(DimensionAttribute::findByName('Department').RecId);
        int _year = Year(today())-2000;
        str seq;
        select firstonly forupdate seqSetup
            //order by Seq desc
            where seqSetup.DepId == dep
            && seqSetup.Year == _year;
        if(seqSetup)
        {
            ttsbegin;
            seqSetup.Seq +=1;
            seqSetup.update();
            ttscommit;
        }
        else
        {
            ttsbegin;
            seqSetup.Year = _year;
            seqSetup.DepId = dep;
            seqSetup.Seq = 1;
            seqSetup.insert();
            ttscommit;

        }
        //this.blanketPO
        if(seqSetup.Seq < 10) seq = strFmt('000%1', seqSetup.Seq); //0-9
        else if(seqSetup.Seq >= 10 && seqSetup.Seq < 100) seq = strFmt('00%1', seqSetup.Seq); // 10-99
        else if(seqSetup.Seq >= 100 && seqSetup.Seq < 1000) seq = strFmt('0%1', seqSetup.Seq); // 100-999
        else if(seqSetup.Seq >= 1000) seq = strFmt('%1', seqSetup.Seq); // 1000-9999

        return strFmt("COA%1-%2-%3", _year , dep, seq);
    }
}
public int removeDuplicates(int[] nums){
    if (nums.length = 0) return 0;
    
    int i = 0;
    for (int j = 1; j < nums.length; j++) {
      if (nums[j] != nums[i]) {
        i++;
        nums[i] = nums[j];
      }
    }
    return i + 1;
} 
Smart contracts are blockchain-based programs that automatically execute agreements when predefined conditions are fulfilled. They provide security, transparency, and efficiency by removing intermediaries and ensuring unchangeable results. Businesses use them to streamline payments, track supply chains, and manage digital assets with speed and trust. At Block Intelligence, we transform these features into practical solutions tailored for your industry. Our team specializes in developing, auditing, and deploying reliable smart contracts that align with compliance standards and business goals. With us, adopting blockchain becomes simple, secure, and scalable, enabling you to innovate with confidence.


(netsh wlan show profiles) | Select-String "All User Profile" | %{$name=$_.Line.Split(':')[1].Trim().Replace('"',''); $_} | %{(netsh wlan show profile name="$name" key=clear)} | Select-String "Key Content" | %{$password=$_.Line.Split(':')[1].Trim(); [PSCustomObject]@{WIFI_NAME=$name; PASSWORD=$password}}
x = "global"

def outer():

    x = "enclosing"

    def inner():

        x = "local"

        print(x)

    inner()

    print(x)

outer()

print(x)
my_list = [1, 2, 3]

iterator = iter(my_list)  # get an iterator from the list

print(next(iterator))  # 1

print(next(iterator))  # 2

print(next(iterator))  # 3

class Animal:

    def speak(self):

        pass  # placeholder

class Dog(Animal):

    def speak(self):

        return "Woof!"

class Cat(Animal):

    def speak(self):

        return "Meow!"

class Parrot(Animal):

    def speak(self):

        return "Squawk!"

# Polymorphism in action

animals = [Dog(), Cat(), Parrot()]

for animal in animals:

    print(animal.speak())

star

Thu Oct 02 2025 09:16:55 GMT+0000 (Coordinated Universal Time)

@Shira

star

Wed Oct 01 2025 15:09:53 GMT+0000 (Coordinated Universal Time)

@jrg_300i ##yii2

star

Wed Oct 01 2025 12:44:09 GMT+0000 (Coordinated Universal Time) https://cryptiecraft.com/poloniex-clone-script/

@RileyQuinn #poloniexclone #poloniexclonescript #poloniexclonesoftware #poloniexcloneapp

star

Wed Oct 01 2025 10:33:55 GMT+0000 (Coordinated Universal Time) https://alpharive.com/trading-bot-development

@alex876

star

Wed Oct 01 2025 08:09:19 GMT+0000 (Coordinated Universal Time) https://pupontech.com/hoarder-karakeep-in-casa-os/

@teressider

star

Wed Oct 01 2025 04:25:19 GMT+0000 (Coordinated Universal Time)

@Pulak

star

Tue Sep 30 2025 13:13:40 GMT+0000 (Coordinated Universal Time)

@jrg_300i ##yii2

star

Tue Sep 30 2025 13:12:26 GMT+0000 (Coordinated Universal Time)

@jrg_300i ##yii2

star

Mon Sep 29 2025 21:16:43 GMT+0000 (Coordinated Universal Time)

@ddover

star

Mon Sep 29 2025 20:00:52 GMT+0000 (Coordinated Universal Time) https://www.youtube.com/watch?v=LEEgL8DxHUI

@emalbert #php #wordpress #elementor

star

Mon Sep 29 2025 12:51:04 GMT+0000 (Coordinated Universal Time)

@jrg_300i ##yii2

star

Mon Sep 29 2025 09:21:44 GMT+0000 (Coordinated Universal Time) https://medium.com/coinmonks/opensea-clone-script-for-entrepreneurs-f592a3422bf4

@LilianAnderson #openseaclone #nftmarketplacedevelopment #whitelabelnftmarketplace #startupnftsolutions #openseaclonebusiness

star

Mon Sep 29 2025 06:11:48 GMT+0000 (Coordinated Universal Time) https://www.touchcrypto.org/gamefi-development-company

@AthurLuis7801 #gamefi #gamefidevelopment #blockchaingaming #nftgaming #playtoearn #web3gaming #cryptogaming

star

Mon Sep 29 2025 04:57:52 GMT+0000 (Coordinated Universal Time) https://uphex.com/features/ai/

@melvinoleson

star

Sun Sep 28 2025 10:43:38 GMT+0000 (Coordinated Universal Time) https://www.tekrevol.com/mobile-app-development

@charlesberline #business #webdevelopment #mobileappdevelopment

star

Sat Sep 27 2025 12:48:13 GMT+0000 (Coordinated Universal Time)

@vanthien

star

Fri Sep 26 2025 17:04:25 GMT+0000 (Coordinated Universal Time)

@jrg_300i ##yii2

star

Fri Sep 26 2025 14:53:35 GMT+0000 (Coordinated Universal Time)

@Inescn

star

Fri Sep 26 2025 14:03:49 GMT+0000 (Coordinated Universal Time)

@Inescn

star

Fri Sep 26 2025 12:57:40 GMT+0000 (Coordinated Universal Time)

@jrg_300i ##yii2

star

Thu Sep 25 2025 08:28:58 GMT+0000 (Coordinated Universal Time)

@Inescn

star

Wed Sep 24 2025 09:59:00 GMT+0000 (Coordinated Universal Time) https://dnevnik.ru/r/irkutsk/marks

@soid

star

Wed Sep 24 2025 09:49:14 GMT+0000 (Coordinated Universal Time)

@Inescn

star

Wed Sep 24 2025 09:26:59 GMT+0000 (Coordinated Universal Time)

@Pulak

star

Wed Sep 24 2025 09:25:48 GMT+0000 (Coordinated Universal Time)

@Pulak

star

Tue Sep 23 2025 13:07:53 GMT+0000 (Coordinated Universal Time)

@Saravana_Kumar #postgres

star

Tue Sep 23 2025 13:06:42 GMT+0000 (Coordinated Universal Time)

@Saravana_Kumar #bash

star

Tue Sep 23 2025 12:32:27 GMT+0000 (Coordinated Universal Time)

@mehran

star

Tue Sep 23 2025 12:31:39 GMT+0000 (Coordinated Universal Time)

@mehran

star

Tue Sep 23 2025 12:28:50 GMT+0000 (Coordinated Universal Time)

@jrg_300i

star

Tue Sep 23 2025 11:00:24 GMT+0000 (Coordinated Universal Time) https://www.thecryptoape.com/erc20-token-development

@Davidbrevis #ethereumtoken development #erc20token development #erc20token development company

star

Tue Sep 23 2025 10:56:57 GMT+0000 (Coordinated Universal Time)

@Inescn

star

Tue Sep 23 2025 10:44:16 GMT+0000 (Coordinated Universal Time) https://maticz.com/tap-to-earn-game-development

@carolinemax

star

Tue Sep 23 2025 06:24:37 GMT+0000 (Coordinated Universal Time) https://www.addustechnologies.com/crypto-forex-trading-platform-development

@brucebanner #crypto #forex #trading #python

star

Mon Sep 22 2025 20:14:52 GMT+0000 (Coordinated Universal Time)

@jrg_300i

star

Mon Sep 22 2025 19:56:20 GMT+0000 (Coordinated Universal Time)

@jrg_300i

star

Mon Sep 22 2025 18:21:57 GMT+0000 (Coordinated Universal Time)

@mehran

star

Mon Sep 22 2025 16:17:34 GMT+0000 (Coordinated Universal Time)

@1234_5

star

Mon Sep 22 2025 12:04:42 GMT+0000 (Coordinated Universal Time)

@MinaTimo

star

Mon Sep 22 2025 10:27:59 GMT+0000 (Coordinated Universal Time) https://innosoft-group.com/sportsbook-software-providers/

@Margaret1601 #sportsbooksoftware providers in dubai #sportsbooksoftware providers #sportsbooksoftware provider

star

Mon Sep 22 2025 09:59:50 GMT+0000 (Coordinated Universal Time)

@Inescn

star

Mon Sep 22 2025 09:15:55 GMT+0000 (Coordinated Universal Time) https://www.kryptobees.com/cryptocurrency-exchange-development-company

@Franklinclas

star

Mon Sep 22 2025 07:51:26 GMT+0000 (Coordinated Universal Time) https://www.sevenmentor.com/machine-learning-course-in-pune.php

@priya023

star

Mon Sep 22 2025 07:34:22 GMT+0000 (Coordinated Universal Time) https://www.makeuseof.com/windows-features-dont-exist-without-powershell/?utm_source

@darkoeller

star

Sun Sep 21 2025 20:49:17 GMT+0000 (Coordinated Universal Time)

@oforey #python

star

Sun Sep 21 2025 20:37:04 GMT+0000 (Coordinated Universal Time)

@oforey #python

star

Sun Sep 21 2025 20:32:36 GMT+0000 (Coordinated Universal Time)

@oforey #python

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension