FiveTech Support Forums

FiveWin / Harbour / xBase community
Board index FiveWin para Harbour/xHarbour Ejemplos para aprender a usar HASH
Posts: 147
Joined: Tue Oct 11, 2005 08:22 PM
Ejemplos para aprender a usar HASH
Posted: Tue Sep 11, 2018 02:57 PM

Hola compa帽eros, he estado viendo que los HASH se asimilan a los Arrays pero con grandes ventajas, pero no logro encontrar literatura sobre su uso y aplicaci贸n en Harbour y FW, donde puedo encontrar la forma de utilizarlos o un buen ejemplo de su aplicaci贸n?

Saludos!

Eduardo Borond贸n Mu帽iz

Posts: 6755
Joined: Wed Feb 15, 2012 08:25 PM
Re: Ejemplos para aprender a usar HASH
Posted: Tue Sep 11, 2018 07:03 PM

Los ejemplos de la clase TLayout en samples puede ser un buen comienzo ( lay.prg )

Cristobal Navarro

Hay dos tipos de personas: las que te hacen perder el tiempo y las que te hacen perder la noci贸n del tiempo

El secreto de la felicidad no est谩 en hacer lo que te gusta, sino en que te guste lo que haces
Posts: 147
Joined: Tue Oct 11, 2005 08:22 PM
Re: Ejemplos para aprender a usar HASH
Posted: Wed Sep 12, 2018 03:59 PM

Mil Gracias Crist贸bal, comienzo con eso

Saludos !!

Eduardo Borond贸n Mu帽iz

Posts: 2170
Joined: Fri Jul 18, 2008 01:24 AM
Re: Ejemplos para aprender a usar HASH
Posted: Wed Sep 12, 2018 08:39 PM
Mira este codigo, talvez te sea de ayuda.
Code (fw): Select all Collapse
//----------------------------------------------------------------------------//
Function EditCata( oLbx, lAppend, oCatalogo )
local oDlg, lSave:=.f., oCkBox,lCkBox:=.f., oBmp,oFont
local nOldRec := oCatalogo:RecNo()
local oSay1,oSay2,oSay3,oSay4,oSay5,oSay6,oSay7,oSay8,oSay9,n
local hVars, oGets:= Array(7), cCodCta
local cCodiAnter,cCodigoCta,cNivelCta,cNombreCta,cUsuarioEdit
local oControl

DEFAULT lAppend := .f.

 if !cPermiso $ "T/M"
   MsgStop("Acceso denegado. Consulte con Administrador del Sistema.","Alto")
   Return nil
 endif

if !lAppend 
  if oCatalogo:LastRec() == 0
     MsgStop("No existe ningun registro.","Alto")
     return nil
  endif
