Snippets Collections
<p style="text-align:center; margin: 1em;"><iframe allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen=""
frameborder="0" height="315" src="https://www.youtube.com/embed/#########" width="560"></iframe></p>
function display(param){
    console.log(param)
}
display(2);
const function1 = function(){
    console.log('hello');
};
function1()
<div class="col-xs-4">
                <?php
                // Obtener el id_ente del usuario conectado
                $entes = Yii::$app->user->identity->id_ente;

                // Verificar si el usuario es administrador
                if ((Userbackend::isUserAdmin(Yii::$app->user->identity->username)) || (Userbackend::isUserDesp_Ministro(Yii::$app->user->identity->username))) {
                        // Si el usuario es administrador, mostrar todas las opciones
                        echo $form->field($model, 'id_ente')->dropDownList(
                                ArrayHelper::map(Entes::find()->where(['id_sector' => 2])->orderBy('nombre_ente')->all(), 'id_ente', 'nombre_ente'),
                                ['prompt' => 'Seleccione ', 'id' => 'id-ente']
                        );
                } else {
                        // Si el usuario no es administrador, mostrar solo el id_ente del usuario conectado
                        echo $form->field($model, 'id_ente')->dropDownList(
                                ArrayHelper::map(Entes::find()->where(['id_ente' => $entes])->orderBy('nombre_ente')->all(), 'id_ente', 'nombre_ente'),
                                ['prompt' => 'Seleccione ', 'id' => 'id-ente']
                        );
                }
                ?>
        </div>


//otro ejemplo mas complejo
<div class="row">  

        <div class="col-xs-3">
                    <?php
                    // Obtener el id_ente del usuario conectado
                    $entes = Yii::$app->user->identity->id_ente;


                    // Verificar si el usuario es administrador
                    if ((Userbackend::isUserAdmin(Yii::$app->user->identity->username)) || (Userbackend::isUserDesp_Ministro(Yii::$app->user->identity->username))) {
                        // Si el usuario es administrador, mostrar todas las opciones
                        echo $form->field($model, 'id_ente')->dropDownList(
                            ArrayHelper::map(Entes::find()->where(['id_sector' => 2])->orderBy('nombre_ente')->all(), 'id_ente', 'nombre_ente'),
                            ['prompt' => 'Seleccione ', 'id' => 'id-ente']
                        );
                    } else {
                    $entemus = Entes::getEntenom1($entes);
                        // Si el usuario no es administrador, mostrar solo el id_ente del usuario conectado

                        echo $form->field($model, 'entemus')->textInput(['value' => $entemus, 'readonly' => true]);
                        echo $form->field($model, 'id_ente')->hiddenInput(['value' => $entes, 'readonly' => true/*, 'id' => 'id-ente'*/])->label(false);
                    }
                    ?>
                </div>

                <div class="col-xs-3">
                
                <?php
                if ((Userbackend::isUserAdmin(Yii::$app->user->identity->username)) || (Userbackend::isUserDesp_Ministro(Yii::$app->user->identity->username))) {
                    // Si el usuario es administrador, mostrar todas las opciones
                    ?>
                    <?= $form->field($model, 'id_indicador')->widget(DepDrop::classname(), [
                                     'options' => ['id' => 'id-indicador', 'onchange' => 'buscarEnte(this.value)'],
                                    'data' => [$model->id_indicador => $model->Indicadores],
                                    // ensure at least the preselected value is available
                                    'pluginOptions' => [
                                        'depends' => ['id-ente'],
                                        // the id for cat attribute
                                        'placeholder' => 'Seleccione un indicador...',
                                        'url' => Url::to(['indicadores/listar'])
                                    ]
                                ]);

                } else {

                ?>

                <?= $form->field($model, 'id_indicador')->dropDownList(
                    ArrayHelper::map(Indicadoresentescon::find()->where(['id_ente'=>$entes])->andWhere(['id_identificador' => 1])->andWhere(['id_sector' => 2])->orderBy('nombre_indicador')->all(), 'id_indicador', 'nombre_indicador'),
                    ['prompt' => 'Seleccione ', 'onchange' => 'buscarEnte(this.value)']
                ); }
                            ?>
                </div>

                <div class="col-xs-3">
                    <?= $form->field($model, 'fecha')->widget(
                        DatePicker::classname(),
                        [
                            'language' => 'es',
                            'removeButton' => false,
                            'options' => [
                                'placeholder' => 'Fecha:',
                                'class' => 'form-control',
                                'id' => 'fecha_desde-input',
                                'onchange' => 'buscarProyeccion(this.value)'
                            ],
                            'pluginOptions' =>
                            [
                                'startDate' => '01-01-2000',
                                //'startDate' => date('d-m-Y'),
                                'autoclose' => true,
                                'format' => 'dd-mm-yyyy',
                            ]
                        ]
                    )->label('Fecha'); ?>

                </div>
    </div>
<span style="display:inline-block;font-size:2.62vh !important;">↴</span>
# Check if at least one file name is provided
if ($args.Count -eq 0) {
    Write-Host "Please provide at least one filename."
    exit
}

# Loop through each file name passed as an argument
foreach ($file in $args) {
    # Extract filename without extension for the component name
    $filename = [System.IO.Path]::GetFileNameWithoutExtension($file)

    # Define the content to be written to the file
    $content = @"
import { View, Text } from 'react-native'
import React from 'react'

const $filename = () => {
  return (
    <View>
      <Text>$filename</Text>
    </View>
  )
}

export default $filename
"@

    # Create the file and write the content
    $filePath = ".\$file"
    Set-Content -Path $filePath -Value $content
    Write-Host "$file created with component $filename"
}
#APP
import logging
import sys

from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware


from routers import add_routers
from models.ireg_agent.utility_logging import set_request_id, get_logger, RequestIdFilter, patch_logger
import uuid

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - [%(request_id)s] - %(levelname)s - %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S'
)
logging.getLogger().addFilter(RequestIdFilter())

root_logger = logging.getLogger()
root_logger.addFilter(RequestIdFilter())

# Patch commonly used libraries
patch_logger('requests')
patch_logger('urllib3')
# patch_logger('uvicorn')
# patch_logger('uvicorn.access')
# patch_logger('urllib3')

from config import settings
# Set global logging options
if settings.log_level.lower() == 'critical':
    root_logger.setLevel(logging.CRITICAL)
elif settings.log_level.lower() in ('warn', 'warning'):
    root_logger.setLevel(logging.WARNING)
elif settings.log_level.lower() == 'debug':
    root_logger.setLevel(logging.DEBUG)
else:
    root_logger.setLevel(logging.INFO)




get_logger("httpcore").setLevel(logging.WARNING)
get_logger("httpx").setLevel(logging.WARNING)
# Initialize Application
app = FastAPI()


# Configure CORS
allowed_cors_origins = ['*']
app.add_middleware(
  CORSMiddleware,
  allow_origins=allowed_cors_origins,
  allow_credentials=True,
  allow_methods=["*"],
  allow_headers=["*"],
)

@app.middleware("http")
async def add_request_id(request: Request, call_next):
    request_id = str(uuid.uuid4())
    set_request_id(request_id)
    response = await call_next(request)
    return response

# Add our routers
add_routers(app)

#####Utility login g

import contextvars
import logging
import uuid

request_id_var = contextvars.ContextVar('request_id', default=None)

class RequestIdFilter(logging.Filter):
    def filter(self, record):
        request_id = request_id_var.get()
        if request_id is None:
            request_id = str(uuid.uuid4())
            request_id_var.set(request_id)
        record.request_id = request_id
        return True


def get_logger(name):
    logger = logging.getLogger(name)
    if not any(isinstance(f, RequestIdFilter) for f in logger.filters):
        logger.addFilter(RequestIdFilter())
    return logger

def set_request_id(request_id=None):
    if request_id is None:
        request_id = str(uuid.uuid4())
    request_id_var.set(request_id)

def get_request_id():
    return request_id_var.get()

def patch_logger(logger_name):
    logger = logging.getLogger(logger_name)
    if not any(isinstance(f, RequestIdFilter) for f in logger.filters):
        logger.addFilter(RequestIdFilter())
    for handler in logger.handlers:
        if isinstance(handler, logging.StreamHandler):
            handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - [%(request_id)s] - %(levelname)s - %(message)s'))



# # script1.py
# from shared_logging import get_logger

# logger = get_logger(__name__)

