php-frontend-developer-test-v2-answer

php-frontend-developer-test-v2-answer

Fantastic three sequence

The fantastic three sequence is a series of numbers in which each subsequent number is the sum of the previous three,minus one. The first few numbers in fantastic three sequence are:

0, 1, 1, 1, 2, 3, 5, etc

Write a function that prints the Nth number in the fantastic three sequence to standard output.

<?php

function fantastic3($n) {

$series = array(0,1,1,1);

for($i=3 ; $i<=$n ; $i++){

$a = (isset($series[ (int)$i-3 ]))?$series[ (int)$i-3 ]:0;

$b = (isset($series[ (int)$i-2 ]))?$series[ (int)$i-2 ]:0;

$c = (isset($series[ (int)$i-1 ]))?$series[ (int)$i-1 ]:0;

$d = ($a+$b+$c)-1;

if($d<0){

$d = 0;

}

$series[$i] = $d;

}

echo $series[ (int)$n-1 ];

}

// Do NOT call the fantastic3 function in the code

// you write. The system will call it automatically.

?>



Question 2 of 4

Counts Days

Write a function named countDays which takes a single parameter named dateinstring which is string in the form ”MM.DD.YYYrepresent a real date value. The function should print to the console the number of days from the beginning of the year specified in dateInString until the date represented in dateInString. If the value of dateInString is invalid, the function should print ”Bad format” to the console.

Ans:

  1. function countDays($dateInString)
  2. {
  3. $data = explode(‘.’, $dateInString);
  4. $begining = date_create($data[2] . ‘-01-01’);
  5. $data = date_create($data[2] . ‘-‘ . $data[0] . ‘-‘ . $data[1]);
  6. $interval = $data->diff($begining);
  7. echo $interval->format(‘%R%a days’);
  8. }


Change Nickname

The following from enable user to change their nickname on their website.

 

