Thursday, 3 October 2013

how to get form id from ajax and set it in click function in symfony2

how to get form id from ajax and set it in click function in symfony2

i want to store id in global variable and then store this id for form edit
here is my xml request:
if($request->isXmlHttpRequest()) {
$response = new Response();
$output = array('success' => true, 'title' => $entity->gettitle(),
'id' => $entity->getId(), 'notes' => $entity->getnotes(),
'accountid' => $entity->getaccountid(), 'clientid' =>
$entity->getClientID(), 'status' => $entity->getstatus(),
'totalamount' => $entity->getTotalAmount(), 'paidamount' =>
$entity->getPaidAmount(), 'balanceamount' =>
$entity->getBalanceAmount(), 'createdby' =>
$entity->getcreatedby(), 'updatedby' => $entity->getupdatedby(),
'createddatetime' => $entity->getcreateddatetime(),
'updateddatetime' => $entity->getupdateddatetime());
$response->headers->set('Content-Type', 'application/json');
$response->setContent(json_encode($output));
return $response;
}
and here is my ajax code:
$("form").submit(function(e) {
e.preventDefault();
var url = $(this).attr('action');
var data = $(this).serialize();
$.ajax({
type: "POST",
url: url,
data: data,
}).done(function( result ) {
invoiceid=result.id;
if(result.success) {
$('#result').css({'color':'black','background-color':'#8F8','display':'Block','width':'200px'});
$('#result').html('Invoices Record Inserted');
setTimeout(function(){
$('#result').hide();
},3000);
}
});
this.reset();
});
$("#edit").click(function(){
window.location.href= "{{ path('invoices_edit', {'id': invoiceid }) }}";
});
when i alert invoiceid then it show value of result.id but invoiceid not
pass to click function,how i do this?

Wednesday, 2 October 2013

php rollover link and show image form databse that has same id

php rollover link and show image form databse that has same id

I have a list of categories in a database that our echoed onto the page
like so:
echo '<li><a href=#?id='.$row['category_id'] .' "> ' .
$row['category_name'] . '</a></li>';
How would I echo that corresponding image(category_image) that is in the
database when I hover over these links individually?
Do I hide a div and then have it appear on hover with the image inside?
but then how do I transfer the id?
category_image is a path, not the actual image.

Jquery - using "this" to dynamically show and hide

Jquery - using "this" to dynamically show and hide

<div class="show_hide panel-header" rel="#panel">
<h4>Disclaimer</h4>
</div>
<div id="panel" class="panel">
<p>Lorem ipsum</p>
</div>
Above is my HTML ... a simple div for the header (event handler) and the
hidden div to show/hide. Works perfectly for a simple show/hide, but I may
have several panels on screen at once and I don't want to explicitly ID
each one and give it it's own function. How can I use the "this" selector
to achieve dynamic interactions?
My JQuery currently...
<script type="text/javascript">
$(document).ready(function(){
$(".panel").hide();
$(".show_hide").show(); //Probably don't need this line...
$('.show_hide').click(function(){
$(this).children("div").slideToggle();
});
});
</script>
Any help is appreciated. I'm new to JS/JQuery and having some trouble
understanding the different selectors. Thanks!

Admin Control / Route Issues

Admin Control / Route Issues

