Archive for the ‘Uncategorized’ Category

Eureka Call Library Oracle RightNow get article count per category

Saturday, July 25th, 2015
/**
* Description: Get all categories, display in a list with number of articles in each, alphabetical listing of category level 3
* Date: March 2013
* Classes: GetAllCategories, Generator, Category, CategoryDepot
* Brief Technical:
* Page calls CallLibraryCatList widget
* widget view instantiates GetAllCategories Class, which uses Prodcat model to retrieve categories object
* GetAllCategories Class in turn activates Generator Class
* Generator Class utilizes Category & Category Depot Classes, converting the categories object into instantiated individual category objects that can leverage each other, and then be displayed
*/
class GetAllCategories{
	public $CI;
	public $catListObject;
	public $currentTier = -1;
	public $tier3 = array();
	public $lastLevel = -1;
	public $newLevel = -1;
	public $categoryDepot;

	function __construct() {
		$this->CI =& get_instance();
		$this->CI->load->model('standard/Prodcat_model');
		$this->catListObject = $this->CI->Prodcat_model->getHierPopup(14);
		$this->categoryDepot = new Generator;
		$this->iterateConvert();
	}

	// loops through the returned categories, and uses Generator Class to organize as Category Objects
	function iterateConvert() {
		for( $i=0; $i < count($this->catListObject); $i++ ) {
			if($this->catListObject[$i]['hier_list'] == 588)
			{
				$this->newLevel = $this->catListObject[$i]['level'];

				if ( $this->newLevel < 3 && $this->lastLevel == 3 ) {
					// sort tier 3 alphabetically, then add to collection
					foreach ($this->tier3 as $key => $row) {
						$title[$key] = $row[0];
						$href[$key] = $row['href_list'];
						$level[$key] = $row['level'];
					}
					array_multisort($title, SORT_ASC, $href, SORT_ASC, $level, SORT_ASC, $this->tier3);
					foreach($this->tier3 as $key => $catObject) {
						// create and add tiers 1 & 2 to collection
						$this->categoryDepot->generateCategory($catObject);
					}
					unset($this->tier3);
				}
				if($this->newLevel != 3) {
					// create and add tiers 1 & 2 to collection
					$this->categoryDepot->generateCategory($this->catListObject[$i]);
				}
				if($this->newLevel == 3) {
					// collect tier 3 items
					$this->tier3[] = $this->catListObject[$i];
				}

				$this->lastLevel = $this->newLevel;
				}
			}

			$this->categoryDepot->renderCollection();
		}
	}

class Generator{
	public $categoryDepot;
	public $CI;

	function __construct() {
		$this->categoryDepot = new CategoryDepot;
		$this->CI =& get_instance();
		$this->CI->load->model('custom/AnswersInCategoriesCounter_model');
	}

	function generateCategory($catSent) {
		$category = new Category;
		$category->setTier($catSent['level']);
		$category->setTitle($catSent[0]);
		$categoryArray = $category->setCategories($catSent['hier_list']);
		$finalCategory = $category->getFinalCategory();
		$articleCount = $this->CI->AnswersInCategoriesCounter_model->getCountOfAnswersByCat($finalCategory);
		if($finalCategory != 588 || 0 || null) {
			$this->categoryDepot->addToCollection($category);
		}
		foreach($categoryArray as $key => $categoryId) {
			$this->categoryDepot->updateCategoryArticleCounts($categoryId, $articleCount);
		}
	}	

	function renderCollection() {
		return $this->categoryDepot->getCollection();
	}
}

/**
* $catListObject[$i]['level'] / 0-3
* $catListObject[$i]['hier_list'] / Categories
* $catListObject[$i][0]
*/
class Category {
	public $tier;
	public $categoriesList;
	public $categoryArray;
	public $finalCategory;
	public $title;
	public $parentCategory;
	public $articleCount;
	public $articleTotal;

	function __construct() {
		//echo "Category instantiated";
	}

	function setTier($input) {
		$this->tier = $input;
	}
	
