Thursday, 27 November 2014

Listing running crontab tasks and killing them

  • ps -o pid,sess,cmd afx | grep -A20 "cron$"

3693  3693 /usr/sbin/cron
27050  3693  \_ /USR/SBIN/CRON
27055 27055      \_ /bin/sh -c /var/somescript
27058 27055          \_ /bin/sh -c /var/somescript
3706  3706 /usr/sbin/dovecot -c /etc/dovecot/dovecot.conf
3730  3706  \_ dovecot-auth
3737  3706  \_ dovecot-auth -w
902  3706  \_ imap-login
1339  3706  \_ imap-login
2398  3706  \_ pop3-login
2649  3706  \_ pop3-login
2837  3706  \_ pop3-login
2838  3706  \_ imap-login
3807  3807 pure-ftpd 


Find the process you want above 
  
  • pkill -s 27055

That's it.

Thursday, 25 September 2014

Password-less login over SSH

You can login to a remote Linux server without entering password using ssky-keygen and ssh-copy-id.

ssh-keygen creates the public and private keys. ssh-copy-id copies the local-host’s public key to the remote-host’s authorized_keys file.
ssh-copy-id also assigns proper permission to the remote-host’s home, ~/.ssh, and ~/.ssh/authorized_keys.

1, Create public and private keys using ssh-key-gen on local-host

me@local-host$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/jsmith/.ssh/id_rsa):[Enter key]
Enter passphrase (empty for no passphrase): [Press enter key]
Enter same passphrase again: [Pess enter key]
Your identification has been saved in /home/jsmith/.ssh/id_rsa.
Your public key has been saved in /home/jsmith/.ssh/id_rsa.pub.
The key fingerprint is:
33:b3:fe:af:95:95:18:11:31:d5:de:96:2f:f2:35:f9 jsmith@local-host
Step 2: Copy the public key to remote-host using ssh-copy-id

me@local-host$ ssh-copy-id -i ~/.ssh/id_rsa.pub remote-host
    me@remote-host's password:

Now try logging into the machine, with
ssh 'remote-host'"
 check in .ssh/authorized_keys

Login to remote-host without entering the password

me@local-host$ ssh remote-host
Last login: Sun Nov 15 12:22:33 2008 from 191.128.6.2

me@remote-host$   [Note: You are on remote-host here]

Sunday, 10 August 2014

Regex way of saying "search until X but not including X" is:

Regex way of saying "search until X but not including X" is:
(?:(?!X).)*
where X can be any regular expression.
This is using a lookahead assertion, more specifically a negative lookahead.  Explanation:
(?:       # Match the following any number of times: 
 (?!lazy) # (first assert that it's not possible to match "lazy" here  
 .        # then match any character  
)*        # end of group, zero or more repetitions.

Tuesday, 29 July 2014

PHP onject to array

Handy bit of PHP to convert and object to an array 
 
public function objectToArray($obj) 
{
    if(!is_array($obj) && !is_object($obj)) 
    return $obj;

    if(is_object($obj)) 
    $obj = get_object_vars($obj);

    return array_map(array($this, 'objectToArray'), $obj);
}

Wednesday, 23 July 2014

Mobile DJ site for Somerset and Bristol.

The website for Keith Hards Wedding and Mobile  DJ Somerset is now live, bookings can be made from January 2015. I will be available throughout Somerset and Bristol, have an all new setup including 8 scanner lights, Wharfedale Pro sound system and windup truss system.

Tuesday, 24 June 2014

VMware network problem after sleep and wakeup on windows

After putting your windows machine to sleep and waking up, you will most likely find that the networking no longer works. I have encountered this problem on several machines.

Not to fear I have a solution.

Create a windows batch file .bat and insert the following commands. These commands will reset the VMware network adaptor.

net stop vmnetbridge
net start vmnetbridge
pause


You will need to execute the batch file as Administrator

Wednesday, 11 June 2014

Shameless plug for my fathers online model engine store

My dad's online model engine shop nitrosteamengines.co.uk looks like it needs a bit of an update. It's time to drop oscommerce as good as it's been over the last 5/6 years!
Time to investigate Magento, OpenCart and Zen Cart to see if they will offer a better solution.