Right, I've been really struggling with this routing issues.
I have a nested comment section called snippet and this belongs_to :books
Please see my admin index, snippet controller & routes in that order, I've
just implemented shallow resources.
This is the current error I'm getting:
Couldn't find Book with id=2
There is only one book and it has many snippets but I think it's trying to
look for the snippet ID rather than the book on approval action. I don't
understand why?
<h3>Users</h3>
<div class="span8">
<table class="table table-condensed">
<thead>
<tr>
<th>Username</th>
<th>Email</th>
<th>Registered</th>
<th>Role</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<% @users.each do |user| %>
<tr>
<td><%= link_to user.full_name, user %></td>
<td><%= user.email %></td>
<td><%= user.created_at.to_date %></td>
<td><%= user.roles.first.name.titleize unless user.roles.first.nil?
%></td>
<td>
<a data-toggle="modal" href="#role-options-<%= user.id %>"
class="btn btn-mini" type="button">Change role</a>
<%= render user %>
</td>
<td><%= link_to("Delete user", user_path(user), :data => { :confirm
=> "Are you sure?" }, :method => :delete, :class => 'btn btn-mini')
unless user == current_user %></td>
</tr>
<% end %>
</tbody>
</div>
<div class="span8">
<table class="table table-condensed">
<thead>
<tr>
<th>Username</th>
<th>Book Created</th>
<th>Registered</th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<% @books.each do |book| %>
<tr>
<td><%= link_to book.title, book %></td>
<td><%= book.created_at.to_date %></td>
<td><%= render book %></td>
<td>Status</td>
<td><%= button_to 'Approve', active_book_path(book) %></td>
</tr>
</tr>
<% end %>
</tbody>
</div>
<div class="span8">
<table class="table table-condensed">
<thead>
<tr>
<th>Username</th>
<th>Book Created</th>
<th>Registered</th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<% @snippets.each do |snippet| %>
<tr>
<td><%= link_to snippet.body %></td>
<td><%= snippet.created_at.to_date %></td>
<td><%= render snippet %></td>
<td>Status</td>
<td><%= button_to 'Approve', active_snippet_path(snippet) %></td>
</tr>
</tr>
<% end %>
</tbody>
</div>
Snippet_controller
class SnippetsController < ApplicationController
before_filter :authenticate_user!, only: [:create], :except => [:index,
:show]
before_filter :find_book
def create
@snippet = @book.snippets.create!(params[:snippet])
redirect_to @book
end
def approve
@snippet = Snippet.find(params[:id])
if @snippet.update_attribute(:approved, true)
redirect_to users_path
else
render root_path
end
end
def edit
@snippet = @book.snippets.find(params[:id])
end
def update
@snippet = @book.snippets.find(params[:id])
respond_to do |format|
if @snippet.update_attributes(params[:snippet])
format.html { redirect_to @book, notice: 'Comment was successfully
updated.' }
else
format.html { render action: "edit" }
end
end
end
private
def find_book
@book = Book.find(params[:id])
end
end
Routes
Treebook::Application.routes.draw do
root to: 'pages#home'
post "recurly/push"
get "content/Clerk"
get "content/Author"
get "content/Editor"
match '/home' => 'pages#home'
match '/about' => 'pages#about'
match '/contact' => 'pages#contact'
match '/subscribe' => 'pages#subscribe'
match '/new' => 'pages#new'
match "books/:id/activate" => "books#approve", :as => "active_book"
match "/snippets/:id/activate" => "snippets#approve", :as => "active_snippet"
resources :books do
resources :snippets, shallow: true, :only => [:create, :edit,
:update, :destroy]
end
devise_for :admins
devise_for :users, :controllers => { :registrations => 'registrations' }
devise_scope :user do
put 'update_plan', :to => 'registrations#update_plan'
end
get "profiles/show"
as :user do
get '/register', to: 'devise/registrations#new', as: :register
get '/register1', to: 'devise/registrations#new2', as: :registernew
get '/login', to: 'devise/sessions#new', as: :login
get '/logout', to: 'devise/sessions#destroy', as: :logout
end
resources :users
as :user do
get "/login" => 'devise/sessions#new', as: :new_user_session
post "/login" => 'devise/sessions#create', as: :user_session
delete "/logout" => 'devise/sessions#destroy', as: :destroy_user_session
end
resources :user_friendships do
member do
put :accept
end
end
resources :statuses
get 'feed', to: 'statuses#index', as: :feed
end

Tuesday, 1 October 2013

Firefox cookie read event?

Firefox cookie read event?

Using observer and cookie-changedtopic, we can get to know when a cookie
is added, changed, cleared, or deleted. The script below do the same,
var httpRequestObserver_cookies = { observe: function(aSubject, aTopic,
aData) { if ("cookie-changed" == aTopic) { //cookie was added, changed,
cleared, or deleted } },
get observerService()
{
return
Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService);
},
register: function()
{
this.observerService.addObserver(this, "cookie-changed", false);
},
unregister: function()
{
this.observerService.removeObserver(this, "cookie-changed");
}
};
Without modifying the cookie, I want to serve modified cookie dynamically,
Is there any way to know when a cookie is read and the data passed which
can be modified?