ANS

  1. <?php

    function changeNickname($oldNickname, $newNickname, $users) {

    <?php

    function changeNickname($oldNickname, $newNickname, $users){

    $valid = preg_match(‘/^(([^0-9])+([A-Za-z0-9$#<>-_]+))$/i’, $newNickname, $matches);

    if($valid == true){

    $old_found = false;

    $new_exists = false;

    foreach($users as $id => $user){

    if($user[‘nickname’] == $oldNickname){

    $old_found = true;

    }

    if($user[‘nickname’] == $newNickname){

    $new_exists = true;

    }

    }

    if($old_found == true && $new_exists == false){

    echo ‘Your nickname has been changed from ‘.$oldNickname.’ to ‘.$newNickname;

    } else {

    echo ‘Failed to update’;

    }

    } else {

    echo ‘Failed to update’;

    }

    }

    }

    // Do NOT call the changeNickname function in the code

    // you write. The system will call it automatically.

    ?>



 

Question 4 of 4

Calculate shipping fees

A script is required to calculate shipping fees for a store.the store has two types of shipping local shipping and international shipping. they are calculated according to the following formulas.

Local shipping: number of items * distance * .8

international shipping : number of items * ( local distance * .8 + international distance * 1.2)

Ans:

<?php

// Do not modify the Shipping class.

abstract class Shipping

{

private $_itemsCount;

private $_distance;

public function __construct($itemsCount, $distance)

{

$this->_itemsCount = $itemsCount;

$this->_distance = $distance;

}

abstract public function getFees();

public function getDistance()

{

return $this->_distance;

}

public function getItemsCount()

{

return $this->_itemsCount;

}

}

// You can modify code below this comment.

class InternationalShipping extends Shipping

{

private $_internationalDistance;

public function __construct($itemsCount, $distance, $internationalDistance){

parent::__construct($itemsCount, $distance);

$this->_internationalDistance = $internationalDistance;

}

public function getFees(){

$no_of_items = $this->getItemsCount();

$local_distance = $this->getDistance();

$international_distance = $this->_internationalDistance;

$fees = $no_of_items * ($local_distance * 0.8 + $international_distance * 1.2);

return $fees;

}

}

class LocalShipping extends Shipping

{

public function getFees(){

$no_of_items = $this->getItemsCount();

$local_distance = $this->getDistance();

$fees = $no_of_items * $local_distance * 0.8;

return $fees;

}

}

function calculateShippingFees($items) {

// To print results to the standard output you can use print

// Example:

// print “Hello world!”;

$total = 0;

foreach ($items as $key => $object) {

# code…

if($object instanceof InternationalShipping || $object instanceof LocalShipping){

$total += $object->getFees();

} else {

$total = 0;

break;

}

}

echo $total;

}

// Do NOT call the calculateShippingFees function in the code

// you write. The system will call it automatically.

?>

 

Image cannot be displayed on Website

image cannot be displayed on Website because it contains errors when upload filezilla

 

File is there in server but images cannot display due to various reasons.

  1. check .htaccess file url rewrite or any permission/restrictions etc.
  2. upload any png image and try to open it browser using direct path to ur png file. such ashttp://localhost/images/test.png (if it works fine, it means your apache process your png successfully fully)
  3. check if you have created any symbolic link your images directory in your previous server(host).
  4. check your directory permissions.
  5. clear your browser cache.
  6. check your appach virtual host file httd.conf in your preivous host. may be previous there has been created some alias or something like that. httpd.conf: …
  7. <VirtualHost www.mydomain.com:80>
  8. ServerAdmin hostmaster@www.mydomain.com
  9. DocumentRoot /home/www/www.mydomain.com/htdocs
  10. ScriptAlias /cgi-bin/ /home/www/www.mydomain.com/cgi-bin/
  11. ServerName www.mydomain.com
  12. Alias /images/ /home/www/www.mydomain.com/images/
  13. Alias /pictures/ /home/www/www.mydomain.com/upload/
  14. Alias /errors/ /home/www/www.mydomain.com/errors/
  15. Alias /catalog/ /home/www/www.mydomain.com/catalog/
  16. ErrorLog /home/www/www.mydomain.com/logs/error_log
  17. CustomLog /home/www/www.mydomain.com/logs/access_log
  18. ScriptLog /home/www/www.mydomain.com/logs/script_log
  19. ErrorDocument 403 /errors/403.html
  20. ErrorDocument 404 /errors/404.html
  21. ErrorDocument 500 /errors/500.html
  22. </VirtualHost>

 

 

  1. If your image is a real one: maybe the image was broken during the FTP transfer

Make sure that your Filezilla is in Auto mode.

Go to transfer and you will see transfer type make it auto mode

How to create and add Alexa ranking widget in your website or blog

The two main factors that decides your website’s popularity isAlexa rank and Google Page rank which we have discussed earlier. Alexa shows the information for every websites globally, so adding your website details in Alexa is a good idea. Just a few posts back we have discussed that too about claiming and submitting your site in Alexa. Here we will see how to create and add Alexa ranking widget in your website or blog.

So why is Alexa rank important? Alexa shows the global traffic rank for a website and it is a competitive intelligence tool that is used to measure and compare your website with competitors. The ranking number helps advertisers to analyze the marketing capacity of your website. If you have a good ranking in Alexa then these advertisers will be ready to buy an ad space on your website for a really high price.

There are several strategies to increase your blog rankings in Alexa and one that quite helps to boost your ranking is by adding Alexa ranking widget. For Bloggers and webmasters, Alexa offers a widget which you can add it in your blog. By embedding the Alexa widget your site visitors will have a quick look at your website rank. If your website has a good ranking in Alexa then place this widget and show off your rank. Creating and adding Alexa ranking widget is very simple; here is how you do it.

How to create and add Alexa ranking widget in your website or blog

Head to Alexa >> Site owners >> widgets and you will see three different widgets that is Alexa site status button which shows your website rank with total number of links. The second one isAlexa traffic rank button which simply shows your site rank and the last one is Alexa traffic graph. Alexa offers these gadgets in three different sizes. Just enter your website name, click on build widget, choose the widget size, grab the HTML code and then paste it in your website.

Here are the Alexa widget codes for different sizes.

Alexa site status button

120 x 95

1 <a href="http://www.alexa.com/siteinfo/chandandubey.com"><script type="text/javascript" src="http://xslt.alexa.com/site_stats/js/s/a?url=chandandubey.comm"></script></a>

120 x 240

1 <a href="http://www.alexa.com/siteinfo/chandandubey.com"><script type="text/javascript" src="http://xslt.alexa.com/site_stats/js/s/b?url=chandandubey.com"></script></a>

468 x 60

1 <a href="http://www.alexa.com/siteinfo/chandandubey.com"><script type="text/javascript" src="http://xslt.alexa.com/site_stats/js/s/c?url=chandandubey.com"></script></a>

How to add Alexa ranking widget in Blogger, Alexa site rank widget

Alexa traffic rank button

120 x 65

1 <a href="http://www.alexa.com/siteinfo/chandandubey.com"><script type="text/javascript" src="http://xslt.alexa.com/site_stats/js/t/a?url=chandandubey.com"></script></a>

120 x 90

1 <a href="http://www.alexa.com/siteinfo/blogtimenow.com"><script type="text/javascript" src="http://xslt.alexa.com/site_stats/js/t/b?url=blogtimenow.com"></script></a>

468 x 60

1 <a href="http://www.alexa.com/siteinfo/chandandubey.com"><script type="text/javascript" src="http://xslt.alexa.com/site_stats/js/t/c?url=chandandubey.com"></script></a>

Alexa rank status widget for wordpress and Blogger, Alexa widets

In all the above codes just replace chandandubey.com with your website name. That’s it!

Smart-export-import-opencart-1.5.5.1

Smart-export-import-opencart to Excel the whole data for all your products, including Category / Optionsthe feature1.The Smart Export/Import Tool allows to incremental import/export( Continuous import your product’s data with Excel file one by one)
2.new data will be inserted. old data is still there,exist data is will modify
3.of all the categories, all message of products , and product options to an Excel spreadsheet file.
4.The spreadsheet file can be edited offline and then be re-imported to the OpenCart database.
5.if system product is exist the excel,it will modify your system product’s message.
if system product is not exist the excel,it will add the product’s message to your system
6.you can batch modify your product data ,Such as price or quantity or model or points or seo_keyword or description etc,all the product’s
7.you can export the product’s by product_id ,begin product_id and end product_id
8.you can export the product’s by batch too
9.the program dont delete your system data,your product’s data is secure

buynowbigbtnquestion:
==========
I have solved this problem
Fatal error: Allowed memory size of 67108864 bytes exhausted (tried to allocate 106 bytes)Installation
============

1)
install the vqmod mod

2)
Upload the folders ‘admin’, ‘system’, ‘vqmod’ and their files
from the ‘upload’ directory to your OpenCart root directory. Do not overwrite any files.

How to use:
============
login your store with admin then
1.system -> users -> user group – > select top administrator -> select all -> save

2.back your database use System -> Backup/Restore

3.system -> SmartExportImport

How to obtain the sample
=================
You can export EXCEL, this file is an example,
you can modify and add new products in the excel,
if you want to add a product, need to add a new product ID and information in excel,
if you want to modify the products, please find the corresponding product ID ,it can be modified.
then upload the excel to system by smart export import

enjoy now

these is very simple ,so you do not need the demo website:)

question:
There are several reasons can cause you don’t see this function Smart Export/Import
1, you modify the the path of admin, such as admin modified myadmin
2, you modify adminviewtemplatecommonheader.tpl
3, you use other plugins, compatibility (this can send e-mail to tell me you website admin and ftp info)
4, you do not have installed vqmod or it is not working properly

buynowbigbtn

Returning a list of array keys in MongoDB

Here’s how I return a list of keys from an associative array (i.e. an embedded document) without also returning their value.

The data structure I have is shown below. It’s made up of an associative array [friends], which contains a set of keys (Twitter usernames) and values (details about the user). My aim was to return a list of the Twitter usernames, without all of the details associated to them which – in some cases – could be quite a large amount of data.

[friends] => Array (
[RockSugarBand] => Array (
[realName] => Rock Sugar
...
)
[twitterapi] => Array (
[realName] => Twitter API
...
)
[biz] => Array (
[realName] => Biz Stone
...
)
)

I solved this using MongoDB’s ‘Group’ function. The JavaScript command is:

1
2
3
4
5
6
7
8
9
10
11
12
13
db.users.group(
{
cond: {_id:ObjectId('4c3c32c24b065884c53f35bb')},
initial: { results: [] },
reduce: function(obj,prev)
{
for(var key in obj.friends) {
prev.results.push(key);
}
}
}
);

What this essentially does is:

  • Line 3 – Here I specify the document I want to apply the group function to. In my case I just want to return a list of keys from a specific document, thus I identify it using its document id.
  • Line 4 – I create an empty array – results – into which the keys are added.
  • Line 5 – Here I start to define the reduce function. It takes two arguments.
    • obj – The current document (In my case there is only one).
    • prev – This object contains all the variables defined on Line 4. In this case that’s just results.
  • Line 7 – Here I iterate over all the keys in the [friends] array. Note that in JavaScript the <var foo> in <array bar> structure results in foo containing the key.
  • Line 8 – I simply push the key – key – onto the results array.

…and that’s it! The result looks like:

Array (
[results] => Array (
"RockSugarBand",
"twitterapi",
"biz"
)
)

The reason that results is wrapped in an array is that the function will return one results array per Document iterated over. In my case that’s just one, but had I used a condition that returned more documents, they would all be included within this wrapping array.

Doing this in PHP

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Use all fields
$keys = array();
// Set initial values
$initial = array("results" => array());
// JavaScript function to perform
$reduce = new MongoCode('function(obj,prev)
{
for(var key in obj.friends) {
prev.results.push(key);
}
}');
// The condition on which a document must match in order to be processed
$condition = array('_id' => $userDocId);
// Execute the query
$result = $collection->group($keys, $initial, $reduce, $condition);

Things to note:

  1. According to the MongoDB documentation, the group function does not work in a sharded environment.
  2. This query can’t use any indexes, with the exception of finding the document set to iterate over, i.e. the query defined under “cond“. For my problem this isn’t likely to ever become an issue, but it might if you start iterating over a large number of documents.

This is just how I solved it. There may well be better solutions. If you know of one, please feel free to share it with us all. 🙂

Adding my “3rd party” module into /vendor in Zend Framework

This wasn’t initially obvious to me, but when creating a generic module to use across multiple Zend Framework 2 projects (thus putting it in /vendor) you can include a Module.php file in the root of the module’s directory to make registering the namespace with Zend’s StandardAutoloader simple. (I had assumed this was just how it worked under the /module directory).

So for example – I have a module with the namespace ‘Nas’, so I store it under:
/zf2/vendor/Nas

And then I have Module.php here:
/zf2/vendor/Nas/Module.php
containing…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
namespace Nas;
class Module
{
public function getAutoloaderConfig()
{
return array(
'ZendLoaderStandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__,
),
),
);
}
}