endif

 hVars:= HASH()
 If lAppend
     hVars["CODIANTERIOR"]  := Space(Len(oCatalogo:Codicont))
     hVars["NOMBREANTER"]   := Space(Len(oCatalogo:Nombre))
     hVars["CODI"]          := Space(Len(oCatalogo:Codicont))
     hVars["CUENTA"]        := NIV1
     hVars["SCUENTA1"]      := NIV2
     hVars["SCUENTA2"]      := NIV3
     hVars["SCUENTA3"]      := NIV4
     hVars["SCUENTA4"]      := NIV5
     hVars["NIVEL"]         := Space(Len(oCatalogo:nv))
     hVars["NOMBRE"]         := Space(Len(oCatalogo:nombre))
     *hVars["SALDOI"]        := 0
     *hVars["SALDOANT"]      := 0
     *hVars["MOVDEBE"]       := 0
     *hVars["MOVHABER"]      := 0
     *hVars["SALDOACT"]      := 0
 Else
     hVars["CODIANTERIOR"]  := oCatalogo:Codicont
     hVars["NOMBREANTER"]   := oCatalogo:Nombre
     hVars["CODI"]          := oCatalogo:Codicont
     hVars["CUENTA"]        := Substr(oCatalogo:Codicont,1,len(NIV1))
     hVars["SCUENTA1"]      := Substr(oCatalogo:Codicont,1+len(NIV1),len(NIV2))
     hVars["SCUENTA2"]      := Substr(oCatalogo:Codicont,1+LEN(NIV1)+LEN(NIV2),len(NIV3))
     hVars["SCUENTA3"]      := Substr(oCatalogo:Codicont,1+LEN(NIV1)+LEN(NIV2)+LEN(NIV3),len(NIV4))
     hVars["SCUENTA4"]      := Substr(oCatalogo:Codicont,1+LEN(NIV1)+LEN(NIV2)+LEN(NIV3)+LEN(NIV4),len(NIV5))
     hVars["NIVEL"]         := if(empty(oCatalogo:nv),"N",oCatalogo:nv)
     hVars["NOMBRE"]        := oCatalogo:nombre
     *hVars["SALDOI"]       := oCatalogo:saldoi
     *hVars["SALDOANT"]     := oCatalogo:saldoant
     *hVars["MOVDEBE"]      := oCatalogo:movdebe
     *hVars["MOVHABER"]     := oCatalogo:movhaber
     *hVars["SALDOACT"]     := oCatalogo:saldoact
 Endif


  DEFINE FONT oFont NAME "MS SANS SERIF" SIZE 0,-09 
  DEFINE DIALOG oDlg RESOURCE "CATALOGOEDIT" ;
         TITLE If( lAppend, " Agregar nuevo registro al Catalogo", " Modificar Catalogo de Cuentas" ) ;
         FONT oFont ;
         TRANSPARENT

  For n:=101 to 108   //Los says
    REDEFINE SAY ID n OF oDlg
  Next

   REDEFINE CHECKBOX oCkBox VAR lCkBox ID 110 OF oDlg ON CHANGE if(lCkBox=.t.,MsgInfo("Utilice con cuidado. Puede descuadrar Estados Financieros"),)
   oCkBox:lTransparent := .t.

   REDEFINE GET oGets[1] VAR hVars["CUENTA"]    ID 201 OF oDlg PICTURE "@!"
   REDEFINE GET oGets[2] VAR hVars["SCUENTA1"]  ID 202 OF oDlg PICTURE "@!" VALID campolleno(hVars["SCUENTA1"],NIV2)
   REDEFINE GET oGets[3] VAR hVars["SCUENTA2"]  ID 203 OF oDlg PICTURE "@!" VALID campolleno(hVars["SCUENTA2"],NIV3)
   REDEFINE GET oGets[4] VAR hVars["SCUENTA3"]  ID 204 OF oDlg PICTURE "@!" VALID campolleno(hVars["SCUENTA3"],NIV4)

   REDEFINE GET oGets[5] VAR hVars["SCUENTA4"]  ID 205 OF oDlg PICTURE "@!" VALID campolleno(hVars["SCUENTA4"],NIV5) ;
                 .AND. CATAERROR(hVars["CODIANTERIOR"], hVars["CUENTA"]+hVars["SCUENTA1"]+hVars["SCUENTA2"]+hVars["SCUENTA3"]+hVars["SCUENTA4"], oLbx, lAppend, oGets[1], oGets[5], oCatalogo)

   REDEFINE GET oGets[6] VAR hVars["NIVEL"]     ID 206 OF oDlg PICTURE "@!" Valid NivelAuxi(hVars["NIVEL"])
   REDEFINE GET oGets[7] VAR hVars["NOMBRE"]    ID 207 OF oDlg PICTURE "@!"

   REDEFINE BITMAP oBmp RESOURCE "CONFIG64" ID 400 OF oDLG ; oBmp:lTransparent:=.t.

   REDEFINE BUTTONBMP ID 312 OF oDlg BITMAP "ACEPTAR" TEXTRIGHT ACTION ( IF(CATAERROR(hVars["CODIANTERIOR"], hVars["CUENTA"]+hVars["SCUENTA1"]+hVars["SCUENTA2"]+hVars["SCUENTA3"]+hVars["SCUENTA4"], oLbx, lAppend, oGets[1], oGets[5], oCatalogo),(lSave := .t. , oDlg:End()), lSave:=.f.) )
   REDEFINE BUTTONBMP ID 313 OF oDlg BITMAP "CANCELAR" TEXTRIGHT ACTION oDlg:End() CANCEL

   ACTIVATE DIALOG oDlg CENTERED 
 
   IF lSave .and. !empty( hVars["CUENTA"] )

      cCodiAnter := hVars["CODIANTERIOR"]
      cCodigoCta := hVars["CUENTA"]+hVars["SCUENTA1"]+hVars["SCUENTA2"]+hVars["SCUENTA3"]+hVars["SCUENTA4"]
      cNivelCta  := if(upper(hVars["NIVEL"]) = "N"," ","S")
      cNombreCta := hVars["NOMBRE"]
      cUsuarioEdit:=Substr(cNombUser,1,22)+" "+dtoc(date())+" "+time() //usuario que edita
 
      If lAppend
         oServer:Query( "INSERT INTO catalogo (codicont,nv,nombre,usuario) VALUES ('"+cCodigoCta+"','"+cNivelCta+"','"+cNombreCta+"','"+cUsuarioEdit+"')" )
      Else   
         oServer:Query( "UPDATE catalogo SET codicont = '"+cCodigoCta+"', nv = '"+cNivelCta+"', nombre = '"+cNombreCta+"', modificado = '"+cUsuarioEdit+"' WHERE Codicont = '"+cCodiAnter+"'  ORDER BY codicont LIMIT 1")
      Endif

      if oServer:lError
         MsgStop(oServer:Error)
      endif

     //Sin esto no refresca bien (no se coloca en registro recien ingresado)     
      *If lAppend
         oCatalogo:GoTop()
         oCatalogo:Refresh()
         oCatalogo:Locate("Codicont",cCodigoCta,,)
      *Endif

     if oLbx != NIL    //bandera desde grabar():ExisteCta()
        oCatalogo:Refresh()
        oLbx:Refresh()
     endif

     if alltrim(cCodigoCta)<>alltrim(cCodiAnter  )
        oControl:=oServer:Query("SELECT * FROM control ;")
        if substr(cCodigoCta,1,1)=Substr(alltrim(oControl:Ingr),1,1);
           .or. substr(cCodigoCta,1,1)==Substr(alltrim(oControl:Cost),1,1);
           .or. substr(cCodigoCta,1,1)==Substr(alltrim(oControl:Egre),1,1)
           MsgInfo("La codificacion introducida es de Resultado."+CRLF+;
                   "Revise si debe incluirse en Estado de Resultado definido por el usuario.","ADVERTENCIA")
        endif
        oControl:End()
     endif

     IF !lAppend  //ES MODIF
        if hVars["NOMBRE"] <> hVars["NOMBREANTER"]
           Proceso(alltrim(cNombUser)+ " modif nombre a Cta "+hVars["CODI"]+" de "+alltrim(hVars["NOMBREANTER"])+" a "+hVars["NOMBRE"])
        endif 
        if cCodigoCta<>cCodiAnter
           Proceso(alltrim(cNombUser)+ " modif Codigo a Cta "+ cCodiAnter +" a "+ cCodigoCta )
        endif 
     ENDIF

   ELSE  //Si no se salva el registro...
      oCatalogo:GoTo(nOldRec)
      oCatalogo:Refresh()
   ENDIF

   oFont:End()
   oLbx:SetFocus()