Store a playing cards deck in MySQL (single column)

Store a playing cards deck in MySQL (single column)

I'm doing a game with playing cards and have to store shuffled decks in
MySQL.
What is the most efficient way to store a deck of 52 cards in a single
column? And save/retrieve those using PHP.
I need 6 bits to represent a number from 0 to 52 and thus thought of
saving the deck as binary data but I've tried using PHP's pack function
without much luck. My best shot is saving a string of 104 characters (52
zero-padded integers) but that's far from optimal.
Thanks.

Java installation in Ubuntu for topcoder

Java installation in Ubuntu for topcoder

Can someone help me with an issue? I want to do TopCoder&#65279;. It needs
a Java applet. I'm new to ubuntu, have the 13.04 version and have no idea
how to get Java installed and which version of it should I get for the
applet? Please suggest what to do. Thanks in advance.

Loading 10.04 onto a HP Z220 workstation

Loading 10.04 onto a HP Z220 workstation

Please help! The planned operating system is Ubuntu 10.04 with a
possibility of upgrading to Ubuntu 12.04 LRS 64bit. Trying to load version
10.04 onto our HP Z220 workstation with a Intel Core i3-3240 3.4 3M GT1 2C
CPU. Can someone please advise how we can make this work? Are we missing a
driver? Not doing it properly? Please advise.

Monday, 30 September 2013

Ternary operator in C – stackoverflow.com

Ternary operator in C – stackoverflow.com

Why this program is giving unexpected numbers(ex: 2040866504, -786655336)?
#include <stdio.h> int main() { int test = 0; float fvalue = 3.111f;
printf("%d", test? fvalue : 0); …

A function on binary relations

A function on binary relations

Let $\rho$ is a function mapping every binary relation $f$ (on some set
$U$) into a function which maps binary relations into binary relations by
the formula
$$(\rho(f))(g) = f\circ g.$$
Is $\rho$:
upper adjoint in a Galois connection?
lower adjoint in a Galois connection?
meet-semilattice homomorphisms?
join-semilattice homomorphisms?
(The order assumed is the set-theoretic inclusion of binary relations.)
If it has adjoints, what these adjoints are?

Hadoop and Python: View Error

Hadoop and Python: View Error

I'm using Hadoop streaming to run some Python code. I have noticed that if
there is an error in my Python code (in mapper.py, for example), I won't
be notified about the error. Instead, the mapper program will fail to run,
and the job will be killed after a few seconds. Viewing the logs, the only
error I see is that mapper.py failed to run or was not found, which is
clearly not the case.
My question is, is there a specific log file I can check to see actual
errors that may exist in the mapper.py code? (For example, would tell me
if an import command failed)
Thank you!

adding new rows to table on clicking button in jquery

adding new rows to table on clicking button in jquery

