Recent Entries 10
- pattern minor 112d agoRelated links for WordPress postsI have written the following class which is part of a pagination system in Wordpress. The class works as expected and also works as expected when used in the system. Just as background, the class performs the following task - Takes an array of post ID's and creating links to the posts which ID's is supplied in the array. - Uses Wordpress functions `get_permalink()`, `add_query_arg()` and `get_post_field()` to retrieve the appropriate information to build the links I need a review to asses the correctness of my code, basically how correct is my code, and also, how correct is my use of PHPDoc blocks and the information in these doc blocks. Here is my class: (I have left out the interface) ``` true, 'boundary' => false, 'first' => true, 'anchorText' => '%anchor', 'postLinkText' => '%text', 'spanTextOldest' => 'Oldest post: ', 'spanTextNewest' => 'Newest post: ', 'spanTextPrevious' => 'Older post: ', 'spanTextNext' => 'Newer post: ', ]; /** * Public constructor method * * @param (array) $postIDs Array of post IDs * @param (array) $extraQueryVars Array of query variables to add to the URL's * @param (array) $args Array of arguments. See below * - @param (bool) previous Whether or not to get adjacent post older or newer to current post Default true * - @param (bool) boundary Whether or not to get the boundary posts Default false * - @param (bool) first Whether or not to get the first or last post when the boundary parameter is set to true Default true * - @param (string) anchorText Text to be used as an anchor text Default %anchor * - @param (string) postLinkText Text to be used as link text Default %text * - @param (string) spanTextOldest Text to be used as oldest post link D
- pattern minor 112d agoClass method to insert a record into MySQLI'm just starting out using OOP; classes and methods etc. I've been looking around for some PDO classes/wrappers out there, but there's not much to choose from. So I've tried to make my own. Started out by writing an "insert" method. As a man with low self esteem, I never like what I do myself, so I thought I'd ask you guys here for feedback. Here it is: ``` public function insert($tbl, $data) { $this->_stmt = $this->_dbh->prepare("INSERT INTO $tbl (" . implode(', ', array_keys($data)) . ") VALUES (:" . implode(', :', array_keys($data)) . ")"); foreach($data as $key => $value) { $this->_stmt->bindValue($key, $value, PDO::PARAM_STR); } $this->_stmt->execute(); } ``` The meaning was that it could all be done in one sweep instead of having several methods to do one thing; inserting a record. An example of using this code: ``` $message = 'A message for the ones who like to read it!'; $sent_on = 'Saturday 23rd 2012'; $unique_id = 'unique_as_can_get'; $data = array( 'message' => $message, 'sent_on' => $sent_on, 'unique_id' => $unique_id ); $insert = new DB; $insert->insert('tablename', $data); ``` I've put the database connection into the constructor. The code works as I want it to, but I'm still confused if it's "accepted" amongst you people who are way more skilled that I will ever be. Please let me know if this code if "usable" and/or what is wrong with it, what can be improved/changed etc.
- pattern minor 112d agoEmail Template Parser PHP ClassThis is a very basic PHP class that I am working on which will allow me to provide an HTML template in the form of a string saved to a variable or into an actual template file. I can then pass into my PHP class an array where the array KEYS will be used to find and replace variables in the template HTML. The template will define variables in this format `{{first_name}}`, so my PHP array would have a `key` of `first_name` and its `value` would be parsed into the final result HTML. Example PHP array used to set and replace variables in the templates HTML... ``` $emailValues = array( 'first_name' => 'Jason', 'last_name' => 'Davis' ); ``` This PHP array would then find and replace all occurrences of `{{first_name}}` with `Jason` and `{{last_name}}` with `Davis` I have coded this functionality into countless projects over the years but I generally have defined every single variable that get replaced in the template manually. Purpose I wanted a reusable method of doing this and even better, the flexibility to not have to define what variable are allowed in a template. With this class I can now use it in any project and use any variable I want in a template with `{{varName}}` instead of being confined to a list of variables. It can now have unlimited variables and I don't have to manually set each one up. Simply call the variable in my template and assign a matching `KEY` name in my PHP array of replacement values. I love the concept of it! PHP Email Template Parsing Class ``` _emailValues = $emailValues; $this->_isTemplateFile = $isTemplateFile; if($this->_isTemplateFile){ // Template HTML is stored in a File try { if(file_exists($emailTemplate)){ $this->_emailTemplate = file_get_contents($emailTemplate); }else{ throw new Exception('ERROR: Invalid Email Template Filepath'); } } catch(
- pattern minor 112d agoA User class for visitors to register and log in to a siteI'm just looking for some feedback on my User class. The class is designed to handle users being able to register, login, and logout of the site. I'll be using it in conjunction with a forum I'm also working on. I'm mostly curious how I've handled validation of input, MySQLi interactivity, and whether my code is redundant and horribly structured. ``` username = 'Guest'; $this->password = ''; $this->session = ''; $this->salt = ''; // Checks to see if a cookie is set. If so, examines contents of the // cookie to see if the username and session ID match the set stored // in the database. If a match is found, current Object is initilized // for that user. if(isset($_COOKIE['user'])) { $user_details = explode("|", $_COOKIE['user'], 2); $this->username = $user_details[0]; // First, check that the username is registered in the database. If // the user exists, compare the session ID's and ensure a match. If // one is found, set Object for that user, if not set the Object as a // guest and delete the cookie. if($this->user_exists()) { $connection = user_connection(); $sql = "SELECT session FROM users WHERE username='$this->username'"; $result = $connection->query($sql); $connection->close(); $row = $result->fetch_assoc(); if($row['session'] === $user_details[1]) { $this->session = $row['session']; $_SESSION['user'] = $this; } else { $this->username = 'Guest'; setcookie('user', '', time()-1); } } else { $this->username = 'Guest'; echo "Cookie Login Failed: No such user."; } } // If no cookie is set, check if a session exists. If so, set the current // Object to that user's username and session ID. else if(isset($_SESSION['user'])) { $this->set_
- pattern minor 112d agoChanging a user's passwordI wrote this class for the project I'm currently working on. It's basically used to change a user's password. I'd like to know your thoughts on the basic structure/design of this class and how it can be improved, or if you'd have written it differently. ``` class Recover_password{ //class by sami private $conn; private $password_one; private $password_two; function initialize_connection($conn){ if($conn instanceof PDO){ $this->conn = $conn; }else{ echo "Connection problem accured"; } } function is_posted(){ if(isset($_POST["change_password"])){ $this->is_empty(); }else{ echo "nothing's being posted!"; } } private function is_empty(){ foreach($_POST as $post_value){ if(!empty($post_value)){ $is_empty = false; }else{ echo "Field/s are empty"; break; } } if(isset($is_empty)){ $this->set_values(); } } private function set_values(){ $this->password_one = strip_tags(stripslashes(trim($_POST["password_two"], '"'))); $this->password_two = strip_tags(stripslashes(trim($_POST["password_one"], '"'))); if($this->password_one == $this->password_two){ if( (strlen($this->password_one) > 10) or (strlen($this->password_two) > 10) ){ $this->password_one = md5($this->password_one); $this->change_password_to_new(); }else{ $this->show_message("The password you provided is too weak"); } }else{ $this->show_message("Please make sure the passwords match"); } } private function change_password_to_new(){ $insert_pass_query = $this->conn->prepare("update registered_users set user_password = :user_password where username = :username"); if( $insert_pass_query->execute
- pattern minor 112d agoBasic String classI wanted to create a basic `String` class that will hold a `CString` and have: - constructor, destructor, copy constructor - assignment operator (both from String and CString) - `>` operators to stream with `cout` and `cin` - `==`, `` operators to compare `String`s - `[ ]` operator to access a certain `char` in a string - `Len()` function to get the length of the string - `CStr()` to access the C string in the `String` class This is really a part of my baby steps in C++, so any feedback about style, design and coding will be appreciated. Attached are both the header file (the interface, as I learned it is called) and the cpp file: ``` /* string.h Written by me on Jan 27, 2015 */ #include using namespace std; namespace exercises { class String; ostream& operator>(istream&, String&); class String { public: explicit String(const char* str_=""); ~String(); String(String const &oStr_); String& operator=(const String& oStr_); String& operator=(const char* oStr_); bool operator==(const String& oStr_)const; bool operator(const String& oStr_)const; char operator[](std::size_t)const; char& operator[](std::size_t); const std::size_t Len()const; const char* CStr()const; private: char* m_str; }; } //namespace exercises ``` ``` /* string.cpp Written by me on Jan 27, 2015 */ #include #include #include "string.h" using namespace std; namespace exercises { static int BUFFSIZE = 256; // buffer size limit for streams // ---------- C~=tor funcs ---------- String::String(const char* str_) { m_str = new char[strlen(str_)+1]; strcpy(m_str, str_); } String::~String() { delete[] m_str; } String::String(String const &oStr_) { m_str = new char[strlen(oStr_.m_str)+1]; strcpy(m_str, oStr_.m_str); } String& String::operator=(const String& oStr_) { char* newString = new char[strlen(oStr_.m_str)+1]; delete[] m_str; m_str = newString; strcpy(m_str, oStr
- pattern minor 112d agoBag data structure (a set that can store multiple copies of items)I am trying to make my class a bit cleaner, especially some of its methods like `Count`, `__add__`, `remove` and `__iter__`. I feel like I could use cleaner code on the above methods and get the same results. Bag class represents and defines methods, operators, and an iterator for the Bag class. Bags are similar to sets, and have similar operations but unlike sets they can store multiple copies of items. Store the information in bags as dictionaries whose elements are keys whose associated values are the number of times the key occurs in the bag. ``` from collections import defaultdict from goody import type_as_str import copy from collections import Counter class Bag: def __init__(self, items = []): self.bag_value = defaultdict(int) for item in items: self.bag_value[item] += 1 def __repr__(self): bag_list = [] for item, count in self.bag_value.items(): bag_list.extend(list(item*count)) return 'Bag(' + str(bag_list) + ')' def __str__(self): return 'Bag(' + ','.join(str(item) + '[' + str(count) + ']' for item, count in self.bag_value.items()) + ')' def __len__(self): bag_len = 0 for value in self.bag_value: bag_len += self.bag_value[value] return bag_len def unique(self): return len(self.bag_value) def __contains__(self, item): return item in self.bag_value def count(self, item): if item in self.bag_value: return self.bag_value[item] else: return 0 def add(self, new): self.bag_value[new] += 1 def __add__(self,right): mergedbag = Bag() mergedbag.bag_value = copy.copy(self.bag_value) for item in right.bag_value.keys(): mergedbag.bag_value[item] += right.bag_value[item] return mergedbag def remove(self, item): if item in self.bag_value:
- pattern major 112d agoThe grid looked at the menu and said "Something with class, please"This is a follow up on my previous question: A grid and a menu walked into a program - I integrated classes into the mix. - The program now asks how big you want the grid to be. ``` import java.util.Arrays; import java.util.Random; import java.util.Scanner; class NumberGrid { private static final int RANDOM_NUMBER = 10; static Random rand = new Random(); public int numberColumns; public int numberRows; int [][] grid; public NumberGrid (int chosenNumberRows,int chosenNumberColumns ){ numberColumns = chosenNumberColumns; numberRows = chosenNumberRows; grid = new int [numberRows][numberColumns]; } private static int randomInt(int from, int to) { return rand.nextInt(to - from + 1) + from; } public void amountOfSpecificNumbers() { int[] numbers = new int[11]; for (int y = 0; y < numberRows; y++) { for (int x = 0; x < numberColumns; x++) { int value = grid[y][x]; numbers[value]++; } } for (int i = 1; i < numbers.length; i++) { System.out.println(" " + numbers[i] + " " + i + "s" ); } } public void sumOfColumns() { int sumOfColumns[] = new int[numberColumns]; for (int x = 0; x < numberColumns; x++) { for (int y = 0; y < numberRows; y++) { sumOfColumns[x] += grid[y][x]; } } System.out.println(Arrays.toString(sumOfColumns)); } public void sumOfRows() { int sumOfRows[] = new int[numberRows]; for (int y = 0; y < numberRows; y++) { for (int x = 0; x < numberColumns; x++) { sumOfRows[y] += grid[y][x]; } } System.out.println(Arrays.toString(sumOfRows)); } public void newField() { for (int x = 0; x < numberColumns; x++) { for (int y = 0; y < numberRows; y++) { int randomNumber = (randomInt(1, RA
- pattern minor 112d agoC# static class holding list of member class instancesI was wondering if such a design was a bad idea in C#. Here I have a static class `EventLog` which holds a list of instances of `Event` class. This is a simple event log of actions players can do in a game. What can I be doing in a better way? ``` public class EventLog { private const int maxEventsInLog = 50; private static List events = new List(); private static string[] eventDescriptions = new string[8] { " walked", " waited", " inquired", " allured ", " persuaded ", " bribed ", " hired ", " attacked ", }; public static void AddEvent(GameObject _fromUnit, GameObject _toUnit, Utils.ActionType _actionType) { events.Add(new Event(_fromUnit, _toUnit, _actionType)); if (events.Count > maxEventsInLog) { while (events.Count > maxEventsInLog) { events.RemoveAt(0); } } } public static int NumEventsInLog() { return events.Count; } public static string GetEventDescription(int eventIndex) { if (eventIndex events.Count - 1) return null; return events[eventIndex].description; } private class Event { private GameObject fromUnit; private GameObject toUnit; private Utils.ActionType actionType; public string description; public Event(GameObject _fromUnit, GameObject _toUnit, Utils.ActionType _actionType) { fromUnit = _fromUnit; toUnit = _toUnit; actionType = _actionType; description = eventDescriptions[(int)_actionType]; description = description.Replace("", _fromUnit.GetComponent().firstName + " " + _fromUnit.GetComponent().lastName); description = description.Replace("", _toUnit.GetComponent().firstName + " " + _toUnit.GetComponent().lastName); } } ```
- pattern minor 112d agoTimecode class designI've created a `Timecode` class. The "timecode" that I'm trying to represent is a timecode that is used in video editing quite often, and is seen displayed in the format "hh:mm:ss:ff", or 10:00:05:24, for example ("ff" = frames"). ``` /// /// Immutable timecode. /// /// /// Represents a timecode in hh:mm:ss:ff format. Rolls over at the 24 hour mark. /// [Serializable] public class Timecode { private static readonly Regex TimecodeRegex = new Regex(@"^(?\d{1,2}):(?\d{1,2}):(?\d{1,2}):(?\d{1,3})$", RegexOptions.Compiled | RegexOptions.ExplicitCapture); private int totalFrames; private short frameRate; public Timecode(int totalFrames, short frameRate = 25) { if (frameRate /// The hours segment of the timecode. /// public int Hours { get { return (int)this.totalFrames / this.frameRate / 60 / 60; } } /// /// The minutes segment of the timecode. /// public int Minutes { get { return (int)this.totalFrames / this.frameRate / 60 % 60; } } /// /// The seconds segment of the timecode. /// public int Seconds { get { return (int)this.totalFrames / this.frameRate % 60; } } /// /// The frames segment of the timecode. /// public int Frames { get { return (int)this.totalFrames % this.frameRate; } } /// /// The total number of frames for this timecode. /// public int TotalFrames { get { return this.totalFrames; } } /// /// The framerate of this timecode. /// publ