Showing posts with label using. Show all posts
Showing posts with label using. Show all posts

Thursday, March 12, 2015

Rich signatures for your domain using the Email Settings and the Profiles APIs



A recent addition to the Email Settings API allows domain administrators to use HTML-encoded strings when configuring the default signature for their users.



Updating all signatures to make them adopt the same visually appealing style sounds like a perfect task to automate, however we’d still need to collect various pieces of information for each user, such as phone number or job title, and the Email Settings API has no knowledge of them.



The Google Apps Profiles API provides exactly what we are looking for and in the rest of this article we’ll see how to have the two APIs interact to reach our goal.



Let’s assume we want our signatures to look like the one in the screenshot below, with a bold name, italic job title and clickable link for the email address. Of course you can edit the style as you like with a bit of HTML skills:





Python is the programming language of our choice for this small script and we use the Google Data APIs Python Client Library to send requests to the Email Settings and Profiles APIs.



The first few lines of the script import the required libraries and set the values of the credentials that will be used to authorize our requests. You can find the consumer key and secret for your domain in your Control Panel, under Advanced Tools - Manage OAuth domain key. Remember to replace the dummy values in the script below with yours before running it:

import gdata.apps.emailsettings.client

import gdata.contacts.client

# replace these values with yours



CONSUMER_KEY = mydomain.com

CONSUMER_SECRET = my_consumer_secret

company_name = ACME Inc.

admin_username = admin


We’ll use 2-legged OAuth as the authorization mechanism and set the administrator’s email address as the value of the xoauth_requestor_id parameter, identifying the user we are sending the requests on behalf of.



The consumer key and secret plus the requestor id are the only parameters needed to create an OAuth token that we can pass to the Email Settings and Profiles clients:

# request a 2-legged OAuth token

requestor_id = admin_username + @ + CONSUMER_KEY

two_legged_oauth_token = gdata.gauth.TwoLeggedOAuthHmacToken(

CONSUMER_KEY, CONSUMER_SECRET, requestor_id)



# Email Settings API client

email_settings_client = gdata.apps.emailsettings.client.EmailSettingsClient(

domain=CONSUMER_KEY)

email_settings_client.auth_token = two_legged_oauth_token



# User Profiles API client

profiles_client = gdata.contacts.client.ContactsClient(

domain=CONSUMER_KEY)

profiles_client.auth_token = two_legged_oauth_token


Let’s define a class that generates the signatures for our users on the basis of a set of optional attributes (occupation, phone number, email, etc). This is the class you need to edit or extend if you want to change the style of the signatures for your domain. In the example below, the HtmlSignature() method simply concatenates some strings with hard-coded styling, but you may want to use a more elaborate templating system instead:

# helper class used to build signatures

class SignatureBuilder(object):

def HtmlSignature(self):

signature = %s % self.name

if self.occupation:

signature += %s % self.occupation

if self.company:

signature += %s % self.company

signature += Email: <a href=mailto:%s>%s</a> - Phone: %s % (

self.email, self.email, self.phone_number)

return signature



def __init__(

self, name, company=, occupation=, email=, phone_number=):

self.name = name

self.company = company

self.occupation = occupation

self.email = email

self.phone_number = phone_number


Let’s use profiles_client to retrieve a feed containing all profiles for the domain. Each call to GetProfilesFeed() only returns a page of users, so we need to follow the next links until we get all users:

# get all user profiles for the domain

profiles = []

feed_uri = profiles_client.GetFeedUri(profiles)

while feed_uri:

feed = profiles_client.GetProfilesFeed(uri=feed_uri)

profiles.extend(feed.entry)

feed_uri = feed.FindNextLink()



At this point profiles will contain the list of users we want to process. For each of them, we instantiate a SignatureBuilder object and set its properties name, company, occupation, email and phone_number with the data for that user.

A call to the HtmlSignature() method of the SignatureBuilder instance will provide us with a properly formatted HTML-encoded signature.

# extract relevant pieces of data for each profile

for entry in profiles:

builder = SignatureBuilder(entry.name.full_name.text)

builder.company = company_name

if entry.occupation:

builder.occupation = entry.occupation.text

for email in entry.email:

if email.primary and email.primary == true:

builder.email = email.address

for number in entry.phone_number:

if number.primary and number.primary == true:

builder.phone_number = number.text



# build the signature

signature = builder.HtmlSignature()


The Email Settings API client exposes a method called UpdateSignature to set the signature for a target user. This methods accepts two parameters, the username of the user to be affected and a string containing the signature. We just built the latter, so we only need the retrieve the unique username that identifies each user and that can be easily inferred from the entry identifier returned by the Profiles API, as described in the code and the comment below.



It is worth mentioning that you can also retrieve usernames with the Provisioning API, but for the sake of simplicity we’ll rely on this small hack:

# entry.id has the following structure:

# http://www.google.com/m8/feeds/profiles/domain/DOMAIN_NAME/full/USERNAME

# the username is the string that follows the last /

username = entry.id.text[entry.id.text.rfind(/)+1:]


It’s time to send the requests to the Email Settings API and update the signature:

# set the users signature using the Email Settings API

email_settings_client.UpdateSignature(username=username,

signature=signature)