# def do_something():
#     logger.info("Doing something in script1")
#     # Your logic here

# # script2.py
# from shared_logging import get_logger

# logger = get_logger(__name__)

# def do_something_else():
#     logger.info("Doing something else in script2")
#     # Your logic here

# # script3.py
# from shared_logging import get_logger

# logger = get_logger(__name__)

# def final_operation():
#     logger.info("Performing final operation in script3")
#     # Your logic here
#     return "Operation complete"


# import logging

# logging.basicConfig(
#     level=logging.INFO,
#     format='%(asctime)s - %(name)s - [%(request_id)s] - %(levelname)s - %(message)s',
#     datefmt='%Y-%m-%d %H:%M:%S'
# )

# 2023-05-20 10:15:30 - main_api - [123e4567-e89b-12d3-a456-426614174000] - INFO - Received request
# 2023-05-20 10:15:30 - script1 - [123e4567-e89b-12d3-a456-426614174000] - INFO -

# Add Error Handling:
# Wrap the context management in a try-except block to ensure the request ID is always reset, even if an error occurs:
# @app.middleware("http")
# async def add_request_id(request: Request, call_next):
#     request_id = generate_request_id()
#     token = request_id_var.set(request_id)
#     try:
#         response = await call_next(request)
#         return response
#     finally:
#         request_id_var.reset(token)
Smart contracts are the key to automation, efficiency, and transparent transactions. Smart contract development involves creating self-executing contracts with the terms directly written into code on a blockchain. This innovative approach automates and secures transactions, reducing the need for intermediaries. Skilled developers utilize platforms like Ethereum to design, test, and deploy smart contracts that are transparent and immutable. Don’t miss the chance to leverage this cutting-edge innovation! Discover the leading smart contract development services that can help your startup thrive. Start your journey today >>>
#include <iostream>
#include <stack>
using namespace std;



int main() {
    stack <int > s; // creation
    
    s.push(1); // putting vales 
    s.push(3);
    
    s.pop(); // removing one value 
    
    cout << "elemenst at top " << s.top() << endl;
    // printing top value 
    
    if(s.empty()) // checking 
    {
        cout << "stack is empty " << endl;
    }
    else
    {
         cout << "stack is not empty " << endl;
    }
    return 0;
}
#include <iostream>
#include <stack>
using namespace std;



int main() {
    stack <int > s; // creation
    
    s.push(1); // putting vales 
    s.push(3);
    
    s.pop(); // removing one value 
    
    cout << "elemenst at top " << s.top() << endl;
    // printing top value 
    
    if(s.empty()) // checking 
    {
        cout << "stack is empty " << endl;
    }
    else
    {
         cout << "stack is not empty " << endl;
    }
    return 0;
}
import java.util.*;

public class BITMASKING {
public static void main(String[] args) {
int n = 5; // Number of elements
int visitedMask = 0; // Initially, no element is visited (all bits are 0)


visitedMask = visitNode(visitedMask, 2); // Mark element at index 2 as visited
System.out.println("Visited Mask after visiting node 2: " + Integer.toBinaryString(visitedMask));
visitedMask = unvisitNode(visitedMask, 2);
System.out.println(Integer.toBinaryString(visitedMask));
visitedMask = visitNode(visitedMask, 9);
System.out.println(Integer.toBinaryString(visitedMask));


System.out.println("Is node 2 visited? " + isVisited(visitedMask, 2));
System.out.println("Is node 3 visited? " + isVisited(visitedMask, 3));


visitedMask = visitNode(visitedMask, 4); // Mark element at index 4 as visited
System.out.println("Visited Mask after visiting node 4: " + Integer.toBinaryString(visitedMask));


visitedMask = unvisitNode(visitedMask, 2); // Unmark element at index 2
System.out.println("Visited Mask after unvisiting node 2: " + Integer.toBinaryString(visitedMask));
}


public static int visitNode(int mask, int index) {
return mask | (1 << index);
}


public static boolean isVisited(int mask, int index) {
return (mask & (1 << index)) != 0;
}


public static int unvisitNode(int mask, int index) {
return mask & ~(1 << index);
}
}
// Rabin-Karp algorithm in Java

public class RabinKarp {
  public final static int d = 10;

  static void search(String pattern, String txt, int q) {
    int m = pattern.length();
    int n = txt.length();
    int i, j;
    int p = 0;
    int t = 0;
    int h = 1;

    for (i = 0; i < m - 1; i++)
      h = (h * d) % q;

    // Calculate hash value for pattern and text
    for (i = 0; i < m; i++) {
      p = (d * p + pattern.charAt(i)) % q;
      t = (d * t + txt.charAt(i)) % q;
    }

    // Find the match
    for (i = 0; i <= n - m; i++) {
      if (p == t) {
        for (j = 0; j < m; j++) {
          if (txt.charAt(i + j) != pattern.charAt(j))
            break;
        }

        if (j == m)
          System.out.println("Pattern is found at position: " + (i + 1));
      }

      if (i < n - m) {
        t = (d * (t - txt.charAt(i) * h) + txt.charAt(i + m)) % q;
        if (t < 0)
          t = (t + q);
      }
    }
  }

  public static void main(String[] args) {
    String txt = "ABCCDDAEFG";
    String pattern = "CDD";
    int q = 13;
    search(pattern, txt, q);
  }
}
Searching for the best decentralized exchange development company to bring your crypto vision to life? Block Sentinels is your trusted partner. Renowned for their expertise in creating secure, efficient, and user-friendly decentralized exchanges, Block Sentinels is at the forefront of blockchain innovation. Their skilled team crafts customized solutions that prioritize security, scalability, and seamless user experiences, ensuring your platform stands out in the competitive market. Whether you’re a startup or an established enterprise, Block Sentinels delivers innovative technology and strategic insights to drive your success in the decentralized finance space. Choose Block Sentinels to turn your decentralized exchange project into a reality and lead the future of crypto trading. 

Get a free Demo >> https://blocksentinels.com/decentralized-exchange-development-company 

Reach the experts: 
Whatsapp : 81481 47362
Mail to : sales@blocksentinels.com
Telegram : https://t.me/Blocksentinels
Searching for the best decentralized exchange development company to bring your crypto vision to life? Block Sentinels is your trusted partner. Renowned for their expertise in creating secure, efficient, and user-friendly decentralized exchanges, Block Sentinels is at the forefront of blockchain innovation. Their skilled team crafts customized solutions that prioritize security, scalability, and seamless user experiences, ensuring your platform stands out in the competitive market. Whether you’re a startup or an established enterprise, Block Sentinels delivers innovative technology and strategic insights to drive your success in the decentralized finance space. Choose Block Sentinels to turn your decentralized exchange project into a reality and lead the future of crypto trading. 

Get a free Demo >> https://blocksentinels.com/decentralized-exchange-development-company 

Reach the experts: 
Whatsapp : 81481 47362
Mail to : sales@blocksentinels.com
Telegram : https://t.me/Blocksentinels
Create elements in the below enums.

-> WHSWorkActivity
-> WHSWorkExecuteMode
---------------------------------------------------------------------------------------------------
Enable Work Activity 

  [ExtensionOf(tableStr(WHSRFMenuItemTable))]
public final class CPLDevWHSRFMenuItemTable_Extension
{
    protected boolean workActivityMustUseProcessGuideFramework()
  {
    boolean ret = next workActivityMustUseProcessGuideFramework();
    
    if (this.WorkActivity	    == WHSWorkActivity::CPLProductionStatusChange ||
            this.WorkActivity       ==  WHSWorkActivity::SONEmptyLoc)
    {
      ret = true;
    }

    return ret;
  }

}
-------------------------------------------------------------------------------------------------
  Create Required Fields and its control
  
[WHSFieldEDT(extendedTypeStr(Location))]
public class CPLDev_WhsFieldCPLLocation extends WHSField
{
    private const WHSFieldName             Name        = "CPL Location";
    private const WHSFieldDisplayPriority  Priority    = 10;
    private const WHSFieldDisplayPriority  SubPriority = 20;
    private const WHSFieldInputMode        InputMode   = WHSFieldInputMode::Manual;
    private const WHSFieldInputType        InputType   = WHSFieldInputType::Alpha;
    protected void initValues()
    {
        this.defaultName        = Name;
        this.defaultPriority    = Priority;
        this.defaultSubPriority = SubPriority;
        this.defaultInputMode   = InputMode;
        this.defaultInputType   = InputType;
    }
}
......................................................
[WhsControlFactory('CPLLocation')]
Public class CPLDev_WhsControlCPLLocation extends WhsControl
{
    public boolean process()
    {
        if (!super())
        {
            return false;
        }
 
        fieldValues.insert(CPLDev_conWHSControls::CPLLocation, this.data);
 
        return true;
    }
    public boolean canProcessDefaultValue()
    {
        if (this.parmData())
        {
            return true;
        }

        return false;
    }
    protected boolean defaultValueToBlank()
    {
        return true;
    }

    public void populate()
    {
        {
            fieldValues.insert(this.parmName(), '');
        }
    }

}

