miercuri, 10 ianuarie 2018

State-of-Art Gradient Background for values in a table chart in Qlikview

I have looked very much and didn't find a solution for a gradient background for values in a table chart in Qlikview. The scope is to have values in a sorted fashion (smallest to largest), and by their position in the list, by their position away from the middle of the list, color the background of the cells with red - to - white when the values are below the middle, and white - to - green when they are above. Red is the smallest (-1 normalized) value, middle is white (0 normalized), biggest is green (1 normalized). So use the following function and logic:
Colormix2( (NoOfRows(TOTAL) - rank(OurColumnName) + 1)/ceil(NoOfRows(TOTAL)/2) - 1, red(), green(), white() )
The formula would assign the ranked position away from the middle (-1 to 1) to the current value in the list. If there are NULL's in the column, then NoOfRows(TOTAL) would perhaps render a wrong count, so use a NumericCount(aggr (... )) as in the following example:
(NumericCount(TOTAL aggr( sum( {< %year_q={$(vMaxYearQ_1)}, year={$(vGlobalYear1)} >} alt(marketing_USD,0) ) , global_brand_select ) )
That was a big search and big result!

joi, 7 septembrie 2017

Multiple Series Line Chart with PHPExcel

Below is a sample piece of script which creates a multiple lines (multi - series) chart with the PHPExcel library:


  $dataSeriesLabels = array();
  $xAxisTickValues = array();
  $dataSeriesValues = array();
  $series = array();
  $dataPointCount =  8 /* the count of datapoints: $by-2 to $by+5 inclusive */;
  for ($i=0; $i<=4; $i++)
  {
   $r = 35+$i;
   $dataSeriesLabels[$i] = new \PHPExcel_Chart_DataSeriesValues('String', $sheetTitle.'!$B$'.$r, NULL, 1);
   $xAxisTickValues[$i] = new \PHPExcel_Chart_DataSeriesValues('Number', $sheetTitle.'!$C$34:$J$34', NULL, $dataPointCount);
   $dataSeriesValues[$i] = new \PHPExcel_Chart_DataSeriesValues('Number', $sheetTitle.'!$C$'.$r.':$J$'.$r, NULL, $dataPointCount);
  }
  $series[0] = new \PHPExcel_Chart_DataSeries(
   \PHPExcel_Chart_DataSeries::TYPE_LINECHART,  // plotType
   \PHPExcel_Chart_DataSeries::GROUPING_STANDARD,  // plotGrouping
   range(0, count($dataSeriesValues) - 1),   // plotOrder
   $dataSeriesLabels,        // plotLabel
   $xAxisTickValues,        // plotCategory
   $dataSeriesValues         // plotValues
  );
  $series[0]->setPlotDirection(\PHPExcel_Chart_DataSeries::DIRECTION_HORIZONTAL);

  //  Set the series in the plot area
  $plotarea = new \PHPExcel_Chart_PlotArea(NULL, $series);
  //  Set the chart legend
  $legend = new \PHPExcel_Chart_Legend(\PHPExcel_Chart_Legend::POSITION_RIGHT, NULL, false);
  $title = new \PHPExcel_Chart_Title('');

  //  Create the chart
  $chart = new \PHPExcel_Chart(
    'chart1', // name
    $title, // title
    $legend, // legend
    $plotarea, // plotArea
    true, // plotVisibleOnly
    0, // displayBlanksAs
    NULL, // xAxisLabel
    NULL   // yAxisLabel
  );

  $chart->setTopLeftPosition('L31');
  $chart->setBottomRightPosition('AC43');
  $objWorksheet->addChart($chart);
  header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  header('Content-Disposition: attachment;filename="'.$fname.'"');
  header('Cache-Control: max-age=0');

  // Do your stuff here
  $writer = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  //PHPExcel_Writer_Excel2007
  $writer->setIncludeCharts(TRUE);


  $writer->save('php://output');

vineri, 10 martie 2017

Sample sr_feuser_register typo3 template configuration.

From http://lists.typo3.org/pipermail/typo3-english/2006-September/030773.html A sample good configuration of sr_feuser_register : # ---------- front-end user registration CONSTANTS ----------- # --- folder where FE users are contained --- plugin.tx_srfeuserregister_pi1.pid = 1826 # --- different groups: unprivilaged users --- plugin.tx_srfeuserregister_pi1.userGroupUponRegistration = 1 # --- different groups: privilaged users --- plugin.tx_srfeuserregister_pi1.userGroupAfterConfirmation = 2 # --- page ID of page with login box and FE registration (Login) -- plugin.tx_srfeuserregister_pi1.loginPID = 1822 # --- page ID of second page with FE registration (Second Page) -- plugin.tx_srfeuserregister_pi1.registerPID = 1825 # --- page ID of third page with FE registration (Third Page) -- plugin.tx_srfeuserregister_pi1.editPID = 1828 # --- page ID of fourth page with FE registration (Fourth Page) -- plugin.tx_srfeuserregister_pi1.confirmPID = 1829 plugin.tx_srfeuserregister_pi1.formFields = username, password, gender, first_name,last_name, email, address, city, zip, telephone, fax, title, company, www,module_sys_dmail_html, image, disable, comments plugin.tx_srfeuserregister_pi1.requiredFields = username,password,first_name,last_name,email,comments # ---------- front-end user registration SETUP ----------- # -------------- sr_feuser_register (start) -------------- plugin.tx_srfeuserregister_pi1 { templateFile = {$plugin.tx_srfeuserregister_pi1.file.templateFile} wrap1.wrap = {$plugin.tx_srfeuserregister_pi1.wrap1} wrap2.wrap = {$plugin.tx_srfeuserregister_pi1.wrap2} wrap3.wrap = {$plugin.tx_srfeuserregister_pi1.wrap3} color1.wrap = {$plugin.tx_srfeuserregister_pi1.color1} color2.wrap = {$plugin.tx_srfeuserregister_pi1.color2} color3.wrap = {$plugin.tx_srfeuserregister_pi1.color3} icon_delete = {$plugin.tx_srfeuserregister_pi1.file.icon_delete} pid = {$plugin.tx_srfeuserregister_pi1.pid} registerPID = {$plugin.tx_srfeuserregister_pi1.registerPID} editPID = {$plugin.tx_srfeuserregister_pi1.editPID} confirmPID = {$plugin.tx_srfeuserregister_pi1.confirmPID} confirmType = {$plugin.tx_srfeuserregister_pi1.confirmType} loginPID = {$plugin.tx_srfeuserregister_pi1.loginPID} defaultCODE = {$plugin.tx_srfeuserregister_pi1.defaultCODE} formName = {$plugin.tx_srfeuserregister_pi1.formName} onChangeCountryAttribute = {$plugin.tx_srfeuserregister_pi1.onChangeCountryAttribute} # you may modify here the conditions under which an attachment file will be added to the email addAttachment = {$plugin.tx_srfeuserregister_pi1.enableEmailAttachment} addAttachment.cmd = setfixed addAttachment.sFK = APPROVE addAttachment.file = {$plugin.tx_srfeuserregister_pi1.file.attachmentFile} create = 1 create { preview = {$plugin.tx_srfeuserregister_pi1.enablePreviewRegister} fields = {$plugin.tx_srfeuserregister_pi1.formFields} required = {$plugin.tx_srfeuserregister_pi1.requiredFields} defaultValues { redemptionCode = module_sys_dmail_html = 1 disable = {$plugin.tx_srfeuserregister_pi1.enableEmailConfirmation} } overrideValues { # usergroup = {$plugin.tx_srfeuserregister_pi1.userGroupUponRegistration} disable = {$plugin.tx_srfeuserregister_pi1.enableEmailConfirmation} processed = 0 paid = 0 } evalValues { password = twice, atLeast[{$plugin.tx_srfeuserregister_pi1.passwordAtLeast}], atMost[{$plugin.tx_srfeuserregister_pi1.passwordAtMost}] username = uniqueLocal, atLeast[{$plugin.tx_srfeuserregister_pi1.usernameAtLeast}], atMost[{$plugin.tx_srfeuserregister_pi1.usernameAtMost}] usergroup = # email = email,atMost[255],uniqueLocal email = email,atMost[255] name = atMost[{$plugin.tx_srfeuserregister_pi1.nameAtMost}] first_name = atMost[50] last_name = atMost[50] date_of_birth = date company = atMost[50] city = atMost[40] zip = atMost[20] telephone = atMost[25] fax = atMost[25] image = upload title = address = www = wwwURL payment_method = zone = pco cc_number = creditcard,atMost[20] cc_expiry = expiry,atMost[7] cc_name = atMost[255],trim cc_type = atMost[20] ach_routing = routing,atMost[9] ach_account = int,atMost[17] join_agree = referrer_uri = starttime = endtime = redemptionCode = redemptionCode tt_products = tx_securityquestion_question = int tx_securityquestion_answer = atMost[255],trim } } setfixed = {$plugin.tx_srfeuserregister_pi1.enableEmailConfirmation} setfixed.APPROVE { _FIELDLIST = uid,pid,usergroup # usergroup = {$plugin.tx_srfeuserregister_pi1.userGroupAfterConfirmation} disable = 0 } enableAutoLoginOnConfirmation = {$plugin.tx_srfeuserregister_pi1.enableAutoLoginOnConfirmation} autoLoginRedirect_url = {$plugin.tx_srfeuserregister_pi1.autoLoginRedirect_url} setfixed.DELETE { _FIELDLIST = uid,pid } authcodeFields = {$plugin.tx_srfeuserregister_pi1.authcodeFields} authcodeFields.codeLength = {$plugin.tx_srfeuserregister_pi1.codeLength} invite < .create edit < .create edit { preview = {$plugin.tx_srfeuserregister_pi1.enablePreviewEdit} defaultValues { disable = 0 module_sys_dmail_html > } overrideValues { usergroup > disable = 0 } evalValues { usergroup = unsetEmpty } } infomail = 0 forceFileDelete = {$plugin.tx_srfeuserregister_pi1.forceFileDelete} parseValues { username = nospace,trim usergroup = trim email = lower,nospace,trim password = trim,nospace name = trim first_name = trim last_name = trim date_of_birth = date title = trim company = trim city = trim zip = image = files module_sys_dmail_html = setEmptyIfAbsent www = wwwURL zone = cc_number = trim cc_expiry = cc_name = trim cc_type = trim payment_method = trim ach_routing = trim ach_account = trim join_agree = trim referrer_uri = trim starttime = trim endtime = trim redemptionCode = tt_products = tx_securityquestion_question = tx_securityquestion_answer = trim } parseFromDBValues { date_of_birth = adodb_date } parseToDBValues { date_of_birth = adodb_date } email.from = {$plugin.tx_srfeuserregister_pi1.email} email.fromName = {$plugin.tx_srfeuserregister_pi1.siteName} email.admin = {$plugin.tx_srfeuserregister_pi1.email} email.field = email email.HTMLMail = {$plugin.tx_srfeuserregister_pi1.enableHTMLMail} email.HTMLMailCSS = {$plugin.tx_srfeuserregister_pi1.HTMLMailCSS} email.CREATE_SAVED = {$plugin.tx_srfeuserregister_pi1.enableEmailOnRegister} email.EDIT_SAVED = {$plugin.tx_srfeuserregister_pi1.enableEmailOnUpdate} email.DELETE_SAVED = {$plugin.tx_srfeuserregister_pi1.enableEmailOnDelete} email.SETFIXED_APPROVE = {$plugin.tx_srfeuserregister_pi1.enableEmailOnApprove} email.SETFIXED_DELETE = {$plugin.tx_srfeuserregister_pi1.enableEmailOnRefuse} notify.CREATE_SAVED = {$plugin.tx_srfeuserregister_pi1.enableAdminNotifyOnRegister} notify.EDIT_SAVED = {$plugin.tx_srfeuserregister_pi1.enableAdminNotifyOnUpdate} notify.DELETE_SAVED = {$plugin.tx_srfeuserregister_pi1.enableAdminNotifyOnDelete} notify.SETFIXED_CREATE = {$plugin.tx_srfeuserregister_pi1.enableAdminNotifyConfirmation} notify.SETFIXED_INVITE = {$plugin.tx_srfeuserregister_pi1.enableAdminNotifyConfirmation} notify.SETFIXED_APPROVE = {$plugin.tx_srfeuserregister_pi1.enableAdminNotifyOnApprove} notify.SETFIXED_DELETE = {$plugin.tx_srfeuserregister_pi1.enableAdminNotifyOnRefuse} ccAllowedTypes = {$plugin.tx_srfeuserregister_pi1.ccAllowedTypes} tempuserTimelimit = {$plugin.tx_srfeuserregister_pi1.tempuserTimelimit} timelimit = {$plugin.tx_srfeuserregister_pi1.timelimit} enableAutoLoginTempuser = {$plugin.tx_srfeuserregister_pi1.enableAutoLoginTempuser} enableAutoLogin = {$plugin.tx_srfeuserregister_pi1.enableAutoLogin} enableCreditcardSave = {$plugin.tx_srfeuserregister_pi1.enableCreditcardSave} userGroupUponRegistration = {$plugin.tx_srfeuserregister_pi1.userGroupUponRegistration} dropFields = {$plugin.tx_srfeuserregister_pi1.dropFields} corporateGroup = 16 professionalGroup = 2 complimentaryGroup = 4 memberGroup = 1 corporateMembershipCharge = 2000 professionalMembershipCharge = 249 corporateMembershipProductID = 8 professionalMembershipProductID = 13 _CSS_DEFAULT_STYLE ( .tx-srfeuserregister-pi1 P { font-family:Verdana, sans-serif; font-size:12px; line-height:125%; color:#35006d; margin-top:8px; margin-bottom:0px; padding-top:0px; padding-bottom:0px; padding-right:3px; padding-left:3px; text-indent:0px; } .tx-srfeuserregister-pi1 A:link { background-color:transparent; color:navy; text-decoration:none; font-weight:bold;} .tx-srfeuserregister-pi1 A:visited { background-color:transparent; color:navy; font-weight:bold; text-decoration:none; } .tx-srfeuserregister-pi1 A:hover { background-color:transparent; color:#333333; text-decoration:none; } .tx-srfeuserregister-pi1 A:active { background-color:transparent; color:navy; font-weight:bold; text-decoration:none; } .tx-srfeuserregister-pi1 TD { vertical-align:top; font-family:Verdana, sans-serif; font-size:12px; line-height:125%; color:#35006d; margin-top:8px; margin-bottom:0px; padding-top:0px; padding-bottom:0px; padding-right:3px; padding-left:3px; text-indent:0px;} .tx-srfeuserregister-pi1 INPUT { font-size:10px; font-family:Verdana; background-color:#35006d; color:#ffffff; font-weight:bold; } .tx-srfeuserregister-pi1 INPUT.tx-srfeuserregister-pi1-submit { font-size:10px; font-family:Verdana; background-color:#35006d; color:#ffffff; font-weight:bold; } .tx-srfeuserregister-pi1 INPUT.tx-srfeuserregister-pi1-uploader { font-size:10px; font-family:Verdana; background-color:#35006d; color:#ffffff; font-weight:bold; } .tx-srfeuserregister-pi1 INPUT.tx-srfeuserregister-pi1-icon { font-size:10px; font-family:Verdana; background-color:transparent;} .tx-srfeuserregister-pi1 SELECT { font-size:10px; font-family:Verdana; background-color:#35006d; color:#ffffff; font-weight:bold; } .tx-srfeuserregister-pi1 TEXTAREA { font-size:10px; font-family:Verdana; background-color:#35006d; color:#ffffff; font-weight:bold; } .tx-srfeuserregister-pi1 .tx-srfeuserregister-pi1-radio INPUT { font-size:10px; font-family:Verdana; background-color:transparent; color:#35006d; font-weight:bold; vertical-align:middle; } .tx-srfeuserregister-pi1 .tx-srfeuserregister-pi1-checkbox INPUT { font-size:10px; font-family:Verdana; background-color:transparent; color:#35006d; font-weight:bold; vertical-align:middle; } ) _DEFAULT_PI_VARS { } enableCanspamLogging = {$plugin.tx_srfeuserregister_pi1.enableCanspamLogging} } # -------------- sr_feuser_register (end) --------------

marți, 7 martie 2017

Typo3 hook when user logs in

best is to have your own extension under a folder like vendor_name (notice the underscore and the camelcasing below). in your extensions ext_localconf.php, configure your hook like: // hooks when logging in $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['postUserLookUp'][] = 'VendorName\Classes\Hooks\AfterRegistrationHook->postLogin'; and our file vendor_name/Classes/Hooks/AfterRegistrationHook.php should look like:
function postLogin(&$params, &$pObj) {
  if ($pObj->loginType === 'FE' &&
            $pObj->loginFailure === false &&
            is_array($pObj->user) &&
            $pObj->loginSessionStarted === true
        ) {
   print_r($params);
   die("here we are just after the user has logged in");


        }

 }


luni, 26 septembrie 2016

What is the current mysql license, how to find it?

Hi, You're wondering how to find the current mysql license? One should just query the instance variables, it's as easy as this:
SHOW VARIABLES LIKE '%license%';
That's it! (of course one needs first to connect to the instance like : mysql -u your_username -p )

vineri, 19 august 2016

ASP Classic Recursively Delete Files (older than) and folders

In ASP Classic (VBScript), this piece of script will recursively walk through all subfolders and remove all files older than 6 hours (change it to days, weeks, months), and all empty subdirectories.



DeleteFiles("C:\cleanThisSub")

dim fso
Set fso = Server.CreateObject("Scripting.FileSystemObject")

' recursively deletes files older than 6 hours and the empty directories
Sub DeleteFiles(ByVal sFolder)
    Set folderObj = fso.GetFolder(sFolder)
    dim aFiles, aSubFolders, aSubFolders2, file, folder, folderObj2
    Set aFiles = folderObj.Files
    Set aSubFolders = folderObj.SubFolders

    For Each file in aFiles
        if ( DateDiff("s", file.DateLastModified, Now()) > 6 * 3600 ) then
            'delete files older than 6 hours
            response.write "del " & file.Path & "<br>"
            fso.deleteFile(file.Path)
        End If
    Next

    For Each folder in aSubFolders
        Set folderObj2 = fso.GetFolder(folder.Path)
        DeleteFiles(folder.Path)
        Set aFiles = folderObj2.Files
        if aFiles.Count<1 then
            set asubfolders2 = folderObj2.SubFolders
            if aSubFolders2.Count<1 then
                ' subfolder is empty, can be removed
                response.write "rmdir " & folder.Path & "<br>"
                fso.deleteFolder(folder.Path)
            end if
        end if
    Next
  
End Sub

vineri, 13 mai 2016

Windows 10 Unable to open Link in Mail

For a while now, every time i clicked a link inside any email , within the Windows 10 Mail app,
this failed with the warning 'Unable to open Link: http://... '.

After some research i've figured it is due to the fact that i stopped&disabled the windows Firewall service.
As soon as i opened services.msc , scrolled down to windows firewall, and started it - all windows 10 mail Links started opening up immediately, like magic!


Thanks Microsoft + Windows 10.
You're doing a great job.

joi, 6 august 2015

Backup Database and Website in PHP without MYSQLDUMP

On some configurations, mysqldump is not available.
So how does one backup his database without mysqldump, but only PHP at hand?

 Here is a workaround in pure PHP (just a little additional help from tar and zip - can be completely skipped). This piece of script will create its own backup directories if they don't exist (yes it needs write rights to the destination directory), get a backup of the database (in chunks, not to break or stall the database), tar-zips the backups, and the cherry on top: it will delete old files - so they don't build up to use your whole disk space.

To run it, of course you need to configure it correctly with your database name, username, password, hostname, authorization password, and perhaps the paths to the directories to the backup output files.

If you're gonna use this piece of script, please drop me a line, i'll be happy to hear about it!
 

<?php

// set up a password access - so to prevent abuses
if ( $_GET['p']=='SOMe_Str0ng_Pa55word')
{
    set_time_limit(60*6); // 6 minutes
    $dbname = 'PuT_Your_DB_Name_Here'; // like wordpress
    $user = 'PuT_Your_Username_Here'; // like root
    $pass = 'PuT_Your_Password_Here'; // like 12345
    $host = 'PuT_Your_DB_HOST_Here'; // like localhost or db.mysql.server.org
   
    // check or create directory for DB backup
    if ( !is_dir('/backup/DB') ) {
        mkdir('/backup/DB');
        chmod('/backup/DB', 0755);
    }

    // check or create directory for site backup
    if ( !is_dir('/backup/html') ) {
        mkdir('/backup/html');
        chmod('/backup/html', 0755);
    }



    /************************************
    CREATE A BACKUP OF THE DATABASE
    ************************************/
    // check if a recent backup exists and clean up old files
    $haveRecent = false;
    $dp = opendir('/backup/DB');
    while ( $fname = readdir($dp) )
    {
        if ( $fname && $fname!='.' && $fname!='..' )
        {
            if ( substr($fname, -11)=='.sql.tar.gz' && preg_match('/^[0-9]{14}_/i', $fname) && !preg_match('/[^a-z0-9\_\.]/i', $fname) )
            {
                $dt = substr($fname, 0, 8);
                if ( $dt<=date("Ymd", time()-(86400*30*2) ) )
                {
                    // delete all older than 90 days
                    @unlink('/backup/DB/'.$fname);
                }
                elseif ( (int)$dt>date("Ymd", time()-86400*15) )
                {
                    // we have a recent backup (last 15 days)
                    $haveRecent = true;
                }
               
            }
        }
    }


    //if ( !$haveRecent )
    {
        // dump the DB in the appropriate DB backup directory
        $fn = '/backup/DB/'.date("YmdHis") . '_' . $dbname . '.sql';
        $tfn = $fn . '.tar.gz';
        if ( !is_file($fn) && !is_file($tfn) )
        {
            $MB = new mysqlBackup();
            $MB->backup_tables($host, $user, $pass, $dbname, '*', $fn);
            exec('tar -czf  ' . $tfn . ' -C ' . dirname($tfn) . ' ' . basename($fn));
            @unlink($fn);
        }
    }
    /************************************
    END CREATE A BACKUP OF THE DATABASE
    ************************************/




    /************************************
    CREATE A BACKUP OF THE WEBSITE FILES
    ************************************/
    // check if a recent backup exists and clean up old files
    $haveRecent = false;
    $dp = opendir('/backup/html/');
    while ( $fname = readdir($dp) )
    {
        if ( $fname && $fname!='.' && $fname!='..' )
        {
            if ( preg_match('/^[0-9]{14}\.tar\.gz$/', $fname) )
            {
                $dt = substr($fname, 0, 8);
                if ( (int)$dt<=(int)date("Ymd", time()-(86400*30*2) ) )
                {
                    // delete all older than 90 days
                    @unlink('/backup/html/'.$fname);
                }
                elseif ( (int)$dt>(int)date("Ymd", time()-86400*15) )
                {
                    // we have a recent backup (last 15 days)
                    $haveRecent = true;
                }
            }
        }
    }



    //if ( !$haveRecent )
    {
        // dump the DB in the appropriate DB backup directory
        $fn = '/backup/html/' . date("YmdHis") . '.tar.gz';
        if ( !is_file($fn) )
        {
            exec('tar -czf ' . $fn . ' -C / html');
        }
    }
    /************************************
    END CREATE A BACKUP OF THE WEBSITE FILES
    ************************************/


}


class mysqlBackup
{
    //backup_tables('localhost','username','password','blog');

    /* backup the db OR just a table */
    function backup_tables($host, $user, $pass, $name, $tables = '*', $ofile ='')
    {
        $link = mysql_connect($host, $user, $pass) or die("could not connect");
        mysql_select_db($name, $link);
       
        //save file
        $handle = fopen($ofile, 'w');


        //get all of the tables
        if($tables == '*')
        {
            $tables = array();
            $result = mysql_query('SHOW TABLES');
            while($row = mysql_fetch_row($result))
            {
                $tables[] = $row[0];
            }
        }
        else
        {
            $tables = is_array($tables) ? $tables : explode(',',$tables);
        }


        //cycle through
        foreach($tables as $table)
        {
            $exhaustedTable = false; $iteration = 0; $pageSize = 1000; // to dump the tables in batches of 1000 lines
       
            $colsRes = mysql_query('SHOW COLUMNS FROM `'.$table.'`');
            $cols = array(); $colsStr = '';
            while ( $colRow = mysql_fetch_row($colsRes) )
            {
                $cols[] = $colRow[0];
                $colsStr.= ($colsStr!=''?',':'') . '`' . $colRow[0] . '`';
            }
            $num_fields = count($cols);
            $n1 = ($num_fields-1);


            fwrite($handle, 'DROP TABLE IF EXISTS `'.$table.'`;'. "\n");

            $row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE `'.$table.'`'));
            fwrite($handle, $row2[1].";\n");


            while (!$exhaustedTable)
            {
                $result = mysql_query('SELECT * FROM `'.$table. '` LIMIT '.($iteration*$pageSize).','.$pageSize);

                if ( mysql_num_rows($result) )
                {
                    fwrite($handle, 'INSERT INTO `'.$table.'` (' . $colsStr . ') VALUES');
                    $nc = false;

                    while($row = mysql_fetch_row($result))
                    {
                        if ( $nc )
                        {
                            fwrite($handle, ', ');
                        }

                        fwrite($handle, '(');
                        for($j=0; $j<$num_fields; $j++)
                        {
                            if ( $row[$j] === NULL )
                            {
                                fwrite($handle, 'NULL');
                            }
                            elseif ( $row[$j]==='' )
                            {
                                fwrite($handle, '""');
                            }
                            else
                            {
                                $row[$j] = mysql_real_escape_string(stripslashes($row[$j]));
                                $row[$j] = preg_replace("/\n/m","\\n",$row[$j]);
                                fwrite($handle, '"'.$row[$j].'"');
                            }
                            if ($j<$n1)
                            {
                                fwrite($handle, ',');
                            }
                        }
                        fwrite($handle, ')');
                        $nc = true;
                    }
                    fwrite($handle, ";\n");
                }
                else
                {
                    $exhaustedTable = true;
                }

                $iteration++;

            }

        }
       
        fclose($handle);
    }
}

?>

marți, 21 aprilie 2015

How to add a toolbar to your Windows 8.1 taskbar (for example, QuickLaunch)

I personally was missing in my rather new Windows 8.1, the Quick Launch Toolbar - that used to exist in older Windows versions. So i created my own, new, custom QuickLaunch toolbar. Here's how:

Basically any valid Windows folder can become a new toolbar. So all you need to do is create a folder, wherever you wish on your hard-disk, with any name of your choice. I personally went to the Documents folder (start screen, type Documents, press enter), right-clicked and created a New -> Folder, which i have named 'QuickLaunch'.

Right-Click on an empty area of your Win 8.1 taskbar. From the menu, choose Toolbars -> New Toolbar and just select the folder of your choice - in my case it was C:\Users\luciancostin\Documents\QuickLaunchToolbar

There it goes - the toolbar already appears on our taskbar. Whatever shortcuts or programs we put in there, they will be automatically displayed (here's how to create for example, a 'show desktop' icon).
For adding my Firefox icon, i've browsed to C:\Program Files (x86)\Mozilla Firefox , right-clicked on the 'firefox' program, chose 'Create shortcut' from the context-menu, cut (ctrl+x) this shortcut, and pasted it in my newly created folder.

For further customization of the toolbar (because by default, it has a rather strange appearance, showing the title, and the names of the links in here), one must:
1. unlock the taskbar: right-click your taskbar ,make sure the 'Lock the taskbar' menu item is not checked.
2. feel free to drag the margins and the whole toolbar wherever you like it, and to your preferred size.
3. right-click the toolbar for options, uncheck the 'show title' and 'show text' menu items - to get to the original 'quicklaunch' toolbar look & feel.
4. lock back the taskbar: preferably you'd want it to stay in place, so better to lock it back. Just right-click your taskbar and check the menu item 'Lock the taskbar'

That's it! :-) our new toolbar:


Re-create "Show Desktop" Icon in Windows 8.1


I'm a rather new user of Windows 8.1, and this operating system is cracking me day by day. One of the functions i miss most of older Windows versions is the "Show Desktop" icon.
Of course it exists in the lower-right corner of the taskbar, but i miss it in my 'QuickLaunch' toolbar - just as actually i missed my QuickLaunch toolbar altogether (its default appearance is quite obscure anyway). The Quick Launch toolbar doesn't exist by default in Windows 8.1 (i believe also Win 8 and Win 7).
Luckily, Win 8.1 provides a way to create custom toolbars, and i named mine exactly 'Quick Launch' (here's how to create your personal, customized win 8 "quick launch" toolbar).
And creating a "show desktop" icon is also fairly easy.

  1. Find out the path of your toolbar folder (i've mine under C:\Users\luciancostin\Documents\QuickLaunchToolbar). If you don't know where it is - just right-click your taskbar, make sure the 'Lock the taskbar' menu item is not checked. Then right-click on an empty-area of your toolbar and select "Open Folder".
  2. Open Notepad. Go to your Start screen and type "Notepad" to find and open it. Or go to Start ->Programs->Accessories->Notepad, if you have a start menu installed.
  3. Paste these contents in your new file:
    [Shell]
    Command=2
    IconFile=explorer.exe,3
    [Taskbar]
    Command=ToggleDesktop
  4.   Save your new file in the toolbar folder (found at point 1. above), with the following name: "Show desktop.scf" - use the doublequotes too - so that Notepad does not append a default .txt extension to your file and render it useless
  5. Have fun! :) Windows (at least mine) also adds the old, nice 'Show Desktop' icon to this new button :)


* The content of the file comes directly from Microsoft - more info at this link: https://support.microsoft.com/en-us/kb/190355

miercuri, 8 aprilie 2015

Git trouble on Windows with tilde filenames

I've had apparently unresolvable problems with tilde filenames .
On windows 8.1, immediately as i clone a repository to my hard drive, some filenames containing tilde (interestingly enough, not all of them) - instantly throw out an error. They immediately appear as deleted, and i cannot do anything to add them to the git index, ignore, delete from cache or whatever.

Apparently this is a fairly recent change in Git, dating since December 2014, and yes, the solution is as stated on the given link,  to configure git with the following:
 
git config core.protectNTFS false
 
As the author says, i also recommend putting it back once the files are added to the index, with: 
 
git config core.protectNTFS true
 

Here's the link to the author's reply: 
http://stackoverflow.com/questions/29294910/unable-to-add-files-with-name-containing-tilde-followed-by-a-number

sâmbătă, 14 martie 2015

Wordpress excerpt (fragment)- extragem X cuvinte din text (taiem textul la lungimea fixata)

Cateodata, in lucrul cu textul wordpress, avem nevoie sa afisam doar o parte, un fragment/excerpt - din comentariile deja selectate, sau din textul paginii (post-ului), etc. Functia potrivita pentru a taia textul la o lungime fixata (in cuvinte) este:

WP_trim_words
Ex: wp_trim_words( $comment_text, 20 /* cuvinte */, '...' )

Mai multe informatii la: http://codex.wordpress.org/Function_Reference/wp_trim_words

vineri, 13 martie 2015

ASP VBSCRIPT Regex / regexp (regular Expressions)

The RexExp Object

The RegExp object has three properties and three methods. The properties are:
  • Pattern property - holds the regular expression pattern
  • Global property - True or False (default False). If False, matching stops at first match.
  • IgnoreCase property - True or False (default True). If True, allows case-insensitive matching
The methods are:
  • Execute method - executes a match against the specified string. Returns a Matches collection, which contains a Match object for each match. The Match object can also contain a SubMatches collection
  • Replace method - replaces the part of the string found in a match with another string
  • Test method - executes an attempted match and returns True or False
To set up a RegExp object:
Dim re
Set re = New RegExp
With re
    .Pattern = "some_pattern"
    .Global = True
    .IgnoreCase = True
End With
A Pattern can be any string value. For example, if the pattern is "Hello World", the RegExp object will match that in the target string. If IgnoreCase is True, it will match any case, so "hellO wORld" would be matched. If Global is set to True, it will contine to search the string for all instances of "Hello World". If False, it will stop searching after the first instance is found.

Execute method, returning Matches collection

Dim re, targetString, colMatch, objMatch
Set re = New RegExp
With re
  .Pattern = "a"
  .Global = True
  .IgnoreCase = True
End With 
targetString = "The rain in Spain falls mainly in the plain"

Set colMatch = re.Execute(targetString)
For each objMatch  in colMatch
  Response.Write objMatch.Value & "<br />"
Next 
The above will produce a list of 5 letter a's.

Test method, returning True or False

Dim re, targetString
Set re = New RegExp
With re
  .Pattern = "a"
  .Global = False
  .IgnoreCase = False
End With
targetString = "The rain in Spain falls mainly in the plain"

re.Test(targetString)
The above will return True as soon as it hits the first instance of "a"

Metacharacters

Metacharacters are special characters that can be combined with literal characters (which is all that have been used so far) to extend the power of Regular Expressions way beyond the simple examples already seen, and are what set Regular Expressions apart from simple string functions.
Character Description
\ Marks the next character as either a special character or a literal. For example, "n" matches the character "n". "\n" matches a newline character. The sequence "\\" matches "\" and "\(" matches "(".
^ Matches the beginning of input.
$ Matches the end of input.
* Matches the preceding character zero or more times. For example, "zo*" matches either "z" or "zoo".
+ Matches the preceding character one or more times. For example, "zo+" matches "zoo" but not "z".
? Matches the preceding character zero or one time. For example, "a?ve?" matches the "ve" in "never".
. Matches any single character except a newline character.
(pattern) Matches pattern and remembers the match. The matched substring can be retrieved from the resulting Matches collection, using Item [0]...[n]. To match parentheses characters ( ), use "\(" or "\)".
x|y Matches either x or y. For example, "z|wood" matches "z" or "wood". "(z|w)oo" matches "zoo" or "wood".
{n} n is a nonnegative integer. Matches exactly n times. For example, "o{2}" does not match the "o" in "Bob," but matches the first two o's in "foooood".
{n,} n is a nonnegative integer. Matches at least n times. For example, "o{2,}" does not match the "o" in "Bob" and matches all the o's in "foooood." "o{1,}" is equivalent to "o+". "o{0,}" is equivalent to "o*".
{n,m} m and n are nonnegative integers. Matches at least n and at most m times. For example, "o{1,3}" matches the first three o's in "fooooood." "o{0,1}" is equivalent to "o?".
[xyz] A character set. Matches any one of the enclosed characters. For example, "[abc]" matches the "a" in "plain".
[^xyz] A negative character set. Matches any character not enclosed. For example, "[^abc]" matches the "p" in "plain".
[a-z] A range of characters. Matches any character in the specified range. For example, "[a-z]" matches any lowercase alphabetic character in the range "a" through "z".
[^m-z] A negative range characters. Matches any character not in the specified range. For example, "[m-z]" matches any character not in the range "m" through "z".
\b Matches a word boundary, that is, the position between a word and a space. For example, "er\b" matches the "er" in "never" but not the "er" in "verb".
\B Matches a non-word boundary. "ea*r\B" matches the "ear" in "never early".
\d Matches a digit character. Equivalent to [0-9].
\D Matches a non-digit character. Equivalent to [^0-9].
\f Matches a form-feed character.
\n Matches a newline character.
\r Matches a carriage return character.
\s Matches any white space including space, tab, form-feed, etc. Equivalent to "[ \f\n\r\t\v]".
\S Matches any nonwhite space character. Equivalent to "[^ \f\n\r\t\v]".
\t Matches a tab character.
\v Matches a vertical tab character.
\w Matches any word character including underscore. Equivalent to "[A-Za-z0-9_]".
\W Matches any non-word character. Equivalent to "[^A-Za-z0-9_]".
\num Matches num, where num is a positive integer. A reference back to remembered matches. For example, "(.)\1" matches two consecutive identical characters.
\n Matches n, where n is an octal escape value. Octal escape values must be 1, 2, or 3 digits long. For example, "\11" and "\011" both match a tab character. "\0011" is the equivalent of "\001" & "1". Octal escape values must not exceed 256. If they do, only the first two digits comprise the expression. Allows ASCII codes to be used in regular expressions.
\xn Matches n, where n is a hexadecimal escape value. Hexadecimal escape values must be exactly two digits long. For example, "\x41" matches "A". "\x041" is equivalent to "\x04" & "1". Allows ASCII codes to be used in regular expressions.
Examples
\d+ will match any digit one or more times, and is the equivalent to [0-9]+
<[^>]*> will match any html tag, and looks for an opening "<", followed by anything that isn't a closing block ">", followed finally by a closing block ">". It uses a "negative character set" [^>]

Constructing a RegExp pattern

Form input validation is a key area in which regular expressions can be used, and a common task is to validate the structure of an email address. Initially, the task needs to be broken down into its constituent rules:
  • Must have 1 or more letters or numbers
  • Can have underscores, hyphens, dots, apostrophes
  • Must have an "@" sign following this
  • First part of domain name must follow the "@", and must contain at least 3 letters or numbers
  • May contain underscore, dots or hyphen
  • Must be at least one dot, which must be followed by the TLD.
"[\w\-\'\.]+@{1}[\w\.?\-?]{3,}\.[\a-z]+" will do it, but can be improved upon depending on how specific you want to be.

SubMatches collection

There will be instances where, once a match is found, you want to extract parts of that match for later use. As an example, suppose you have an html page which contains a list of links:
<a href="somepage.asp?id=12345">Company A</a><br />
<a href="somepage.asp?id=45678">Company B</a><br /> 
<a href="somepage.asp?id=66745">Company C</a><br />
<a href="somepage.asp?id=33471">Company D</a><br /> 
<a href="somepage.asp?id=90765">Company E</a><br /> 
...
The required parts are the Company name and the id in the querystring. These need to be collected and inserted into a database, for example. The html is fed in as the strSearchOn, and the pattern uses parenthesis to search for each item - The id ([0-9]{5}), which is a 5 digit number, and ([\w\s]+) which collects a series of letters and spaces, and will stop collecting them when the opening angle bracket is reached (</a>).
Set objRegExpr = New regexp
objRegExpr.Pattern = "somepage.asp\?id=([0-9]{5})" & chr(34) & ">([\w\s]+)"
objRegExpr.Global = True 
objRegExpr.IgnoreCase = True
set colmatches = objRegExpr.Execute(strSearchOn)
For Each objMatch in colMatches
id = objMatch.SubMatches(0)
company = objMatch.SubMatches(1)
sql = "Insert Into table (idfield, company) Values (" & id & ",'" & company & "')"
conn.execute(sql)
Next 




This is just a copy from another Author's page with just so very good and easy to understand info: http://www.mikesdotnetting.com/article/24/regular-expressions-and-vbscript 
Thanks Mike

vineri, 6 februarie 2015

Google star rating microformats

Yes, it's an old situation. In the google search results, one can display rating stars below the page title.
How to do it? What does one add to the HTML code so google displays those stars?
Something like the stars rating found in this image:
   


Here is the current version, in microformat (there are also other options). Note that this code is valid for the current time-being (e.g. 2015), this has been subject of change over the years.
So here's the snippet i'm using:
<div class="hreview-aggregate">
    <span class="item">
        <span class="fn">Restaurant Italia</span>
    </span>
    <span class="rating">
        <span class="average">4,5</span> din
        <span class="best">5</span>
    </span>
    Din <span class="votes">25</span> de voturi
</div>


The code is taken from https://support.google.com/webmasters/answer/146645?hl=en


Good luck!

joi, 16 octombrie 2014

Typo3 6.1 installed , but Extension Manager crashes my Apache

I've finally got Typo3 6.1 installed on my machine, but as soon as i went to the backend section 'Extension Manager' - Apache crashed with no helpful error message or so. 
The window popping up was about Apache HTTPD Server crashed with the following messages:

Problem signature:
Problem Event Name: APPCRASH
Application Name: httpd.exe
Application Version: 2.2.21.0
Application Timestamp: 4e6a3015
Fault Module Name: php5ts.dll
Fault Module Version: 5.3.26.0
Fault Module Timestamp: 51af7101
Exception Code: c00000fd
Exception Offset: 00181e69
OS Version: 6.0.6002.2.2.0.768.3
Locale ID: 1048
Additional Information 1: f1e8
Additional Information 2: d4eb7cf28a4f910486e91a11f70d294f
Additional Information 3: 15a9
Additional Information 4: 60b89fd8e863194dd520967f621c3aa4


After a few facepalms, i've learned that the problem was described in the INSTALL file of Typo3. It was a problem due to the small Thread Stack size allocated by Windows for apache's threads by default.
I had to add these lines in my httpd.conf:
<IfModule mpm_winnt_module>
  ThreadStackSize 18388608
</IfModule>
The above sets the Thread Stack Size for about 18 MB, the original 8 MB given as sample in Typo3's Install file, was not enough.

Don't forget to restart Apache after the edit.

Good luck!

PHP OpenSSL extension not working - though i have enabled php_openssl.dll in my php.ini


Even though i had OpenSSL installed, and even enabled php_openssl.dll in my PHP installation, i still received this error from a local script.
Please note that all the following steps need to be completed:

1. Installing OpenSSL. I've done this selecting an included option of Windows Git, it came together with Git.
2. However, the path to openssl.cnf and openssl.exe need to be known. One solution is to add the paths among the Windows Environment Variables. In my Windows Vista, from the Desktop, i have to right-click 'Computer', choose 'Properties' from the menu, click on Advanced System Settings, on the Advanced Tab, clicking the 'Environment Variables' button at the bottom of the opened window.
  - I added a new entry clicking on 'New' under 'System variables'. Entered at the name: OPENSSL_CONF and at the value: C:\Program Files\Git\ssl\openssl.cnf (choose the path corresponding to your openssl.cnf file)
  - Appended the openssl.exe path to my PATH System Variable. Found the variable PATH in the System Variables window, and appended to it: ;C:\Program Files\Git\bin (please note the semicolon and the path to openssl.exe - you must type the path corresponding to your particular installation)
3. Enable the extension openSSL in PHP.
  - Open php.ini, find the line:
    ;extension=php_openssl.dll
  - Uncomment the line by removing the semicolon at the beginning.
  - If this line does not exist, please check your Start->Settings->Control Panel->Programs & Features->PHP(x.x.x) - click on 'Change', again on 'Change' and see if this extension exists and is selected to be installed - at the third or fourth screen within the Change features of this PHP values. Check it and install it if necessary.
4. And finally, if PHP is installed as an Apache module (my configuration is PHP 5.3.6 as PHP module in Apache 2.2) - restart your web (apache) server.

miercuri, 28 mai 2014

Wkhtmltopdf on Windows: The input line is too long

Trying to run wkhtmltopdf from within PHP, on Windows.
While on Linux, the same command used to run perfectly, on Windows I've been getting:
The input line is too long

I've found some answers and this workaround worked for me too:
Placing my command within a temporary .bat file, executing it and removing it afterwards.
For example:
$myLongCMD = '"C:\program files (x86)\wkhtmltopdf\wkhtmltopdf.exe" -d 600 --margin-bottom 24 --margin-left 0 --margin-right 0 --margin-top 13  --orientation Landscape --page-size A4 "E:\www\tmp\1003832673.html" --footer-html "E:\www\tmp\1957525255.html" --footer-html "E:\www\tmp\2038722390.html" "E:\www\tmp\2082679417.html" --footer-html "E:\www\tmp\2038722390.html" "E:\www\tmp\output.pdf"';

$tmpf = 'D:\\www\\myfile.bat';
$tmpp = fopen($tmpf,'w');
fwrite($tmpp, $myLongCMD);
fclose($tmpp);

$descriptors = array(
    0 => array("pipe", "r"), // stdin
    1 => array("pipe", "w"),  // stdout
    2 => array('pipe', 'a') // stderr - Open this as 'Append' as stream_get_contents gets blocked infinitely and the process never ends just as Luceo (many thanks to him) mentions here: http://www.php.net/manual/en/function.proc-open.php
);


$proc=proc_open('"'.$tmpf.'"', $descriptors, $pipes);
fwrite($pipes[0],$input);
fclose($pipes[0]);
$stdout=stream_get_contents($pipes[1]);
fclose($pipes[1]);
$stderr=stream_get_contents($pipes[2]);
fclose($pipes[2]);
$rtn=proc_close($proc);

@unlink($tmpf);


System config:
PHP ver 5.3.9 , Apache 2.4.9, Windows 2008 x64

joi, 18 iulie 2013

Installing typo3 on windows. try 281039

Reasons for which i hate typo3:

It's the millionth try for me to install typo3 on windows. I think i've managed a couple of times, but then i backed up because of the difficulty in using it.

This time i think i have a new version (dated 2013), so there are NEW installation problems.

Here is a sample: excerpt from the installation instructions that came with it:
On Windows Vista or Windows 7 create a symbolic link named typo3_src
pointing to the source package:
    mklink /D C:\<dir>\typo3_src-4.6.0 C:\<dir>\example.com\typo3_src


Well, how can i put this..? NO!
It just doesn't work like that because the syntax is vice-versa:
MKLINK /D Link Target

        /D      Creates a directory symbolic link.  Default is a file
                symbolic link.
        Link    specifies the new symbolic link name.
        Target  specifies the path (relative or absolute) that the new link
                refers to.



How can one release such a package when this kind of basic information is wrong? I can't even get past the installation point, having this in mind, what kind of problems can one expect when inside?

Just a side-note, it's the third try only today. Cause i've tried different packages and i just couldn't get it to work.

luni, 1 iulie 2013

How to include a php file in typo3

From your typo3 backend, choose from the left menu: Web/Template/Setup section or Web /Template/ Your extension / Setup
And add the following line (change the path to your corresponding file) in the 'setup' section of your template record:

config.includeLibrary = fileadmin/lib/file.inc.php

You can read more here:
http://typo3.org/documentation/document-library/references/doc_core_tsref/current/