This forum is in archive mode. You will not be able to post new content.

Show Posts

This section allows you to view all posts made by this member. Note that you can only see posts made in areas you currently have access to.


Messages - theifyppl

Pages: [1] 2
1
C - C++ / [C] Word Search Puzzle Solver
« on: April 03, 2014, 08:04:01 AM »
Hello EvilZone,

This is the first time I've posted in awhile, but that's because I've been in college for computer engineering!  Anyway, I realized I've been doing some programming for my intro courses, and so I thought I'd post my solution to one of my assignments here.  Keep in mind this is really basic stuff, and since I had programming experience going into the course, this stuff was child's play.  This was the hardest assignment we had last quarter.

The Assignment: Our assignment was to write a program in C (not C++) that reads in 2 files: one that contains a word search puzzle, and one that contains the words to search for.  The size of the puzzles are always 10x10, but one could easily implement a way to allow that size to vary.  Once the program reads in the puzzle, it loops through each word and searches for it.  The specific algorithm I've chosen for searching is explained in the comments at the top of the program, and the rest of the program is well-commented too.  Results of the search are then printed to the standard output.  These results will either be the row and column of the first letter, along with the orientation of the word (right, up, up-right, etc.), or it will simply let the user know the word was not found.  The puzzle itself is also printed before any of the searching begins.

* Note that the rows and columns in the results are numbered from 0-9, not 1-10.

* If a word occurs twice in a puzzle, it will find the first occurrence and print the results.  The second will be ignored.

The Code:

Code: (C) [Select]
/* General method: In order to find the words in the puzzle, searchWord() searches
 * for every occurance of the first letter.  Once the first letter is found, the
 * second letter is searched for all around the first.  For every occurence the
 * first and second letters are found next to each other, the orientation (up, right,
 * down, left, diagonals, etc.) is saved in an orientation_t struct and the
 * searchRestOfWord() function is used.  searchRestOfWord recursively searches
 * for the rest of the word in the orientation specified.  If the rest is found,
 * then the row, column, and orientation of the word is saved and printed to the screen */

#include <stdio.h>
#include <string.h>
#include <ctype.h>

#define UP -1
#define DOWN 1
#define RIGHT 1
#define LEFT -1

typedef struct
{
int upDown;
int leftRight;
char orient_id[30];
}orientation_t;

int searchWord(char word[], char puzzle[][10], orientation_t *orient, int *row, int *col); /* returns 0 or 1 for not found/found */
int searchRestOfWord(char word[], char puzzle[][10], orientation_t orient, int row, int col, int wordIndex); /* returns 0 or 1 for found/not found */
void readPuzzle(char fileName[], char puzzle[][10]);
void printPuzzle(char puzzle[][10]);

int main(int argc, char *argv[])
{

FILE *words;
int end, row = 0, col = 0;
char currentWord[30];
char puzzle[10][10];
orientation_t orient;

if(argc == 3)
{
orient.upDown = 0;
orient.leftRight = 0;
readPuzzle(argv[1], puzzle);
printPuzzle(puzzle);
words = fopen(argv[2], "r");

end = fscanf(words, "%s", currentWord);
while(end != EOF)
{
if(searchWord(currentWord, puzzle, &orient, &row, &col) == 1)
{
/* found: do stuff */
printf("%s: (%s) row: %d column: %d\n", currentWord, orient.orient_id, row, col);

}
else
{
/* not found: do stuff */
printf("%s: word not found\n", currentWord);
}
end = fscanf(words, "%s", currentWord);
}
}
else
{
printf("usage: ./wordsearch puzzleFile wordFile\n");
}

return 0;
}


/* searchWord - searches for a word in the puzzle
 *
 * args:
 * char word[] - the word to search for
 * char puzzle[][10] - the puzzle to search inside
 * orientation_t *orient - pointer to the orientation
 * structure to fill with the word's orientation
 * in the puzzle (if found)
 * int *row - pointer to the row to be filled if found
 * int *col - pointer to the col to be filled if found
 *
 * return value: returns 1 if found and 0 if not found */
int searchWord(char word[], char puzzle[][10], orientation_t *orient, int *row, int *col)
{

/* search for first letter */

int i, j;

for(i = 0; i<10; i++)
{
for(j = 0; j<10; j++)
{
if(puzzle[i][j] == word[0])
{

/* first letter found, search for second letter */
if(j!=9)
{
if(puzzle[i][j+1] == word[1])
{
orient->upDown = 0;
orient->leftRight = RIGHT;
strcpy(orient->orient_id, "FORWARD");
if(searchRestOfWord(word, puzzle, *orient, i, j+1, 2) == 1)
{
*row = i;
*col = j;
return 1;
}
}
}

if(j!=0)
{
if(puzzle[i][j-1] == word[1])
                    {       
orient->upDown = 0;
                        orient->leftRight = LEFT;
strcpy(orient->orient_id, "BACKWARD");
if(searchRestOfWord(word, puzzle, *orient, i, j-1, 2) == 1)
                        {
*row = i;
*col = j;
return 1;
                        }
                    }
                }

if(i!=9)
                {
                    if(puzzle[i+1][j] == word[1])
                    {       
                        orient->upDown = DOWN;
orient->leftRight = 0;
strcpy(orient->orient_id, "DOWN");
if(searchRestOfWord(word, puzzle, *orient, i+1, j, 2) == 1)
                        {
*row = i;
*col = j;
return 1;
                        }
                    }
                }

if(i!=0)
                {
                    if(puzzle[i-1][j] == word[1])
                    {       
                        orient->upDown = UP;
orient->leftRight = 0;
strcpy(orient->orient_id, "UP");
if(searchRestOfWord(word, puzzle, *orient, i-1, j, 2) == 1)
                        {
*row = i;
*col = j;
return 1;
}
}
}

if(j != 9 && i != 0)
                {
                    if(puzzle[i-1][j+1] == word[1])
                    {       
orient->upDown = UP;
                        orient->leftRight = RIGHT;
strcpy(orient->orient_id, "UP-RIGHT");
if(searchRestOfWord(word, puzzle, *orient, i-1, j+1, 2) == 1)
                        {
*row = i;
*col = j;
return 1;
}
}
}

if(j != 9 && i != 9)
                {
                    if(puzzle[i+1][j+1] == word[1])
                    {       
orient->upDown = DOWN;
                        orient->leftRight = RIGHT;
strcpy(orient->orient_id, "DOWN-RIGHT");
if(searchRestOfWord(word, puzzle, *orient, i+1, j+1, 2) == 1)
                        {
*row = i;
*col = j;
return 1;
}
}
}

if(j != 0 && i != 0)
                {
                    if(puzzle[i-1][j-1] == word[1])
                    {       
orient->upDown = UP;
                        orient->leftRight = LEFT;
strcpy(orient->orient_id, "UP-LEFT");
if(searchRestOfWord(word, puzzle, *orient, i-1, j-1, 2) == 1)
                        {
*row = i;
*col = j;
return 1;
}
}
}

if(j != 0 && i != 9)
                {
                    if(puzzle[i+1][j-1] == word[1])
                    {       
orient->upDown = DOWN;
                        orient->leftRight = LEFT;
strcpy(orient->orient_id, "DOWN-LEFT");
if(searchRestOfWord(word, puzzle, *orient, i+1, j-1, 2) == 1)
                        {
*row = i;
*col = j;
return 1;
}
}
}
}
}
}

return 0;
}