RETURN NIL

Saludos.
Francisco J. Alegr铆a P.

Chinandega, Nicaragua.



Fwxh-MySql-TMySql
Posts: 147
Joined: Tue Oct 11, 2005 08:22 PM
Re: Ejemplos para aprender a usar HASH
Posted: Wed Sep 26, 2018 09:02 PM

Mil gracias Francisco, muy claro el ejemplo.

Saludos!

Eduardo Borond贸n Mu帽iz

Posts: 1380
Joined: Fri Oct 14, 2005 01:28 PM
Re: Ejemplos para aprender a usar HASH
Posted: Tue Oct 02, 2018 11:48 AM
Hola;
Si no es tarde; este es el ejemplo vino en alguna distribuci贸n de Harbour o xHarblour; ya no recuerdo
Code (fw): Select all Collapse
*****************************************************
* Hash Grammar test
*
* Giancarlo Niccolai (C) 2003
*
* This is a test that demonstrates how to use hashes
*
* $Id: hash.prg,v 1.9 2003/12/13 19:27:00 ronpinkas Exp $
*

PROCEDURE Main()
聽 聽LOCAL hHash, hTemp
聽 聽LOCAL nSum, nLevel, eError
聽 聽LOCAL xKey, xValue, hDest

聽 聽SET DATE TO ITALIAN
聽 聽CLEAR SCREEN