---------------------------------------------------------------------------------------------------
 Create Required Controls 
 
 class CPLDev_conWHSControls
{
  //[pavanKini]- Combining SP Pick RM and Rm capture Packaging details -15-feb-2023
  public static const str SalesID = "SalesId";
    public static const str CPLLoadID = "CPLLoadId";//added by manju Y
  //[PavanKini]AGV-Int-WorkPriority changes 09-june-2023
  public static const str WorkPriority = "WorkPriority";
  public static const str CPLLocation = "CPLLocation"; //added by Manju Y 9/25/2024
}

---------------------------------------------------------------------------------------------------
 Create Controller class
 
[WHSWorkExecuteMode(WHSWorkExecuteMode::CPLEmptyLocation),
WHSWorkExecuteMode(WHSWorkExecuteMode::CPLFilledLocation)]
class CPLDev_WHSProcessGuideEmptyLocationDetailsController extends ProcessGuideController
{
  protected ProcessGuideStepName initialStepName()
  {
    return classStr(CPLDev_WHSProcessGuidInquiryLocationProfileStep);
  }
  protected ProcessGuideNavigationAgentAbstractFactory navigationAgentFactory()
  {
    return new CPLDev_InventProcessGuideLocationDetailsNavigationAgentFactory();
  }
}
-------------------------------------------------------------------------------------------------
Create Navigation agent factory or define navigation on the controller class

class CPLDev_InventProcessGuideLocationDetailsNavigationAgentFactory extends ProcessGuideNavigationAgentAbstractFactory
{
  #define.LocId('Location Profile Id')
  public final ProcessGuideNavigationAgent 			      createNavigationAgent(ProcessGuideINavigationAgentCreationParameters _parameters)
  {
    ProcessGuideNavigationAgentCreationParameters creationParameters = _parameters as      ProcessGuideNavigationAgentCreationParameters;           
    if (!creationParameters)
    {
      throw error(Error::wrongUseOfFunction(funcName()));
    }
    WhsrfPassthrough pass = creationParameters.controller.parmSessionState().parmPass();
    return this.initializeNavigationAgent(creationParameters.stepName, pass);
  }

  private ProcessGuideNavigationAgent initializeNavigationAgent(ProcessGuideStepName _currentStep,
                                                                    WhsrfPassthrough _pass)
  {
    str menuitemname  = _pass.lookupStr(ProcessGuideDataTypeNames::MenuItem);
    WHSLocProfileId  profileId;
    WHSLoadId   loadid ;
    Location _Location;
    switch (_currentStep)
    {
      case classStr(CPLDev_WHSProcessGuidInquiryLocationProfileStep) :
           profileId = _pass.lookupStr(#LocId);
           if(WHSLocationProfile::find(profileId))
                return new CPLDev_InventProcessGuideLocDetailsNavigationAgent();
           else
                return new  CPLDev_InventProcessGuideLocationProfileNavigationAgent();
      case classStr(CPLDev_WHSProcessGuidEmptyLocationDetailsDStep) :
            _Location=_pass.lookup(ProcessGuideDataTypeNames::LocOrLP);
            if(_Location)
                return new CPLDev_WHSProcessGuideSelectedEmptyLocNavigationAgent();
            else
                return new CPLDev_InventProcessGuideLocDetailsNavigationAgent();
            break;
      default : return new  CPLDev_InventProcessGuideLocationProfileNavigationAgent();
    } 
  }
}
------------
class CPLDev_WHSProcessGuideSelectedEmptyLocNavigationAgent extends ProcessGuideNavigationAgent
{
    protected ProcessGuideStepName calculateNextStepName()
    {
        return classStr(CPLDev_WHSProcessGuideSelectedEmptyLocStep);
    }

}
--------------------------------------------------------------------------------------------------
Create Step and Pagebuilder

Step 1. Page Builder--------->

[ProcessGuidePageBuilderName(classStr(CPLDev_WHSProcessGuideLocationProfilePageBuilder))]
class CPLDev_WHSProcessGuideLocationProfilePageBuilder extends ProcessGuidePageBuilder
{
  public static const str OR = '||';
  public static const str WHSLocationProfileID = 'Location Profile Id';

  protected final void addDataControls(ProcessGuidePage _page)
  {
    WHSLocProfileId  profileId;
    _page.addComboBox(
          WHSLocationProfileID,
               "Location profile Id",
               extendedTypeNum(WHSLocProfileId),this.getLocationProfileID(), true);
  }