/* searchRestOfWord - after a word's orientation is found, this function searches recursively
 * until the end of the word is found
 *
 * args:
 * char word[] - the word being searched for
 * char puzzle[][10] - the puzzle to search in
 * orientation_t orient - the orientation of the word
 * int row - the current row
 * int col - the current col
 *
 * return value: returns 1 if the entire word is found and 0 if not */
int searchRestOfWord(char word[], char puzzle[][10], orientation_t orient, int row, int col, int wordIndex)
{
if(word[wordIndex] == puzzle[row+orient.upDown][col+orient.leftRight]) /* if next letter matches */
{
if(wordIndex == strlen(word)-1)
{
return 1;
}
else
{
return searchRestOfWord(word, puzzle, orient, row+orient.upDown, col+orient.leftRight, wordIndex+1);
}
}
else
{
/* next letter doesn't match - return false */
return 0;

}
}

/* readPuzzle - read in the puzzle from a file
 *
 * args:
 * char fileName[] - the file to read
 * char puzzle[][10] - the puzzle to read into
 *
 * return value: none */
void readPuzzle(char fileName[], char puzzle[][10])
{

FILE *in;
int i = 0, j = 0, end;
char c;

in = fopen(fileName, "r");
end = fscanf(in, "%c", &c);

while(end != EOF && i < 10)
{
if(c == '\n')
{
i++;
j = 0;
}
else if(isalpha(c))
{
puzzle[i][j] = c;
j++;
}

end = fscanf(in, "%c", &c);
}

fclose(in);
}

/* printPuzzle - prints the puzzle to the terminal
 *
 * args:
 * char puzzle[][10] - the puzzle to print
 *
 * return value: none */
void printPuzzle(char puzzle[][10])
{
int i, j;

printf("Puzzle:\n");
for(i = 0; i < 10; i++)
{
for(j = 0; j < 10; j++)
{
printf("%c", puzzle[i][j]);
}
printf("\n");
}
}

Here's a picture of an example run:



I can post more of my assignments on here if some want me to - I have a whole quarter's worth of C programs.  That being said, they're very basic programs that would only be useful to beginners.  This quarter we're working with Java and object-oriented programming, so hopefully they give me more assignments worth posting.

2
C - C++ / Re: [C] THREADED FTP dictionary attack tool
« on: July 28, 2013, 02:19:39 AM »
Impressive stuff! +1
I love that you have credit where credit is due as well.

3
Java / [Java Source] Theify Java Text Editor & JFontChooser
« on: July 08, 2013, 05:39:42 AM »
Hello EZ,

I was going through some old projects of mine, and I found a text editor I programmed in Java from awhile back.  I just went through the forums I posted this on back then, and it seems it dates back to August of 2010.  Anyway, I coded this text editor just for fun and practice with GUI applications in Java. The project has two parts: the text editor and the font chooser dialogue.  Swing does not include a dialogue for font choosing, so I coded my own for this project.  Again, this is from 2010.

JFontChooser:

This is a subclass of JDialog, and works a lot like a JFileChooser or JColorChooser (with small differences, of course). It has full support for font color, and detects all the font families currently installed on your system, whatever OS you might have installed.

Here is the class file (I rushed through it and commented it a tiny bit):

Code: (java) [Select]
package textEdit;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;