聽 聽@0,0 SAY "*** Hash test ***"
聽 聽? "Giancarlo Niccolai"
聽 聽?

聽 聽* Creation by PP command:
聽 聽* Equivalent to Hash( K1, V1, ... KN, VN )

聽 聽hHash := Hash()
聽 聽HSetPartition( hHash, 2, 2 )


聽 聽/* Insertion by API */
聽 聽hHash["Kval"] = 'StrKey 0'
聽 聽hHash[ 8 ] = 'Num Key 0'
聽 聽HSet( hHash, 4, 聽"Numeric key 1" )
聽 聽HSet( hHash, 2, 聽"Numeric key 2" )
聽 聽HSet( hHash, "Str8", "String key 1" )
聽 聽HSet( hHash, "Str1", "String key 2" )
聽 聽HSet( hHash, CToD("1/1/2003"), "Date key 1" )
聽 聽HSet( hHash, CToD("30/11/2002") , "Date key 2" )

聽 聽? "Standard API compliance test:"
聽 聽? "Hash type:", ValType( hHash )
聽 聽? "Hash length:", Len( hHash )
聽 聽? "Hash value:", ValToPrg( hHash )
聽 聽? "Empty hash value:", ValToPrg( { => } )
聽 聽? "String representation (should be nothing):", {=>}
聽 聽? "Equality of hashes (Success for .T. , .F.): ", hHash == hHash, hHash == {=>}
聽 聽HGetPartition(hHash, @nSum, @nLevel )
聽 聽? "Hash partitioned as: ", nSum, nLevel

聽 聽? "Plus operator: ", ValToPrg( { 1=>1, 'a'=>2} + { 3=>3, 'b'=>4 } )
聽 聽hHash += { 5=> "numkey 3" }
聽 聽? "Plusequal operator (success if Len(hHash) == 9: ", Len(hHash), ",(", hHash[5], ")"
聽 聽hTemp := {'a'=>1, 1=>2, 'c'=>3}
聽 聽? "Minus hash - hash operator: ", ValToPrg( hTemp - { 1=>2, 'c'=>3} )
聽 聽? "Minus hash - array operator: ", ValToPrg( hTemp - { 1, 'a'} )
聽 聽? "Minus hash - item operator: ", ValToPrg( hTemp - 'a' )
聽 聽? "Hash is now: ", ValToPrg( hHash )
聽 聽? "operator kval IN hash", ('Str1' IN hHash)
聽 聽? "operator {=>} IN hash", ({ "Str8" => "String key 1" } IN hHash)
聽 聽? "Turning autoadd off (currently:", HGetAutoAdd( hHash ), ")"
聽 聽HSetAutoAdd( hHash, .F. )
聽 聽TRY
聽 聽 聽 hHash[ 'a very new key' ] := 'a value'
聽 聽 聽 ? "Failure (new key inserted)"
聽 聽CATCH eError
聽 聽 聽 ? "Success: ", eError:description
聽 聽END
聽 聽HSetAutoAdd( hHash, .T. )

聽 聽? "Press a Key to continue"
聽 聽?
聽 聽Inkey(0)

聽 聽? "VM compliance test:"
聽 聽? "Numeric key value hHash[4]:", hHash[4]
聽 聽? "Date key value hHash[CToD('1/1/2003')]:", hHash[CToD('1/1/2003')]
聽 聽? "String key value hHash['Kval']:", hHash['Kval']
聽 聽? "Assign eval hHash['Kval'] := 100", (hHash['Kval'] := 100)
聽 聽? "Assign eval result hHash['Kval']", hHash['Kval']
聽 聽M->iPos := 2
聽 聽? "Memvar test hHash[ m->iPos ]: ", hHash[ m->iPos ]
聽 聽m->hMem := hHash
聽 聽? "Memvar assign m->hMem := hHash, ValType( m->hMem ): ", ValType( m->hMem )
聽 聽TRY
聽 聽 聽 ? "Wrong index test: hHash[Array()]: Failed", hHash[Array()]
聽 聽CATCH eError
聽 聽 聽 ? "Wrong index test: hHash[Array()]: Passed (", eError:description, ")"
聽 聽END
聽 聽HSetCaseMatch( hHash, .F. )
聽 聽? "Hash gramar ':' existing key insensitive:", hHash:kval
聽 聽HSetCaseMatch( hHash, .Y. )
聽 聽? "Hash gramar ':' adding key:", ( hHash:ColonKey := 'Colon value' )
聽 聽? "Hash gramar ':' retreiving key:", hHash:ColonKey
聽 聽? "Hash grammar ':' classname:", hHash:ClassName
聽 聽? "Hash grammar ':' keys:", ValToPrg( hHash:Keys )
聽 聽? "Hash grammar ':' values:", ValToPrg( hHash:Values )