	function setCategories($input) {
		$this->categoriesList = $input;
		$this->setCategoryArray();
		$this->setParentCategory();
		$this->setFinalCategory();
		return $this->categoryArray;
	}

	function setCategoryArray() {
		$this->categoryArray = explode(',',$this->categoriesList);
	}

	function setParentCategory() {
		$itemLevel = $this->tier - 1;
		$this->parentCategory = $this->categoryArray[$itemLevel];
	}

	function setFinalCategory() {
		$this->finalCategory = $this->categoryArray[$this->tier];
	}

	function setTitle($input) {
		$this->title = $input;
	}

	function setArticleCount($input) {
		$newSet = array_unique(array_merge((array)$this->articleCount,(array)$input));
		$this->articleCount = $newSet;
		$this->setArticleTotal();
	}

	function getFinalCategory() { return $this->finalCategory; }
	
	function setArticleTotal() {
		$this->articleTotal = count($this->articleCount);
		return $this->articleTotal;
	}
}

// archives Category Objects, updates each Class's article count, and returns/displays the Collection
class CategoryDepot {
	public $collection;
	public $baseURL = '/app/list_call_library_no_search/r_id/108720/p/646/c/';
	public $currentTier = -1;

	function __construct() {
	}

	function addToCollection($input) {
		$this->collection[] = $input;
	}

	function getCollection() {
		foreach($this->collection as $category) {
			// if articleCount is 0, don't even show count
			if($category->articleTotal != 0){ $articleCount = " (" . $category->articleTotal . ")"; }else{ $articleCount = ''; }

			if($category->tier > $currentTier) {
				$currentTier = $category->tier;
				echo "<ul><li><a href='" . $this->baseURL . $category->categoriesList . "' class='noIntercept'>" . $category->title . $articleCount . "</a>";
			} elseif( $category->tier == $currentTier ) {
				echo "</li><li class='level_" . $category->tier . "'><a href='" . $this->baseURL . $category->categoriesList . "'>" . $category->title . $articleCount . "</a>";
			} elseif($category->tier < $currentTier) {
				$numberToClose = ($currentTier - $category->tier);
				$currentTier = $tier;
				switch ( $numberToClose ) {
					case 1:
						echo "</li></ul></li></ul><ul><li><a href='" . $this->baseURL . $categoriesList . "' class='noIntercept'>" . $category->title . $articleCount . "</a>";
					break;
					case 2:
						echo "</li></ul></li></ul></li></ul><ul><li><a href='" . $this->baseURL . $categoriesList . "' class='noIntercept'>" . $category->title . $articleCount . "</a>";
					break;
				}
			}
		}
	}

	// accepts a finalCategory int and the amount to increment that object's article count
	function updateCategoryArticleCounts($categoryId, $articleCount) {
		foreach ( $this->collection as $category ) {
			if ( $categoryId == $category->finalCategory ) {
				$category->setArticleCount($articleCount);
				break;
			}
		}
	}
}

Git frequently used

Tuesday, February 24th, 2015

// reset local branch to origin’s state

git checkout {branch}

git reset –hard origin/{branch}

 

// checkout new branch from origin

git checkout –track origin/{branch}

 

// merge

git merge {{branch}}

 

// stash when you need to keep changes but aren’t ready to commit them, say to switch branches or pull new work from team members into your unfinished state

git stash

git stash list

git stash apply {stashName}

 

// get git remote url

git config –get remote.origin.url
or
git remote show origin


// create a local branch and switch to it

git checkout -b {name the new branch}

 

// invalidate user so to force password reset

git config –global credential.helper store

 

// remove already added files/folder from git and add to ignore 

git rm -r –cached file-path

 

// did hard reset, clean, need it back!? It hasn’t been garbage collected yet, pfew

$ git reflog
1a75c1d… HEAD@{0}: reset –hard HEAD^: updating HEAD
f6e5064… HEAD@{1}: commit: added file2

$ git reset –hard f6e5064
HEAD is now at f6e5064… added file2

 

// commit everything including untracked

git commit -A

 

// delete folder from repo

git rm -r folder-name

 

// output all branches

git branch -a

 

// delete local branch

