Monty Hall Problem in PHP

November 23, 2016
define('HAS_PRICE', true);
define('HAS_NO_PRICE', false);
$tries    = 0;
$won      = 0;
$wonFirst = 0;
$i        = 0;
$pick     = 0;

/**
 * Bottom line, you play against being wrong the first time
 */
while (++$i <= 100000) {
    $scenario = [HAS_NO_PRICE, HAS_NO_PRICE, HAS_NO_PRICE];
    /**
     * Set random scenario element to true
     */
    $scenario[mt_rand(0, 2)] = HAS_PRICE;

    /**
     * First pick - 1 in 3
     */
    $pick = mt_rand(0, 2);
    if ($scenario[$pick] === HAS_PRICE) {
        $wonFirst++;
    } else {
        $won++;
    }

    $tries++;
}

echo 'Won: ' . $won . ' from ' . $tries . ' = ' . ($won / $tries) . '% and first pick won ' . $wonFirst . ' ' . ($wonFirst / $tries) . '%' . PHP_EOL;

Won: 66780 from 100000 = 0.6678% and first pick won 33220 0.3322%

HTTP Request showing progress on background task without ajax

November 17, 2016

The idea: show progress for process that is running in the background
Execution: takes advantage of the fact that JavaScript is loaded in parallel

ignore_user_abort();
set_time_limit(3600);
session_write_close();
@ob_end_clean();
@ob_end_flush();
@header('Content-Encoding: text/html');

echo 'I am doing some very very very long job 
'; $taskId = uniqueId(); touch($taskId); echo ''; echo 'Doing it '; while (file_exists($taskId)) { echo '|'; sleep(5); } echo '
'; /** * Job done, do something else */

P.S. Dont forget to unlink the file when the background task is done

Simple as that.

How to solve VR moving ? #E3onTwitch

June 13, 2016

So, I am watching some TotalBiscuit’s E3 Snarkathon VR Killing Floor… whatever

The idea, consoles have solved the moving by having 2 sticks on the controller (I hope am right about that), so lets have 2 sticks on VR, wait this is bullshit, you will say?

Well may be, we already have the right stick by moving your head, the only question is how to make the left stick?

Do it like:

1. Make the chair you are sitting on detect movement, the way to image it like you are sitting on the left controller stick, which will move you through your experience by bending the chair in the 4 directions. YOU better add sensitivity calibration all right?

2. May be a cheaper way, using your right leg to move forward, backward, left leg moving left and right or using just one leg doing all the movement. This will allow me do lay on my couch, niceee.

 

I don’t have third solution, but think of the controller sticks when trying to solve this problem.

 

simple as that :)

PHP Games – Solution to The Impossible Bet

April 8, 2016

/**
 * 100 people put a number in box.
 * every one must find his box within 50 tries
 */
$allTries = 100000;
$usedTries = $allTries;
$players  = 50;
$tries    = 25;
$settings = [];
$people   = [];
for ($i = 0; $i < $players; $i++) {
    $settings[$i]  = $i;
    $people[$i]    = $i;
}

$mostPeopleWon = 0;
while (--$usedTries >= 0) {
    $boxes = $settings;
    shuffle($boxes);

    $peopleWon = 0;
    for ($p = 0; $p < $players; $p++) {

        $personBoxes = $boxes;
        $started     = false;
        $won         = false;
        for ($t = 0; $t < $tries; $t++) {
            if ($started === false) {
                $num     = array_rand($personBoxes, 1);
                $started = true;
            }

            $value = $personBoxes[$num];
            unset($personBoxes[$num]);

            if ($value === $people[$p]) {
                $won = true;
                unset($boxes[$num]);
                break;
            } elseif (!array_key_exists($value, $personBoxes)) {
                $started = false;
            } else {
                $num = $value;
            }
        }

        if($won) {
            $peopleWon++;
        } else {
            break;
        }
    }
    
    if ($peopleWon > $mostPeopleWon) {
        $mostPeopleWon = $peopleWon;
    }
    
    if ($mostPeopleWon >= $players) {
        var_dump('game won in ' . ($allTries - $usedTries) . ' games');
        exit;
    }
}

var_dump('game lost. most people won ' . $mostPeopleWon);

Zf2 Naviagation Custom Active Page

October 31, 2015

Zf2 Naviagation Custom Active Page
Call in layout/view

$nav = $this->navigation('Navigation');
$pages = $nav->getContainer()->getPages();
foreach ($pages as $page) {
    if ($page->getId() == 'admin') {
            $page->setActive(true);
    }
}

Set php error_log dynamicaly in .htaccess

September 20, 2015

1. Open your .htaccess file and add this lines to be bottom.
2. Create your php.error.log file.