I am pretty new to jquery..i have the following code. here i wants to get
new rows in the table on clicking add button.. but i cant get it.,
can someone tell me what mistake i ve done here?
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title> Adding Next Rows </title>
<link rel="stylesheet" href="resources/css/jquery.ui.all.css">
<script src="resources/scripts/jquery.ui.effect.js"></script>
<script src="resources/scripts/jquery.ui.effect-explode.js"></script>
<style>
h3
{
color:#0000FF;
display:inline-block;
}
.pdzn_tbl1 th
{
background:#DFDFDF;
border:#D6D6D6 1px solid;
}
.pdzn_tbl1 td
{
border-right:#729111 1px solid;
border-bottom:#729111 1px solid;
padding-top: 5px;
}
</style>
</head>
<body>
<h3> Adding Next Rows </h3>
<script type="text/javascript">
function ajax()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
alert("Your browser does not support XMLHTTP!");
return;
}
}
var $ = jQuery.noConflict();
$("#addrows").click(function () {
if(document.getElementById("hiddenprice").value == "") {
imagecounter = 4;
} else {
imagecounter =
parseFloat(document.getElementById("hiddenprice").value) + 1;
}
//imagecounter=4;
var newImageDiv = $(document.createElement('div'))
.attr("id", 'add_div' + imagecounter);
/*onchange="return
fn_productname(this.value,\'prdname'+imagecounter+'\')"*/
newImageDiv.after().html('<table width="100%" cellpadding="0"
cellspacing="0" class="pdzn_tbl1" border="0">'+
'<tr>'+
'<td style="padding:5px;" >'+'<input type="text"
name="rollno<? $i ?>" />' + '</td>' + '<td
style="padding:5px;">'+ '<input type="text"
name="firstname<? $i ?>" />'+'</td>'+'<td
style="padding:5px;">'+'<input type="text"
name="lastname<? $i ?>"
/>'+'</td>'+'</tr>'+'</table>');
newImageDiv.appendTo("#addgroup");
$("tr:last").after(newImageDiv);
document.getElementById("hiddenprice").value = imagecounter;
imagecounter++;
});
</script>
<div class="common" style="width:1040px; -overflow-x:scroll; padding: 5px
5px 0 5px;">
<table id="maintable" width="50%" cellpadding="0" cellspacing="0"
class="pdzn_tbl1" border="#729111 1px solid" >
<tr> <th align="center"> Roll No </th>
<th align="center"> First Name </th>
<th align="center"> Last Name </th>
</tr>
<?php
$t_row=3;
for($i=1;$i<=$t_row;$i++)
{
?>
<tr id="rows">
<div style="padding-left: 5px">
<td style="padding:5px;" > <input type="text" name="rollno<? $i ?>" /> </td>
<td style="padding:5px;"> <input type="text" name="firstname<? $i ?>" />
</td>
<td style="padding:5px;"> <input type="text" name="lastname<? $i ?>" /> </td>
</tr>
</div>
<? } ?>
<div id="addgroup">
<div id="add_div1"> </div>
</div> <table>
&nbsp;
<br />
<input type="button" name="add" value="+Add" id="addrows"
style="color:#3300FF; font-size:16px; " />
<input type="hidden" id="hiddenprice" name="hiddenprice"
value="3"/> </table>
</div>
</body>
</html>
thanks in advance..!!!!

Sunday, 29 September 2013

How to get the actual vAxis max value of Google Chart API?

How to get the actual vAxis max value of Google Chart API?

I have two LineChart, each has a rangeFilter (like the one here
https://code.google.com/apis/ajax/playground/?type=visualization#chartrangefilter_control)
I want to synchronize the scale of the two chart. That is, when one chart
changed the range of view, it will change vAxis max value to suite the
maximum data in that range, and I want the other chart change scale to the
same value.
I've no idea how I can get the vAxis.viewWindow.max in realtime. Any help
would be appreciated.

Fastest way to implement a sprite

Fastest way to implement a sprite

I'm using PyOpenGL to implement a small 2D game engine. I'm hesitating on
the way I implement a Sprite class.
I'm already keeping all the scene (tiled map) in a VBO, and all textures
are kept in the same big texture. All the sprite's images are also in this
texture. So I suppose that, for performance, I should include the sprite
in the VBO, let say from position sprite_start_position.
The first question is : since a sprite can have several stances (images),
is it better to :
setting only one entry in the VBO for the sprite, and modifying the
texture coords in this entry accordingly to the stance, using
glBufferSubData
setting as many entries in the VBO as there are stances, but drawing only
the current one with glDrawArrays
other ?
The second is the similar with sprite position. Must I :
change the position of the right entry in the VBO with glBufferSubData
use some glTranslate before glDrawArrays(GL_QUADS, sprite_start_position, 1)
other ?
I'm relatively new to OpenGL and I still feel a little lost in this API...

Char pointer giving me some really strange characters

Char pointer giving me some really strange characters

When I run the example code, the wordLength is 7 (hence the output 7). But
my char array gets some really weird characters in the end of it.
wordLength = word.length();
cout << wordLength;
char * wordchar = new char[wordLength]; //new char[7]; ??
for (int i = 0; i < word.length(); i++) //0-6 = 7
{
wordchar[i] = 'a';
}
cout << wordchar;
The output: 7 aaaaaaa²²²²¦¦¦¦¦ÂD&#9577;2¦&#9792;
Desired output is: aaaaaaa... What is the garbage behind it?? And how did
it end up there?

Saturday, 28 September 2013

copy object pointer into dynamic object array

copy object pointer into dynamic object array

I am working with a class I created that has a function addClass which
allow the user to add A an Instance of Class to a dynamically allocated
array.
Here is the code of the class and a simple test:
Class.h Listing
#ifndef CLASS_H
#define CLASS_H
#include<iostream>
class Class {
public:
Class(std::string text);
Class(const Class& orig);
virtual ~Class();
Class(std::string text, Class * name, int size); //"The Other
constructor"
std::string toString();
void addClass(Class * name, int size = 1);
Class getClass(int index);
private:
Class * classArray;
std::string value;
int size;
};

I'm recieving an error when formatting a date in Python, why?

I'm recieving an error when formatting a date in Python, why?

This is my code for formatting a date:
def updateUserDBDates():
global userDB, currentDate, previousDate, changeInDate
index = 0
index2 = 0
userDB[1] = datetime.strptime("%d-%m-%Y", userDB[0])
userDB[0] = datetime.today().strftime("%d-%m-%Y")
saveData()
currentDate = userDB[0]
previousDate = userDB[1]
changeInDate = currentDate - previousDate
and I get this error:
File "/home/nathan/Documents/project001/programFiles/Project 001.py",
line 170, in updateUserDBDates
userDB[1] = datetime.strptime("%d-%m-%Y", userDB[0])
File "/usr/lib/python2.7/_strptime.py", line 325, in _strptime
(data_string, format))
ValueError: time data '%d-%m-%Y' does not match format '28-09-2013'
From what I can see everything should work fine, what is causing this
error and how can I fix it easily?
Sorry, I'm still rather new at this.
Thank you,
Nathan

Update icloud calendar via php curl

Update icloud calendar via php curl

I want to realize a script for managing events to a shared icloud
calendar. I've stored on my db several events and, on request, i need to
create an event to be seen on remote phones/ipad and so on.
Thanks to Andy and his post I had no problem for write an event to icloud,
but when I try to update or delete an event, icloud doesn't seem to record
any change. Below you can find part of the function I use to create the
event
$body = <<<__EOD
BEGIN:VCALENDAR
PRODID:-// blablabla
VERSION:2.0
BEGIN:VEVENT
METHOD:UPDATE
UID:$id
DTSTAMP:$tstamp
ORGANIZER;CN=$organizer:MAILTO:$email
DTSTART:$tstart
DTEND:$tend
SUMMARY:$name
LOCATION:$location
DESCRIPTION:$description
SEQUENCE:2
END:VEVENT
END:VCALENDAR
__EOD;
$headers = array(
'Content-Type: text/calendar; charset=utf-8',
'If-None-Match: *',
'Expect: ',
'Content-Length: '.strlen($body),
);
// CONNESSIONE E SCRITTURA
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, $userpwd);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_exec($ch);
if(curl_errno($ch)) echo 'Curl error: '.curl_error($ch);
curl_close($ch);
If I exclude the connection to the icloud server and print $body the .ics
generated update without any problem my local calendar (and then replicate
the changes to icloud). Otherwise if I try to connect to icloud it won't
save the changes. I've tried to change the server request but still can't
get out of it

Friday, 27 September 2013

How to authenticate user with symfony and facebook

How to authenticate user with symfony and facebook

I was able to connect Symfony and Facebook API. I am getting all data that
I need including email.
I do not want to use ready to use solution (FOS or something like that) .
Once I got email from fb I am checking that email against db table with
doctrine and I am getting User object.
How can I authenticate that User object?
Give me some hints.

Django Views - Block Consecutive Quick Calls

Django Views - Block Consecutive Quick Calls

A button click in my app calls a view which does a few database changes
and then redirects to a new views which renders html. When the user
typically clicks on the link, he accidentally clicks on in twice to thrice
in a couple of seconds. I want to block the view call if the same call was
made less than 10 seconds ago. Of course I can do it by checking in the
database, but I was hoping to have a faster solution by using some
decorator in django.