聽 聽? "Press a Key to continue"
聽 聽?
聽 聽Inkey(0)

聽 聽? "HASH api test:"
聽 聽? "HGetPos existing key:", HGetPos( hHash, 2 )
聽 聽? "HGetPos unexisting key:", HGetPos( hHash, 1000 )
聽 聽? "HDel key Str1: (should be ok) "
聽 聽 聽 HDel( hHash, "Str1" )
聽 聽? "HGetKeys: ", ValToPrg( hGetKeys( hHash ) )
聽 聽? "HGetValues: ", ValToPrg( hGetValues( hHash ) )
聽 聽? "HGetKeyAt 3d pos: ", HGetKeyAt( hHash, 3 )
聽 聽? "HGetValueAt 3d pos: ", HGetValueAt( hHash, 3 )
聽 聽? "HGetPairAt 4th pos (as array):", ValToPrg( HGetPairAt( hHash, 4 ) )
聽 聽HGetPairAt( hHash, 4, @xKey, @xValue )
聽 聽? "HGetPairAt 4th pos (as byref):", xKey, xValue
聽 聽? "HDelAt 4th position:"
聽 聽 聽 HDelAt( hHash, 4 )
聽 聽? "Setting 4th value to 'A newer value'"
聽 聽 聽 HSetValueAt( hHash, 4, 'A newer value' )
聽 聽? "Hash is now: ", ValToPrg( hHash )
聽 聽? "Press a Key to continue"
聽 聽?
聽 聽Inkey(0)

聽 聽? "HASH Case insensitive test:"
聽 聽HSetCaseMatch( hHash, .F. )
聽 聽hHash[ 'a' ] := 100
聽 聽TRY
聽 聽 聽 HSetCaseMatch( hHash, .T. )
聽 聽 聽 ? "Sensitivity test failed: ", hHash[ 'A' ]
聽 聽CATCH eError
聽 聽 聽 ? "Sensitivity test Passed (", eError:description, 聽")"
聽 聽END

聽 聽HSetCaseMatch( hHash, .F. )
聽 聽TRY
聽 聽 聽 ? "Insensitivity test passed: ", hHash[ 'A' ]
聽 聽CATCH eError
聽 聽 聽 ? "Insensitivity test Failed (", eError:description, 聽")"
聽 聽END

聽 聽TRY
聽 聽 聽 hHash['A'] := 50
聽 聽 聽 ? "Insensitive assignment (success if 50): ", hHash[ 'a' ]
聽 聽CATCH eError
聽 聽 聽 ? "Insensitivity assignment Failed (", eError:description, 聽")"
聽 聽END
聽 聽? "Press a Key to continue"
聽 聽?
聽 聽Inkey(0)


聽 聽? "HGetPos existing key:", HGetPos( hHash, 2 )
聽 聽? "HGetPos unexisting key:", HGetPos( hHash, 1000 )
聽 聽? "HDel key Str1: (should be ok) "
聽 聽 聽 HDel( hHash, "Str8" )
聽 聽? "HGetKeys: ", ValToPrg( hGetKeys( hHash ) )
聽 聽? "HGetValues: ", ValToPrg( hGetValues( hHash ) )
聽 聽? "HGetKeyAt 3d pos: ", HGetKeyAt( hHash, 3 )
聽 聽? "HGetValueAt 3d pos: ", HGetValueAt( hHash, 3 )
聽 聽? "HGetPairAt 4th pos (as array):", ValToPrg( HGetPairAt( hHash, 4 ) )
聽 聽HGetPairAt( hHash, 4, @xKey, @xValue )
聽 聽? "HGetPairAt 4th pos (as byref):", xKey, xValue
聽 聽? "HDelAt 4th position:"
聽 聽 聽 HDelAt( hHash, 4 )
聽 聽? "Setting 4th value to 'A newer value'"
聽 聽 聽 HSetValueAt( hHash, 4, 'A newer value' )
聽 聽? "Hash is now: ", ValToPrg( hHash )
聽 聽? "Press a Key to continue"
聽 聽?
聽 聽Inkey(0)