php_value log_errors 1
php_value error_log ./php.error.log

If your file is still empty, add in your php

error_reporting(E_ALL);

Simple as that

Zf2 Doctrine 2 Log Every Entity Change

September 18, 2015

In this article I will show a simple way to log every change to doctrine 2 entity.
This one will not be copy / paste. Just check out the code and help yourself.

1. Create event service

/**
 * @developer Ivan Gospodinow
 */

namespace Application\Service;

use Application\Entity\DbLogEntity;
use Application\Entity\AbstractEntity;
use Doctrine\Common\Persistence\Event\LifecycleEventArgs;
use \DateTime;

class DoctrineLogChangesService
{

    /**
     * Hold the changes
     * @var type
     */
    protected static $rows = [];
    protected $sm;
    protected $disabled = [
        //'Application\Entity\UserEntity',
    ];

    public function __construct($sm)
    {
        $this->sm = $sm;
        $sm->get(‘Application’)
                ->getEventManager()
                ->attach(‘finish ’, [$this, 'flush']);
    }

    public function flush()
    {
        $orm = $this->sm->get(‘doctrine.entitymanager.orm_default’);

        foreach (self::$rows as $row) {
            $orm->persist($row);
        }
        if (!empty(self::$rows)) {
            $orm->flush();
        }
    }

    public function getUnitOfWork()
    {
        return $this->sm->get(‘doctrine.entitymanager.orm_default’)->getUnitOfWork();
    }

    public function getEntityTableName(LifecycleEventArgs $args)
    {
        $meta = $args->getObjectManager()->getClassMetadata(get_class($args->getObject()));
        return $meta->table['name'];
    }

    public function getEntityFields(LifecycleEventArgs $args)
    {
        $meta = $args->getObjectManager()->getClassMetadata(get_class($args->getObject()));
        $fields = [];
        foreach ($meta->fieldMappings as $field) {
            $fields[$field['fieldName']] = $field['columnName'];
        }

        foreach ($meta->associationMappings as $field) {
            if (isset($field['sourceToTargetKeyColumns'])) {
                $fields[$field['fieldName']] = key($field['sourceToTargetKeyColumns']);
            }
        }

        return $fields;
    }

    /**
     * Adds all initial fields
     * @param LifecycleEventArgs $args
     * @return type
     */
    public function postPersist(LifecycleEventArgs $args)
    {
        $entity = $args->getObject();
        if (in_array(get_class($entity), $this->disabled)) {
            return;
        }

        $tableName = $this->getEntityTableName($args);
        $fields = $this->getEntityFields($args);

        foreach ($fields as $field => $column) {
            $value = call_user_func_array([$entity, 'get' . ucfirst($field)], []);
            $row = [
                'user' => $this->sm->get('User')->getId(),
                'table' => $tableName,
                'pk' => $entity->getId(),
                'column' => $column,
                'oldValue' => null,
                'newValue' => $value instanceof AbstractEntity ? $value->getId() : $value
            ];
            $log = new DbLogEntity();
            $log->exchangeArray($row);
            self::$rows[] = $log;
        }
    }

    /**
     * Add only new changes
     * @param LifecycleEventArgs $args
     * @return type
     */
    public function preUpdate(LifecycleEventArgs $args)
    {
        $entity = $args->getObject();
        if (in_array(get_class($entity), $this->disabled) || !$entity->canUseLifecycleEvents()) {
            return;
        }

        $tableName = $this->getEntityTableName($args);
        $fields = $this->getEntityFields($args);
        $set = $this->getUnitOfWork()->getEntityChangeSet($entity);
        foreach ($set as $property => $changes) {
            $oldValue = $changes[0];
            $newValue = $changes[1];
            if ($changes[0] instanceof AbstractEntity || $changes[1] instanceof AbstractEntity) {
                if ($changes[0] instanceof AbstractEntity) {
                    $oldValue = $changes[0]->getId();
                }
                if ($changes[1] instanceof AbstractEntity) {
                    $newValue = $changes[1]->getId();
                }
            }

            if ($oldValue == $newValue) {
                continue;
            }

            $row = [
                ‘user’ => $this->sm->get(‘User’)->getId(),
                ‘ table’ => $tableName,
                ‘ pk’ => $entity->getId(),
                ‘ column’ => $fields[$property],
                ‘ oldValue’ => $this->getStringValue($oldValue),
                ‘ newValue’ => $this->getStringValue($newValue)
            ];

            $log = new DbLogEntity();
            $log->exchangeArray($row);
            self::$rows[] = $log;
        }
    }

    public function getStringValue($value)
    {
        if (is_scalar($value)) {
            return $value;
        }

        if ($value instanceof DateTime) {
            return $value->format('Y-m-d H:i:s');
        } elseif (is_array($value)) {
            return serialize($value);
        }

        return $value;
    }

}