  protected final void addActionControls(ProcessGuidePage _page)
  {
    #ProcessGuideActionNames

    _page.addButton(step.createAction(#ActionOK), true);
    _page.addButton(step.createAction(#ActionCancelExitProcess));
  }

  public str getLocationProfileID()
  {
    str   elements;
    boolean first = true;
    WHSLOCATIONPROFILE  WHSLOCATIONPROFILE;

    while select * from WHSLOCATIONPROFILE
      where WHSLOCATIONPROFILE.CPLDisplayLocation == NoYes::Yes
    {
      if (!first)
      {
        elements += OR ;
      }
      elements += WHSLOCATIONPROFILE.LocProfileId;
      first = false;
    }

    return elements;
  }

}

  Step calss---------->

[ProcessGuideStepName(classStr(CPLDev_WHSProcessGuidInquiryLocationProfileStep))]
class CPLDev_WHSProcessGuidInquiryLocationProfileStep extends ProcessGuideStep
{
  protected final ProcessGuidePageBuilderName pageBuilderName()
  {
    return classStr(CPLDev_WHSProcessGuideLocationProfilePageBuilder);
  }

}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Step 2. Page Builder-------------->
  
  [ProcessGuidePageBuilderName(classStr(CPLDev_WHSProcessGuideEmptyLocDetailsPageBuilder))]
class CPLDev_WHSProcessGuideEmptyLocDetailsPageBuilder  extends ProcessGuidePageBuilder
{
  #define.LocId('Location Profile Id')
  protected final void addDataControls(ProcessGuidePage _page)
  {
    WhsrfPassthrough pass = controller.parmSessionState().parmPass();
    WHSMenuItemName menuitems = pass.lookupStr(ProcessGuideDataTypeNames::MenuItem);
    WMSLocationId   locationID = pass.lookupStr(#LocId);
   
    InventLocationId inventLocationId = WHSWorkUserSession::find(pass.lookupstr(ProcessGuideDataTypeNames::UserId)).InventLocationId;

    _page.addLabel(ProcessGuideDataTypeNames::InventLocation, strFmt("@WAX1112", inventLocationId), extendedTypeNum(WHSRFUndefinedDataType));

    if(menuitems == "Empty Locations")
    {
      this.BuildEmptyLocation(_page,pass,  inventLocationId,locationID);
    }
    else
    {
      this.BuildFilledLocation(_page,pass, inventLocationId,locationID);
    }

  }

  protected final void addActionControls(ProcessGuidePage _page)
  {
    #ProcessGuideActionNames

    _page.addButton(step.createAction(#ActionOK), true);
    _page.addButton(step.createAction(#ActionCancelExitProcess));
  }

  private void BuildFilledLocation(ProcessGuidePage _page,  WhsrfPassthrough _pass, InventLocationId inventLocationId, WMSLocationId   locationID)
  {
    WMSLocation  WmsLocation;
    int labelCounter;
    InventSum   inventSum;
    InventDim   inventdim;
    
    #ProcessGuideActionNames
    while select * from WmsLocation
        where WmsLocation.LocProfileId == locationID
    {
      select count(RecId),Sum(Received),Sum(postedQty) ,Sum(DEDUCTED),sum(registered), sum(picked) from inventSum
        join inventdim
        where  inventSum.InventDimId == inventdim.inventDimId
        && inventdim.wMSLocationId == WmsLocation.wMSLocationId;
      {
       
        if( (inventSum.PostedQty + inventSum.Received - inventSum.Deducted + inventSum.Registered - inventSum.Picked) > 0)
        {
            _page.CPLAddMultiActionButton(step.createAction(#ActionOK),extendedTypeNum(WMSLocationId),WmsLocation.wMSLocationId);
          //_page.addLabel(int2str(labelCounter), WmsLocation.wMSLocationId , extendedTypeNum(WMSLocationId));
          ++labelCounter;
        }
      }
    }

  }

  private void BuildEmptyLocation(ProcessGuidePage _page,  WhsrfPassthrough _pass, InventLocationId inventLocationId, WMSLocationId   locationID)
  {

    WMSLocation  WmsLocation;
    int labelCounter;
    InventSum   inventSum;
    InventDim   inventdim;
    #ProcessGuideActionNames
    while select * from WmsLocation
       where WmsLocation.LocProfileId == locationID
    {
      select count(RecId),Sum(Received),Sum(postedQty) ,Sum(DEDUCTED),sum(registered), sum(picked) from inventSum
        join inventdim
        where  inventSum.InventDimId == inventdim.inventDimId
        && inventdim.wMSLocationId == WmsLocation.wMSLocationId;
      {
        if( (inventSum.PostedQty + inventSum.Received - inventSum.Deducted + inventSum.Registered - inventSum.Picked) <= 0)
        {
        //_page.addLabel(int2str(labelCounter), WmsLocation.wMSLocationId , extendedTypeNum(WMSLocationId));
        _page.CPLAddMultiActionButton(step.createAction(#ActionOK),extendedTypeNum(WMSLocationId),WmsLocation.wMSLocationId);
        ++labelCounter;
        }
      }
    }

  }

}
  Step class ----------------->
    
   [ProcessGuideStepName(classStr(CPLDev_WHSProcessGuidEmptyLocationDetailsDStep))]
class CPLDev_WHSProcessGuidEmptyLocationDetailsDStep extends ProcessGuideStep
{
  protected final ProcessGuidePageBuilderName pageBuilderName()
  {
    return classStr(CPLDev_WHSProcessGuideEmptyLocDetailsPageBuilder);
  }

  public void doExecute()
  {
      #ProcessGuideActionNames
      str value;
      ProcessGuidePage pages;
      value = controller.parmClickedData();
      WhsrfPassthrough pass = controller.parmSessionState().parmPass();
      pass.insert(ProcessGuideDataTypeNames::LocOrLP,value);
      super(); 
  }

}
 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 Step 3. Page builder --------------->
[ProcessGuidePageBuilderName(classstr(CPLDev_WHSProcessGuideSelectedLocPageBuilder))]
class CPLDev_WHSProcessGuideSelectedLocPageBuilder extends ProcessGuidePageBuilder
{
    #ProcessGuideActionNames
    protected final void addDataControls(ProcessGuidePage _page)
    {
        int labelCounter;
        SalesId salesId;
        WhsrfPassthrough pass = controller.parmSessionState().parmPass();
        str locations= pass.lookup(ProcessGuideDataTypeNames::LocOrLP);
        if(locations !="" )
        {
            _page.addLabel(ProcessGuideDataTypeNames::RFTitle,"Confirm Selected location",extendedTypeNum(WHSRFTitle));
            _page.addTextBox(CPLDev_conWHSControls::CPLLocation,'',extendedTypeNum(Location),false,locations);
      //    _page.addLabel(int2str(labelCounter),locations,extendedTypeNum(SalesId));
            labelCounter++;
        }
        else
        {
            _page.addLabel(ProcessGuideDataTypeNames::Error,"No location selected",extendedTypeNum(WHSRFUndefinedDataType));
        }
    }

    protected final void addActionControls(ProcessGuidePage _page)
    {
        #ProcessGuideActionNames
        if(this.isInDetourSession())
        {
            _page.addButton(step.createAction(#ActionCancelExitProcess),true,'Confirm');
        }
        else
        {
        _page.addButton(step.createAction(#ActionOK), true);
        _page.addButton(step.createAction(#ActionCancelExitProcess));
        }
    }
}

    Step class --------------------->
      
[ProcessGuideStepName(classStr(CPLDev_WHSProcessGuideSelectedEmptyLocStep))]
class CPLDev_WHSProcessGuideSelectedEmptyLocStep extends ProcessGuideStep
{
    protected final ProcessGuidePageBuilderName pageBuilderName()
    {
        return classStr(CPLDev_WHSProcessGuideSelectedLocPageBuilder);
    }

}

-------------------------------------------------------------------------------------------------
 xml decorator class 
   
 [WHSWorkExecuteMode(WHSWorkExecuteMode::CPLEmptyLocation),
WHSWorkExecuteMode(WHSWorkExecuteMode::CPLFilledLocation)]
class CPLDev_WHSMobileAppServiceXMLDecoratorFactoryLocationDetails implements WHSIMobileAppServiceXMLDecoratorFactory
{

  public WHSMobileAppServiceXMLDecorator getDecorator(container _con)
  {
    if (this.inputInquiryScreen(_con))
    {
      return new WHSMobileAppServiceXMLDecoratorInquiryInput();
    }
    else if(this.getCurrentStep(_con) == this.emptyLocationSelectedStep())
    {
      return new WHSMobileAppServiceXMLDecoratorInquiryInput();
    }
    return new CPLDev_WHSMobileAppServiceXMLDecoratorLocationDetails();
  }

  private boolean inputInquiryScreen(container _con)
  {
    str currentStep = this.getCurrentStep(_con);

    return (currentStep == this.inputLocationProfileStepName());
  }

  private str getCurrentStep(container _con)
  {
    container subCon = conPeek(_con, 2);
    for (int i  = 1; i <= conLen(subCon); i++)
    {
      if (conPeek(subCon, i - 1) == "CurrentStep")
      {
        return conPeek(subCon, i);
      }
    }

    //Default behavior.
    return conPeek(subCon, 8);
  }

  delegate void inquiryLocationProfileDelegate(EventHandlerResult _result)
  {
  }

  private str inputLocationProfileStepName()
  {
    EventHandlerResult result = new EventHandlerResult();
    this.inquiryLocationProfileDelegate(result);

    str inputStep;

    if (result.result() != null)
    {
      inputStep = result.result();
    }

    return inputStep;
  }

  delegate void inquiryLocationDetailsDelegate(EventHandlerResult _result)
  {
  }

  private str inputLocationDetails()
  {
    EventHandlerResult result = new EventHandlerResult();
    this.inquiryLocationDetailsDelegate(result);

    str inputStep;

    if (result.result() != null)
    {
      inputStep = result.result();
    }

    return inputStep;
  }

  private str emptyLocationSelectedStep()
  {
      return "CPLDev_WHSProcessGuideSelectedEmptyLocStep";
  }

}
-----------
class CPLDev_WHSMobileAppServiceXMLDecoratorLocationDetails extends WHSMobileAppServiceXMLDecorator
{
  protected void registerRules()
  {
    rulesList.addEnd(CPLDev_WHSMobileAppServiceDecoratorRuleInquiryLocationDisplayArea::construct());
  }

  public WHSMobileAppPagePattern requestedPattern()
  {
      return WHSMobileAppPagePattern::InquiryWithNavigation;
  }

}
 ++++++++++++++++++++++++++++++++
 Display Area
 class CPLDev_WHSMobileAppServiceDecoratorRuleInquiryLocationDisplayArea implements WHSIMobileAppServiceXMLDecoratorRule

{
  
  #WHSRF
  #WHSWorkExecuteControlElements
  #XmlDocumentation

  private const str Footer1 = 'Qty';
  private const str Footer2 = 'Inventory status';
  private const str newLine = '\n';
  private str prevLPLabel;

  private const ExtendedTypeId LPExtendedType             = extendedTypeNum(WHSLicensePlateId);
  private const ExtendedTypeId LocationExtendedType       = extendedTypeNum(WMSLocationId);
  private const ExtendedTypeId ItemInfoExtendedType       = extendedTypeNum(WHSRFItemInformation);
  private const ExtendedTypeId QuantityInfoExtendedType   = extendedTypeNum(WHSRFQuantityInformation);

  protected void new()
  {
  }

  public static CPLDev_WHSMobileAppServiceDecoratorRuleInquiryLocationDisplayArea construct()
  {
    return new CPLDev_WHSMobileAppServiceDecoratorRuleInquiryLocationDisplayArea();
  }

  private boolean mustSetFooters(ExtendedTypeId _controlInputType)
  {
    switch (_controlInputType)
    {
      case ItemInfoExtendedType:
        return false;//todo
    }
    return false;
  }

  private boolean isNewLPHeaderGroup(str _currentLabel)
  {
    if (prevLPLabel != _currentLabel)
    {
      prevLPLabel = _currentLabel;
      return true;
    }
    return false;
  }

  private str getDisplayArea(ExtendedTypeId _controlInputType, str _currentLabel)
  {
    switch (_controlInputType)
    {
      case LPExtendedType:
        return WHSMobileAppXMLDisplayArea::BodyArea;
        break;
      case LocationExtendedType:
        return WHSMobileAppXMLDisplayArea::BodyArea;//GroupHeaderArea;
      case ItemInfoExtendedType,
                 QuantityInfoExtendedType:
                return WHSMobileAppXMLDisplayArea::BodyArea;
      default:
        return WHSMobileAppXMLDisplayArea::SubHeaderArea;
    }
    return '';
  }

  public void run(WHSMobileAppPageInfo _pageInfo)
  {
    ListEnumerator le = _pageInfo.parmControlsEnumerator();

    while (le.moveNext())
    {
      Map controlMap = le.current();
      if (this.mustDecorateControl(controlMap))
      {
        this.decorateControl(controlMap);
      }
    }
  }

  private void decorateControl(Map _controlMap)
  {
    ExtendedTypeId controlInputType = _controlMap.lookup(#XMLControlInputType);
    str currentLabel = _controlMap.lookup(#XMLControlLabel);
    if(currentLabel !='OK' && currentLabel !='Cancel')
    {
        str displayArea = this.getDisplayArea(controlInputType, currentLabel);
        if (displayArea)
        {
          this.setDisplayArea(_controlMap, displayArea);
        }

        if (this.mustSetFooters(controlInputType))
        {
          this.setFooters(_controlMap);
        }
    }
  }

  private boolean mustDecorateControl(Map _controlMap)
  {
    //return _controlMap.lookup(#XMLControlCtrlType) == #RFLabel &&
    //           !this.newLineControl(_controlMap.lookup(#XMLControlLabel));
    return true;
  }

  private void setDisplayArea(Map _controlMap, str _displayArea)
  {
    //_controlMap.insert(#XMLControlDisplayArea, _displayArea);
    str currentLabelBuildId = '';
    currentLabelBuildId = _controlMap.lookup(#XMLControlName);
    _controlMap.insert(#XMLControlAttachedTo, currentLabelBuildId);
  }

  private void setFooters(Map _controlMap)
  {
    _controlMap.insert(#XMLControlFooter1, Footer1);
    _controlMap.insert(#XMLControlFooter2, Footer2);
  }

  private boolean newLineControl(str _controlLabel)
  {
    return _controlLabel == newLine;
  }

}
----------------------------------------------------------------------------------------------
Create MobileAppFlow for detour use

before that create fields mobile app fields

[WHSWorkExecuteMode(WHSWorkExecuteMode::CPLEmptyLocation)]
final class CPLDev_WHSMobileAppFlowEmptyLocation extends WHSMobileAppFlow
{
    protected void initValues()
    {
        #WHSRF
        this.addStep('CPLLocation');
        this.addAvailableField(extendedTypeNum(Location));
    }

}
{% comment %}
  Shopify If Conditions Cheat Sheet
{% endcomment %}

<!-- Check Page Types -->
{% if template == 'index' %}
  <!-- Home Page -->
{% endif %}

{% if template == 'product' %}
  <!-- Product Page -->
{% endif %}

{% if template == 'collection' %}
  <!-- Collection Page -->
{% endif %}

{% if template == 'cart' %}
  <!-- Cart Page -->
{% endif %}

{% if template == 'contact' %}
  <!-- Contact Page -->
{% endif %}

{% if template == 'blog' %}
  <!-- Blog Page -->
{% endif %}

<!-- Check URL or Handle -->
{% if page.handle == 'about-us' %}
  <!-- About Us Page -->
{% endif %}

{% if product.handle == 'my-product' %}
  <!-- Specific Product Page -->
{% endif %}

{% if collection.handle == 'my-collection' %}
  <!-- Specific Collection Page -->
{% endif %}

{% if request.path == '/about' %}
  <!-- Specific URL Page -->
{% endif %}

{% if request.path contains 'sale' %}
  <!-- URL Contains "sale" -->
{% endif %}

<!-- Check Customer Login Status -->
{% if customer %}
  <!-- Customer Logged In -->
{% endif %}

{% unless customer %}
  <!-- Guest (Not Logged In) -->
{% endunless %}

<!-- Check Product Details -->
{% if product.available %}
  <!-- Product is Available -->
{% endif %}

{% if product.compare_at_price > product.price %}
  <!-- Product on Sale -->
{% endif %}

{% if product.tags contains 'new' %}
  <!-- Product Tagged as "new" -->
{% endif %}

<!-- Check Collection Conditions -->
{% if collection.products_count > 0 %}
  <!-- Collection is Not Empty -->
{% endif %}

{% if collection.products contains product %}
  <!-- Collection Contains This Product -->
{% endif %}

<!-- Cart Conditions -->
{% if cart.item_count > 0 %}
  <!-- Cart is Not Empty -->
{% endif %}

{% if cart.total_price > 5000 %}
  <!-- Cart Total is Above $50 -->
{% endif %}

<!-- Check Language/Locale -->
{% if localization.country_iso_code == 'FR' %}
  <!-- French Language Pages -->
{% endif %}

<!-- Check Product Metafields -->
{% if product.metafields.custom_field_namespace.field_name %}
  <!-- Product has Specific Metafield -->
{% endif %}

<!-- Conditional on Collection/Tags -->
{% if product.collections contains collection %}
  <!-- Product Belongs to a Specific Collection -->
{% endif %}

{% if collection.tags contains 'summer-sale' %}
  <!-- Collection Tagged with "summer-sale" -->
{% endif %}

<!-- Miscellaneous Conditions -->
{% if request.user_agent contains 'Mobile' %}
  <!-- Mobile User -->
{% endif %}

{% if shop.myshopify_domain contains 'localhost' %}
  <!-- Development Mode -->
{% endif %}

<!-- Combining Conditions -->
{% if template == 'product' and product.tags contains 'new' %}
  <!-- New Product on Product Page -->
{% endif %}
<!-- No Payment Box (For Awaiting Payment Except Partial) -->
  <div
    class="no-payment"
    *ngIf="
      (ordersData?.paymentDTO?.status | lowercase) == 'awaiting payment' &&
      (ordersData?.paymentDTO?.partial | lowercase) == 'no'
    "
  >
    <img
      src="https://ik.imagekit.io/2gwij97w0o/Client_portal_frontend_assets/img/no-payment.svg?updatedAt=1633070377316"
    />
    <p>
      Payment for this order item has not been reconciled yet. Ensure that all the latest payment reports for this sales
      channel have been uploaded
    </p>
    <a class="add-payment" (click)="onNavigate('payout')"> + Add payment report </a>
  </div>

<ng-template #settingsSalesChannel>
  <div class="settings-channel">
    <img src="https://ik.imagekit.io/2gwij97w0o/no-data-order-details.svg?updatedAt=1727270008916" />
    <img src="https://ik.imagekit.io/2gwij97w0o/configure-payment.svg?updatedAt=1727270118860" />
    <div class="settings-channel-text">
      <span>Payment reconciliation settings have not been enabled for this sales channel</span>
      <div class="settings-channel-button" (click)="navigateToAppSettings()">Configure now</div>
    </div>
  </div>
</ng-template>








  navigateToAppSettings() {
    if (this.matchedSalesChannel.connectionData.appInstallationId && this.matchedSalesChannel.connectionData.id) {
      this.router.navigate(['installed-app-list/detail', this.matchedSalesChannel.connectionData.appInstallationId], {
        queryParams: {
          connectionId: this.matchedSalesChannel.connectionData.id
        }
      });
    }
  }






.settings-channel {
  display: grid;
  justify-content: center;
  padding: 24px;
  width: 100%;
  grid-template-rows: auto 0px auto;
  gap: 16px;
  img {
    object-fit: none;
    margin: 0 auto;
  }
  img:nth-child(2) {
    position: relative;
    bottom: 92px;
  }
  &-text {
    display: flex;
    justify-content: center;
    flex-direction: column;
    gap: 12px;
    span {
      font-family: Inter;
      font-size: 12px;
      font-weight: 400;
      line-height: 14.52px;
      text-align: center;
    }
  }
  &-button {
    font-family: Inter;
    font-size: 14px;
    font-weight: 500;
    line-height: 16.94px;
    text-align: left;
    color: #fa5c5d;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
  }
  &-button:before {
    content: '';
    display: inline-block;
    width: 20px;
    height: 20px;
    margin-right: 8px;
    cursor: pointer;
    background-image: url('https://ik.imagekit.io/2gwij97w0o/external-redirect-link.svg?updatedAt=1705046079687');
  }
}
import { ElMessage, MessageOptions } from "element-plus";

enum indexs {
    fulfilled,
    Rejected
}

interface Options {
    onFulfilled?: Function;
    onRejected?: Function;
    onFinish?: Function;
    // 是否需要提示:[ 成功时的 , 失败时的]。
    // 默认:[true, true]
    isNeedPrompts?: boolean[];
    // 提示配置:[成功时的 , 失败时的]
    msgObjs?: MessageOptions[];
    // 提示配置的快捷message配置:[ 成功时的 , 失败时的]。
    // 默认:['成功', '失败']
    msgs?: string[];
    [key: string]: any;
}


export function getHint(pro: Promise<any>, options: Options = {}) {
    const ful = indexs.fulfilled;
    const rej = indexs.Rejected;
    const { isNeedPrompts, msgs } = options;

    const opt: Options = {
        ...options,
        isNeedPrompts: Object.assign([true, true], isNeedPrompts),
        msgs: Object.assign(['成功', '失败'], msgs),
    }

    const onFulfilled = (res: any) => {
        if (opt.isNeedPrompts?.[ful]) {
            ElMessage({
                message: opt.msgs?.[ful],
                type: 'success',
                ...opt.msgObjs?.[ful]
            });
        }
        if (opt.onFulfilled) opt.onFulfilled(res);
    }
    const onRejected = (err: Error) => {
        if (opt.isNeedPrompts?.[rej]) {
            ElMessage({
                message: opt.msgs?.[rej],
                type: 'error',
                ...opt.msgObjs?.[rej]
            });
        }

        if (opt.onRejected) opt.onRejected(err);
    }
    const onFinish = () => {
        console.log(opt, opt.onFinish);

        if (opt.onFinish) opt.onFinish();
    }

    pro.then(onFulfilled).catch(onRejected).finally(onFinish);

    return pro;
}
new Promise((res, rej) => {
        setTimeout(() => {
            Math.random() < 0.5 ? res(200) : rej(404);
        }, (Math.random() + 0.2) * 1000)
})
int TotalEggs = 0, eggsPerChicken = 5, chickenCount = 3;
 TotalEggs=eggsPerChicken*chickenCount;
 TotalEggs+=eggsPerChicken*++chickenCount;
 TotalEggs+=eggsPerChicken*(chickenCount/2);
System.out.println(TotalEggs);
    
 
 TotalEggs = 0;
 eggsPerChicken = 4;
 chickenCount = 8;
 TotalEggs=eggsPerChicken*chickenCount; 
 TotalEggs+=eggsPerChicken*++chickenCount; 
 TotalEggs+=eggsPerChicken*(chickenCount/2); 
System.out.println(TotalEggs);

    }
}
       
  double Monday = 100;
    double Tuesday = 121;
    double Wednesday = 117;
    double dailyAverage = 0;
    double monthlyAverage = 0;
    double monthlyProfit = 0;
    dailyAverage = (Monday+Tuesday+Wednesday)/3;
    monthlyAverage = dailyAverage*30;
    monthlyProfit = monthlyAverage*0.18;
    System.out.println("Daily Average:   " +dailyAverage);
    System.out.println("Monthly Average: " +monthlyAverage);
    System.out.println("Monthly Profit:  $" +monthlyProfit);
input_nums=list(map(int,input("Enter the numbers separated by space:").split()))
input_nums.sort(reverse=True)
max_product=input_nums[0]*input_nums[1]
print("Maximum  Product:",max_product)
def odd_numbers(n):
	return[i for i in range(0, n+1) if i % 2 != 0]
n = int(input("Enter an integer: "))
result = odd_numbers(n)
print(result)
lst=list(map(int, input("Enter list of integers: ").split()))
result_lst = [lst[i] for i in range(len(lst)) if i==0 or lst[i]!= lst[i-1]]
print("List with consecutive duplicates removed:",result_lst)
n=int(input("Enter a number: "))
result=["even" if i%2==0 else "odd" for i in range(1,n+1)]
print(result)
input_string=input("Enter a string: ")
vowels_list=[char for char in input_string if char in 'aeiouAEIOU']
print(vowels_list)
input_string=input("Enter a string: ")
vowels_list=[char for char in input_string if char in 'aeiouAEIOU']
print(vowels_list)
def odd_numbers(n):
    return[i for i in range(0,n+1) if i %2!=0]
n=int(input("Enter an integer: "))
result=odd_numbers(n)
print(result)
function x(){
    const strings = ["apple", "orange"]
    console.log(strings)
}

x()
function displayWords() {
  const words = ["Hello", "World", "JavaScript", "Coding", "Infinity"];
  setInterval(() => {
    console.log(words[Math.floor(Math.random() * words.length)]);
  }, 60000); // 60000 milliseconds = 1 minute
}

displayWords();
#include <bits/stdc++.h>
using namespace std;

// Function to generate all prime numbers
// that are less than or equal to n
void SieveOfEratosthenes(int n, bool prime[]) {
    prime[0] = prime[1] = false; // 0 và 1 không phải số nguyên tố
    for (int p = 2; p * p <= n; p++) {
        if (prime[p] == true) { // Nếu p là số nguyên tố
            for (int i = p * p; i <= n; i += p) // Đánh dấu tất cả bội số của p
                prime[i] = false; // Không phải số nguyên tố
        }
    }
}

// Function to find the count of N-digit numbers
// such that the sum of digits is a prime number
int countOfNumbers(int N) {
    // Stores the dp states
    int dp[N + 1][1000];

    // Initializing dp array with 0
    memset(dp, 0, sizeof(dp));

    // Initializing prime array to true
    bool prime[1005];
    memset(prime, true, sizeof(prime));

    // Find all primes less than or equal to 1000,
    // which is sufficient for N up to 100
    SieveOfEratosthenes(1000, prime);

    // Base cases
    for (int i = 1; i <= 9; i++)
        dp[1][i] = 1; // Chỉ có các số từ 1 đến 9 là hợp lệ cho số 1 chữ số

    if (N == 1)
        dp[1][0] = 1; // Nếu N = 1, có một số hợp lệ là 0

    // Fill the dp table
    for (int i = 2; i <= N; i++) {
        for (int j = 0; j <= 900; j++) {
            for (int k = 0; k <= 9; k++) {
                dp[i][j + k] += dp[i - 1][j]; // Cộng số cách cho các số có tổng các chữ số là j
            }
        }
    }

    int ans = 0;
    for (int i = 2; i <= 900; i++) {
        if (prime[i]) // Kiểm tra xem tổng có phải là số nguyên tố không
            ans += dp[N][i]; // Cộng các cách cho số N chữ số
    }

    // Return the answer
    return ans;
}

// Driver Code
int main() {
    // Given Input
    int N = 5; // Số chữ số cần tìm

    // Function call
    cout << countOfNumbers(N); // In ra kết quả

    return 0;
}
import 'dart:async';

import 'package:flutter/foundation.dart';

class UseDebounce {
  final int milliseconds;
  Timer? _timer;

  UseDebounce({required this.milliseconds});

  void run(VoidCallback action) {
    _timer?.cancel();
    _timer = Timer(Duration(milliseconds: milliseconds), action);
  }

  void dispose() {
    _timer?.cancel();
  }
}
const string = 'cars, house';
const replaceString = string.replace("house", "money")
console.log(replaceString)
Bio-Matric Device Import Data from SQL Server To ERPNex


+++++++++++++
Open Terminal.
+++++++++++++
  
Cd frappe-bench
sudo apt update
sudo apt install python3



1- // Create Virtual Environment:
python3 -m venv venv
source venv/bin/activate

2- // Install Dependencies: (Python libraries)
pip install pyodbc requests

3- curl https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add -
   curl https://packages.microsoft.com/config/ubuntu/$(lsb_release -rs)/prod.list | sudo tee /etc/apt/sources.list.d/mssql-release.list

4- sudo apt-get update
5- sudo ACCEPT_EULA=Y apt-get install -y msodbcsql17 unixodbc-dev
6- odbcinst -q -d -n "ODBC Driver 17 for SQL Server"



3- // Configure SQL Server:
  // Ensure your SQL Server allows remote connections.
 // Install ODBC Driver for SQL Server:
sudo apt-get install unixodbc-dev msodbcsql17

4- //Generate an API Key and API Secret for an ERPNext user (like Administrator).

5- // Write the Python Script:
  //Create a Python file (erpnext_sql.py) with the code you provided.
  //Download or Copy the following Link File and Save.
  https://www.thiscodeworks.com/embed/66f3fc60f4dcb900149d8681
  
6- // Run the Script: (Mannually)
python3 erpnext_sql.py

============================================================
To Run The Script Automatically Install The Following Script:
=============================================================

7- //Automate the Script (Optional):
crontab -e

8- //Add the cron job to run at desired intervals:

30 8 * * * /path/to/your/venv/bin/python3 /path/to/erpnext_sql.py
0 10 * * * /path/to/your/venv/bin/python3 /path/to/erpnext_sql.py
0 18 * * * /path/to/your/venv/bin/python3 /path/to/erpnext_sql.py

//To schedule the script to run at 
8:30 AM, 
10:00 AM, 
6:00 PM
every day, you can set the cron job like this:


import pyodbc
import requests
from datetime import datetime

# SQL Server Connection Details
conn = pyodbc.connect(
    'DRIVER={ODBC Driver 17 for SQL Server};'
    'SERVER=192.168.1.110\HRMSERVER;DATABASE=Hikvision;UID=sa;PWD=sa@12345'
)

# Create cursor
cursor = conn.cursor()

# ERPNext API details
ERPNEXT_API_KEY = '44453e3edfdf94f6ce'
ERPNEXT_API_SECRET = '98c1d44ddfdfeer88'
ERPNEXT_URL = 'http://192.168.1.222:8000/api/method/hrms.hr.doctype.employee_checkin.employee_checkin.add_log_based_on_employee_field'

headers = {
    "Authorization": f"token {ERPNEXT_API_KEY}:{ERPNEXT_API_SECRET}",
    "Content-Type": "application/json"
}

# Fixed latitude and longitude
latitude = 31.287604
longitude = 74.169660

# Fetch data from SQL Server
cursor.execute("""
    SELECT employeeID, authDateTime, direction, deviceName
    FROM [Hikvision].[dbo].[attlog]
    ORDER BY employeeID, authDateTime
""")

last_employee = None
log_type = 'IN'  # Initial log type

# Loop through check-in logs and send data to ERPNext Employee Checkin
for row in cursor.fetchall():
    employee_id = row[0]
    timestamp_str = row[1].strftime('%Y-%m-%d %H:%M:%S')

    # Switch between IN and OUT based on employee
    if employee_id != last_employee:
        log_type = 'IN'  # First log is IN
    else:
        log_type = 'OUT'  # Second log is OUT

    data = {
        "employee_field_value": employee_id,  # Employee's Biometric ID
        "timestamp": timestamp_str,  # Log time as string
        "device_id": row[3],  # Device IP or name (deviceName)
        "log_type": log_type,  # IN or OUT
        "latitude": latitude,  # Fixed latitude
        "longitude": longitude,  # Fixed longitude
        "fetch_geolocation": 0,  # Set to 0, since you are using fixed coordinates
        "skip_auto_attendance": 0,  # Skip auto attendance
        "employee": employee_id,  # Employee ID
        "employee_name": row[0]  # Assuming employee_name is stored in employeeID
    }

    # Send data to ERPNext Employee Checkin
    response = requests.post(ERPNEXT_URL, json=data, headers=headers)

    # Print response
    print(f"Employee {row[0]} log: {log_type}, {response.status_code}, {response.text}")

    # Alternate between IN and OUT for the same employee
    last_employee = employee_id

conn.close()
const fruits = ["apple", "banana", "grapes", "peaches"]
if(fruits.includes("carrots")) {
    console.log('idla lelo carrot')
} else {
    console.log('ngifuna i fruit')
}
const fruits = ["grapes", "banana", "mango"]
fruits.push("apple")
console.log(fruits)
function reverseString(str){
    return str.split('').reverse('').join('')
}
console.log(reverseString('string'))
function add(a,b){
    return a + b; 
}

console.log(add(10,20))
package com.example.tipamountapp

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.tooling.preview.Preview
import com.example.tipamountapp.ui.theme.TipAmountAppTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
        calculateTipAmount()
        }
    }






    @Composable
    fun calculateTipAmount() {
        val amnt = 0
//        val newText=""
        var text by remember { mutableStateOf(TextFieldValue("")) }
        Column(
            modifier = Modifier.fillMaxSize(),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center
        ) {


            TextField(
                value = text,
                onValueChange = {
                    text = it

                }, placeholder = { Text(text = "please enter your bill") }
            )
            Button(onClick = {
                val bill = Integer.parseInt(text.toString())
                val res = 0.05 * (bill)
//                Text(text = "your tip amount is ${res}")
               print(res)

            }) {
                Text(text = "Press to Calculate")
            }


        }


    }

//fun print(res:Double){
//    Text(text = "your tip is :${res}")
//
//}



}


const materials = ['Hydrogen', 'Helium', 'Lithium', 'Beryllium'];

console.log(materials.map((material) => material.length));
// Expected output: Array [8, 6, 7, 9]
package com.example.fragment

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.example.fragment.ui.theme.FragmentTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            val nav_Controller = rememberNavController()
            NavHost(navController = nav_Controller, startDestination = "fragment1") {
                composable("fragment1"){ Fragment1(nav_Controller)}
                composable("fragment2"){ Fragment2(nav_Controller)}
            }
        }
    }
}

@Composable
fun Fragment1(navController: NavController){
    Column(modifier = Modifier.fillMaxSize()) {
        Spacer(modifier = Modifier.height(120.dp))
        Text(text = "This is Fragment 1", color = Color.Magenta, fontSize = 30.sp)
    }
    Box(modifier = Modifier.fillMaxSize(),
    contentAlignment = Alignment.Center) {
        Button(onClick = {navController.navigate("fragment2")}) {
            Text(text = "Go to Fragment 2", fontSize = 30.sp)
        }
    }
}

@Composable
fun Fragment2(navController: NavController){
    Column(modifier = Modifier.fillMaxSize()) {
        Spacer(modifier = Modifier.height(120.dp))
        Text(text = "This is Fragment 2", color = Color.Magenta, fontSize = 30.sp)
    }
    Box(modifier = Modifier.fillMaxSize(),
        contentAlignment = Alignment.Center) {
        Button(onClick = {navController.navigateUp()}) {
            Text(text = "Go Back to Fragment 1", fontSize = 30.sp)
        }
    }
}
package com.example.myfragment

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.example.myfragment.ui.theme.MyFragmentTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
        val nav_controller=rememberNavController()
            NavHost(navController = nav_controller, startDestination = "fragment1") {
                composable("fragment1"){Fragment1(nav_controller)}
                composable("fragment2"){Fragment2(nav_controller)}
                composable("fragment3"){Fragment3(nav_controller)}
            }
        }
    }




@Composable
fun Fragment1(navcontroller: NavController){

    Column(
        modifier = Modifier
            .fillMaxSize()
        , horizontalAlignment =Alignment.CenterHorizontally,
        verticalArrangement =Arrangement.Center
    ){
        Text(text = "This is fragment 1")
        Spacer(modifier = Modifier.height(30.dp))
        Button(onClick = { navcontroller.navigate("fragment2")  }) {
            Text(text = "Go to Fragment 2")
        }
    }



}


    @Composable
    fun Fragment2(navcontroller: NavController){



        Column(
            modifier = Modifier
                .fillMaxSize()
            , horizontalAlignment =Alignment.CenterHorizontally,
            verticalArrangement =Arrangement.Center
        ) {
                Text(text = "This is fragment 2")
                Spacer(modifier = Modifier.height(30.dp))
                Button(onClick = { navcontroller.navigate("fragment3") }) {
                    Text(text = "Go to Fragment 3")
                }
            }

    }

    @Composable
    fun Fragment3(navcontroller: NavController){



            Column(
                modifier = Modifier
                    .fillMaxSize()
                    , horizontalAlignment =Alignment.CenterHorizontally,
verticalArrangement =Arrangement.Center
            ) {
                Text(text = "This is fragment 3")
                Spacer(modifier = Modifier.height(30.dp))
                Button(onClick = { navcontroller.navigate("fragment1") }) {
                    Text(text = "Back to Fragment 1")
                }
            }

    }





}
implementation("androidx.navigation:navigation-compose:2.5.3")
package com.example.prog2

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.example.prog2.ui.theme.Prog2Theme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            val navcontroller = rememberNavController()
            NavHost(navController = navcontroller,
                startDestination = "fragment1") {
                composable("fragment1") {
                    Fragment1(navcontroller)
                }
                composable("fragment2") {
                    Fragment2(navcontroller) }
                composable("fragment3") {
                   Fragment3(navcontroller)}
            }
        }
    }
}


@Composable
fun Fragment1(navController: NavController){
    Column() {
        Text(text = "This is Fragment1 ")
        Spacer(modifier = Modifier.height(45.dp))
        Button(onClick={ navController.navigate("fragment2")}) {
            Text(text = " Go to Fragment 2")
        }
    }
}


@Composable
fun Fragment2(navController: NavController) {
    Row(horizontalArrangement = Arrangement.SpaceEvenly){
             Text(text = "This is Fragment2 ")
        Button(onClick = { navController.navigate("fragment3") }) {
            Text(text = "Go to Fragment 3")
        }
    }
}
@Composable
fun Fragment3(navController: NavController){
    Row(horizontalArrangement = Arrangement.SpaceEvenly){
        Text(text = "This is Fragment3 ")
        Button(onClick = { navController.navigate("fragment1") }) {
            Text(text = "Go to Fragment 1")
        }
    }
}
star

Thu Sep 26 2024 23:21:19 GMT+0000 (Coordinated Universal Time) https://web1.clackamas.us/web-cheat-sheet

@nmeyer

star

Thu Sep 26 2024 20:19:32 GMT+0000 (Coordinated Universal Time)

@linezito

star

Thu Sep 26 2024 20:10:51 GMT+0000 (Coordinated Universal Time)

@linezito

star

Thu Sep 26 2024 14:28:15 GMT+0000 (Coordinated Universal Time)

@KaiTheKingRook

star

Thu Sep 26 2024 13:45:31 GMT+0000 (Coordinated Universal Time)

@skfaizan2301 #bash

star

Thu Sep 26 2024 12:02:41 GMT+0000 (Coordinated Universal Time)

@CarlosR

star

Thu Sep 26 2024 11:02:30 GMT+0000 (Coordinated Universal Time) https://www.coinsclone.com/smart-contract-development-company/

@zaramarley

star

Thu Sep 26 2024 10:33:53 GMT+0000 (Coordinated Universal Time) https://innosoft-group.com/sports-betting-api-integration-service/

@Hazelwatson24 #sportsbetting api providers #sportsbetting api provider #bettingapi provider

star

Thu Sep 26 2024 09:28:43 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Thu Sep 26 2024 09:28:26 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Thu Sep 26 2024 07:58:37 GMT+0000 (Coordinated Universal Time) https://markedcode.com/index.php/2022/11/18/d365-x-odata-actions/

@Manjunath

star

Thu Sep 26 2024 07:35:22 GMT+0000 (Coordinated Universal Time)

@Abhi@0710

star

Thu Sep 26 2024 07:33:57 GMT+0000 (Coordinated Universal Time)

@Abhi@0710

star

Thu Sep 26 2024 07:00:37 GMT+0000 (Coordinated Universal Time) https://blocksentinels.com/decentralized-exchange-development-company

@Saramitson ##decentralizedexchange ##dexdevelopment

star

Thu Sep 26 2024 07:00:37 GMT+0000 (Coordinated Universal Time) https://blocksentinels.com/decentralized-exchange-development-company

@Saramitson ##decentralizedexchange ##dexdevelopment

star

Thu Sep 26 2024 05:48:10 GMT+0000 (Coordinated Universal Time) https://www.coinsclone.com/nft-marketplace-development/

@LilianAnderson #nftmarketplacedevelopment #developnftmarketplace #nftmarketplacedevelopmentcompany #buildnftmarketplace

star

Thu Sep 26 2024 05:43:44 GMT+0000 (Coordinated Universal Time)

@Manjunath

star

Thu Sep 26 2024 05:31:00 GMT+0000 (Coordinated Universal Time)

@danishnaseerktk

star

Thu Sep 26 2024 04:06:56 GMT+0000 (Coordinated Universal Time)

@shivamog

star

Thu Sep 26 2024 03:53:30 GMT+0000 (Coordinated Universal Time)

@vasttininess #javascript

star

Thu Sep 26 2024 03:52:45 GMT+0000 (Coordinated Universal Time)

@vasttininess #javascript

star

Thu Sep 26 2024 03:22:49 GMT+0000 (Coordinated Universal Time)

@pipinskie

star

Thu Sep 26 2024 03:16:28 GMT+0000 (Coordinated Universal Time)

@pipinskie

star

Thu Sep 26 2024 00:42:22 GMT+0000 (Coordinated Universal Time)

@JC

star

Thu Sep 26 2024 00:36:11 GMT+0000 (Coordinated Universal Time)

@pipinskie

star

Thu Sep 26 2024 00:31:25 GMT+0000 (Coordinated Universal Time)

@JC

star

Thu Sep 26 2024 00:22:30 GMT+0000 (Coordinated Universal Time)

@JC

star

Thu Sep 26 2024 00:15:33 GMT+0000 (Coordinated Universal Time)

@JC

star

Thu Sep 26 2024 00:14:58 GMT+0000 (Coordinated Universal Time)

@JC

star

Thu Sep 26 2024 00:12:20 GMT+0000 (Coordinated Universal Time)

@JC

star

Wed Sep 25 2024 23:29:24 GMT+0000 (Coordinated Universal Time) https://www.seha.sa/

@mazen12455

star

Wed Sep 25 2024 22:34:29 GMT+0000 (Coordinated Universal Time)

@linezito

star

Wed Sep 25 2024 21:37:02 GMT+0000 (Coordinated Universal Time)

@linezito

star

Wed Sep 25 2024 18:16:31 GMT+0000 (Coordinated Universal Time) https://www.programiz.com/cpp-programming/online-compiler/

@LizzyTheCatto

star

Wed Sep 25 2024 14:45:39 GMT+0000 (Coordinated Universal Time)

@Samuel1347

star

Wed Sep 25 2024 13:34:07 GMT+0000 (Coordinated Universal Time)

@linezito

star

Wed Sep 25 2024 12:26:15 GMT+0000 (Coordinated Universal Time)

@Taimoor

star

Wed Sep 25 2024 12:04:48 GMT+0000 (Coordinated Universal Time)

@Taimoor

star

Wed Sep 25 2024 11:19:24 GMT+0000 (Coordinated Universal Time)

@linezito

star

Wed Sep 25 2024 11:10:56 GMT+0000 (Coordinated Universal Time)

@linezito

star

Wed Sep 25 2024 10:26:03 GMT+0000 (Coordinated Universal Time)

@linezito

star

Wed Sep 25 2024 10:14:51 GMT+0000 (Coordinated Universal Time)

@linezito

star

Wed Sep 25 2024 10:11:14 GMT+0000 (Coordinated Universal Time)

@signup

star

Wed Sep 25 2024 09:41:10 GMT+0000 (Coordinated Universal Time)

@linezito

star

Wed Sep 25 2024 09:09:38 GMT+0000 (Coordinated Universal Time)

@signup

star

Wed Sep 25 2024 09:09:04 GMT+0000 (Coordinated Universal Time)

@signup

star

Wed Sep 25 2024 09:04:34 GMT+0000 (Coordinated Universal Time)

@signup

star

Wed Sep 25 2024 09:00:27 GMT+0000 (Coordinated Universal Time)

@signup

star

Wed Sep 25 2024 08:49:19 GMT+0000 (Coordinated Universal Time) https://learn.microsoft.com/en-us/windows-server/administration/openssh/openssh_install_firstuse?tabs

@GIJohn71184 #win10 #win11 #powershell #openssh #ssh

Save snippets that work with our extensions

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