@SuppressWarnings("serial")
public class JFontChooser extends JDialog implements ActionListener, ListSelectionListener{

private JList fontList; //declare all GUI components, etc
private DefaultListModel fontListModel;
private JScrollPane fontListScroller;

private JList styleList;
private DefaultListModel styleListModel;
private JScrollPane styleListScroller;

private JList sizeList;
private DefaultListModel sizeListModel;
private JScrollPane sizeListScroller;

private JButton chooseColorButton;
private JButton OK;
private JButton cancelButton;
private JLabel sampleLabel;

public static final int APPROVED = 0; //will be used to see whether the cancel button
public static final int CANCELED = 1; //or OK button was pressed
public int result; //will contain either APPROVED or CANCELED

private String[] availableFonts; //will filter in all available fonts on the system

private Color newColor; //new font color gathered from Dialog
private Font newFont; //new font gathered from Dialog

private String currentFontFace; //these three are used for constructing the new font
private int currentFontStyle;
private int currentFontSize;

public JFontChooser(JFrame parent, String title) { //constructor #1

super(parent, title, true);
setupGUI();

}

public JFontChooser() { // constructor #2

super();
setupGUI();

}

public void showFontDialog() { //makes Dialog visible
this.setVisible(true);
}

private void setupGUI() { //builds GUI, but does not make it visible

this.setBounds(400, 150, 400, 330);
this.setResizable(false);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
//this.setLayout(new GridLayout(2, 3, 10, 10));
this.setLayout(null);

fontListModel = new DefaultListModel();
fontListModel.addElement("Serif");
fontListModel.addElement("Sans-serif");
fontListModel.addElement("Monospaced");
fontListModel.addElement("Dialog");
fontListModel.addElement("DialogInput");


availableFonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();

for(int i = 0; i < availableFonts.length; i++) {

fontListModel.addElement(availableFonts[i]);

}

fontList = new JList(fontListModel);
fontList.setSelectedIndex(0);
fontList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
fontListScroller = new JScrollPane(fontList);

styleListModel = new DefaultListModel();
styleListModel.addElement("Plain");
styleListModel.addElement("Bold");
styleListModel.addElement("Italic");
styleListModel.addElement("BoldItalic");

styleList = new JList(styleListModel);
styleList.setSelectedIndex(0);
styleList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
styleListScroller = new JScrollPane(styleList);

sizeListModel = new DefaultListModel();
sizeListModel.addElement("8");
sizeListModel.addElement("9");
sizeListModel.addElement("10");
sizeListModel.addElement("11");
sizeListModel.addElement("12");
sizeListModel.addElement("14");
sizeListModel.addElement("16");
sizeListModel.addElement("18");
sizeListModel.addElement("20");
sizeListModel.addElement("24");
sizeListModel.addElement("28");
sizeListModel.addElement("32");
sizeListModel.addElement("36");
sizeListModel.addElement("48");
sizeListModel.addElement("72");

sizeList = new JList(sizeListModel);
sizeList.setSelectedIndex(3);
sizeList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
sizeListScroller = new JScrollPane(sizeList);

chooseColorButton = new JButton("Color...");
chooseColorButton.addActionListener(this);
OK = new JButton("OK");
OK.addActionListener(this);
cancelButton = new JButton("Cancel");
cancelButton.addActionListener(this);

sampleLabel = new JLabel();
sampleLabel.setText("Sample!");

fontList.addListSelectionListener(this);
styleList.addListSelectionListener(this);
sizeList.addListSelectionListener(this);

this.add(fontListScroller);
this.add(styleListScroller);
this.add(sizeListScroller);
this.add(chooseColorButton);
this.add(OK);
this.add(cancelButton);
this.add(sampleLabel);

fontListScroller.setBounds(20, 20, 113, 148);
styleListScroller.setBounds(163, 20, 93, 148);
sizeListScroller.setBounds(286, 20, 73, 148);
chooseColorButton.setBounds(20, 250, 90, 30);
OK.setBounds(190, 250, 90, 30);
cancelButton.setBounds(295, 250, 90, 30);
sampleLabel.setBounds(100, 160, 400, 80);

}

public void actionPerformed(ActionEvent evt) {

String source = evt.getActionCommand();

if(source.equals("Color...")) { //set new font color using JColorChooser

newColor = JColorChooser.showDialog(this, "Choose your font color!", null);
sampleLabel.setForeground(newColor);

}

if(source.equals("OK")) { //set result to APPROVED and close dialog

result = APPROVED;
this.dispose();
}

if(source.equals("Cancel")) { //set result to CANCELED and close dialog

result = CANCELED;
this.dispose();

}
}

public Color getNewColor() { //getter for the new font color

return newColor;

}

public Font getNewFont() { //getter for the new font

return newFont;

}

public void valueChanged(ListSelectionEvent arg0) { //selection listener for the JLists
//sets new font and displays it in
//the sample label

currentFontFace = (String) fontList.getSelectedValue();
currentFontStyle = styleList.getSelectedIndex();
currentFontSize = Integer.parseInt((String) sizeList.getSelectedValue());

newFont = new Font(currentFontFace, currentFontStyle, currentFontSize);

sampleLabel.setFont(newFont);

}

}

And here is a picture:



Usage with a JTextArea:

Code: (java) [Select]
JFontChooser fontChooser = new JFontChooser(myJFrame, "Choose your font!");
fontChooser.showFontDialog();
if(fontChooser.result == JFontChooser.APPROVED) {

textarea.setFont(fontChooser.getNewFont());
textarea.setForeground(fontChooser.getNewColor());

}



Theify's Java Text Editor:

Code: (java) [Select]
package textEdit;
import javax.swing.*; //import errything
import javax.swing.filechooser.FileNameExtensionFilter;


import java.awt.*;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;

import textEdit.JFontChooser;