2. Add the event service to Doctrine 2

/**
 * @developer Ivan Gospodinow
 */

namespace Application;

use Zend\Mvc\MvcEvent;

class Module
{

    public function onBootstrap(MvcEvent $e)
    {
        $application = $e->getApplication();
        $sm = $application->getServiceManager();
        $doctrineEntityManager = $sm->get('doctrine.entitymanager.orm_default');
        $doctrineEventManager = $doctrineEntityManager->getEventManager();
        $doctrineEventManager->addEventListener(
            [
                \Doctrine\ORM\Events::postPersist,
                \Doctrine\ORM\Events::preUpdate,
            ],
            new Service\DoctrineLogChangesService($sm)
        );
    }
}

3. DbLogEntity

/**
 * @developer Ivan Gospodinow
 */

namespace Application\Entity;

use Doctrine\ORM\Mapping as ORM;
use \Exception;

/**
 * @ORM\Table(name="__dblog")
 * @ORM\Entity()
 */
class DbLogEntity
{

    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer", name="id")
     */
    protected $id;

    /**
     * @ORM\Column(type="string", name="user_id")
     */
    protected $user;

    /**
     * @ORM\Column(type="string", name="table_name")
     */
    protected $table;

    /**
     * @ORM\Column(type="integer", name="pk")
     */
    protected $pk;

    /**
     * @ORM\Column(type="string", name="column_name")
     */
    protected $column;

    /**
     * @ORM\Column(type="string", name="old_value")
     */
    protected $oldValue;

    /**
     * @ORM\Column(type="string", name="new_value")
     */
    protected $newValue;

    /**
     * @ORM\Column(type="datetime", name="timestamp")
     */
    protected $timestamp;

}

Simple as that.
Suggestions or problems ? Write a comment.

Zend Framework 2 change layout for ajax requests

September 15, 2015

How to change layout for ajax requests in Zend Framework 2

1. Module.php

    public function onBootstrap(MvcEvent $e)
    {
        $e->getApplication()
          ->getEventManager()
          ->getSharedManager()
          ->attach(
              'Zend\Mvc\Controller\AbstractController',
              'dispatch',
              function ($e) {
                  $controller      = $e->getTarget();
                  if ($controller->getRequest() instanceof HttpRequest) {
                    if ($controller->getRequest()->isXmlHttpRequest()) {
                          $controller->layout('layout/ajax');
                    }
                  }
              },
              100
          );
    }

2. module.config.php Add the layout path

    'view_manager' => array(
        'template_map' => array(
            'layout/ajax' => __DIR__ . '/../view/layout/layout.ajax.phtml',
        ),
    ),

Creating issues in Jira for multiple users with Jira API

September 12, 2015

1. Creating Jira issue

   $jiraUsername = 'Jira login username';
   $jiraPassword = 'Jira login password';
   $jiraHost     = 'http://my-jira-host.com/';
   $data = array(
        'fields' => array(
            'project' => array('key' => 'PR'/* Project Key*/),
            'summary'=> 'Issue title',
            'description' => 'Some text here, no html tags',
            'labels' => array('API', 'IvanGospodinow'/* Put the username so you know which one added it */),
            'issuetype' => array('id' => 1 /* or similar */)
        )
    );

    $ch = curl_init();
    $headers = array(
        'Accept: application/json',
        'Content-Type: application/json'
    );
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_VERBOSE, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_URL, $jiraHost . 'rest/api/2/issue/');
    curl_setopt($ch, CURLOPT_USERPWD, "$jiraUsername:$jiraPassword");
    $response = curl_exec($ch);
    $error = curl_error($ch);
    if (!empty($error)) {
        throw new Exception('EQ Error: ' . $error);
    }
    curl_close($ch)

2. Getting all issues for user

        $ch = curl_init();
        $headers = array(
            'Accept: application/json',
            'Content-Type: application/json'
        );
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_VERBOSE, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_URL, $jiraHost . 'rest/api/2/search?jql=' . urlencode('labels in (API, 'IvanGospodinow')'));
        curl_setopt($ch, CURLOPT_USERPWD, "$jiraUsername:$jiraPassword");
        $response = curl_exec($ch);
        curl_close($ch);

Simple as that.

Zend Framework 2 load multiple config files from Module

September 7, 2015

Module.php

    public function getConfig()
    {
        return
        (include __DIR__ . '/config/module.config.php')
        +
        (include __DIR__ . '/config/module.config.permissions.php');
    }

Simple as that.

 
Powered by Wordpress and MySQL. Theme by Shlomi Noach, openark.org