50% OFF!!!

Showing posts with label code. Show all posts
Showing posts with label code. Show all posts

Thursday, December 3, 2020

php merge dateranges code algorithm


Here is a code for merging date-ranges in array. The method gives new array, with the maximum mergining between the date-ranges, meaning if there is a date-range that already exists with-in other, it can just skip, so just if two or more dates can be combined into one big date-range - it will be made :) . 
 
-------------------------------Example #1:
  array 
  0 => 's' => '2020-01-06' 'e' => '2020-01-10'
  1 => 's' => '2020-01-07' 'e' => '2020-01-12'
  2 => 's' => '2020-01-13' 'e' => '2020-01-16'
  3 => 's' => '2020-01-22' 'e' => '2020-01-24'

RESULT:
array 
  0 => 's' => '2020-01-06' 'e' => '2020-01-16'
  1 => 's' => '2020-01-22' 'e' => '2020-01-24'
 
-------------------------------Example #2:
array (size=8)
  0 => 's' => '2020-01-01' 'e' => '2020-01-01'
  1 => 's' => '2020-01-03' 'e' => '2020-01-03'
  2 => 's' => '2020-01-09' 'e' => '2020-01-10'
  3 => 's' => '2020-01-11' 'e' => '2020-01-22'
  4 => 's' => '2020-01-14' 'e' => '2020-02-02'
  5 => 's' => '2020-02-02' 'e' => '2020-02-03'
  6 => 's' => '2020-02-04' 'e' => '2020-02-04'
  7 => 's' => '2020-02-05' 'e' => '2020-02-07'

RESULT:
array (size=3)           
  0 => 's' => '2020-01-01' 'e' => '2020-01-01'
  1 => 's' => '2020-01-03' 'e' => '2020-01-03'
  2 => 's' => '2020-01-09' 'e' => '2020-02-07'
 
 
And here is the CODE:

$arrDateranges = array(
    array('s' => '2020-01-22', 'e' => '2020-01-24'),
    array('s' => '2020-01-06', 'e' => '2020-01-10'),
    array('s' => '2020-01-07', 'e' => '2020-01-12'),
    array('s' => '2020-01-13', 'e' => '2020-01-16'),
);
$arrMerged = mergeDateRanges($arrDateranges);
var_dump($arrDateranges);
var_dump($arrMerged);

//---------------------------------------------------------

// helper funciton to get NEXT date (or any modified date)
function getRelativeDate($p_sDate, $p_sModify, $p_sFormatIn = 'Y-m-d', $p_sFormatOut = 'Y-m-d') {
    $oDT = DateTime::createFromFormat($p_sFormatIn, $p_sDate);
    $oDT->modify($p_sModify);
    return $oDT->format($p_sFormatOut);
}

function mergeDateRanges($p_arrDateranges) {
    // sort by start date
    usort($p_arrDateranges, function($a1, $a2) {
        return $a1['s'] === $a2['s'] ? 0 : ($a1['s'] < $a2['s'] ? -1 : 1);
    });
    
    $arrMerged = array();
    $arrLastDR = null;
    foreach ($p_arrDateranges as $arrDR) {
        if ($arrLastDR === null) {
            $arrLastDR = $arrDR;
            continue;
        }
        //
        // NOTE: dateS is sorted thus $sDateS >= $arrLastDR['s']
        //
        if ($arrDR['e'] <= $arrLastDR['e']) {
            continue; // already in the range.
        }
        // --- [e] > lastDR[e] ---
        $sLastDateE_1 = getRelativeDate($arrLastDR['e'], '+1 day');
        if ($arrDR['s'] <= $sLastDateE_1) { // lapping date-range until day+1
            $arrLastDR['e'] = $arrDR['e'];
            continue;
        }

        // there is gap, so need to create new date-range
        array_push($arrMerged, $arrLastDR);
        $arrLastDR = $arrDR;
    }

    if ($arrLastDR === null) {
        array_push($arrMerged, $arrLastDR);
    }
    return $arrMerged;
}


Friday, November 13, 2015

PHP | XML to Html Table elment convertion

In this thread,
I will show generic & universal function that
gets XML string,
convert it,
and display it as an HTML table.
(you can add any css style to design your table later on of course)