@SuppressWarnings("serial")
public class TextEditorGUI extends JFrame implements ActionListener{


private static String fileName = "Untitled"; //declare GUI components and some others
private static JFrame window;
private static JTextArea textarea;
private static JPanel content;
private JScrollPane scroller;
private JMenuBar menuBar;
private JMenu fileMenu;
private JMenuItem openFile;
private JMenuItem saveFile;
private JMenuItem saveAsFile;
private JMenuItem exitFile;
private JMenu formatMenu;
private JMenuItem fontFormat;
private JMenuItem backgroundColorFormat;
private JCheckBoxMenuItem wordWrapFormat;
private static JFileChooser chooser = new JFileChooser(System.getProperty("user.dir"));
private JFontChooser fontChooser;
private static int returnVal;
private boolean hasBeenSaved = false;
private Color backColor;

public static void main(String[] args) { //basically, initiate the program

window = new TextEditorGUI();
window.setDefaultCloseOperation(EXIT_ON_CLOSE);
window.setVisible(true);

}

public TextEditorGUI() { //constructor, no args...setup GUI

super(fileName + " - Theify's Java Text Editor");
this.setSize(new Dimension(700, 600));
this.setLocation(300, 100);

fontChooser = new JFontChooser(window, "Choose your font!");
content = new JPanel();
textarea = new JTextArea();
textarea.setLineWrap(true);
textarea.addKeyListener(new changedListener());
scroller = new JScrollPane(textarea);
content.setLayout(new BorderLayout());
content.add(scroller, BorderLayout.CENTER);

menuBar = new JMenuBar();

fileMenu = new JMenu("File");
openFile = new JMenuItem("Open");
openFile.addActionListener(this);
saveFile = new JMenuItem("Save");
saveFile.addActionListener(this);
saveAsFile = new JMenuItem("Save As...");
saveAsFile.addActionListener(this);
exitFile = new JMenuItem("Exit");
exitFile.addActionListener(this);

fileMenu.add(openFile);
fileMenu.add(saveFile);
fileMenu.add(saveAsFile);
fileMenu.add(exitFile);
menuBar.add(fileMenu);

formatMenu = new JMenu("Format");
fontFormat = new JMenuItem("Font");
fontFormat.addActionListener(this);
backgroundColorFormat = new JMenuItem("Back-Color");
backgroundColorFormat.addActionListener(this);
wordWrapFormat = new JCheckBoxMenuItem("Word Wrap");
wordWrapFormat.addActionListener(this);
wordWrapFormat.setSelected(true);

formatMenu.add(fontFormat);
formatMenu.add(backgroundColorFormat);
formatMenu.add(wordWrapFormat);
menuBar.add(formatMenu);

add(content);
this.setJMenuBar(menuBar);

FileNameExtensionFilter filter = new FileNameExtensionFilter("Text Files", "txt");
chooser.setFileFilter(filter);
}



public void actionPerformed(ActionEvent evt) { //when any menu item is pressed

Object source = evt.getActionCommand();

if(source.equals("Open")) { //use JFileChooser to select a file, and open it

if(hasBeenSaved == false) { //check if the current file has been saved and confirm the user's actions

String message = "Opening a new file will disregard any unsaved changes made to your current file.  Continue?";
String title = "Continue?";
returnVal = JOptionPane.showConfirmDialog(window, message, title, JOptionPane.YES_NO_OPTION);
if(returnVal == JOptionPane.NO_OPTION) {
return;
}
else if(returnVal == JOptionPane.YES_OPTION) {

try {
OpenFile();
}
catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(window, "File Not Found.");
}
}
}
else {
try {
OpenFile();
}
catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(window, "File Not Found.");
}
}
}

if(source.equals("Save")) { //check if the current file has been saved, and save

if(fileName == "Untitled") SaveAsFileProc();
else SaveFileProc(fileName);

}

if(source.equals("Save As...")) { //run saveAs function

SaveAsFileProc();

}

if(source.equals("Exit")) { //exit

System.exit(0);

}

if(source.equals("Font")) { //use JFontChooser to select and set a new font/font color

fontChooser.showFontDialog();
if(fontChooser.result == JFontChooser.APPROVED) {

textarea.setFont(fontChooser.getNewFont());
textarea.setForeground(fontChooser.getNewColor());

}

}


if(source.equals("Back-Color")) { //use JColorChooser to set the back-color of the textarea

backColor = JColorChooser.showDialog(window, "Choose a color!", Color.black);
textarea.setBackground(backColor);

}

if(source.equals("Word Wrap")) { //on/off switch for word wrap

if(textarea.getLineWrap() == true) textarea.setLineWrap(false);
else textarea.setLineWrap(true);

}

}

void OpenFile() throws FileNotFoundException { //open file function

returnVal = chooser.showOpenDialog(window); //use JFileChooser
if(returnVal == JFileChooser.APPROVE_OPTION) {

File newFile = chooser.getSelectedFile();

fileName = newFile.getPath();
hasBeenSaved = true;
saveFile.setEnabled(false);
resetWindowTitle();

FileReader fr = new FileReader(newFile); //use FileReader and BufferedReader
BufferedReader br = new BufferedReader(fr);
String nextLine = null;
textarea.setText(null);

try { //read file line by line into textarea
while((nextLine = br.readLine()) != null) {

textarea.append(nextLine + "\n");

}

}
catch (IOException e) {
JOptionPane.showMessageDialog(window, "IO Exception.");
}
}
}

void SaveFileProc(String fileName2) { //save file using FileWriter and BufferedWriter

FileWriter file;
try {
file = new FileWriter(fileName2);

BufferedWriter out = new BufferedWriter(file);

//save line by line
StringReader sr = new StringReader(textarea.getText());
BufferedReader br = new BufferedReader(sr);
String nextLine = "";
while ((nextLine = br.readLine()) != null){ //write it out line by line
out.write(nextLine);
out.newLine();
}

out.close();

hasBeenSaved = true;
saveFile.setEnabled(false);

}
catch (IOException e) {
JOptionPane.showMessageDialog(window, "IO Exception.");
}
}

void SaveAsFileProc() { //use JFileChooser to select file to save as, and use SaveFileProc

returnVal = chooser.showSaveDialog(window);
if(returnVal == JFileChooser.APPROVE_OPTION) {

File newFile = chooser.getSelectedFile();
fileName = newFile.getPath();
resetWindowTitle();

SaveFileProc(fileName);
}
}

void resetWindowTitle() {

window.setTitle(fileName + " - Theify's Java Text Editor");

}



public class changedListener implements KeyListener { //whenever a key is typed, file is declared unsaved

public void keyPressed(KeyEvent evt) { }
public void keyReleased(KeyEvent evt) { }
public void keyTyped(KeyEvent evt) {

if(hasBeenSaved == true) hasBeenSaved = false;
if(saveFile.isEnabled() == false) saveFile.setEnabled(true);
}
}
}

Picture (from 2010):





Anyway, that's it.  The only reason I decided to post this old project after I dug it up is because I thought it might have some educational value.  It shows how to go about creating GUI applications in Java, along with click event handling, etc.  Let me know what you think!

4
Web Oriented Coding / Re: Code preview using jQuery not working
« on: July 06, 2013, 09:23:57 AM »
Thank you sooo much!!! Its really appreciated.

Glad I could help!  Feel free to post any other web design questions you have here, I'll always try to get to them eventually.

