Showing posts with label projects. Show all posts
Showing posts with label projects. Show all posts
August 10, 2014
Write a python program for creating virtual file system on Linux environment.
# Developer: Manish Raj (technoslab@gmail.com) import shelve, time, sys class File(object): def __init__(self, name, type, parent=None, text=''): self.list = [] self.name = name self.type = type self.time = int(time.time()) self.parent = parent self.text = text def is_file(self, name): for node in self.list: if node.name == name: return True return False def is_dir(self, name): if(self.is_file(name)) and self.get(name).type == 'dir': return True return False def get(self, name): for node in self.list: if node.name == name: return node def add(self, name, type, text=''): self.list.append(File(name, type, self, text)) def remove(self, name): self.list.remove(self.get(name)) def rename(self, name): self.name = name def copy(self, src, dest): src = self.get(src) self.add(dest, src.type, src.text) def stat(self): print 'Listing', self.name for node in self.list: print 'Name:', node.name, '; Created:', node.time, '; Type:', node.type def read(self): print 'Reading file:', self.name print self.text class FileSystem(object): COMMANDS = ['ls', 'mkdir', 'chdir', 'cd', 'rmdir', 'create', 'read', 'rm', 'mv', 'cp', 'help', 'exit'] def __init__(self): self.io = shelve.open('file.sys', writeback=True) if self.io.has_key('fs'): self.root = self.io['fs'] else: self.root = File('/', 'dir') self.curr = self.root def mkdir(self, cmd): if len(cmd) < 2 or cmd[1] == '': print 'mkdir - make directory' print 'usage: mkdir <dir_name>' else: name = cmd[1] if self.curr.is_file(name) == False: self.curr.add(name, 'dir') else: print name, ' - already exists.'; def chdir(self, cmd): if len(cmd) < 2 or cmd[1] == '': print 'chdir - change directory.' print 'usage: chdir <dir_name>' else: name = cmd[1] if name == '..': if self.curr.parent is not None: self.curr = self.curr.parent elif self.curr.is_dir(name): self.curr = self.curr.get(name) else: print name, ' - invalid directory.' def rmdir(self, cmd): if len(cmd) < 2 or cmd[1] == '': print 'rmdir - remove directory' print 'usage: rmdir <dir_name>' else: name = cmd[1] if self.curr.is_dir(name): self.curr.remove(name) print 'Directory deleted.' else: print name, ' - invalid directory.' def rm(self, cmd): if len(cmd) < 2 or cmd[1] == '': print 'rm - remove file' print 'usage: rm <file_name>' else: name = cmd[1] if self.curr.is_file(name) and not self.curr.is_dir(name): self.curr.remove(name) print 'File deleted.' else: print name, ' - invalid file.' def ls(self, cmd): if(len(cmd) > 1): print 'ls - list stats' print 'usage: ls' self.curr.stat() def create(self, cmd): if len(cmd) < 2 or cmd[1] == '': print 'create - create a file' print 'usage: create <file_name>' else: name = cmd[1] self.curr.add(name, 'file', raw_input('Enter file context: ')) def read(self, cmd): if len(cmd) < 2 or cmd[1] == '': print 'read - read a file' print 'usage: read <file_name>' else: name = cmd[1] if self.curr.is_file(name): self.curr.get(name).read() else: print name, 'invalid file' def mv(self, cmd): if len(cmd) < 3 or cmd[1] == '': print 'mv - rename a file' print 'usage: mv <old_name> <new_name>' else: old_name = cmd[1] new_name = cmd[2] if self.curr.is_file(old_name): self.curr.get(old_name).rename(new_name) else: print old_name, 'invalid file' def cp(self, cmd): if len(cmd) < 3 or cmd[1] == '': print 'cp - copy a file' print 'usage: cp <src> <dest>' else: src = cmd[1] dest = cmd[2] if self.curr.is_file(src): self.curr.copy(src, dest) else: print src, 'invalid file' def save(self): self.io['fs'] = self.root self.io.sync() def help(self, cmd): print 'COMMANDS: mkdir, ls, chdir, rmdir, create, read, mv, cp, rm, exit' def exit(self, cmd): sys.exit(0) def main(): fs = FileSystem() while True: cmd = raw_input('> ').split(' '); method = None try: method = getattr(fs, cmd[0]) except AttributeError: print 'Invalid command. Type "help".' if method is not None and cmd[0] in FileSystem.COMMANDS and callable(method): method(cmd) fs.save() else: print 'Invalid command. Type "help".' main()
February 23, 2013
Java transparent widget