The following code is using XML example from http://www.w3schools.com/xml/simple.xml.
The XML looks like that:
<breakfast_menu>
  <food>
    <name>Belgian Waffles</name>
    <price>$5.95</price>
    <description>Two of our famous...</description>
    <calories>650</calories>
  </food>
  <food>
    <name>Strawberry Belgian Waffles</name>
    <price>$7.95</price>
    <description>Light Belgian waffles...</description>
    <calories>900</calories>
  </food>
  <food>
    <name>Berry-Berry Belgian Waffles</name>
    <price>$8.95</price>
    <description>Light Belgian....</description>
    <calories>900</calories>
  </food>
  <food>
    <name>French Toast</name>
    <price>$4.50</price>
    <description>Thick slices made....</description>
    <calories>600</calories>
  </food>
  <food>
    <name>Homestyle Breakfast</name>
    <price>$6.95</price>
    <description>Two eggs, bacon...</description>
    <calories>950</calories>
  </food>
</breakfast_menu>



The function xmlToHtmlTable 
gets a SimpleXMLElement parameter which points to main parent for which will print all his children,
and returns html table representing the XML as string.

The Code:
 <?php  
   
 // get XML remotely / locally / or / just set it as string '<root>...</root>'  
 $sXml = file_get_contents('http://www.w3schools.com/xml/simple.xml');  
   
 // parse XML  
 $oXML = simplexml_load_string($sXml);  
 if (!$oXML) {  
      die('xml format not valid or simplexml module missing.');  
 }  
   
 // assuming running the root  
 $oXmlRoot = $oXML; // or can be [$oXML->food]  
   
 //echo '<pre>'; print_r( $oXmlRoot ); echo '</pre>';  
 echo xmlToHtmlTable($oXmlRoot);  
   
   
 function xmlToHtmlTable($p_oXmlRoot) {  
      $bIsHeaderProceessed = false;  
        
      $sTHead = '';  
      $sTBody = '';       
      foreach ($p_oXmlRoot as $oNode) {  
           $sTBody .= '<tr>';  
           foreach ($oNode as $sName => $oValue){  
                if (!$bIsHeaderProceessed) {  
                     $sTHead .= "<th>{$sName}</th>";  
                }  
                $sValue = (string)$oValue;  
                $sTBody .= "<td>{$sValue}</td>";                 
           }  
           $bIsHeaderProceessed = true;  
           $sTBody .= '</tr>';  
      }  
        
      $sHTML = "<table border=1>  
                     <thead><tr>{$sTHead}</tr></thead>  
                     <tbody>{$sTBody}</tbody>  
                </table>";  
      return $sHTML;  
 }  

This will output:

 
Hope it helps!
MDB BLOG!




 

Wednesday, December 8, 2010

C# | Check if app is installed for “All users” or "Just me"


Today I bring a very HARD-to-find topic about getting an installed application "Installation context".
An installation context may be Per-Machine Installation Context (ALLUSERS=1) and Per-User Installation Context (ALLUSERS="").

When installing an application, the user may select one of two options:
a. Install [APP] for yourself
b. or for anyone who uses this computer

[a] installs only for the current user(just me) while [b] installs for the Local System user which is for all-users(everyone).

In this post I will give a code for checking is an installed application was installed for "Everyone" or "Just me".

The validation process is check if the APPLICATION-NAME exists in the registry keys under UserData.
(*) Everyone - check under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Products\ (S-1-5-18 represents the Local System user)