5
Web Oriented Coding / Re: Code preview using jQuery not working
« on: July 05, 2013, 12:44:32 AM »
There are a couple things wrong with it.

First off, you never included JQuery in your HTML file.  Do that with:

Code: (html) [Select]
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
Second, your selectors are wrong when you're getting the val() of the two textboxes.  You need to include the "#" like so:

Code: (javascript) [Select]
$("#pastecode").val();

Lastly, I took out the XML and htmlentities stuff from your PHP file.  That was screwing everything up.  That made everything work with my C++ example and what not.  Also, I can still print the raw html I put in the textarea, but there is no highlighting for it when it displays.  That's a separate problem on it's own though.  I also used the post() Jquery function instead of ajax(), but both would work.  I just use post() because it's easier in this case (it's the same thing as ajax() but simplified specifically for POSTs).  I went ahead and recreated the situation on my server, with all the changes made:

index.php

Code: (html) [Select]
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 <html>
 <head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
 <script type="text/javascript" src="preview.js"></script>
 <meta http-equiv="content-type" content="text/html; charset=windows-1250"> <title>Test Code Preview</title>
 </head>
 <body>
 <textarea id="pastecode" rows="20" cols="50" name="pastecode"></textarea>
 <br /><input type="text" id="language" name="language"/>
 <br /><input type="button" onclick="process()" value="Preview"/>
 <br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
 <div id="previewcode"><>
 </body>
 </html>

preview.js

Code: (javascript) [Select]
function process(){

pastecodeVal = $("#pastecode").val();
languageVal = $("#language").val();

$.post("preview.php", { pastecode: pastecodeVal, language: languageVal },
         function(data) {
           
            $("#previewcode").html(data);
         
      });

}

preview.php

Code: (php) [Select]

<?php
 
   
if(!empty($_POST['pastecode']) && !empty($_POST['language']))
   {
       
$code=$_POST['pastecode'];
       
$language=$_POST['language'];
       include(
"geshi/geshi.php");
       
$path     '';
       
$geshi    = new GeSHi($code$language$path);
       
$geshi->set_overall_style('background-color: #ffffee;'true);
       
$out $geshi->parse_code();
       echo 
$out;
   }
   else
   {
       echo 
"<p>Nothing to display</p>";
   }

?>


Works like a charm on my end.



6
Scripting Languages / [Python] EZ Reputation Grabber
« on: July 01, 2013, 10:36:49 PM »
Hey EZ,

I was bored today and thought of the idea to code an EZ reputation checker.  Basically, you enter in your user ID, which can be found in the URL of your profile page after clicking on your name anywhere in the forums.  The link will look like: http://evilzone.org/profile/?u=[your user id]

After you enter that in, it checks your current reputation and displays it.  Then, it checks your rep again every 5 minutes and displays it if it has changed since the last time you checked.  Basically this just gave me some practice with httplib2.  I wanted to incorporate a Qt Message Box or something, but I'll do that later.  Here's the code:

Code: (python) [Select]
#!/usr/bin/env python3

import httplib2
import re
import time

httpObject = httplib2.Http(".cache")

def lookUpRep(uID):
    URL = "http://evilzone.org/profile/?u=" + str(uID)
    response, content = httpObject.request(URL, headers={'cache-control':'no-cache'})
    contentString = content.decode('utf-8')
    x = re.search(r"\+[0-9]{1,4}", contentString)
    if x:
        rep = x.group(0)
        return rep
    else:
        return False
       
if __name__ == '__main__':
    userID = input("Please enter a valid EvilZone User ID: ")
    currentRep = lookUpRep(int(userID))
    if currentRep != False:
        print("Your current rep is: ", currentRep)
        print("I will notify you when it changes...")
        while 1:
            time.sleep(300)
            newRep = lookUpRep(int(userID))
            if newRep != currentRep:
                print("Rep has changed!")
                print("New rep: ", newRep)
                currentRep = newRep
    else:
        print("You entered an incorrect user ID.")

I'll edit it a bit later to put proper docstrings in and what not.

7
C - C++ / Re: My intro to control structures
« on: July 01, 2013, 08:47:13 AM »
Isn't that primarily a C function? If so, I don't think it's a good idea to mix-and-match C and C++.

Anyway:Source: http://stackoverflow.com/questions/6222583

Also, you're a lot better at explaining things than me, Theifyppl :P

Ah you're totally right. I was getting my C strings and C++ Strings mixed up. I just remembered having to use the strcmp() function before, but that's when I was using C strings with sockets. Good save :) +1

And thank you, haha. You're definitely not bad yourself, though.

8
C - C++ / Re: My intro to control structures
« on: July 01, 2013, 01:48:42 AM »
That does look alot better. I'm not being lazy and just writing shitty code - this is code I have written from what I been learning from the tutorials, so my bad.
Thanks for answering my questions. :)

Don't feel bad at all.  You're still learning and it takes time to be able to write clean, well organized code.  The errors you have below are because of your if statements.

if (x= option 1) does not work for a number of reasons.  First of all, in any if statement, you need a boolean operation (true/false outcome) to determine if the if statement should run.  The boolean operator to check if something is equivalent is "==" not "=".  This is very important.  Always use "=" when assigning a value to a variable, and always use "==" when comparing values.  This is what Fur was saying as well.

So now we have if (x == option 1) so far.

Second of all, I don't understand what you're trying to compare x to.  Are you seeing if x equals the string "option 1"?  If so, there's two things that need to be addressed: if the user enters "hi my name is james" and you use "cin," cin will only return the first word ("hi").  Therefore, in this case, you should use a getline() function.  Secondly, you would need quotation marks around the "option 1" in your if statement:

if (x == "option 1")


Note: Actually, if you're comparing strings, you should use the strcmp() function.  There's a good example of how to use it in the third post here: http://www.cplusplus.com/forum/beginner/38544/
However, if (x == "option 1") will probably still work.

EDIT: Nevermind, strcmp() is for C strings, not C++ strings. Thank Fur for pointing that out.