For further details on what can be accomplished with the Google Apps APIs, please check our documentation and don’t hesitate to reach out to us on our forums if you have any questions.







Claudio Cherubino profile | twitter | blog



Claudio is a Developer Programs Engineer working on Google Apps APIs and the Google Apps Marketplace. Prior to Google, he worked as software developer, technology evangelist, community manager, consultant, technical translator and has contributed to many open-source projects, including MySQL, PHP, Wordpress, Songbird and Project Voldemort.


Saturday, February 14, 2015

Java program to swap two numbers without using temp variable

Java program to swap two numbers without using temp variable

class Swap
{
public static void main(String...s)
{
int a,b;
a=Integer.parseInt(s[0]);
b=Integer.parseInt(s[1]);

System.out.println("
Before Swap:
"+"a="+a+" b="+b);


a=a+b;
b=a-b;
a=a-b;

System.out.println("
After Swap:
"+"a="+a+" b="+b);

}
}

Wednesday, February 11, 2015

C program to produce the following design using s


#include<stdio.h>
#include<conio.h>

void main()
{
int i,j,k,n;
clrscr(); //to clear the screen
printf("How many lines?");
scanf("%d",&n);
n*=2;
printf("
");


for(i=0;i<n;i+=2)
{
for(j=1;j<i;j+=2)
printf(" ");
for(k=n-1;k>i;--k)
printf("*");
printf("
");

}
getch(); //to stop the screen
}

Selecting and Downloading Raster Data via ftp using Python

My problem was to browse through a large number of Radarsat-2 images on a ftp-server and download the ones falling into my area of interest. Each image is available as a *.zip file and a corresponding *.tif map projected quicklook

There is two main pieces that help solving this problem:

1) You can in fact use gdalinfo to retrieve information about a raster file on ftp without having to download the file itself. The command (which I found documented here ) is, the output is here redirected to the output_tempfile:

gdalinfo /vsicurl/ftp://username:password@ftp.adress.no/outfolder/filename.tif >  output_tempfile


or calling from within Python using os.system with the variables defined before:

os.system(rgdalinfo /vsicurl/ftp:// + username + : + password + "@" + ftpserver + workingfolder + file +  >  + output_tempfile)


2) The second step is then to read the centre coordinate from the output_tempfile and if matching download the file. The ftp download is described here , lets see the whole script, which hopefully is self-explanatory with its comments:



import ftplib, os


#DEFINE FTP SERVER PARAMETERS

ftpserver = ftp.youradress.no
username = anonymous
password = guest
workingfolder = /Out/max/

#temporary file storing location info from quicklook
output_tempfile = C:UsersmaxDesktop\test.txt
#destinationfolder for download
destination_folder = C:UsersmaxDocuments\

#Open ftp
ftp = ftplib.FTP(ftpserver, username , password)
ftp.cwd(workingfolder)

#Create a file list of all quicklooks
filelist = []

try:
filelist = ftp.nlst(*.tif)
except ftplib.error_perm, resp:
if str(resp) == "550 No files found":
print "No files in this directory"
else:
raise

for file in filelist:

#get quicklook file info and save in temporary file
os.system(rgdalinfo /vsicurl/ftp:// + username + : + password + "@" + ftpserver + workingfolder + file + > + output_tempfile)

#Read from temporary file the centre coordinates of the quicklook
search = open(output_tempfile)

for line in search:
if "Center" in line:
longitude_quicklook = float(line[15:25])

latitude_quicklook = float(line[28:38])


search.close()

print Longitude , longitude_quicklook
print Latitude , latitude_quicklook


#Check if scene is contained in area of interest, divided in two areas since not rectangular
if ((-23.0 < longitude_quicklook < 67.0) and (71.0 < latitude_quicklook < 90.0)):
contained = True
print true
elif ((-33.0 < longitude_quicklook < 14.0) and (66.0 < latitude_quicklook < 71.0)):
contained = True
print true
else:
contained = False


zipfile = file[:-7] + .zip
zipsavefile = destination_folder + file[:-7] + .zip

print zipfile
print zipsavefile

#If file contained in area of interest, download the file
if contained == True:
print transferring , zipfile
ftp.cwd(workingfolder)
ftp.retrbinary(RETR + zipfile, open(zipsavefile, wb).write)
print transferred , zipfile

#Close ftp connection
ftp.quit()

#Remove temporary file
os.remove(rC:UsersmaxDesktop est.txt)

#End

Tuesday, February 10, 2015

C C Program to Find GCD of Two Numbers Using Recursion

In this program we will use recursion and Euclids algorithm to find greatest common divisor of two numbers. The definition of Euclids algorithm is as follows:

Also Read: C program to find factorial of any number using recursion
Also Read: How to Convert a Recursive Function or Algorithm to Non-Recursive?



C Program


#include<stdio.h>

int gcd(int n,int m)
{
if((n>=m)&&((n%m)==0))
return(m);
else
gcd(m,(n%m));
}

int main()
{
int n,m,result;
printf("Input the first integer number:");
scanf("%d",&n);
printf("Input the second integer number:");
scanf("%d",&m);
result=gcd(n,m);
printf("
GCD of %d and %d is %d",n,m,result);

return 0;
}


C++ Program


#include<iostream>
#include<cstdlib>

using namespace std;

int gcd(int n,int m)
{
if((n>=m)&&((n%m)==0))
return(m);
else
gcd(m,(n%m));
}

int main()
{
int n,m,result;
cout<<"Input the first integer number:";
cin>>n;
cout<<"Input the second integer number:";
cin>>m;
result=gcd(n,m);
cout<<"
GCD of "<<n<<" and "<<m<<" is "<<result;

return 0;
}

C/C++ Program to Find GCD of Two Numbers Using Recursion

Friday, January 30, 2015

Creating a Pentomino game using AS3 Part 37

Today well work on improving our solving algorithm.

The first two changes will be made in the onFrame() function. We need to add a line that calls removeHere() after calling tryRemainingShapes(), so that a step backwards is taken in order to properly look for solutions, and we need to move the line that deletes the first element in tempShapes array under the loop. This way the shape ids will have proper values and the calculations will be more accurate.

private function onFrame(evt:Event):void {
// set temporary values
tempGrid = clone(givenGrid);
tempShapes = clone(givenShapes);
// perform a new cycle
var i:int;
var u:int;
var currentShapeValues:Array;
// Take the first shape in this cycle...
currentShapeValues = clone(shapeValues[tempShapes[cycleNum]]);
// ...try putting it in each available cell...
for (i = 0; i < allCells.length; i++) {
// ...try putting the shape in all 8 possible positions...
for (u = 0; u < 8; u++) {
// ...if successful, continue placing other cells...
if (canPut(currentShapeValues, allCells[i].x, allCells[i].y, tempGrid, u)) {
// ...first put the first shape on the grid...
putHere(currentShapeValues, allCells[i].x, allCells[i].y, tempGrid, u, tempShapes[cycleNum] + 2);
// ...try all remaining shapes...
tryRemainingShapes(tempShapes, tempGrid);
removeHere(currentShapeValues, allCells[i].x, allCells[i].y, tempGrid, u);
}
}
}
// ...remove it from shapes array (so that it isnt used twice)...
tempShapes.splice(cycleNum, 1);
// display info
tInfo.text = Solving level " + levelName + "
Attempts: + attempts + "
Solutions: " + solutions.length;
// next cycle
nextCycle();
}

In tryRemainingShapes() add an if..statement inside the for..loop that cycles through allCells. Set the conditional of statement to a hasSpace() function which returns a boolean value. Pass innerTempGrid, allCells[e].x and allCells[e].y as parameters.

Then update the line that pushes an element to the solutions array, call a doWin() function instead of pushing an item. Pass a clone of innerTempGrid as parameter.

private function tryRemainingShapes(tShapes:Array, tGrid:Array):void {
var innerTempShapes:Array = clone(tShapes);
var innerTempGrid:Array = clone(tGrid);
var e:int;
var t:int;
// ...take each remaining shape...
while (innerTempShapes.length > 0) {
var currentShapeValues:Array = clone(shapeValues[innerTempShapes[0]]);
// ...try putting it in each cell...
for (e = 0; e < allCells.length; e++) {
// ...rotate the shape...
if(hasSpace(innerTempGrid, allCells[e].x, allCells[e].y)){
for (t = 0; t < 8; t++) {
// ...check if it can be put...
if (canPut(currentShapeValues, allCells[e].x, allCells[e].y, innerTempGrid, t)) {
// ...on success, put this shape and try all remaining shapes...
putHere(currentShapeValues, allCells[e].x, allCells[e].y, innerTempGrid, t, innerTempShapes[0] + 2);
tryRemainingShapes(clone(innerTempShapes).splice(0, 1), innerTempGrid);
// ...if no empty cells remaining, then the puzzle is solved.
if (checkWin(innerTempGrid)) doWin(clone(innerTempGrid));
// ...step backwards...
removeHere(currentShapeValues, allCells[e].x, allCells[e].y, innerTempGrid, t);
}
}
}
}
// ...get rid of the shape and continue...
innerTempShapes.shift();
}
}

The hasSpace() function right now checks if the provided cells value is 1. If it isnt, return false.

private function hasSpace(mapGrid:Array, cX:int, cY:int):Boolean {
if (mapGrid[cY][cX] != 1) return false;
return true;
}

I turned that into a function because I am planning on expanding the function and adding more checks that improve the algorithm speed.

The doWin() function has an "exists" variable which is set to false by default. Then we compare all existing solutions to the one that we have and check if a solution like that already exists. If it doesnt - add it to the array.

Use a compare() function to compare two grids:

private function doWin(grid:Array):void {
var exists:Boolean = false;
for (var i:int = 0; i < solutions.length; i++) {
if (compare(solutions[i], grid)) {
exists = true;
break;
}
}
if (!exists) solutions.push(grid);
}

The compare() functions loops through values of the first array and compares them to the values of the other array. False is returned if a value doesnt match:

private function compare(arr1:Array, arr2:Array):Boolean {
for (var i:int = 0; i < arr1.length; i++) {
for (var u:int = 0; u < arr1[i].length; u++){
if (arr1[i][u] != arr2[i][u]) {
return false;
break;
}
}
}
return true;
}

Full code so far:

package  
{
import fl.controls.TextInput;
import flash.display.MovieClip;
import flash.display.Shape;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.Point;
import flash.net.SharedObject;
import flash.text.TextField;
import flash.utils.ByteArray;

/**
* Open-source pentomino game engine
* @author Kirill Poletaev
*/

public class level_solver extends MovieClip
{

private var allCells:Array;
private var tempGrid:Array;
private var tempShapes:Array;
private var givenGrid:Array;
private var givenShapes:Array;
private var cycleNum:int;
private var attempts:int;
private var solutions:Array;
private var levelName:String;
private var shapeValues:Array;

public function level_solver()
{
}

public function solve(levelItem:Object):void {
drawPreview(levelPreview, levelItem.grid);
tInfo.text = Solving level " + levelItem.name + ";
var shapes:Array = levelItem.shapes;
var i:int
var u:int;
givenShapes = [];
for (i = 1; i <= 12; i++) {
this["tShape" + i].text = shapes[i - 1];
for (u = 0; u < shapes[i - 1]; u++) {
givenShapes.push(i - 1);
}
}
allCells = [];
for (i = 0; i < levelItem.grid.length; i++) {
for (u = 0; u < levelItem.grid.length; u++) {
if (levelItem.grid[i][u] == 1) {
allCells.push(new Point(u, i));
}
}
}
givenGrid = levelItem.grid;
tempGrid = [];
tempShapes = [];
solutions = [];
levelName = levelItem.name;
attempts = 0;
cycleNum = 0;
shapeValues = [
[[0, 0], [0, 1], [0, 2], [0, -1], [0, -2]],
[[0, 0], [0, -1], [0, 1], [1, 0], [1, -1]],
[[0, 0], [0, 1], [0, 2], [0, -1], [ -1, -1]],
[[0, 0], [0, 1], [0, -1], [ -1, 0], [1, -1]],
[[0, 0], [ -1, 0], [ -2, 0], [0, -1], [1, -1]],
[[0, 0], [0, 1], [0, -1], [1, -1], [ -1, -1]],
[[0, 0], [1, 0], [ -1, 0], [1, -1], [ -1, -1]],
[[0, 0], [ -1, 0], [ -2, 0], [0, -1], [0, -2]],
[[0, 0], [0, 1], [ -1, 1], [1, 0], [1, -1]],
[[0, 0], [0, 1], [0, -1], [1, 0], [ -1, 0]],
[[0, 0], [ -1, 0], [ -2, 0], [1, 0], [0, -1]],
[[0, 0], [0, 1], [1, 1], [0, -1], [-1, -1]]
];
addEventListener(Event.ENTER_FRAME, onFrame);
}

private function onFrame(evt:Event):void {
// set temporary values
tempGrid = clone(givenGrid);
tempShapes = clone(givenShapes);
// perform a new cycle
var i:int;
var u:int;
var currentShapeValues:Array;
// Take the first shape in this cycle...
currentShapeValues = clone(shapeValues[tempShapes[cycleNum]]);
// ...try putting it in each available cell...
for (i = 0; i < allCells.length; i++) {
// ...try putting the shape in all 8 possible positions...
for (u = 0; u < 8; u++) {
// ...if successful, continue placing other cells...
if (canPut(currentShapeValues, allCells[i].x, allCells[i].y, tempGrid, u)) {
// ...first put the first shape on the grid...
putHere(currentShapeValues, allCells[i].x, allCells[i].y, tempGrid, u, tempShapes[cycleNum] + 2);
// ...try all remaining shapes...
tryRemainingShapes(tempShapes, tempGrid);
removeHere(currentShapeValues, allCells[i].x, allCells[i].y, tempGrid, u);
}
}
}
// ...remove it from shapes array (so that it isnt used twice)...
tempShapes.splice(cycleNum, 1);
// display info
tInfo.text = Solving level " + levelName + "
Attempts: + attempts + "
Solutions: " + solutions.length;
// next cycle
nextCycle();
}

private function tryRemainingShapes(tShapes:Array, tGrid:Array):void {
var innerTempShapes:Array = clone(tShapes);
var innerTempGrid:Array = clone(tGrid);
var e:int;
var t:int;
// ...take each remaining shape...
while (innerTempShapes.length > 0) {
var currentShapeValues:Array = clone(shapeValues[innerTempShapes[0]]);
// ...try putting it in each cell...
for (e = 0; e < allCells.length; e++) {
// ...rotate the shape...
if(hasSpace(innerTempGrid, allCells[e].x, allCells[e].y)){
for (t = 0; t < 8; t++) {
// ...check if it can be put...
if (canPut(currentShapeValues, allCells[e].x, allCells[e].y, innerTempGrid, t)) {
// ...on success, put this shape and try all remaining shapes...
putHere(currentShapeValues, allCells[e].x, allCells[e].y, innerTempGrid, t, innerTempShapes[0] + 2);
tryRemainingShapes(clone(innerTempShapes).splice(0, 1), innerTempGrid);
// ...if no empty cells remaining, then the puzzle is solved.
if (checkWin(innerTempGrid)) doWin(clone(innerTempGrid));
// ...step backwards...
removeHere(currentShapeValues, allCells[e].x, allCells[e].y, innerTempGrid, t);
}
}
}
}
// ...get rid of the shape and continue...
innerTempShapes.shift();
}
}

private function hasSpace(mapGrid:Array, cX:int, cY:int):Boolean {
if (mapGrid[cY][cX] != 1) return false;
return true;
}

private function checkWin(mapGrid:Array):Boolean {
var i:int;
var u:int;
var didWin:Boolean = true;
var width:int = mapGrid[0].length;
var height:int = mapGrid.length;

for (i = 0; i < height; i++) {
for (u = 0; u < width; u++) {
if (mapGrid[i][u] == 1) {didWin = false;}
}
}

return didWin;
}

private function doWin(grid:Array):void {
var exists:Boolean = false;
for (var i:int = 0; i < solutions.length; i++) {
if (compare(solutions[i], grid)) {
exists = true;
break;
}
}
if (!exists) solutions.push(grid);
}

private function compare(arr1:Array, arr2:Array):Boolean {
for (var i:int = 0; i < arr1.length; i++) {
for (var u:int = 0; u < arr1[i].length; u++){
if (arr1[i][u] != arr2[i][u]) {
return false;
break;
}
}
}
return true;
}

private function nextCycle():void {
cycleNum++;
if (cycleNum == givenShapes.length) {
removeEventListener(Event.ENTER_FRAME, onFrame);
// display info
tInfo.text = SOLVED " + levelName + "
Attempts: + attempts + "
Solutions: " + solutions.length;
}
}

private function canPut(cValues:Array, cellX:int, cellY:int, mapGrid:Array, rotation:int):Boolean {
attempts++;
var canPutHere:Boolean = true;
var currentValues:Array = clone(cValues);
updateCurrentValues(currentValues, rotation);
for (var i:int = 0; i < currentValues.length; i++) {
var cX:int = currentValues[i][0] + cellX;
var cY:int = currentValues[i][1] + cellY;
if (cX < 0 || cY < 0 || cX >= mapGrid[0].length || cY >= mapGrid.length || mapGrid[cY][cX]!=1) {
canPutHere = false;
}
}
return canPutHere;
}

private function putHere(currentValues:Array, cellX:int, cellY:int, mapGrid:Array, rotation:int, shape:int):void {
currentValues = clone(currentValues);
updateCurrentValues(currentValues, rotation);
for (var i:int = 0; i < currentValues.length; i++) {
var cX:int = currentValues[i][0] + cellX;
var cY:int = currentValues[i][1] + cellY;
mapGrid[cY][cX] = shape;
}
}

private function removeHere(currentValues:Array, cellX:int, cellY:int, mapGrid:Array, rotation:int):void {
currentValues = clone(currentValues);
updateCurrentValues(currentValues, rotation);
for (var i:int = 0; i < currentValues.length; i++) {
var cX:int = currentValues[i][0] + cellX;
var cY:int = currentValues[i][1] + cellY;
mapGrid[cY][cX] = 1;
}
}

private function updateCurrentValues(currentValues:Array, rot:int):void{
for (var i:int = 0; i < 5; i++) {
// do nothing if rot == 0
if (rot == 1) {
currentValues[i].reverse();
currentValues[i][0] *= -1;
}
if (rot == 2) {
currentValues[i][0] *= -1;
currentValues[i][1] *= -1;
}
if (rot == 3) {
currentValues[i].reverse();
currentValues[i][1] *= -1;
}
if (rot == 4) {
currentValues[i][0] *= -1;
}
if (rot == 5) {
currentValues[i].reverse();
}
if (rot == 6) {
currentValues[i][1] *= -1;
}
if (rot == 7) {
currentValues[i].reverse();
currentValues[i][1] *= -1;
currentValues[i][0] *= -1;
}
}
}

private function clone(source:Object):*{
var myBA:ByteArray = new ByteArray();
myBA.writeObject(source);
myBA.position = 0;
return(myBA.readObject());
}

private function drawPreview(levelPreview:MovieClip, mapGrid:Array):void {
var columns:int = mapGrid[0].length;
var rows:int = mapGrid.length;
var frameWidth:int = levelPreview.width;
var frameHeight:int = levelPreview.height;
var padding:int = 5;
var fitWidth:int = levelPreview.width - (padding * 2);
var fitHeight:int = levelPreview.height - (padding * 2);
var gridStartX:int;
var gridStartY:int;

// calculate width of a cell:
var gridCellWidth:int = Math.round(fitWidth / columns);

var width:int = columns * gridCellWidth;
var height:int = rows * gridCellWidth;

// calculate side margin
gridStartX = (frameWidth - width) / 2;

if (height < fitHeight) {
gridStartY = (fitHeight - height) / 2;
}
if (height >= fitHeight) {
gridCellWidth = Math.round(fitHeight / rows);
height = rows * gridCellWidth;
width = columns * gridCellWidth;
gridStartY = (frameHeight - height) / 2;
gridStartX = (frameWidth - width) / 2;
}

// draw map
levelPreview.shape.x = gridStartX;
levelPreview.shape.y = gridStartY;
levelPreview.shape.graphics.clear();
var i:int;
var u:int;

for (i = 0; i < rows; i++) {
for (u = 0; u < columns; u++) {
if (mapGrid[i][u] == 1) {
drawCell(u, i, 0xffffff, 1, 0x999999, gridCellWidth, levelPreview.shape);
}
}
}
}

private function drawCell(width:int, height:int, fill:uint, thick:Number, line:uint, gridCellWidth:int, gridShape:MovieClip):void {
gridShape.graphics.beginFill(fill);
gridShape.graphics.lineStyle(thick, line);
gridShape.graphics.drawRect(width * gridCellWidth, height * gridCellWidth, gridCellWidth, gridCellWidth);
}
}

}

The code is now more accurate and slightly faster, but it still is slow and should only be tested on small puzzles.

Thanks for reading!

Thursday, January 29, 2015

Creating a Pentomino game using AS3 Part 35

Today we continue working on our solving algorithm.

We left off with an empty canPut() function and an if..statement that is supposed to try place all the other shapes after the first one.

Right now we try to put the first shape in each cell and if we succeed, continue on to the code inside the if..statement (which is empty right now). The method that we use to check if a shape can be put here is called canPut(), and is also empty right now.

The issue right now with placing the shapes is that we are placing them without rotating. There are 4 possible rotation positions for each shape, and 2 ways for the shapes to be flipped, so that makes 8 possible variations of how a shape can be positioned. That means we need to try putting the first shape in each cell in each of the 8 possible positions.

Create another loop inside of the allCells.length loop in onFrame() that cycles 8 times, inside of it have the canPut() if...statement.

Count attempts in the second loop, and also push a placeholder item in solutions array if the canPut() conditional is true.

Instead of passing just 3 values as parameters to canPut(), we also pass tempGrid and the second cycles cycle number:

private function onFrame(evt:Event):void {
// set temporary values
tempGrid = clone(givenGrid);
tempShapes = clone(givenShapes);
// perform a new cycle
var i:int;
var u:int;
var currentShapeValues:Array;
// Take the first shape in this cycle...
currentShapeValues = clone(shapeValues[tempShapes[cycleNum]]);
// ...remove it from shapes array (so that it isnt used twice)...
tempShapes.splice(cycleNum, 1);
// ...try putting it in each available cell...
for (i = 0; i < allCells.length; i++) {
// ...try putting the shape in all 8 possible positions...
for (u = 0; u < 8; u++) {
attempts++;
// ...if successful, continue placing other cells...
if (canPut(currentShapeValues, allCells[i].x, allCells[i].y, tempGrid, u)) {
// ---code that places other shapes---
solutions.push("test");
}
}
}
// display info
tInfo.text = Solving level " + levelName + "
Attempts: + attempts + "
Solutions: " + solutions.length;
// next cycle
nextCycle();
}

In the canPut() function we declare a canPutHere boolean, set it to true by default. Then we set currentValues value to a clone() of its own. Call a function updateCurrentValues(), pass currentValues and the rotation number (the one received from the second loop in onFrame()). This function will modify currentValues array to match the needed rotation.

Then create a loop that cycles through currentValues elements and checks if all the cells are placeable in their spots. If a cell isnt, set canPutHere to false.

In the end, return canPutHere.

private function canPut(currentValues:Array, cellX:int, cellY:int, mapGrid:Array, rotation:int):Boolean {
var canPutHere:Boolean = true;
currentValues = clone(currentValues);
updateCurrentValues(currentValues, rotation);
for (var i:int = 0; i < currentValues.length; i++) {
var cX:int = currentValues[i][0] + cellX;
var cY:int = currentValues[i][1] + cellY;
if (cX < 0 || cY < 0 || cX >= mapGrid[0].length || cY >= mapGrid.length || mapGrid[cY][cX]!=1) {
canPutHere = false;
}
}
return canPutHere;
}

The updateCurrentValues() modifies the received values based on the rotation number.

private function updateCurrentValues(currentValues:Array, rot:int):void{
for (var i:int = 0; i < 5; i++) {
// do nothing if rot == 0
if (rot == 1) {
currentValues[i].reverse();
currentValues[i][0] *= -1;
}
if (rot == 2) {
currentValues[i][0] *= -1;
currentValues[i][1] *= -1;
}
if (rot == 3) {
currentValues[i].reverse();
currentValues[i][1] *= -1;
}
if (rot == 4) {
currentValues[i][0] *= -1;
}
if (rot == 5) {
currentValues[i].reverse();
}
if (rot == 6) {
currentValues[i][1] *= -1;
}
if (rot == 7) {
currentValues[i].reverse();
currentValues[i][1] *= -1;
currentValues[i][0] *= -1;
}
}
}

Full code so far:

package  
{
import fl.controls.TextInput;
import flash.display.MovieClip;
import flash.display.Shape;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.Point;
import flash.net.SharedObject;
import flash.text.TextField;
import flash.utils.ByteArray;

/**
* Open-source pentomino game engine
* @author Kirill Poletaev
*/

public class level_solver extends MovieClip
{

private var allCells:Array;
private var tempGrid:Array;
private var tempShapes:Array;
private var givenGrid:Array;
private var givenShapes:Array;
private var cycleNum:int;
private var attempts:int;
private var solutions:Array;
private var levelName:String;
private var shapeValues:Array;

public function level_solver()
{
}

public function solve(levelItem:Object):void {
drawPreview(levelPreview, levelItem.grid);
tInfo.text = Solving level " + levelItem.name + ";
var shapes:Array = levelItem.shapes;
var i:int
var u:int;
givenShapes = [];
for (i = 1; i <= 12; i++) {
this["tShape" + i].text = shapes[i - 1];
for (u = 0; u < shapes[i - 1]; u++) {
givenShapes.push(i - 1);
}
}
allCells = [];
for (i = 0; i < levelItem.grid.length; i++) {
for (u = 0; u < levelItem.grid.length; u++) {
if (levelItem.grid[i][u] == 1) {
allCells.push(new Point(u, i));
}
}
}
givenGrid = levelItem.grid;
tempGrid = [];
tempShapes = [];
solutions = [];
levelName = levelItem.name;
attempts = 0;
cycleNum = 0;
shapeValues = [
[[0, 0], [0, 1], [0, 2], [0, -1], [0, -2]],
[[0, 0], [0, -1], [0, 1], [1, 0], [1, -1]],
[[0, 0], [0, 1], [0, 2], [0, -1], [ -1, -1]],
[[0, 0], [0, 1], [0, -1], [ -1, 0], [1, -1]],
[[0, 0], [ -1, 0], [ -2, 0], [0, -1], [1, -1]],
[[0, 0], [0, 1], [0, -1], [1, -1], [ -1, -1]],
[[0, 0], [1, 0], [ -1, 0], [1, -1], [ -1, -1]],
[[0, 0], [ -1, 0], [ -2, 0], [0, -1], [0, -2]],
[[0, 0], [0, 1], [ -1, 1], [1, 0], [1, -1]],
[[0, 0], [0, 1], [0, -1], [1, 0], [ -1, 0]],
[[0, 0], [ -1, 0], [ -2, 0], [1, 0], [0, -1]],
[[0, 0], [0, 1], [1, 1], [0, -1], [-1, -1]]
];
addEventListener(Event.ENTER_FRAME, onFrame);
}

private function onFrame(evt:Event):void {
// set temporary values
tempGrid = clone(givenGrid);
tempShapes = clone(givenShapes);
// perform a new cycle
var i:int;
var u:int;
var currentShapeValues:Array;
// Take the first shape in this cycle...
currentShapeValues = clone(shapeValues[tempShapes[cycleNum]]);
// ...remove it from shapes array (so that it isnt used twice)...
tempShapes.splice(cycleNum, 1);
// ...try putting it in each available cell...
for (i = 0; i < allCells.length; i++) {
// ...try putting the shape in all 8 possible positions...
for (u = 0; u < 8; u++) {
attempts++;
// ...if successful, continue placing other cells...
if (canPut(currentShapeValues, allCells[i].x, allCells[i].y, tempGrid, u)) {
// ---code that places other shapes---
solutions.push("test");
}
}
}
// display info
tInfo.text = Solving level " + levelName + "
Attempts: + attempts + "
Solutions: " + solutions.length;
// next cycle
nextCycle();
}


private function nextCycle():void {
cycleNum++;
if (cycleNum == givenShapes.length) {
removeEventListener(Event.ENTER_FRAME, onFrame);
trace("complete");
}
}

private function canPut(currentValues:Array, cellX:int, cellY:int, mapGrid:Array, rotation:int):Boolean {
var canPutHere:Boolean = true;
currentValues = clone(currentValues);
updateCurrentValues(currentValues, rotation);
for (var i:int = 0; i < currentValues.length; i++) {
var cX:int = currentValues[i][0] + cellX;
var cY:int = currentValues[i][1] + cellY;
if (cX < 0 || cY < 0 || cX >= mapGrid[0].length || cY >= mapGrid.length || mapGrid[cY][cX]!=1) {
canPutHere = false;
}
}
return canPutHere;
}

private function updateCurrentValues(currentValues:Array, rot:int):void{
for (var i:int = 0; i < 5; i++) {
// do nothing if rot == 0
if (rot == 1) {
currentValues[i].reverse();
currentValues[i][0] *= -1;
}
if (rot == 2) {
currentValues[i][0] *= -1;
currentValues[i][1] *= -1;
}
if (rot == 3) {
currentValues[i].reverse();
currentValues[i][1] *= -1;
}
if (rot == 4) {
currentValues[i][0] *= -1;
}
if (rot == 5) {
currentValues[i].reverse();
}
if (rot == 6) {
currentValues[i][1] *= -1;
}
if (rot == 7) {
currentValues[i].reverse();
currentValues[i][1] *= -1;
currentValues[i][0] *= -1;
}
}
}

private function clone(source:Object):*{
var myBA:ByteArray = new ByteArray();
myBA.writeObject(source);
myBA.position = 0;
return(myBA.readObject());
}

private function drawPreview(levelPreview:MovieClip, mapGrid:Array):void {
var columns:int = mapGrid[0].length;
var rows:int = mapGrid.length;
var frameWidth:int = levelPreview.width;
var frameHeight:int = levelPreview.height;
var padding:int = 5;
var fitWidth:int = levelPreview.width - (padding * 2);
var fitHeight:int = levelPreview.height - (padding * 2);
var gridStartX:int;
var gridStartY:int;

// calculate width of a cell:
var gridCellWidth:int = Math.round(fitWidth / columns);

var width:int = columns * gridCellWidth;
var height:int = rows * gridCellWidth;

// calculate side margin
gridStartX = (frameWidth - width) / 2;

if (height < fitHeight) {
gridStartY = (fitHeight - height) / 2;
}
if (height >= fitHeight) {
gridCellWidth = Math.round(fitHeight / rows);
height = rows * gridCellWidth;
width = columns * gridCellWidth;
gridStartY = (frameHeight - height) / 2;
gridStartX = (frameWidth - width) / 2;
}

// draw map
levelPreview.shape.x = gridStartX;
levelPreview.shape.y = gridStartY;
levelPreview.shape.graphics.clear();
var i:int;
var u:int;

for (i = 0; i < rows; i++) {
for (u = 0; u < columns; u++) {
if (mapGrid[i][u] == 1) {
drawCell(u, i, 0xffffff, 1, 0x999999, gridCellWidth, levelPreview.shape);
}
}
}
}

private function drawCell(width:int, height:int, fill:uint, thick:Number, line:uint, gridCellWidth:int, gridShape:MovieClip):void {
gridShape.graphics.beginFill(fill);
gridShape.graphics.lineStyle(thick, line);
gridShape.graphics.drawRect(width * gridCellWidth, height * gridCellWidth, gridCellWidth, gridCellWidth);
}
}

}

Thanks for reading!

Tuesday, January 27, 2015

Responsive image carousel using bootstrap

Hai now a days bootstrap becoming more popular using bootstrap we can easily design our web application and it also provides various custom jQuery plugins. Go to official website of twitter bootstrap to learn the different features of bootstrap. Because of the popularity of bootstrap, im creating horizontal responsive image carousel using bootstrap. Some times image carousel is also called as image slider.

                  The main feature of this carousel is responsive. Responsive means we can use and view this carousel on different screen sizes. Whenever the screen size changes the carousel size also automatically change according to screen size it is known as responsive. Now way days most of the websites and web applications are responsive because of the increased usage of smart phones, tablets. Lets start our example.

Sample Screenshot

carousel using bootstrap

Note: This carousel is based on bootstrap v2.3.2 so please download the exact version of  bootstrap and   give the correct path of bootstrap.css, bootstrap.min.js and images. 

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive Image Carousel using Bootstrap</title>
<link href="css/bootstrap.css" rel="stylesheet" type="text/css">
<!-- HTML5 shim for IE backwards compatibility -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js">
</script>
<![endif]-->
</head>
<body>
<div class="carousel slide" id="imageslider">
<div class="carousel-inner">
<div class="item active">
<img src="img/pic1.jpg" alt="One Hour Sand Timer. ">
<div class="carousel-caption">
<h4>Wallpaper 1</h4>
<p>Here we can write caption for images.For ex:-This is wallpaper 1.</p>
</div>
</div>
<div class="item">
<img src="img/pic2.jpg" alt="Half an Hour Sand Timer.">
<div class="carousel-caption">
<h4>Wallpaper 2</h4>
<p>----------This is wallpaper 2.----------</p>
</div>
</div>
<div class="item">
<img src="img/pic3.jpg" alt="1 Min Timer.">
<div class="carousel-caption">
<h4>Wallpaper 3</h4>
<p>----------This is wallpaper 3.----------</p>
</div>
</div>
</div>
<a href="#imageslider" class="left carousel-control" data-slide="prev">&lsaquo;
</a> 
<a href="#imageslider" class="right carousel-control" data-slide="next">&rsaquo;
</a>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script src="js/bootstrap.min.js"></script>
<script>
$("#imageslider").carousel({
interval:5000,
cycle:true
});
</script>
</body>
</html>

Sunday, January 25, 2015

Creating icons logo using PowerPoint 2007

Many a times, you may have felt helpless when it comes to get an appealing icon/logo for your website/blog/profile etc. Major concerns are: you dont know Adobe Photoshop, you cant afford buying Photoshop license or your budget dont allow you to hire a professional designer.

Well, in all such situations Microsoft PowerPoint can come to your rescue. You can create professional looking icon/logo using PowerPoint and Paint. Here is the video which demonstrates how you can create awesome icons using PowerPoint and Microsoft paint.



Icon thus created was used on http://www.youtube.com/user/yutubemedia
Reblog this post [with Zemanta]

Using The Clone Stamp Tool

Heres a 4-minute tutorial from IceFlowStudios on YouTube that demonstrates how to use the Clone Stamp tool in Photoshop. NOTE: When you follow along this tutorial, make sure that you select the Clone Stamp tool and NOT the Pattern Stamp tool. The speaker in the video mentions the keyboard shortcut for accessing the Clone Stamp tool (which would be the S key), but if the Pattern Stamp tool is active in the Toolbar, then youll end up selecting that. So do verify that you actually have the Clone Stamp tool selected as you follow along this tutorial.