(*) Just me (Current user) - check under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-?!?!?!?!\Products\ (S-?!?!?!?! represents the Current user. this value found by the code: WindowsIdentity.GetCurrent().User.Value.


[Code] Method's return type:
private enum InstallationContexts { NotInstalled, Everyone, JustMe };

[Code] Method declaration:
private InstallationContexts GetInstalledContext(string p_appDisplayName)
{
    //The S-1-5-18  =
Local System user (Everyone) | HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Products\

    //The S-XXXXXX  =
Current user (Just me)       |
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-?!?!?!?!\Products\

    string key;
    string keyFormat = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\{0}\Products\";
 
    // Check if installed for -> Everyone
    key = string.Format(keyFormat, "S-1-5-18");
    bool res = GetInstalledContext_IsRegKeyExists(key, p_appDisplayName, StringComparison.OrdinalIgnoreCase);
    if (res == true)
    {
        return InstallationContexts.Everyone;
    }
 
    // Check if installed for -> Just me
    key = string.Format(keyFormat, WindowsIdentity.GetCurrent().User.Value);
    res = GetInstalledContext_IsRegKeyExists(key, p_appDisplayName, StringComparison.OrdinalIgnoreCase);
    if (res == true)
    {
        return InstallationContexts.JustMe;
    }
 
    return InstallationContexts.NotInstalled;
}
private bool GetInstalledContext_IsRegKeyExists(string p_regKey, string p_appDisplayName, StringComparison p_scompare)
{
    using (RegistryKey regkey = Registry.LocalMachine.OpenSubKey(p_regKey))
    {
        if (regkey != null)
        {
            RegistryKey rk;
            string[] arrProducs = regkey.GetSubKeyNames();
            for (int i = 0; i < arrProducs.Length; i++)
            {

               using (rk = regkey.OpenSubKey(arrProducs[i] + @"\InstallProperties"))
               {
if (rk != null &&
                        p_appDisplayName.Equals(rk.GetValue("DisplayName").ToString(), p_scompare) == true)
                   {
                        return true;
                   }
               }
            }
        }
    }
 
    return false;
}

[Code] Method's usage example:
InstallationContexts appContext = GetInstalledContext("APP-DISPLAY-NAME");

This code gives the ability to detect previously installed application or previously installed software is installed to ALLUSERS (everyone) or only to CURRENT USER (just me).



Addition on 19.12.2010:
(*) This checking operation is valid ONLY for an application and software which were installed using Microsoft's Windows Installer.
For general checking for installed application, check my post about check if program/application is installed.


Enjoy...
MDB-Blog

Monday, October 4, 2010

Trim Image white-spaces (black&white) | C# Winforms

I searched for a simple code that preform "TRIMMING" to an image.
By "trimming" i mean, that if i have a LARGE image that contains information (painting/drawing...) only in small part of the image and all other is white-space (WHITE or BLACK pixels).

I needed to remove such whitespace and also to decrease image size.
Following three code examples:

Code #1 - Gets the NON-WHITE-SPACE bounds of an image
private Rectangle GetImageNonWhiteSpaceBounds(Bitmap p_img, bool p_isBlackWhitespace)
{
    Rectangle rect = new Rectangle();
    unsafe
    {
        BitmapData bdActual = null;
        try
        {
            int width = p_img.Width;
            int height = p_img.Height;

            bdActual = p_img.LockBits(new Rectangle(0, 0, width, height), System.Drawing.Imaging.ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
            Int32 i;
            Int32 pSize = 3;
            Byte whiteTrashold = (Byte)240;
            Byte blackTrashold = (Byte)10;
            Byte* sourceRow;

            Int32 minX = width;
            Int32 maxX = 0;
            Int32 minY = height;
            Int32 maxY = 0;
            bool isWhitepace;

            for (Int32 _y = 0; _y < height; ++_y)             {                 sourceRow = (Byte*)bdActual.Scan0 + (_y * bdActual.Stride);                 for (Int32 _x = 0; _x < width; ++_x)                 {                     i = _x * pSize;                     isWhitepace =                         (p_isBlackWhitespace && sourceRow[i] <= blackTrashold && sourceRow[i + 1] <= blackTrashold && sourceRow[i + 2] <= blackTrashold)                         ||                         (!p_isBlackWhitespace && sourceRow[i] >= whiteTrashold && sourceRow[i + 1] >= whiteTrashold && sourceRow[i + 2] >= whiteTrashold);

                    if (isWhitepace == false)
                    {
                        // NO whitespace!!!
                        minX = Math.Min(_x, minX);
                        maxX = Math.Max(_x, maxX);

                        minY = Math.Min(_y, minY);
                        maxY = Math.Max(_y, maxY);
                    }
                }
            }

            rect.X = minX;
            rect.Y = minY;
            rect.Width = maxX - minX;
            rect.Height = maxY - minY;
        }
        finally
        {
            if (bdActual != null)
            {
                p_img.UnlockBits(bdActual);
            }
        }
    }
    return rect;
}

Code #2 - Draw rectangle around the NON-WHITE-SPACE
private void DrawNonWhiteSpaceRectangle(Bitmap p_img, bool p_isBlackWhitespace, Color p_color)
{
    unsafe
    {
        BitmapData bdActual = null;
        try
        {
            int width = p_img.Width;
            int height = p_img.Height;

            bdActual = p_img.LockBits(new Rectangle(0, 0, width, height), System.Drawing.Imaging.ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
            Int32 i;
            Int32 pSize = 3;
            Byte whiteTrashold = (Byte)240;
            Byte blackTrashold = (Byte)10;
            Byte* sourceRow;

            Int32 minX = width;
            Int32 maxX = 0;
            Int32 minY = height;
            Int32 maxY = 0;
            bool isWhitepace;

            for (Int32 _y = 0; _y < height; ++_y)             {                 sourceRow = (Byte*)bdActual.Scan0 + (_y * bdActual.Stride);                 for (Int32 _x = 0; _x < width; ++_x)                 {                     i = _x * pSize;                     isWhitepace =                         (p_isBlackWhitespace && sourceRow[i] <= blackTrashold && sourceRow[i + 1] <= blackTrashold && sourceRow[i + 2] <= blackTrashold)                         ||                         (!p_isBlackWhitespace && sourceRow[i] >= whiteTrashold && sourceRow[i + 1] >= whiteTrashold && sourceRow[i + 2] >= whiteTrashold);

                    if (isWhitepace == false)
                    {
                        // NO whitespace!!!
                        minX = Math.Min(_x, minX);
                        maxX = Math.Max(_x, maxX);

                        minY = Math.Min(_y, minY);
                        maxY = Math.Max(_y, maxY);
                    }
                }
            }

            // draw rectagle:
            for (Int32 _y = minY; _y <= maxY; ++_y)             {                 sourceRow = (Byte*)bdActual.Scan0 + (_y * bdActual.Stride);                 i = minX * pSize;                 sourceRow[i] = (Byte)p_color.R;                 sourceRow[i + 1] = (Byte)p_color.G;                 sourceRow[i + 2] = (Byte)p_color.B;                 i = maxX * pSize;                 sourceRow[i] = (Byte)p_color.R;                 sourceRow[i + 1] = (Byte)p_color.G;                 sourceRow[i + 2] = (Byte)p_color.B;             }             Byte* sourceRowX1 = (Byte*)bdActual.Scan0 + (minY * bdActual.Stride);             Byte* sourceRowX2 = (Byte*)bdActual.Scan0 + (maxY * bdActual.Stride);             for (Int32 _x = minX; _x <= maxX; ++_x)             {                 i = _x * pSize;                 sourceRowX1[i] = (Byte)p_color.R;                 sourceRowX1[i + 1] = (Byte)p_color.G;                 sourceRowX1[i + 2] = (Byte)p_color.B;                 sourceRowX2[i] = (Byte)p_color.R;                 sourceRowX2[i + 1] = (Byte)p_color.G;                 sourceRowX2[i + 2] = (Byte)p_color.B;             }         }         finally         {             if (bdActual != null)             {                 p_img.UnlockBits(bdActual);             }         }     } }


Code #3 - Trim Image whitespaces
private Bitmap CropImageWhitespaces(Bitmap p_img, bool p_isBlackWhitespace)
{
    Rectangle rect = new Rectangle();
    unsafe
    {
        BitmapData bdActual = null;
        try
        {
            int width = p_img.Width;
            int height = p_img.Height;

            bdActual = p_img.LockBits(new Rectangle(0, 0, width, height), System.Drawing.Imaging.ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
            Int32 i;
            Int32 pSize = 3;
            Byte whiteTrashold = (Byte)240;
            Byte blackTrashold = (Byte)10;
            Byte* sourceRow;

            Int32 minX = width;
            Int32 maxX = 0;
            Int32 minY = height;
            Int32 maxY = 0;
            bool isWhitepace;

            for (Int32 _y = 0; _y < height; ++_y)             {                 sourceRow = (Byte*)bdActual.Scan0 + (_y * bdActual.Stride);                 for (Int32 _x = 0; _x < width; ++_x)                 {                     i = _x * pSize;                     isWhitepace =                         (p_isBlackWhitespace && sourceRow[i] <= blackTrashold && sourceRow[i + 1] <= blackTrashold && sourceRow[i + 2] <= blackTrashold)                         ||                         (!p_isBlackWhitespace && sourceRow[i] >= whiteTrashold && sourceRow[i + 1] >= whiteTrashold && sourceRow[i + 2] >= whiteTrashold);

                    if (isWhitepace == false)
                    {
                        // NO whitespace!!!
                        minX = Math.Min(_x, minX);
                        maxX = Math.Max(_x, maxX);

                        minY = Math.Min(_y, minY);
                        maxY = Math.Max(_y, maxY);
                    }
                }
            }

            rect.X = minX;
            rect.Y = minY;
            rect.Width = maxX - minX;
            rect.Height = maxY - minY;
        }
        finally
        {
            if (bdActual != null)
            {
                p_img.UnlockBits(bdActual);
            }
        }
    }

    return p_img.Clone(rect, p_img.PixelFormat);
}

I hope it will be helpful for you.
this code if fast and easy to use.

Monday, August 25, 2008

Picture with transparent label


A picturebox object that supports a label (transparent).
this allow to create a piture button and add text it.
This control tested and working :)

use it with wisdom... or not:
have fun:



public class PictureText : PictureBox, ISupportInitialize
{
#region #region Private Data-Members

private string _textDisplayed = string.Empty;

private Font _textFont = new System.Drawing.Font("Arial", 10F, System.Drawing.FontStyle.Bold);

private Color _textForeColor = Color.Black;

#endregion

public string TextDisplayed
{
get { return _textDisplayed; }
set
{
_textDisplayed = value;
this.Invalidate();
}
}
public Font TextFont
{
get { return _textFont; }
set
{
_textFont = value;
this.Invalidate();
}
}
public Color TextForeColor
{
get { return _textForeColor; }
set
{
_textForeColor = value;
this.Invalidate();
}
}

//protected override void OnPaintBackground(PaintEventArgs e)
//{
// base.OnPaintBackground(e);

// //HorizontalAlignment.
// if (string.IsNullOrEmpty(TextDisplayed) == false)
// {
// e.Graphics.DrawString(this.TextDisplayed, this.TextFont, new SolidBrush(this.TextForeColor), this.Location.X, this.Location.Y);
// }
//}

protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);

if (string.IsNullOrEmpty(TextDisplayed) == false)
{
using (StringFormat sf = new StringFormat())
{
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;

e.Graphics.DrawString(this.TextDisplayed, this.TextFont, new SolidBrush(this.TextForeColor), this.Width / 2, this.Height / 2, sf);
}
}
}

#region ISupportInitialize Members
public void BeginInit()
{
}
public void EndInit()
{
}
#endregion
}




Tuesday, August 19, 2008

Validation Israel ID



try
{
string txtId = p_text.PadLeft(9, '0');

int sum = 0;
int[] arrIdDigits = new int[9];
for (int i = 0; i < arrIdDigits.Length; i++)
{
arrIdDigits[i] = int.Parse(p_text[i].ToString());

if (i % 2 != 0)
{
arrIdDigits[i] *= 2;
if (arrIdDigits[i] > 9)
{
arrIdDigits[i] = (arrIdDigits[i] % 10) + 1;
}
}

sum += arrIdDigits[i];
}

sum = (sum % 10);
if (sum == 0)
{
return true;
}
}
catch (Exception ex)
{
}

return false;

Making control RTL or LTR

As many people asked me for making rtl or ltr controls on the compactframework.
My best solution for this question is:

public const int GWL_EXSTYLE = (-20);
public const int WS_EX_LAYOUTRTL = 0x400000;
public static void SetControlDirection(Control c, bool p_isRTL)
{
int style = GetWindowLong(c.Handle, GWL_EXSTYLE);

// set default to ltr (clear rtl bit)
style &= ~WS_EX_LAYOUTRTL;

if (p_isRTL == true)
{
// rtl
style = WS_EX_LAYOUTRTL;
}

SetWindowLong(c.Handle, GWL_EXSTYLE, style);
c.Invalidate();
}


[DllImport("coredll.dll")]
static extern int GetWindowLong(IntPtr hWnd, int cmd);

[DllImport("coredll.dll")]
static extern IntPtr SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);





CE OS supported:

I tried on "Windows Mobile 6 Classic" emulator and it worked. (CE OS = 5.2)

On "Windows Mobile 5.0 Pocket PC" emulator, also worked. (CE OS = 5.1)


On "Pocket PC 2003 SE" emulator, it did NOT worked! (CE OS = 4.21)


Free Image Hosting at www.ImageShack.us

Download sample test





I hope it will be helpful for you... :)