聽 聽? "HASH Secondary API test:"
聽 聽? "Scanning for value 'A newer value': ", HScan( hHash, 'A newer value' )
聽 聽? "Scanning for value 'A newer value' using CB: ",;
聽 聽 聽 聽HScan( hHash, {| cKey, cVal| HB_ISSTRING(cVal) .and. cVal == 'A newer value'} )

聽 聽nSum := 0
聽 聽HEval( hHash, { | cKey, cVal|;
聽 聽 聽 聽IIF (HB_ISNUMERIC(cKey), nSum += cKey, )} )

聽 聽? "Eval summing up all the numeric keys :", nSum
聽 聽? "Clone of the hash:", ValToPrg(HClone( hHash ))
聽 聽hDest := { 'A'=> 1, 'b'=>2 }
聽 聽? "Merging hash with { 'a'=> 1, 'b'=>2 }:"
聽 聽? "Result: ", ValToPrg(HCopy( hHash, hDest ))

聽 聽hDest := { 'B'=> 1, 'A'=>2 }
聽 聽? "Merging limited with a codeblock (Only numeric values): "
聽 聽? "Result: ", ValToPrg( HMerge( hDest, hHash, { |cKey, nVal| HB_IsNumeric( nVal ) } ) )
聽 聽* The last "2" means XOR
聽 聽? "Doing a xor merge with the original one (first 4 elements): "
聽 聽? "Result: ", 聽ValToPrg( HCopy( hHash, hDest, , , 2 ) )

聽 聽? "Doing an AND merge with { 'A'=>0, 'B'=>1 } "
聽 聽? "Result: ", 聽ValToPrg( HMerge( hDest, {'A'=>0, 'B'=>1 }, 1) )

聽 聽? "Press a Key to continue"
聽 聽?
聽 聽Inkey(0)
Resistencia - "Ciudad de las Esculturas"

Chaco - Argentina
Posts: 147
Joined: Tue Oct 11, 2005 08:22 PM
Re: Ejemplos para aprender a usar HASH
Posted: Tue Oct 02, 2018 03:02 PM

Muchisimas gracias Mario

Excelente ejemplo, muy completo y en muy buen momento.

Gracias de nuevo

Eduardo Borond贸n Mu帽iz

Posts: 1067
Joined: Wed Nov 09, 2005 02:17 AM
Re: Ejemplos para aprender a usar HASH
Posted: Thu Oct 31, 2019 09:08 PM

Hi guys,

Is possible to use hash arrays as a multidimensional array? something like this:

? aHash[ 'A',1]
? aHash[ 'A',2]

Sds,
Vilian F. Arraes
vilian@vfatec.com.br
Bel茅m-Pa-Brazil
Posts: 6755
Joined: Wed Feb 15, 2012 08:25 PM
Re: Ejemplos para aprender a usar HASH
Posted: Thu Oct 31, 2019 10:49 PM
Dear Vilian
Yes, same as arrays
Code (fw): Select all Collapse
聽 聽 //In this case aItems is a array of Hash and aItems[ x ] is a Hash
聽 聽 if hb_hHaskey( aItems[ x ][ "end" ], "timeZone" )
聽 聽 聽 聽cTime 聽 := aItems[ x ][ "end" ][ "timeZone" ]
聽 聽 endif
Cristobal Navarro

Hay dos tipos de personas: las que te hacen perder el tiempo y las que te hacen perder la noci贸n del tiempo

El secreto de la felicidad no est谩 en hacer lo que te gusta, sino en que te guste lo que haces
Posts: 1067
Joined: Wed Nov 09, 2005 02:17 AM
Re: Ejemplos para aprender a usar HASH
Posted: Fri Nov 01, 2019 06:06 PM

Thank you ;)

Sds,
Vilian F. Arraes
vilian@vfatec.com.br
Bel茅m-Pa-Brazil

Continue the discussion