Monday, 24 February 2014

PHP Array to stdClass <–> stdClass to Array

Function to Convert stdClass Objects to Multidimensional Arrays

<?php
 
 function objectToArray($d) {
  if (is_object($d)) {
   // Gets the properties of the given object
   // with get_object_vars function
   $d = get_object_vars($d);
  }
 
  if (is_array($d)) {
   /*
   * Return array converted to object
   * Using __FUNCTION__ (Magic constant)
   * for recursive call
   */
   return array_map(__FUNCTION__, $d);
  }
  else {
   // Return array
   return $d;
  }
 }
 
?>

Function to Convert Multidimensional Arrays to stdClass Objects

<?php
 
 function arrayToObject($d) {
  if (is_array($d)) {
   /*
   * Return array converted to object
   * Using __FUNCTION__ (Magic constant)
   * for recursive call
   */
   return (object) array_map(__FUNCTION__, $d);
  }
  else {
   // Return object
   return $d;
  }
 }
 
?>

Function usage

 // Create new stdClass Object
 $init = new stdClass;
 
 // Add some test data
 $init->foo = "Test data";
 $init->bar = new stdClass;
 $init->bar->baaz = "Testing";
 $init->bar->fooz = new stdClass;
 $init->bar->fooz->baz = "Testing again";
 $init->foox = "Just test";
 
 // Convert array to object and then object back to array
 $array = objectToArray($init);
 $object = arrayToObject($array);
 
 // Print objects and array
 print_r($init);
 echo "\n";
 print_r($array);
 echo "\n";
 print_r($object);
Test output:
stdClass Object
(
    [foo] => Test data
    [bar] => stdClass Object
        (
            [baaz] => Testing
            [fooz] => stdClass Object
                (
                    [baz] => Testing again
                )

        )

    [foox] => Just test
)

Array
(
    [foo] => Test data
    [bar] => Array
        (
            [baaz] => Testing
            [fooz] => Array
                (
                    [baz] => Testing again
                )

        )

    [foox] => Just test
)

stdClass Object
(
    [foo] => Test data
    [bar] => stdClass Object
        (
            [baaz] => Testing
            [fooz] => stdClass Object
                (
                    [baz] => Testing again
                )

        )

    [foox] => Just test
)

Wednesday, 15 January 2014

Mutex's and Semaphores - The toilet Example.

Mutex:

Is a key to a toilet. One person can have the key - occupy the toilet - at the time. When finished, the person gives (frees) the key to the next person in the queue.
Officially: "Mutexes are typically used to serialise access to a section of re-entrant code that cannot be executed concurrently by more than one thread. A mutex object only allows one thread into a controlled section, forcing other threads which attempt to gain access to that section to wait until the first thread has exited from that section." Ref: Symbian Developer Library
(A mutex is really a semaphore with value 1.)

Semaphore:

Is the number of free identical toilet keys. Example, say we have four toilets with identical locks and keys. The semaphore count - the count of keys - is set to 4 at beginning (all four toilets are free), then the count value is decremented as people are coming in. If all toilets are full, ie. there are no free keys left, the semaphore count is 0. Now, when eq. one person leaves the toilet, semaphore is increased to 1 (one free key), and given to the next person in the queue.
Officially: "A semaphore restricts the number of simultaneous users of a shared resource up to a maximum number. Threads can request access to the resource (decrementing the semaphore), and can signal that they have finished using the resource (incrementing the semaphore)." Ref: Symbian Developer Library

Tuesday, 7 January 2014

Zend Framework 2 Cheat Sheet

Zend framework 2 cheat sheet

http://zendframework2.de/cheat-sheet.html
http://slides.mwop.net/2012-01-27-Zf2Workshop/Zf2Workshop.html#slide26

Zend Framework 2 Cheat Sheet