Lastly, if you were intending to compare x to a variable "option 1," know that variable names are not allows to have spaces in them.  So you would need to declare a variable named option1, or something.  But I assumed you were comparing x to the string "option 1."

Everything I just mentioned also applies to line 36, which I assume is where you have if (x == option 2). 

Edit: I also see that you have x declared as an unsigned char.  Were you intending the user to just enter 1 or 2? If so, you should be more clear in your instructions.  And your if statement would look like:

if (x == '1') or if (x == '2')

Please note the single quotes instead of doubles quotes.  Using double quotes, like "1," tells the compiler that you're comparing to an array of characters (a string) that only contains one character.  Using single quotes, like '1', tells the compiler that you're comparing to the character '1'.

9
C - C++ / Re: My intro to control structures
« on: June 30, 2013, 07:55:00 AM »
Shouldn't your if statements be checking data2, not data? In the last part I mean. Sorry if I'm mistaken, I didn't read through the whole thing because I'm not home right now.

10
Glad you guys enjoyed it!

I added in a small section for drop shadows, an HTML5/CSS3 disclaimer, and a couple other changes. Like I said, if there's anything else you guys would like to see me add, just let me know!

11
Awesome tutorial, but this belongs in the tutorial section, so I moved it :)

Thanks for that! I wasn't sure where to put it so I was counting on something like that happening :)

12
Hello EZ,

Since I’m relatively new here, not many of you are aware that I do freelance website design for extra money on the side.  I do it with a graphic design partner, and the process of creating a website usually begins with my partner creating the full design in Photoshop.  After the design is approved by the client, I go ahead and slice the design into several pictures to use with HTML/CSS to create the design. I’m writing this tutorial on splicing the images based on my experiences.  My partner and I don’t use any frameworks – our designs are 100% unique and customized to the clients’ requests.  This means that every time we create a website, I have to go through this process. 

This is a living document. Right now I’m submitting explanations on how to splice the images in certain situations, but every design is different.  If there is a certain aspect I have not covered, feel free to comment and I will eventually get to updating the tutorial. Also, this was my best bet for a forum section that fit this topic.  If a moderator/admin disagrees, feel free to move it.

This tutorial is about slicing Photoshop templates into images in order to recreate the template with HTML/CSS, but it does not cover the HTML/CSS required (as of now).  It assumes some basic background knowledge in those two subjects as well (Javascript w/ Jquery will also be beneficial).   It also assumes very basic familiarity with the Photoshop UI.  The Photoshop version I use is a portable version of CS5. Location of buttons, dialogues, etc. may be different on other versions of Photoshop.  Search around.

The Main Objective:

Anyone can slice a bunch of images up and set it as the background of a DIV element in order to recreate Photoshop templates.  However, that’s not the point of the process.  The idea behind the process is to use the least amount of images, and the smallest images possible to minimize the time it takes to load the page. Believe me, the time it takes to load a webpage increases exponentially with each large picture you add to the design.

The techniques used to slice images in this tutorial are also recommended for maximizing the ability to modify the design without having to use Photoshop.  If you do it right, you can edit box sizes, add more navigation items, etc. without having to re-slice any images.  So, let’s dive in!

HTML5/CSS3 Disclaimer:

I assume that use of CSS3 or HTML5 techniques are not an option in this tutorial because they are not always backward-compatible with older browsers, which is very important as a freelance website designer. However, there are libraries/techniques you can find online that replicate HTML5/CSS3 capabilities for older browsers. I've been forced to use them in some cases, and they've worked for my needs at that time. But that was only in the case that I could not achieve what I needed with these techniques. I recommended sticking with these techniques as far as they take you since they are guaranteed to work all the time. However, I also encourage you to experiment with those libraries if you're interested in doing so.

How to Slice:

Before I can teach you the best ways to slice the correct images, you must first know how to slice. “Slicing” is selecting different sections of a Photoshop template to be saved separately, as their own image.  In order to slice a section out of a template, you must use the Slice Tool:



Using the Slice Tool is pretty self-explanatory.  But you should know that, when slicing, it’s very important to be accurate to the exact pixel.  Zoom in to 2000% if you have to.  Trust me, being exact really reduces stress/annoyances later. 

After you slice your selection, you can use the Slice Select Tool (also shown in that picture) to select your slice.  Right click your slice and choose “Edit Slice Options.”  In this dialogue, you can change the name of the slice, the x,y coordinates, and it’s height and width.  You should definitely change the name of the slice, as this is the name that the separate image file will be named after you save it.

You may do as many slices as you want.  Once you want to save all your slices, choose “File -> Save for Web & Devices”. Use this dialogue to save all your slices.  You can select each individual slice and change the file type it should be saved as (JPEG, PNG, etc.), and choose a destination folder for all the images. Use the dialogue, see how it works, and get used to it.

Backgrounds (Body, Div, etc.):

Every design has a background, whether it’s a simple color, a gradient, a pattern, etc.
 
Simple Color: If it’s a simple color, you’re in the clear! Here’s what you do:

  • Click the color chooser in Photoshop.
  • Move the color chooser dialogue out of the way and, while it’s still open, click the background color.
  • The color’s hex code and RGB code should now be displayed in the color chooser dialogue.  Use one of those codes in CSS to set the background-color of the div, body, or whatever element you want.
Gradient: Gradients are a bit more complicated.  Actually, if the gradient is not completely vertical or horizontal, you must skip to giving up and saving the whole picture.  Otherwise, you can use the technique I’m about to explain. Know your repeat-x and repeat-y. In CSS, when you define a background image for any element, you can also specify its background-repeat attribute.  By default, the image is set to repeat vertically and horizontally until it fills the height and width of the element.  Setting this attribute to no-repeat results in the image not repeating at all.  Setting this attribute to repeat-x results in the image only repeating horizontally, and setting this attribute to repeat-y results in the image only repeating vertically.  This is very advantageous in certain situations.  Repeat-x is most commonly used, and it can be used in navigation menus, div elements, body backgrounds, whatever.  With repeat-x, the width of the box can be edited by simply editing the width of the element in CSS.  With repeat-y, the same is true for the height.
 