Finally I needed to add the module into /zf2/config/application.config.php:

1
2
3
4
5
6
'modules' => array(
'Application',
'Album',
'Nas',
),

And that’s it. After that I can start accessing classes under my ‘Nas’ namespace from anywhere within my ZF2 app.

Facebook PHP SDK Zend Framework 2

In ZF1 I would generally include 3rd party API wrappers (Facebook, MailChimp, Google, etc) in Bootstrap.php using something like:

1
2
3
4
5
6
7
8
9
protected function _initIncludes(){
include_once( 'MobileDetect/Mobile-Detect-2.php' );
include_once( 'Facebook/php-sdk-v3.1.1-27/src/facebook.php' );
include_once( 'Google/google-api-php-client-0.5.0/src/apiClient.php' );
include_once( 'MailChimp/MCAPI-1.3.class.php' );
} //_initIncludes

Facebook PHP SDK Zend Framework 2

However there isn’t really anywhere appropriate to ‘include’ things this way in ZF2. Ideally we want to include the 3rd party class in the (/all) module(s) that actually use it, but without trying to include it more than once.

The best way I’ve found of doing this is to add the 3rd party class into Zend’s Class Map Autoloader like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public function getAutoloaderConfig() {
return array(
'ZendLoaderClassMapAutoloader' => array(
__DIR__ . '/autoload_classmap.php',
array(
'Facebook' => 'vendor/facebook/php-sdk/src/facebook.php',
),
),
'ZendLoaderStandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}

This shows how I’m including the ‘Facebook’ class. Remember that ZF2 chdir()’s to the application’s root directory, so the path is relative to that. I can then just create a Facebook instance with:

1
2
3
4
5
$facebook = new Facebook(array(
'appId' => 'xxx',
'secret' => 'xxx',
));

Adding things via this method has a few advantages:

  1. The class is included lazily.
  2. The same entry can be included in multiple modules without there being a risk of conflict.
  3. Zend’s Class Map Autoloader is very, very, very fast.

Newsletter Subscribe

Get the Latest Posts & Articles in Your Email

We Promise Not to Send Spam:)