index.phpZend\ServiceManager\ServiceManagerSTARTEventManagerZend\Mvc\Service\EventMnagerFactoryModuleManagerZend\Mvc\Service\EventMnagerFactorySharedEventManagerZend\EventManager\ShareEventManagerServiceManagerConfiguration Zend\ModuleManagr\ModuleManagerZend\Loader\ModuleAutoloaderZend\ModuleManagerListener\ModuleResoverListenerloadModulesloadModule.resolveloadModules.postInvokablesFactoriesDispatchListenerZend\Mvc\DispatchListenr$defaultServiceConfiguration Module EventsDefaultListenerAggregateApplicationZend\Mvc\Service\ApplictionFactoryZend\ModuleManage\Listener\AutoloaderListenerZend\ModuleManagerListener\InitTriggerZend\ModuleManagerListener\OnBootstrapListenerZend\ModuleManage\Listener\LocatorReistrationListenerZend\ModuleManage\Listener\ConfigListenerRequestZend\Http\PhpEnvironmet\RequestZend\Mvc\Application::init()InvokablesFactoriesModuleEventonloadModulesPre()onloadModulesPost()register()__invoke()onLoadModule()__invoke()__invoke()__invoke()onLoadModule()loadModulelöst aus inloadModules()und loadModule()bindet Listenerin createService()Stellt sicher, dass dieKlasse Module automatischgeladen werden kann.Instanziert die Module.phpbasiert auf ZF2 Beta 5(c) 2012 Michael Romer http://zendframework2.de/cheat-sheet.htmlFeedback? zf2buch@michael-romer.deRuft die MethodegetAutoloaderConfig() inder Module.php auf.Ruft die Methode init() inder Module.php auf.Sorgt dafür, dass die MethodeonBootstrap() in der Module.php fürden Event "bootstrap" derApplication registiriert wird Stellt sicher, dass alle Modul-Klassen, die dasLocatorRegisteredInterface implementieren, im ServiceManager verfügbargemacht werdenonLoadModulesPost()Ruft die MethodegetConfig() derModul-Klasse auf undvereinigt alleKonfigurationen.erzeugterzeugtZend\ModuleManagerListener\ServiceListeeronLoadModulesPost()onLoadModule()Ruft ggf. die Methoden getServiceConfiguration(),getControllerConfiguration(),getControllerPluginConfiguration(),getViewHelperConfiguration() in der Module.php auf,verarbeitet die zusammengeführten Configs und konfiguriertdamit die ServiceManager und ergänzt den ServiceManager umweitere Services. ResponseZend\Http\PhpEnvironmet\ResponseRouteListenerZend\Mvc\RouteListenerViewManagerZend\Mvc\View\ViewMangerConfigurationZend\Mvc\Service\ConfigrationFactoryDependencyInjectorZend\Mvc\Service\DiFactryRouterZend\Mvc\Service\RouteractoryViewFeedRendererZend\Mvc\Service\ViewFedRendererFactoryViewFeedStrategyZend\Mvc\Service\ViewFedStrategyFactoryViewJsonRendererZend\Mvc\Service\ViewJsnRendererFactoryViewJsonStrategyZend\Mvc\Service\ViewJsnStrategyFactoryViewHelperManagerZend\Mvc\Service\ViewHlperManagerFactoryControllerPluginMangerZend\Mvc\Service\ControlerPluginManagerFactoryControllerLoaderZend\Mvc\Service\ControlerLoaderFactoryScoped ServiceManagerbootstraproutedispatch.errorMVC EventsMvcEventdispatchonRoute()Ruft den Router auf, der versucht, einepassende Route für die aufgerufene URL zuermitteln. onDispatch()Instanziert mithilfe des ContollerLoader denim Rahmen des Routings ermitteltenController.onBootstrap()löst aus in run()Bereitet den View Layer vor.renderfinishZend\Mvc\ApplicatinControllerabgeleitet von:Zend\Mvc\Controller\AbtractActionControllerdispatchlöst ausexecute()registriert in onBootstrap()RouteNotFoundStrateyZend\Mvc\View\RouteNotoundStrategieServicesSetzt den Statuscode auf 404, falls keine passendeRoute ermittelt oder kein Controller ermitteltwerden konnen und erzeugt ggf. ein speziellesViewModel für die "File-Not-Found" - Seite. prepareNotFoundViewModel()detectNotFoundError()prepareNotFoundViewModel()ExceptionStrategyZend\Mvc\View\ExceptioStrategybindet listener inbootstrap()prepareExceptionViewModel()Setzt den Statuscode auf 500, falls im MVC-Eventein Error vom Typ Application::ERROR_EXCEPTIONzu finden ist und erzeugt ein spezielles ViewModelfür die "Application Error" - Seite. DefaultRenderingStraegyZend\Mvc\View\DefaultRederingStrategyrender()Stößt das Rendering der View an.ENDEZend\Mvc\View\CreatViewModelListenerZend\Mvc\View\InjectTemplateListeneZend\Mvc\View\InjecViewModelListenerbindet Listener in onBootstrap()send()createViewModelFromArray()createViewModelFromNull()Stellt sicher, dass ein Objekt vom Typ"ViewModel" für das rendering bereitsteht.injectTemplate()Stellt sicher, dass ein Objekt vom Typ"ViewModel" für das rendering bereitsteht.Fügt das passende Template für dasRendering in das ViewModel hinzu.injectViewModel()Fügt das ViewModel dem MVC-Event hinzu.injectViewModel()ViewZend\View\ViewrendererresponseViewEventViewPhpRendererStraegyZend\View\Strategy\PhpRndererStrategyselectRenderer()injectResponse()Wählt den zu verwendenen Renderer und überträgt das Ergebnis des Rederingsvon der View in das Response-Objekt.ViewRendererZend\View\Renderer\PhpendererViewTemplateMapReolverZend\View\Resolver\ViewemplateMapResolverViewTemplatePathStakZend\View\Resolver\ViewemplatePathStackViewResolverZend\View\Resolver\AggrgateResolverFindet den Pfad zu einem Template auf Basis eineszuvor festgelegten Keys in einer Key-ValueDatenstruktur.Findet den Pfad zu einem Template auf Basis eineszuvor festgelegten Stacks vom Pfaden.Aggregiert ViewTemplateMapResolver &ViewTemplatePathStackZend Framework 2 Request Dispatch FlowÜberblick Ablauf Request-Verarbeitung1. Request wird auf index.php umgeschrieben2. index.php: 2.1 Autoloading konfigurieren2.2 application.config.php einlesen 2.3Zend\Mvc\Application::init() aufrufen, dabei Configübergeben3. Zend\Mvc\Application::init() 3.1 initialisiert den ServiceManager3.2 legt Inhalte der application.config.php als Service ab3.3 fordert beim ServiceManager den ModuleManager anund ruft dessen loadModules() - Methode auf3.4 fordert dann beim ServiceManager die Application anund ruft dessen bootstrap() - Methode auf4. index.php: 4.1 ruft Methode run() der Application auf4.2 ruft Methode send() der Application aufEinsprungpunkt für alle Requests durchEinsatz von mod_rewrite und ggf. .htaccess -File.Repräsentiert die gesamte Anwendung und istEinsprungspunkt ins Zend Framework. Bietetdie Klassenmethode init() zur Erzeugungeiniger Basisdienste.Verwaltet die Services der Anwendung.Ermöglicht die Registrierung von Listenernfür Events, wenn der eigentlich zuständigeEventManager noch nicht verfügbar ist.Verwaltet die Module derAnwendung.Erzeugt einen Service, derZugriff auf die vereinteKonfiguration bietet. Ermöglicht es einem anderen Objekte,Ereignisse auszulösen und Listener zuverwalten.ApplicationConfigurationarrayInhalt der application.config.phpServiceIdentifiersSharedEventManager:- ModuleManager- module_manager- Zend\ModuleManager\ModuleManagerIdentifiersSharedEventManager:- application- Zend\Mvc\ApplicationErzeut den ViewHelperManager, derViewHelper zur Nutzung bereitstellt.Erzeut den ControllerPluginmanager,der Controller Plugins zur Nutzungbereitstellt.Erzeut den ControllerLoader, der dieController der Anwendungbereitstellt.Diese Services stellen selbstwieder spezialisierteServiceManager dar.IdentifiersSharedEventManager:- Zend\Stdlib\DispatchableInterface-Zend\Mvc\Controller\AbstractActionController- der erste Teil desNamespaces des ControllersErzeugt aus Templates und ViewModelfinales Markup.Repräsentiert die visuelle Darstellung. create and share your own diagrams at gliffy.com