Cool widget in java
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.io.File;
import java.net.Socket;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Scanner;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.WindowConstants;
public class Status {
public static void main(String[] args) {
final int w = 130;
final int h = 500;
Dimension x = Toolkit.getDefaultToolkit().getScreenSize();
final JDialog d = new JDialog();
d.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
d.setUndecorated(true);
d.setSize(w, h);
d.setBackground(new Color(0, 0, 0, 0));
d.setBounds(x.width - w - 20, 20, w, h);
d.setAlwaysOnTop(true);
JLabel l = new JLabel();
l.setBackground(new Color(0, 0, 0, 0));
l.setForeground(new Color(255, 255, 255));
try {
l.setFont(Font.createFont(Font.TRUETYPE_FONT, l.getClass().getResourceAsStream("/consola.ttf")).deriveFont(Font.PLAIN, 13));
} catch (Exception e) {
l.setFont(l.getFont().deriveFont(Font.PLAIN, 13));
e.printStackTrace();
}
l.setBorder(javax.swing.BorderFactory.createMatteBorder(5, 0, 0, 0, new Color(255, 255, 255)));
l.setVerticalAlignment(l.TOP);
l.setHorizontalAlignment(l.LEFT);
d.add(l);
d.setVisible(true);
String user = System.getProperty("user.name");
String os = System.getProperty("os.name");
double ram = 0;
try {
Process p = Runtime.getRuntime().exec("wmic OS get TotalVisibleMemorySize /Value");
Scanner scan = new Scanner(p.getInputStream());
while (scan.hasNext()) {
String temp = scan.nextLine();
//System.out.println(temp);
if (temp.startsWith("TotalVisibleMemorySize")) {
ram = Long.parseLong(temp.split("=")[1]);
//System.out.println("RAM :" + ram);
break;
}
}
} catch (Exception e) {
}
d.addMouseMotionListener(new java.awt.event.MouseMotionListener() {
@Override
public void mouseDragged(MouseEvent e) {
d.setBounds(e.getXOnScreen(), e.getYOnScreen(), d.getWidth(), d.getHeight());
}
@Override
public void mouseMoved(MouseEvent e) {
}
});
d.addMouseListener(new java.awt.event.MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON2) {
System.exit(0);
}
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
});
long itime = Calendar.getInstance().getTimeInMillis();
while (true) {
StringBuilder status = new StringBuilder();
status.append("Current user: ").append(user);
status.append("
------------------");
Calendar c = Calendar.getInstance();
status.append("
Time: ").append(c.get(Calendar.HOUR_OF_DAY)).append(":").append(c.get(Calendar.MINUTE)).append(":").append(c.get(Calendar.SECOND));
status.append("
Date: ").append(c.get(Calendar.DATE)).append("/").append(c.get(Calendar.MONTH) + 1).append("/").append(c.get(Calendar.YEAR));
status.append("
------------------");
status.append("
OS: " + os);
status.append("
Memory: ").append(new DecimalFormat("#.##").format(ram / 1024 / 1024)).append(" GB");
status.append("
------------------");
File[] f = File.listRoots();
long total = 0;
long free = 0;
for (int i = 0; i < f.length; i++) {
total = f[i].getTotalSpace();
free = f[i].getFreeSpace();
if (total > 0) {
long p = (free * 100 / total);
status.append("
").append(f[i].getAbsolutePath().replace(File.separator, "")).append(" ").append(total / 1024 / 1024 / 1024).append(" GB");
status.append("
").append(p).append("% free : ").append(free / 1024 / 1024 / 1024).append(" GB");
}
}
status.append("
------------------");
try {
Socket s = new Socket("www.google.com", 80);
s.getInputStream();
s.setSoTimeout(500);
s.close();
status.append("
Internet: On");
} catch (Exception e) {
status.append("
Internet: Off");
}
status.append("
Uptime: ").append((c.getTimeInMillis() - itime) / 1000).append(" s");
status.append("
------------------");
//status.append("
Geek.Manish");
status.append("");
l.setText(status.toString());
try {
Thread.sleep(1000);
} catch (Exception e) {
}
}
}
}
January 25, 2013
HTML, JavaScript Snake v1.2
Because Retro is cool!
Source:
Download: http://pastebin.com/raw.php?i=gEdVMMJG
Demo: http://pastehtml.com/view/cqkp8hmf1.html
Source:
- <!DOCTYPE html>
- <html>
- <head>
- <title>Snake v1.2</title>
- <script type="text/javascript">
- /**
- * @author Manish Raj
- * @version 1.2
- * @website http://www.technoslab.in/
- */
- window.onload = function(){
- // Constants
- var KEY_UP = 38;
- var KEY_LEFT = 37;
- var KEY_DOWN = 40;
- var KEY_RIGHT = 39;
- var DIR_UP = 38;
- var DIR_LEFT = 37;
- var DIR_DOWN = 40;
- var DIR_RIGHT = 39;
- // Play ground width and height
- var ground_width = window.innerWidth;
- var ground_height = window.innerHeight;
- // Snake configurations
- var snake_width = 15;
- var snake_audio = new Audio("b.ogg");
- var snake_speed = 100;
- var snake_initial_length = 1;
- var snake_color = '#FFFFFF';
- var food_color = '#FFFFFF';
- var game_level = 0;
- var speed_increment = 10;
- var game_score = 0;
- var body = document.getElementsByTagName('body')[0];
- var set_style = function(element, styles){
- for (var key in styles){
- element.style[key] = styles[key];
- }
- }
- set_style(body, {
- 'padding' : '0px',
- 'margin' : '0px'
- });
- // Snake ground
- var snake_ground = document.createElement("div");
- set_style(snake_ground, {
- 'background' : '#000000',
- 'display' : 'block',
- 'width' : ground_width + 'px',
- 'height' : ground_height + 'px',
- 'margin' : '0px;',
- 'padding' : '0px',
- 'position' : 'relative',
- 'overflow' : 'hidden'
- });
- // Add snake ground
- body.appendChild(snake_ground);
- // Food block
- var food = document.createElement("div");
- var food_position = [0,0]
- var boundary = 50;
- var max1 = ground_width - boundary;
- var max2 = ground_height - boundary;
- var min1 = snake_width + boundary;
- var min2 = snake_width + boundary;
- var map_food_position = function(){
- food_position[0] = Math.floor((Math.random() * (max1 - min1) + min1)/min1) * min1;
- food_position[1] = Math.floor((Math.random() * (max2 - min2) + min2)/min2) * min2;
- }
- map_food_position();
- set_style(food, {
- 'background' : food_color,
- 'display' : 'block',
- 'width' : snake_width + 'px',
- 'height' : snake_width + 'px',
- 'position' : 'absolute',
- 'left' : food_position[0] + 'px',
- 'top' : food_position[1] + 'px',
- 'border' : '2px solid #000000'
- });
- // Add food block to ground
- snake_ground.appendChild(food);
- // Game stats
- var game_stat_right = document.createElement('div');
- set_style(game_stat_right, {
- 'display' : 'block',
- 'position' : 'absolute',
- 'right' : '10px',
- 'top' : '10px',
- 'font' : 'bold 25px Arial',
- 'color' : '#FFFFFF'
- });
- var game_stat_left = document.createElement('div');
- set_style(game_stat_left, {
- 'display' : 'block',
- 'position' : 'absolute',
- 'left' : '10px',
- 'top' : '10px',
- 'font' : 'bold 25px Arial',
- 'color' : '#FFFFFF'
- });
- // Add game stats to ground
- snake_ground.appendChild(game_stat_right);
- snake_ground.appendChild(game_stat_left);
- // Snake
- var snake = new Array();
- // Define first two blocks or elements of snake
- snake[0] = [Math.floor((Math.random() * (max1 - min1) + min1)/min1) * min1, Math.floor((Math.random() * (max2 - min2) + min2)/min2) * min2];
- for(var i = 1; i <= snake_initial_length; i++){
- snake[i] = [snake[0][0] - i * snake_width, snake[0][1]];
- }
- // Set initial direction to right
- var snake_direction = DIR_RIGHT;
- // Variable to track game position
- var game_over = false;
- // Loop for as long as needed
- var game_loop =
- function(){
- if(!game_over){
- move_snake({keyCode : snake_direction});
- window.setTimeout(game_loop, snake_speed - speed_increment * game_level);
- }else{
- var gameover_dialog = document.createElement("div");
- set_style(gameover_dialog, {
- 'display' : 'block',
- 'position' : 'absolute',
- 'width' : '400px',
- 'height' : '100px',
- 'font' : 'bold 25px Arial',
- 'color' : 'orangered',
- 'background' : '#DDDDDD',
- 'left' : '50%',
- 'top' : '50%',
- 'marginLeft' : '-200px',
- 'marginTop' : '-50px',
- 'z-index' : '99',
- 'textAlign' : 'center'
- });
- gameover_dialog.innerHTML = 'GAME OVER!';
- gameover_dialog_button = document.createElement('button');
- set_style(gameover_dialog_button, {
- 'display' : 'block',
- 'margin' : 'auto',
- 'font' : 'bold 15px Merienda',
- });
- gameover_dialog_button.innerHTML = 'Click To Play Again';
- gameover_dialog_button.onclick = function(){
- document.location.reload(false);
- }
- gameover_dialog.appendChild(gameover_dialog_button);
- body.appendChild(gameover_dialog);
- gameover_dialog_button.focus();
- }
- }
- window.setTimeout(game_loop, snake_speed);
- // Add keyDown event handler
- document.onkeydown = function(e){
- move_snake({keyCode : e.keyCode});
- };
- // Move snake according to direction
- var move_snake = function(e){
- // Ignore keyDown events if game is over
- if(game_over){
- return null;
- }
- // Prevent snake from moving in reverse direction
- if(snake_direction == DIR_UP && e.keyCode == KEY_DOWN){
- return null;
- }
- if(snake_direction == DIR_RIGHT && e.keyCode == KEY_LEFT){
- return null;
- }
- if(snake_direction == DIR_LEFT && e.keyCode == KEY_RIGHT){
- return null;
- }
- if(snake_direction == DIR_DOWN && e.keyCode == KEY_UP){
- return null;
- }
- // If one of the four navigation keys was pressed
- if(e.keyCode == KEY_UP || e.keyCode == KEY_LEFT || e.keyCode == KEY_DOWN || e.keyCode == KEY_RIGHT){
- // Store position of last block, will be used when adding new tail block i.e. when snake's head eats food block
- var last_x_position = snake[snake.length - 1][0];
- var last_y_position = snake[snake.length - 1][1];
- // Update every element to move to position of block ahead
- for(var i = snake.length - 1; i > 0 ; i--){
- snake[i][0] = snake[i-1][0];
- snake[i][1] = snake[i-1][1];
- }
- // If UP key was pressed ( basically released )
- if(e.keyCode == KEY_UP){
- snake[0][1] -= snake_width;
- snake_direction = DIR_UP;
- }
- // If LEFT key was pressed
- if(e.keyCode == KEY_LEFT){
- snake[0][0] -= snake_width;
- snake_direction = DIR_LEFT;
- }
- // If DOWN key was pressed
- if(e.keyCode == KEY_DOWN){
- snake[0][1] += snake_width;
- snake_direction = DIR_DOWN;
- }
- // If RIGHT key was pressed
- if(e.keyCode == KEY_RIGHT){
- snake[0][0] += snake_width;
- snake_direction = DIR_RIGHT;
- }
- // Wrap the snake at right egde
- if(snake[0][0] > ground_width){
- snake[0][0] = 0;
- }
- // Wrap the snake at bottom edge
- if(snake[0][1] > ground_height){
- snake[0][1] = 0;
- }
- // Wrap the snake at left edge
- if(snake[0][0] < 0){
- snake[0][0] = ground_width;
- }
- // Wrap the snake at top edge
- if(snake[0][1] < 0){
- snake[0][1] = ground_height;
- }
- for(var i = 1; i < snake.length; i++){
- if(snake[0][0] == snake[i][0] && snake[0][1] == snake[i][1]){
- game_over = true;
- }
- }
- }
- // If snake's head has approached a food block
- if(Math.abs(snake[0][0] - food_position[0]) < snake_width && Math.abs(snake[0][1] - food_position[1]) < snake_width){
- // Add a new tail block
- snake[snake.length] = [last_x_position, last_y_position];
- game_score++;
- if(game_score != 0 && game_score%10 == 0 && game_level != 10){
- game_level++;
- }
- // Play the audio
- snake_audio.play();
- // Find and update food block's new position
- map_food_position();
- set_style(food, {
- 'left' : food_position[0] + 'px',
- 'top' : food_position[1] + 'px'
- });
- }
- game_stat_left.innerHTML = 'Score: ' + game_score;
- game_stat_right.innerHTML = 'Level: ' + (game_level + 1);
- // Add or modify snake blocks on each event
- for(var i = 0; i < snake.length; i++){
- var snake_elem = document.getElementById("snake_"+i);
- if(snake_elem == null){
- snake_elem = document.createElement("div");
- snake_elem.setAttribute("id", "snake_"+i);
- set_style(snake_elem, {
- 'position' : 'absolute',
- 'display' : 'block',
- 'width' : snake_width + 'px',
- 'height' : snake_width + 'px',
- 'border' : '0px solid #000000',
- 'background' : snake_color
- });
- snake_ground.appendChild(snake_elem);
- }
- set_style(snake_elem, {
- 'left' : snake[i][0] + 'px',
- 'top' : snake[i][1] + 'px'
- });
- }
- };
- }
- </script>
- </head>
- <body>
- <noscript>
- <h1 style="text-align: center;">Please use a Javascript enabled web browser. Thank you.</h1>
- </noscript>
- </body>
- </html>
Download: http://pastebin.com/raw.php?i=gEdVMMJG
Demo: http://pastehtml.com/view/cqkp8hmf1.html
December 16, 2012
Display random labels on blogspot blog
2 comments:
Author:
tec
at
12/16/2012 05:14:00 pm
Labels:
blogger random labels,
projects,
random labels,
yql
This Javascript snippet will retrieve random labels from a blogspot blog and display it in sidebar or anywhere else, useful if you've too many labels and only want show 'x' number of random labels on each page load.
Technology used:
Javascript, YQL, JSON feed
Usage:
- Configure and include the snippet and add label div to blog template/html.
View/Copy snippet:
Or Download: http://pastebin.com/raw.php?i=PkZY87yV
Technology used:
Javascript, YQL, JSON feed
Usage:
- Configure and include the snippet and add label div to blog template/html.
View/Copy snippet:
- /**
- * @author Manish Raj
- * @website http://www.technoslab.in
- */
- // Configure
- var blog_url = 'www.technoslab.in'; // Just the host. Example. yourblog.blogspot.com
- var max_labels = 50; // Maximum number of random labels to show.
- var label_element = 'labels'; // id of the element where labels would be displayed. Example: <div id="labels"></div>
- function showLabels(){
- var queryUrl = 'http://query.yahooapis.com/v1/public/yql?q=select%20feed.category%20from%20json%20where%20url%3D%22http%3A%2F%2F' + blog_url + '%2Ffeeds%2Fposts%2Fsummary%3Falt%3Djson%26max-results%3D0%22&format=json&callback=labelCb'
- var script = document.createElement('script');
- script.setAttribute('type', 'text/javascript');
- script.setAttribute('src', queryUrl);
- document.getElementsByTagName('body')[0].appendChild(script);
- }
- // Label Callback
- function labelCb(response){
- var html = '';
- if(response.query.count > 0){
- response.query.results.json = response.query.results.json.shuffle();
- for(var i = 0; i < response.query.count && i < max_labels; i++){
- html += '<a href="http://'+blog_url+'/search/label/'+response.query.results.json[i].feed.category.term+'">'+response.query.results.json[i].feed.category.term+'</a>, ';
- }
- }
- document.getElementById(label_element).innerHTML = html;
- }
- // From SO: http://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array-in-javascript
- Array.prototype.shuffle = function () {
- for (var i = this.length - 1; i > 0; i--) {
- var j = Math.floor(Math.random() * (i + 1));
- var tmp = this[i];
- this[i] = this[j];
- this[j] = tmp;
- }
- return this;
- }
- // Load and show labels
- window.onload = function(){
- showLabels();
- }
Or Download: http://pastebin.com/raw.php?i=PkZY87yV
November 25, 2012
JSP, HTML basic snake game
2 comments:
Author:
tec
at
11/25/2012 04:38:00 pm
Labels:
basic snake game code,
projects,
snake html
Who doesn't like the "snake" game, right? I'm no exception. I did this basic game just for the fun.
To begin playing, select initial level and snake's length and then start the game.
Demo: http://techno-slab.appspot.com/snake.jsp
Source code: http://pastebin.com/tyYe1SsP
Snake v1
To begin playing, select initial level and snake's length and then start the game.
Demo: http://techno-slab.appspot.com/snake.jsp
Source code: http://pastebin.com/tyYe1SsP
November 03, 2012
C Program To Add, Subtract or Multiply two Matrices
No comments:
Author:
tec
at
11/03/2012 09:03:00 pm
Labels:
c program,
matrix multiplication in c,
projects
- Add, Subtract or Multiply two Matrices
- Command line based
- Menu driven
- Uses Structs, functions, dynamic allocations etc.
- Command line based
- Menu driven
- Uses Structs, functions, dynamic allocations etc.
- #include <stdio.h>
- #include <conio.h>
- #include <stdlib.h>
- struct matrix{
- int **elements;
- int rows;
- int cols;
- };
- matrix read(){
- int rows = 0, cols = 0, i, j;
- matrix m = {NULL, 0, 0};
- printf("\nEnter the number of rows: ");
- scanf("%d", &rows);
- printf("\nEnter the number of columns: ");
- scanf("%d", &cols);
- if( rows <= 0 || cols <= 0){
- printf("%dx%d matrix does not exist!", rows, cols);
- }else {
- m.rows = rows;
- m.cols = cols;
- m.elements = (int **)malloc(m.rows * sizeof(int *));
- for( i = 0; i < rows; i++){
- m.elements[i] = (int *)malloc(m.cols * sizeof(int));
- for( j = 0; j < cols; j++){
- printf("\nEnter element at %d x %d: ", i + 1, j + 1);
- scanf("%d", &m.elements[i][j]);
- }
- }
- }
- return m;
- }
- void display(char msg[], matrix m){
- int i, j;
- printf("\n========== %s ==========\n", msg);
- for(i = 0; i < m.rows; i++){
- for(j = 0; j < m.cols; j++){
- printf("%d\t", m.elements[i][j]);
- }
- printf("\n");
- }
- }
- matrix process(matrix m1, matrix m2, char opr){
- int i, j, k;
- matrix m = {NULL, 0, 0};
- if((opr == '1' || opr == '2') && (m1.rows != m2.rows || m1.cols != m2.cols)){
- printf("\nMatrix addition or subtraction is not possible since number of rows and columns of the two matrices are not equal.");
- }else if(opr == '3' && m1.cols != m2.rows){
- printf("\nMatrix multiplication is not possible since number of columns of first matrix is not equal to number of rows of second matrix.");
- }else{
- if(opr == '1' || opr == '2'){
- m.rows = m1.rows;
- m.cols = m1.cols;
- m.elements = (int **)malloc(m.rows * sizeof(int *));
- for(i = 0; i < m1.rows; i++){
- m.elements[i] = (int *)malloc(m.cols * sizeof(int));
- for( j = 0; j < m1.cols; j++){
- if(opr == '1'){
- m.elements[i][j] = m1.elements[i][j] + m2.elements[i][j];
- }else if(opr == '2'){
- m.elements[i][j] = m1.elements[i][j] - m2.elements[i][j];
- }
- }
- }
- }else if(opr == '3'){
- m.rows = m1.rows;
- m.cols = m2.cols;
- m.elements = (int **)malloc(m.rows * sizeof(int *));
- for(i = 0; i < m1.rows; i++){
- m.elements[i] = (int *)malloc(m.cols * sizeof(int));
- for( j = 0; j < m2.cols; j++){
- m.elements[i][j] = 0;
- for(k = 0; k < m2.rows; k++){
- m.elements[i][j] += m1.elements[i][k] * m2.elements[k][j];
- }
- }
- }
- }
- }
- return m;
- }
- int main(){
- while(1){
- printf("\nPress 1 to add two matrices\nPress 2 to subtract\nPress 3 to multiply two matrices\nPress q to quit");
- char opt = getch();
- if(opt == 'q' || opt == 'Q'){
- break;
- }
- matrix m1 = read();
- matrix m2 = read();
- if(m1.elements != NULL && m2.elements != NULL && (opt == '1' || opt == '2' || opt == '3')){
- matrix m3 = process(m1, m2, opt);
- if(m3.elements != NULL){
- display("Matrix 1", m1);
- display("Matrix 2", m2);
- display("Result", m3);
- }
- }
- }
- return 0;
- }
October 18, 2012
[PHP] URL Shrinking script - download

Setup:
1. Create table, see table.sql
2. Edit configs in index.php
3. Upload
Demo:
Download:
http://www.2shared.com/file/QNbtMalj/short.html
1. Create table, see table.sql
2. Edit configs in index.php
3. Upload
Demo:
Download:
http://www.2shared.com/file/QNbtMalj/short.html
August 31, 2012
[PHP] Mobile number trace script
17 comments:
Author:
tec
at
8/31/2012 12:38:00 am
Labels:
number tracing script,
php script,
projects

A mobile number tracing script that can be easily integrated as a widget or as a standalone page.
Demo: http://technoslab.1x.net/trace
Demo: http://technoslab.1x.net/trace
August 27, 2012
C program to accept length of three sides of a triangle and find out the type of triangle
- #include <stdio.h>
- #include <conio.h>
- int main(){
- int s1;
- int s2;
- int s3;
- printf("Enter side 1: ");
- scanf("%d", &s1);
- printf("Enter side 2: ");
- scanf("%d", &s2);
- printf("Enter side 3: ");
- scanf("%d", &s3);
- printf("Triangle is ");
- if(s1 == s2 && s1 == s3){
- printf("Equilateral");
- }else if(s1 == s2 || s2 == s3 || s1 == s3){
- printf("Isoscles");
- if(s1*s1 == s2*s2 + s3*s3 || s1*s1 == s2*s2 - s3*s3 || s1*s1 == - s2*s2 + s3*s3){
- printf(" and is Right Angled");
- }
- }else{
- printf("Scalene");
- if(s1*s1 == s2*s2 + s3*s3 || s1*s1 == s2*s2 - s3*s3 || s1*s1 == - s2*s2 + s3*s3){
- printf(" and is Right Angled");
- }
- }
- printf(".");
- getch();
- return 0;
- }
C program to calculate sum of numbers from 0 to 100 which are divisible by 4
- #include <stdio.h>
- #include <conio.h>
- int main(){
- int i;
- int sum = 0;
- for(i = 0; i <= 100; i++){
- if(i % 4 == 0){
- sum = sum + i;
- }
- }
- printf("Sum: %d", sum);
- getch();
- return 0;
- }
C program to obtain five numbers from user and display them back in ascending order

Source uploaded to Pastebin.com
* Users Bubble Sort algorithm
Here's an animation from Wikipedia explaining Bubble sort.
- #include <stdio.h>
- #include <conio.h>
- int main(){
- const int length = 5;
- int numbers[length];
- int swapped;
- int temp;
- int i;
- for(i = 0; i < length; i++){
- printf("Enter number %d: ", i + 1);
- scanf("%d", &numbers[i]);
- }
- /* Implement Bubble sort Algorithm */
- while(1){
- swapped = 0;
- for(i = 0; i < length - 1; i++){
- if(numbers[i] > numbers[i+1]){
- temp = numbers[i];
- numbers[i] = numbers[i+1];
- numbers[i+1] = temp;
- swapped = 1;
- }
- }
- if(swapped == 0){
- break;
- }
- }
- for(i = 0; i < length; i++){
- printf("Number %d = %d\n", i+1, numbers[i]);
- }
- getch();
- return 0;
- }
August 24, 2012
Easy to Integrate Way2SMS sender for Wapsites

- Sends SMS from Way2SMS servers via ubaid.tk API
- Easy to Integrate
- Single file source
- Clean interface
August 20, 2012
Basic Command Line Calculator source in C
1 comment:
Author:
tec
at
8/20/2012 06:40:00 am
Labels:
C basic calculator source,
calculator in c,
projects
I'm officially learning C now and this is a small program I put together just to practice what I learned. Have fun!
- /*
- ===================================
- Program: Calculate version 1.0
- Author: Manish Raj
- Website: http://www.technoslab.in/
- Description: Simple CLI calculator for beginners
- ===================================
- */
- /* Include header files */
- #include <stdio.h>
- #include <conio.h>
- /* Begin main method */
- int main(){
- /* Display program information */
- printf("\nCalculate v1 by Manish");
- /* Declare variables */
- char cmd, oprt;
- int num1, num2;
- /* Loop infinitely till 'x' is pressed */
- while(1){
- /* Initialize variables to default value on each iteration */
- cmd = '?';
- oprt = '?';
- num1 = 0;
- num2 = 0;
- /* Ask user for action to be performed */
- printf("\nPress x to exit, Press c to calculate: ");
- cmd = getch();
- if(cmd == 'X' || cmd == 'x'){
- /* If 'x' was pressed -> exit */
- printf("%c", cmd);
- break;
- }
- else if(cmd == 'c' || cmd == 'C'){
- /* If 'c' was pressed -> calculate */
- printf("%c", cmd);
- /* Display instructions */
- printf("\nEnter expression in this form - number1 operator number2.\nAllowed operators: + , -, *, /, %.\nExample: 2 + 2\nEnter now:");
- scanf("%d %c %d", &num1, &oprt, &num2);
- /* Begin calculation */
- switch(oprt){
- case '+' :
- printf("%d %c %d = %d", num1, oprt, num2, num1 + num2);
- break;
- case '-' :
- printf("%d %c %d = %d", num1, oprt, num2, num1 - num2);
- break;
- case '*' :
- printf("%d %c %d = %d", num1, oprt, num2, num1 * num2);
- break;
- case '/' :
- if( num2 == 0){
- printf("%d %c %d = Math Error. You can not divide any number by 0", num1, oprt, num2);
- }else{
- printf("%d %c %d = %d", num1, oprt, num2, num1 / num2);
- }
- break;
- case '%' :
- printf("%d %c %d = %d", num1, oprt, num2, num1 % num2);
- break;
- default:
- printf("Invalid expression. Operator %c is not allowed. Try again!", oprt);
- break;
- }
- }else{
- /* Display error */
- printf("\nInvalid selection. Try again!");
- }
- }
- /* Display exit message */
- printf("\nThank you for using the program.");
- /* Return 0 to OS */
- return 0;
- }
May 22, 2012
MyBB plugin - IP history

Information:
Displays a list of recent IP addresses that were used to access forum from your account. It also displays time alongside.
Purpose:
Keep track of your own IP.
Find who used your account in case someone accesses it illegally.
Technologies used:
PHP, MySQL, MyBB and JSON.
Screenshot:
Installation notes:
- Upload ip_history.php to MYBB_ROOT/inc/plugins
- Go to Admin panel - Plugins - Install and activate ip_history plugin
- Done
Displays a list of recent IP addresses that were used to access forum from your account. It also displays time alongside.
Purpose:
Keep track of your own IP.
Find who used your account in case someone accesses it illegally.
Technologies used:
PHP, MySQL, MyBB and JSON.
Screenshot:
Installation notes:
- Upload ip_history.php to MYBB_ROOT/inc/plugins
- Go to Admin panel - Plugins - Install and activate ip_history plugin
- Done
April 30, 2012
How to send email from a Java program via Gmail's SMTP server

This Java function uses your Email, Password to send a Message to other Email address via Gmail's SMTP server.
Download JavaMail Library: http://www.oracle.com/technetwork/java/javamail/index-138643.html
Extract the Zip Archive
Import mail.jar into your project
Download
Download JavaMail Library: http://www.oracle.com/technetwork/java/javamail/index-138643.html
Extract the Zip Archive
Import mail.jar into your project
- public void sendMailViaGmail(final String email, final String password, String sendTo, String subject, String body) {
- java.util.Properties properties = new java.util.Properties();
- properties.put("mail.smtp.auth", "true");
- properties.put("mail.smtp.starttls.enable", "true");
- properties.put("mail.smtp.host", "smtp.gmail.com");
- properties.put("mail.smtp.port", "587");
- javax.mail.Session session = javax.mail.Session.getInstance(properties, new javax.mail.Authenticator() {
- protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
- return new javax.mail.PasswordAuthentication(email, password);
- }
- });
- try {
- javax.mail.Message message = new javax.mail.internet.MimeMessage(session);
- message.setFrom(new javax.mail.internet.InternetAddress(email));
- message.setRecipients(javax.mail.Message.RecipientType.TO, javax.mail.internet.InternetAddress.parse(sendTo));
- message.setSubject(subject);
- message.setText(body);
- javax.mail.Transport.send(message);
- } catch (Exception e) {
- System.out.println(e);
- }
- }
Download
April 20, 2012
Way2SMS desktop application

Why use it?
It's a simple portable Java application that you can place on your desktop and simply click to send quick text messages to near and dear ones. It does not use any third party API services so your login credentials as safe as they are with you because this application sends every request directly to way2sms's server.It is a Java application so you must have JRE installed on your PC to run it.
Download: http://www.2shared.com/file/Cq5HUbDB/way2smsApp.html
Here's the source in case you want to check it out. http://pastebin.com/raw.php?i=T4rprvS8
April 01, 2012
How to use PHP Built-in webserver

PHP 5.4 supports a built-in web server which can be used for testing purpose which is good because we can test scripts quickly without having to install Apache.
1. Download and extract PHP 5.4.0 on your system. Follow this guide if you are an XAMPP user.
2. Open console ( Start -> Run -> cmd on Windows ) and navigate to PHP's current directory.
3. Now execute following command to start the build-in server:
php -S localhost:5555
Here we are telling PHP to start local server on port 5555
If everything works fine you'll see a message saying "PHP development server has started".
PHP will also output errors and warnings. ( In my case DLL for zip extension if missing )
Now lets see if our server is listening and responding to requests.
4. Create a simple index.php in Document Root. ( F:\Installs\Xampp\php\ in my case )
5. Open your favorite browser. I use Firefox.
6. Go to this URL: http://localhost:5555/index.php
7. You should see something like this.
Congratulations! The Built-in webserver is working properly and responding to requests and we can now test our script even without installing Apache on our Systems. Note that this built-in PHP server should not be used in production but only for testing.
March 29, 2012
PHP script - retrieve email from your Gmail account
This script can be used to retrieve recent emails from your Gmail account. It was developed in hurry and is meant to provide a sort of conceptual base for more advanced scripts/programs.
Usage:
Just declare some variables in the top section of the script and run it. You can also extend it to do advance stuffs like read and automatically delete spam mails, create auto responders etc.
Requirement:
Your server must have imap extension.
DOWNLOAD
Do inform me if you use it or released an extended version of this script. :)
Usage:
Just declare some variables in the top section of the script and run it. You can also extend it to do advance stuffs like read and automatically delete spam mails, create auto responders etc.
Requirement:
Your server must have imap extension.
- <?php
- session_start() ;
- //error_reporting(-1);
- error_reporting( 0 ) ;
- // DEFINE VARIABLES.
- $pass = "ZZZZZ" ; // password to access this page.
- $gmail_username = "myusername@gmail.com" ; // your google account username.
- $gmail_password = "mypassword" ; // your google account password.
- $perpage = 20 ; // number of mails to be display per page.
- if ( isset( $_POST['pass'] ) )
- {
- if ( $pass == $_POST['pass'] )
- {
- $_SESSION['logged'] = 1 ;
- }
- else
- {
- echo "Invalid Login Details !" ;
- }
- }
- ?>
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <title>FETCH MAIL</title>
- <style type="text/css">
- body{font:12px sans-serif;background:rgb(210,210,250);}
- .topbar{background:rgb(150,0,250);font:15px cursive;font-weight:bold;color:white;border:1px solid silver;padding:5px;}
- .message{background:rgb(255,255,255);border:1px solid rgb(0,0,155);padding:5px;}
- .mailbox{border:1px dashed silver;padding:5px;}
- input,submit,select{padding:3px;font:12px cursive;font-weight:bold;background:transparent;border:1px solid rgb(50,50,50);}
- .header{font:40px 'script mt bold';font-weight:bold;color:purple;}
- </style>
- </head>
- <body>
- <?php
- if ( ! isset( $_SESSION['logged'] ) && ! isset( $_POST['pass'] ) )
- {
- exit( "Please Log In<form method='post'><input type='password' name='pass'><input type='submit' value='Go'></form>" ) ;
- }
- $link = imap_open( "{imap.gmail.com:993/imap/ssl}INBOX", $gmail_username, $gmail_password ) or exit( "Connection aborted: " . imap_last_error() ) ;
- $mails = imap_search( $link, 'ALL' ) ;
- rsort( $mails ) ;
- $total = count( $mails ) ;
- if ( isset( $_GET['page'] ) )
- {
- if ( is_numeric( $_GET['page'] ) )
- {
- $begin = round( $_GET['page'], 0 ) * $perpage ;
- }
- else
- {
- $begin = $total ;
- }
- }
- else
- {
- $begin = $total ;
- }
- echo "<table class='main'><tr><td><h2 class='header'>FETCH EMAIL</h2></td></tr><tr><td>" ;
- for ( $i = $begin; $i >= $begin - $perpage; $i-- )
- {
- if ( $i <= $total )
- {
- $overview = imap_fetch_overview( $link, $i, 0 ) ;
- $message = imap_fetchbody( $link, $i, 2 ) ;
- $message = preg_replace( "@<style.+?</style>@is", "", $message ) ;
- $message = strip_tags( $message ) ;
- $read = ( $overview[0]->seen == 0 ) ? 'NOT READ YET' : 'ALREADY READ' ;
- echo "
- <div class='mailbox'>
- <br/>
- <div class='topbar'>
- [ $i ]. SUBJECT : {$overview[0]->subject} || SENT FROM: {$overview[0]->from} || SENT AT: {$overview[0]->date} || $read
- </div>
- <br/>
- <div class='message'>
- <pre>{$message}</pre>
- </div>
- </div>
- " ;
- }
- }
- echo "</td></tr></table>" ;
- // pagination
- echo "<table class='nav'><tr><td>" ;
- if ( $begin > 0 )
- {
- $pre = $begin - 1 ;
- echo "<form method='get' action=''>
- <input type='hidden' name='page' value='{$pre}' />
- <input type='submit' value='Previous' />
- </form>" ;
- }
- echo "</td><td>" ;
- if ( $begin < $total )
- {
- $nxt = $begin + 1 ;
- echo "<form method='get' action=''>
- <input type='hidden' name='page' value='{$nxt}' />
- <input type='submit' value='Previous' />
- </form>" ;
- }
- echo "</td><td>" ;
- $factor = round( $total / $perpage, 0 ) ;
- echo "<form method='get' action=''>
- <select name='page'>
- " ;
- while ( $factor >= 0 )
- {
- echo "<option value='{$factor}'>{$factor}</option>" ;
- $factor-- ;
- }
- echo "</select> <input type='submit' value='Goto Page'></form>" ;
- echo "</td></tr></table>" ;
- ?>
- </body>
- </html>
DOWNLOAD
Do inform me if you use it or released an extended version of this script. :)
March 10, 2012
Post to your Google plus stream with a bookmarklet
With this bookmarklet, you can post to your Google plus stream about current page.
[Drag me to bookmark toolbar]
- javascript:window.location='https://plusone.google.com/_/+1/confirm?hl=en&url='+window.location;
March 08, 2012
Download Vatikag.com download portal script

Planning to host a download portal ?
Vatikag CMS is a simple but powerful content management system designed primarily to quickly create and maintain file download portals. It sports exciting features like automatic thumbnail creation, image watermarking, mobile optimized view etc. The CMS is also heavily search engine optimized to boost your rankings and traffic.
Check out this CMS in action on vatikag.com
PS:
* This is not a clone but the actual script.
* The source was released by it's author on his website.
Download the first version of this popular CMS: http://www.4shared.com/zip/13GQMvLh/vcms.html
Subscribe to:
Posts (Atom)