The repeat-x/repeat-y technique:

This technique is very simple, actually.  If the background of the body of your website is a vertical gradient/pattern, and using a repeat-x technique applies to it, all you have to do is slice a picture of the background that is 1px wide and the height of the background.  So, if your Photoshop template’s canvas height is 1000px, you will save a slice of your background that is 1000px tall and 1px wide. 

What if your actual webpage is taller than the repeat-x image?

This is a common issue with the repeat-x/repeat-y technique.  Here’s what you do:

  • Create a separate div element inside the body tags to be the “background” of your web-page.  Have it be as wide as the whole page, and as tall as the template. So, in our example, it would be 1000px tall, and the width would be 100% (*). 
  • Then, use the color chooser dialogue (like we did earlier) to get the color code of the color at the VERY bottom of the 1px wide image. 
  • Set the background-color attribute of the body element to this color.  That way, if the document is taller than 1000px, it will just continue on with the gradients last color.
*Sometimes certain browsers don’t bode well with width:100% in CSS.  In this case, what I do is use JQuery to create a method for whenever the browser window resizes.  This method calculated the total width of the document, and sets the width of the background div to this width.  This method should also be ran on document.load().   

If the situation calls for a repeat-y instead of a repeat-x, do everything you did with width, but with height (1px tall image, 100% height).

Pattern: If the background is a pattern (one that you can’t use a repeat-x or repeat-y technique with), then your only option is to attempt to slice a square image that will work with a default repeat. This could be anything.  If you have a pattern of flowers that repeats every 50px, slice out a 50px by 50px square and keep the repeat settings defaulted. If this type of pattern exists, it’s very likely the graphic designer behind the template (if not you) used a pattern to create it.  If you cannot come up with the square to slice, it might be a good idea to contact the designer to see if they can manage something.  If not, the only other option is to give up and save the whole picture.

Transparency:

Although this is a very small topic to cover, it’s used enough to deserve its own section.  Transparency in images is a very common problem – after all, you can only slice images in the shape of a box.  What happens when you have a different shape in your template? Well, you need to find the section of Photoshop that displays all of the layers with checkboxes (although the “checks” are eyeballs):



One of those layers contains the shape that you want to slice, and other layers probably provide background for that shape.  Find those layers and uncheck them until all you see is the shape with the checkered Photoshop background behind it.  From there, you may slice the image and go to “File -> Save for Web & Devices…” and save the slice as a PNG.  It’s important that you save it as a PNG – PNG is the only format that supports transparency (besides GIF, but GIF sucks in comparison).  There are two options in the menu under file type for PNG: PNG-8 and PNG-24.  Choose PNG-24.  You can experiment with GIF and PNG-8, but I’ve always found they come out with much less quality than PNG-24. 

There are two ways to slice the image in this case.  Once the background is gone, you can use the select tool (which is what I call it, it has some other fancy name):



Use the tool to just roughly select the shape you want to save.  Make sure the correct layer is selected. Then, right click the selection, and click “Layer via Copy.” This will create a new layer with just your selection in it.  Find that layer in the dialogue that displays the layers, right click it, and click “Duplicate Layer.”  Once the dialogue pops up, under “Destination,” select “New.”  This will create a new canvas with just your layer on it.  If the background is already transparent (and it should be), you can then go to the menu, click “Image,” and find “Trim…”. Click that, and make sure all these boxes are checked:



Press OK, and then your image should be reduced to its minimum size.  You can then save it as a PNG. 

Your other option is to skip all of the “Layer via Copy” crap and use the Slice Tool on the same document.  But if this is your choice, you must zoom in enough to make sure your slice is accurate and concise to the very pixel.  This will reduce annoyances later.

Fonts:

Fonts are a big issue in converting a Photoshop template to HTML/CSS.  Photoshop has such a large variety of amazing and artistic fonts available for download, while there are very few web-safe fonts available.  By “web-safe fonts,” I am referencing fonts that will be visible by everyone, no matter what fonts they have installed on their system. This is actually a big issue. Many clients are picky about fonts, and some designs require specific fonts to look just right.  If you use font in your CSS that is installed on your system, the browser will display it; however, if it’s not installed, it will default to a different font.  If you’re using some special Photoshop font, I really doubt everyone that visits your site will have it installed.  In the case that you have a non-web-safe font in your Photoshop template, you have two options: either settle with a web-safe font, or search GoogleFonts or sites like http://www.fontsquirrel.com to safely import other fonts.  Since the issue of fonts has been around for so long, Google Fonts and sites like the one I just linked to are dedicated to providing the capability of using their free services to safely use fonts that are not officially declared “web-safe.”  Google Fonts hosts the fonts on their servers and allows you to import them.  That way, the font is server-side (taken from the web server), not client-side (taken from the browser’s computer).  Font Squirrel does the same thing, except instead of just allowing you to link to their server, they give you all the font files you need.  All you need to do is link to the CSS file they give you, and then reference the font as you would normally in your CSS.  Both are great.  If you cannot find your font on any websites like those, give up and settle for a similar font, or slice a picture of the words you’re using.  Slicing a picture of the words you’re using is very inconvenient if you ever have to change the words or anything, though.

Rounded Corners:

Rounded corners are one of the most popular topics asked about when converting Photoshop templates to HTML/CSS, and I’ve seen it done multiple ways.  The way I’m about to explain has always worked best for me.  Of course, with CSS3, it’s possible to create boxes with rounded corners and shadows without Photoshop.  Hell, it’s even possible to create gradient backgrounds in CSS3.  But I usually refrain from using HTML5/CSS3 because I know 90% of the world hasn’t upgraded their browsers enough to support those.  This isn’t important if you’re just creating a website for your own personal needs, but if you’re creating a website for an older client that still uses IE 8, they will be very particular about the design being exactly correct. Using Photoshop to slice images and create the rounded corners yourself will be the most cross-browser compatible and backward-compatible technique. 