git branch branch-name -D

 

// delete remote branch, just add -r for remote flag

git branch -dr branch-name

Definition: What is a RESTful web service?

Saturday, December 15th, 2012

Ran across this explanation lately of what a RESTful web service is, think it’s the clearest one I’ve read in a long while:

Take the primary HTTP protocol request methods:

  • POST: submit forms, new data
  • GET: request a view
  • PUT: modify a resource
  • DELETE: delete a resource

and line them up to the usual database operations…CRUD (if need reminding just continue…)
and voila you’ve got a ‘RESTful web service’

  • POST/Create: Create a resource
  • GET/Read: Request a specific resource
  • PUT/Update: Edit a resource
  • DELETE/Delete: Delete a resource

Ruby on Rails : rateatrack app notes to self

Tuesday, February 22nd, 2011

add in item to an array/object example:

@artists << track.artist

order object contents example:

def index
@tracks = Track.all(:order => ‘artist‘)

simple rating average math:

rating = params[‘rating’].to_i
@track.average = ((@track.average * @track.numberofvotes) + newlysubmittedrating)/(@track.numberofvotes + 1)
@track.numberofvotes = @track.numberofvotes + 1

simple db update conditional redirect with reporting:

if @track.update_attributes(params[:track])
format.html { redirect_to(“/”, :notice => ‘Track updated.’) }

similar db object one liners:

  • @object.save
  • @object.destroy
  • @track = Track.find(params[:id])
  • @object = Track.new
  • @record = Track.find_by_sql “SELECT * …”

simple char substitution:

somevariablename = variablecontainingcharstoswap.gsub(“_”, ” “)

method simply needs to render a view other than that matching its name:

render :viewname

.each loop fills text variable, then renders it:

@record.each do |track|
$str << “#EXTINFO:#{track.length},#{track.title}<br />#{track.url}<br />”
end
render :text => $str

notice: to substitute variables into such a statement, #{variablename}

simple and example model with validation and some messaging:

class Track < ActiveRecord::Base
validates :url,  :presence => true
validates :title, :presence => true, :length => { :minimum => 1 }
validates :artist, :presence => true
validates :length, :presence => true
validates_format_of :url, :title, :artist, :length, :with =>/^[a-zA-Z \\ \/. : 0-9]+$/x, :message=>”alphanumeric characters, colons, periods, forward/backward slashes only please”
end

routes.rb

Rateatrack::Application.routes.draw do

match “tracks/generate/” => “tracks#generate” // custom :action route
resources :tracks

get “home/index”

root :to => “tracks#index” // sidestep app index, route to desired controller
end

heroku only uses Postgres, used MySQL locally, fun experiment to RELY on persistence:

database.yml

development:
adapter: mysql2
encoding: utf8
reconnect: false
database: rateatrack_development
pool: 5
username: user_name
password: password_removed
socket: /tmp/mysql.sock

production:
encoding: unicode
adapter: postgresql
database: rateatrack_production

simple schema.rb

ActiveRecord::Schema.define(:version => 0) do

create_table “tracks”, :force => true do |t|
t.string  “url”,     :limit => 64
t.string  “title”,   :limit => 64
t.string  “artist”,  :limit => 64
t.integer “length”
t.decimal “average”, :default => 0.0, :precision => 8, :scale => 2
t.integer “votes”,   :default => 0
end

end

RoR version of include, partial, snippet, and so on…

<%= render ‘form’ %>

this will pull from the same folder as the calling resource, file name _form.erb

form example with error checking:

<% @track %>
<%= form_for(@track) do |track_form| %>
<% if @track.errors.any? %>
<%= pluralize(@track.errors.count, “error”) %> prohibited this post from being saved:
<% @track.errors.full_messages.each do |msg| %>
<%= msg %>
<% end %>
</ul>
</div>
<% end %>
<table><tr><th><%= track_form.label :url %></th></tr>
<tr><td><%= track_form.text_field :url %></td></tr></table>
<%= track_form.submit %>
<% end %>

Gemfile

gem ‘rails’, ‘3.0.4’
gem ‘mysql2’