Since I’ve already explained saving transparent images and using the repeat-x technique, then all you need to know is this:

 
  • Make sure that behind the box is only a transparent area (no other layers).
  • Slice the left edge of the box.  Make sure to get all of the curved sections in that slice.
  • Do the same with the right edge.
  • Slice a repeat-x 1px wide image anywhere in the middle of the box.
  • Make sure to save the edges as PNG-24 for transparency in the corners.
  • In HTML, create a div with the repeat-x image as the background. Before and after the div, place the rounded images and use relative positioning to position them correctly. Or, you can do whatever else you want to position them.  You could also maybe put the images inside the div and relatively position them using negative left and right values or something.  Experiment with the CSS.  As stated at the beginning of the tutorial, I’m not writing this to show you how to do that part.


If you need the box to have a varied height, you could also slice the top and bottom edges of the box, and use a repeat-y. 

Drop Shadows:

The use of drop shadows (or any kind of outer shadows) is a very common design technique to give off a nice 3D effect. Since I've already covered transparency and the importance of zooming to the exact pixel, all you need to know is this:

  • You will need to zoom in a lot in order to be exact with the pixels and how far outward the shadow extends when you slice.
  • Seeing how far the shadow goes outward is a little harder with the checkered background. If it helps, you can slice it with other layers behind it and later remove the other layers.
  • As I just explained, before you save, make sure no other layers are behind the shadowed shape you want to slice. You should see the checkered background behind it.
  • As with all transparent images, save the slice as a PNG-24.

Navigation Menus:

Using HTML/CSS/JQuery to create navigation menus is probably the hardest task in converting a Photoshop template to a webpage.  The CSS and HTML of each navigation menu is sort of different.  That subject is beyond the scope of this tutorial, but slicing the images for it is not.  Take a look at a simple yet good-looking navigation menu I converted from a Photoshop template:



Slicing the images for a navigation menu is probably the easiest part.  I’ve already covered all the techniques required:

  • If the template has a navigation menu that uses rounded corners (like the one above does), use the same techniques I explained above.
  • Make sure to always use the repeat-x technique.  This way, your menu items can be a varied character length, and you can even add/remove menu items by just adding another item in HTML.
  • For hover/onclick events, simply save a modified/darker (whatever you want) slice of the repeat-x image and use the a:hover or a:active CSS selectors to change the background-image attribute of the menu item.  More information on that can be Googled. 
  • Also save a slice that contains a separator in the menu, used to visually separate each menu item (refer to the menu above).


Of course, all of this is optional and depends on the template you’re using.  If you’re template just uses a regular horizontal list with no special effects, so be it.  Slicing the images isn’t your main worry, the CSS is.

When dealing with navigation menus or boxes with rounded corners (or any slices that are required to be the same height or width), right click the slice with the Slice Select Tool. Click "Edit Slice Options" and make sure all the slices are the height or width needed. If you mess this up, it'll probably end up fucking you when you go to do the CSS.

The reason it’s important and better to use repeat-x images instead of just taking separate pictures of the full menu items is more of an issue of flexibility than load speed. Sure, the images will be smaller and that’s great.  But imagine finishing a navigation menu, only for your client to ask you to either add a link, or change the words of a link.  You would have to go through Photoshop, change everything up, possibly resize/reposition the slices, and re-save the images.  It’s just a pain that should be avoided.  With the repeat-x technique, you can simply change the HTML and solve the issue in a matter of seconds.

Giving Up and Saving the Full Image:
 
Sometimes, when all of the methods I mentioned above (or any other methods you can think of) fail, you just have to save a full image and deal with it.  Just accept the loss of load time (maybe compress the file to be smaller?) and the loss of flexibility.  This option should only be used if there’s absolutely no other option.
   
Well, that’s all I have for now.  As I said in the beginning of this tutorial, this is a living document.  This is just version one.  If you have any suggestions for additions I can make, let me know. If you have anything you would like me to elaborate on, let me know. If you would like to contribute to the tutorial yourself, you can PM me and I’ll give you credit in the section you contributed.  Also, if you spot any typos or anything, please let me know.  I haven’t read over this draft at all, so I’m sure there will be some.  Thank you! Look for more website design tutorials in the future.

13
C - C++ / Re: Day 1 of me learning C++
« on: June 29, 2013, 12:57:13 AM »
Yeah I know there are so many different ways to approach it! It's causing me to feel lost on what to do!
I need guidance! Lol


My advice is to choose what you're most interested in.  You will have much more fun and learn faster if you're learning something you think is cool.  For example, I've always thought that socket client/server applications were especially cool.  So you can guarantee that when I'm learning a new language, programming a client/server application is at the top of my to-do list.  That being said, you don't even need to worry about this stuff until you're ready to move on from the basics of programming. 

14
C - C++ / Re: Day 1 of me learning C++
« on: June 27, 2013, 10:41:47 PM »
I do want to eventually get into hacking, white hat and black hat. I want to have a vast knowledge around it all. After learning C, my route will head where?


Well, wherever you want it to go.  There are a ton of different programming concepts you can use and apply to hacking/cracking/etc.  If you're interested in programming malware, you could look into socket programming in order to create client/server applications that communicate over the internet.  That way, if you can get one of the ends on the victim's computer, they can communicate and you can program it to do whatever you want.  You could also learn about hardware hooks, to use a keyboard hook to code a keylogger and email you back the logs.  You could learn about HTTP libraries in order to gather information from websites.  There's so many different ways to approach it. 

15
C - C++ / Re: C++ programs and cmd?
« on: June 27, 2013, 06:45:05 PM »
Very nice looking book. I will definitely begin reading this one. What exactly Qt in relation to C++?


Qt is a cross-platform application framework written in C++, although it can also be used in several other languages.  For example, PyQt was written to allow developers to use Qt with Python.  More information here: http://en.wikipedia.org/wiki/Qt_(framework)


And you can also google to find their main website.




Pages: [1] 2


Want to be here? Contact Ande, Factionwars or Kulverstukas on the forum or at IRC.