Monday, 30 September 2013

How do I install qps from repositories on ubuntu 13?

How do I install qps from repositories on ubuntu 13?

I'm trying to install qps on ubuntu with
aptitude install qps
Where I get
Couldn't find package "qps". ...
I probably could download the sources and recompile, but I think I might
be missing some repositories or something (and that's a better way because
I'll get the updates automatically afterwards).
Can anybody tell me how I can install qpt from repositories, and how I
find repositories where the package is located in the future?

A screens-Question

A screens-Question

I'm trying to have a quick overview over my servers stats, so I'm writing
a little sh script, but I don't really get it right.
#!/sh/bash
screen -AmdS mgmt
screen -S mgmt -X screen -t HTop htop
screen -S mgmt -X screen -t ifTop iftop
screen -S mgmt -X screen -t Sensors watch sensors -c /home/ken/sensors.conf
screen -r mgmt
this nearly works, my problem is, that this results in 4 "tabs", but I
don't want the 4th tab (which is page 0; "bash")
I tried this and several other commands, without success
#screen -S mgmt -p 0 -X htop -t HTop
Thanks in advance!

NSAttributedString only works with Helvetica Neue

NSAttributedString only works with Helvetica Neue

I'm trying to load a UITextView with an NSAttributedString. I'm loading
the NSAttributedString from a Rich Text File ".rtf".
The Names of the files in my [NSBundle mainBundle] are My
Text-HelveticaNeue.rtf, My Text-TimesNewRomanPSMT.rtf, and My
Text-MarkerFelt-Thin.rtf These files each have the correct font set. They
also have some text Bold.
Here's my code:
NSString *resourseName = [NSString stringWithFormat:@"My Text-%@",
self.currentFontName];
NSURL *rtfUrl = [[NSBundle mainBundle] URLForResource:resourseName
withExtension:@".rtf"];
NSError *error;
NSAttributedString *myAttributedTextString = [[NSAttributedString alloc]
initWithFileURL:rtfUrl options:nil documentAttributes:nil error:&error];
myTextView.attributedText = myAttributedTextString;
NSLog(@"%@", myAttributedTextString);
The Helvetica Neue file retains all formatting, including the text that is
bold. But the other files only retain their font; they do not retain what
text was bold. What could I be doing wrong?

SMTP Server configuration in localhost

SMTP Server configuration in localhost

I have setup SMTP server on my linux (Ubuntu) server and send mail using
PHPmailer. its eorks perfect. but i want to send mail throw my local host
using that server..so how can i do that...
i have already change the php.ini file like:
[mail function]
; For Win32 only.
; http://php.net/smtp
;SMTP = localhost
smtp_server = 192.168.1.106
; http://php.net/smtp-port
smtp_port = 25
; For Win32 only.
; http://php.net/sendmail-from
sendmail_from = you@yourdomain
; For Unix only. You may supply arguments as well (default: "sendmail -t
-i").
; http://php.net/sendmail-path
sendmail_path = /usr/sbin/sendmail
192.168.1.106 is my server where i have config the SMTP server...
please help me i am stuck..

Sunday, 29 September 2013

Why result is that? -2.22044604925E-16

Why result is that? -2.22044604925E-16

When you use the range function, with a range between zero and 1,
incrementing by 0.05 each step, the loop produces an incorrect result when
you attempt to minus the current value in the loop from 1.
As you can see below, the last element in the array is the integer 1. The
script should echo the result of 1 minus 1. However, for some reason PHP
treats 1-1 as -2.22044604925E-16 instead of zero.
Reproduce code:
foreach (range(0,1,0.05) as $t)
{
echo (1-$t).'<br />';
}
Expected result:
----------------
1
0.95
0.9
0.85
0.8
0.75
0.7
0.65
0.6
0.55
0.5
0.45
0.4
0.35
0.3
0.25
0.2
0.15
0.1
0.05
0
Actual result:
--------------
1
0.95
0.9
0.85
0.8
0.75
0.7
0.65
0.6
0.55
0.5
0.45
0.4
0.35
0.3
0.25
0.2
0.15
0.1
0.05
-2.22044604925E-16

Symfony2 Birthday form field has blank years

Symfony2 Birthday form field has blank years

The birthday form type is rendering the following HTML. Notice years
1893-1901, which are blank. It looks really bad and I'm not sure why it is
blank. According to the docs, this might be expected if using a timestamp,
but I am using the default options, so it should be a DateTime.
<div class=" controls" >
<select id="study_mainbundle_userprofile_dateOfBirth_month"
name="study_mainbundle_userprofile[dateOfBirth][month]"
required="required" class="inline input-mini">
<option value="1">Jan</option>
<option value="2">Feb</option>
<option value="3">Mar</option>
<option value="4">Apr</option>
<option value="5">May</option>
<option value="6">Jun</option>
<option value="7">Jul</option>
<option value="8">Aug</option>
<option value="9">Sep</option>
<option value="10">Oct</option>
<option value="11">Nov</option>
<option value="12">Dec</option>
</select>
<select id="study_mainbundle_userprofile_dateOfBirth_day"
name="study_mainbundle_userprofile[dateOfBirth][day]"
required="required" class="inline input-mini">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option>
<option value="29">29</option>
<option value="30">30</option>
<option value="31">31</option>
</select>
<select id="study_mainbundle_userprofile_dateOfBirth_year"
name="study_mainbundle_userprofile[dateOfBirth][year]"
required="required" class="inline input-small">
<option value="1893"></option>
<option value="1894"></option>
<option value="1895"></option>
<option value="1896"></option>
<option value="1897"></option>
<option value="1898"></option>
<option value="1899"></option>
<option value="1900"></option>
<option value="1901"></option>
<option value="1902">1902</option>
<option value="1903">1903</option>
<option value="1904">1904</option>
<option value="1905">1905</option>
<option value="1906">1906</option>
<option value="1907">1907</option>
<option value="1908">1908</option>
<option value="1909">1909</option>
<option value="1910">1910</option>
<option value="1911">1911</option>
<option value="1912">1912</option>
<option value="1913">1913</option>
<option value="1914">1914</option>
<option value="1915">1915</option>
<option value="1916">1916</option>
<option value="1917">1917</option>
<option value="1918">1918</option>
<option value="1919">1919</option>
<option value="1920">1920</option>
<option value="1921">1921</option>
<option value="1922">1922</option>
<option value="1923">1923</option>
<option value="1924">1924</option>
<option value="1925">1925</option>
<option value="1926">1926</option>
<option value="1927">1927</option>
<option value="1928">1928</option>
<option value="1929">1929</option>
<option value="1930">1930</option>
<option value="1931">1931</option>
<option value="1932">1932</option>
<option value="1933">1933</option>
<option value="1934">1934</option>
<option value="1935">1935</option>
<option value="1936">1936</option>
<option value="1937">1937</option>
<option value="1938">1938</option>
<option value="1939">1939</option>
<option value="1940">1940</option>
<option value="1941">1941</option>
<option value="1942">1942</option>
<option value="1943">1943</option>
<option value="1944">1944</option>
<option value="1945">1945</option>
<option value="1946">1946</option>
<option value="1947">1947</option>
<option value="1948">1948</option>
<option value="1949">1949</option>
<option value="1950">1950</option>
<option value="1951">1951</option>
<option value="1952">1952</option>
<option value="1953">1953</option>
<option value="1954">1954</option>
<option value="1955">1955</option>
<option value="1956">1956</option>
<option value="1957">1957</option>
<option value="1958">1958</option>
<option value="1959">1959</option>
<option value="1960">1960</option>
<option value="1961">1961</option>
<option value="1962">1962</option>
<option value="1963">1963</option>
<option value="1964">1964</option>
<option value="1965">1965</option>
<option value="1966">1966</option>
<option value="1967">1967</option>
<option value="1968">1968</option>
<option value="1969">1969</option>
<option value="1970">1970</option>
<option value="1971">1971</option>
<option value="1972">1972</option>
<option value="1973">1973</option>
<option value="1974">1974</option>
<option value="1975">1975</option>
<option value="1976">1976</option>
<option value="1977">1977</option>
<option value="1978">1978</option>
<option value="1979">1979</option>
<option value="1980">1980</option>
<option value="1981">1981</option>
<option value="1982">1982</option>
<option value="1983">1983</option>
<option value="1984">1984</option>
<option value="1985">1985</option>
<option value="1986">1986</option>
<option value="1987">1987</option>
<option value="1988">1988</option>
<option value="1989">1989</option>
<option value="1990">1990</option>
<option value="1991">1991</option>
<option value="1992">1992</option>
<option value="1993">1993</option>
<option value="1994">1994</option>
<option value="1995">1995</option>
<option value="1996">1996</option>
<option value="1997">1997</option>
<option value="1998">1998</option>
<option value="1999">1999</option>
<option value="2000">2000</option>
<option value="2001">2001</option>
<option value="2002">2002</option>
<option value="2003">2003</option>
<option value="2004">2004</option>
<option value="2005">2005</option>
<option value="2006">2006</option>
<option value="2007">2007</option>
<option value="2008">2008</option>
<option value="2009">2009</option>
<option value="2010">2010</option>
<option value="2011">2011</option>
<option value="2012">2012</option>
<option value="2013">2013</option>
</select>
</div>
</div>
Entity part:
/**
* @var \DateTime
*
* @ORM\Column(name="date_of_birth", type="date")
* @Assert\NotBlank()
*/
private $dateOfBirth;
form part:
->add('dateOfBirth', 'birthday', array(
'label' => 'Date of Birth'
))
I am using MopaBootstrapBundle if that makes a difference.

Email form data to user's email

Email form data to user's email

i am trying to email what the submitter filles out in the textarea to him
after her clicks the "Submit" button. the "current_user" is a wordpress
codex that takes the logged-in user's email.
my code does print out the correct email + what i fill out in the
textarea, but it does not send it to this email. i don't know what to fix.
thanks for your help!
<form action="#" method="post">
<textarea name="lesson1"></textarea><br>
<input type="submit" name="Send" value="Send to your Email" />
</form>
</div>
<?php
global $current_user;
get_currentuserinfo();
$email = $current_user->user_email;
$lesson1 = htmlspecialchars($_POST['lesson1']);
echo $lesson1, $email;
$email_subject = "Test E-Mail (This is the subject of the E-Mail)";
(mail($email, $email_subject, $lesson1);
if(mail($email, $email_subject, $lesson1)){
echo "The email($email_subject) was successfully sent.";
} else {
echo "The email($email_subject) was NOT sent.";
?>

which is better? start using language from scratch or from a framework? [on hold]

which is better? start using language from scratch or from a framework?
[on hold]

I am a newbie to the web development, I want to develop some website for
different purposes.
I started using Django with python, however, I found it fuzzy to me since
I don't have enough experience with python. I also need to develop with
php, but I jumped directly to Laravel.
Is it better to start developing from a framework , or I should first
learn the language then go to the framework?

Saturday, 28 September 2013

Raid 1 or 5 for Colocation server with 5 wordpress sites, 1 CRM and 1 mail server?

Raid 1 or 5 for Colocation server with 5 wordpress sites, 1 CRM and 1 mail
server?

I want to buil colocation server with :
5 Wordpress sites with 50 view at a time (5*50 = 250)
1 CRM ASP.NET site with 50 view at a time
1 mailserver Kerio connect or MDaemon wiht 120 user
My model :
Server A - ESXi 5.1
Mysql1 on CentOS 6.4
SQL1 on Win2k8
IIS1 on Win2k8
Apache1 on CentOS 6.4
MDaemon1 on Win2k8
Server B - ESXi 5.1
Mysql2 on CentOS 6.4 (cluster Mysql1)
SQL2 on Win2k8 (cluster SQL1)
IIS2 on Win2k8 (cluster IIS1)
Apache2 on CentOS 6.4 (cluster Apache1)
MDaemon2 on Win2k8 (backup for Mdaemon1)
Please advise me should use :
2 HDD SAS 15k with Raid 1
3 HDD SATA 10k with Raid 5
Thanks

ArrayIndexOutOfBoundsException: 4

ArrayIndexOutOfBoundsException: 4

I'm writing a little program to analyze some data I have and this code,
which worked yesterday, is no longer working. For the life of me, I can't
tell why. To my eye, everything is as it should be. I've tried re-syncing
the folder on my computer with my GitHub Repo and still was receiving the
same error. Maybe a second pair of eyes could help me out?
The text file being read from can be found here.
Here are the methods referred to by the stack trace:
public static void main(String[] args) throws IOException{
FileManagementMethods fmm = new FileManagementMethods();
fmm.runProgram();
}
void runProgram() throws IOException{
boolean doesFileExist = doesFileExist();
if(doesFileExist){
int numLines = getNumberOfLines();
String[] linesFromFile = getLines(numLines);
WeatherAnalysisMethods wam = new WeatherAnalysisMethods();
wam.parseFileAverageTemp(linesFromFile);
wam.parseFileAverageHumidity(linesFromFile);
wam.predictNextTemperature(linesFromFile);
} else{
try {
throw new IOException("Could not find log.txt in default
directory");
} catch (IOException e) {
e.printStackTrace();
}
}
}
void parseFileAverageHumidity(String[] linesFromFile) throws IOException{
int[] humiditiesFromFile = new int[linesFromFile.length];
humiditiesFromFile = getHumiditiesFromFile(linesFromFile.length);
int averageFromFile = 0;
for(int i = 0; i < humiditiesFromFile.length; i++){
averageFromFile += humiditiesFromFile[i];
}
averageFromFile = averageFromFile / humiditiesFromFile.length;
String outString = "Average humidity for whole file = " +
averageFromFile;
FileManagementMethods fmm = new FileManagementMethods();
fmm.saveAnalyzedData(outString);
}
int[] getHumiditiesFromFile(int numLines){
int[] humiditiesFromFile = new int[numLines];
FileManagementMethods fmm = new FileManagementMethods();
String[] lines = fmm.getLines(numLines);
int i = 0;
while(1 < numLines){
String[] lineDivides = lines[i].split(",");
String tempString = lineDivides[4];
humiditiesFromFile[i] = Integer.parseInt(tempString);
i++;
}
return humiditiesFromFile;
}
And here is the stack trace:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at
org.weatheralert.analysis.WeatherAnalysisMethods.getHumiditiesFromFile(WeatherAnalysisMethods.java:51)
at
org.weatheralert.analysis.WeatherAnalysisMethods.parseFileAverageHumidity(WeatherAnalysisMethods.java:22)
at
org.weatheralert.analysis.FileManagementMethods.runProgram(FileManagementMethods.java:22)
at org.weatheralert.analysis.Main.main(Main.java:9)
If you guys need more information, don't hesitate to ask.

Removing duplicate values from SplDoublyLinkedList

Removing duplicate values from SplDoublyLinkedList

Is there a method to remove duplicate values from a list? I was trying to
create my own method, but it takes quite a lot time depending on how much
there is duplicate values:
$arr = new SplDoublyLinkedList();
for ($i = 0; $i < count($arr); $i++) {
for ($j = $i; $j < count($arr); $j++) {
if ($arr[$i] == $arr[$j] && $i != $j) {
$arr->offsetUnset($j);
$j -= 1;
}
}
}
E.g. if there is a 4000 items and about 1000 unique items on a list, it
takes about 7 seconds to remove these items.

Get the value of certain column in datagridview before and after changes

Get the value of certain column in datagridview before and after changes

i have a problem where i can't solve it by myself. And before i start, it
is important to let you guys know that
This problem i wrote from the beginning to the end, i want to make you
guys understand properly what my problem is, for those who are lazy to
read this, please forgive me, i am not attach any code in here, only just
logic
Probably people in this forum could help me. But, i already got a solution
to my problem (but only the logic, i can't prove it by code and don't know
where to start)
Well, here is my case:
I got a Quantity column in DataGridView, and i got a feature where user
could edit the Quantity column in DataGridView and automatically updating
the Quantity value in the Database.
For Example (still at the case):
I have 1000 on Quantity in the Database, and i enter the value of 50 in
the Quantity column in system and after that i add to the DataGridView by
clicking a "OK" button, once clicked, the Quantity in the Database should
update it Quantity become 950, from 1000. Because i use a formula
valueOfQuantityInDatabase - valueOfQuantityInSystem, it update properly
and successful
Here is my problem goes:
Let's say i got a DataGridView with Quantity column and the value of it is
50 (This make a Quantity value in Database become 950) and let's say
customer want to add his Quantity from 50 to 150, so i change the value of
Quantity in DataGridView to 150 from 50, and when i click "OK" button, the
Database should update based on the formula valueOfQuantityInDatabase -
valueOfQuantityInSystem, and the Quantity in Database should have 850 in
Quantity value (Because 1000 - 150), but it is not as i expected, the
Quantity value in database is 800 (Because first time i add is 50, so the
Quantity in database is 950, next i add another 150 and the Quantity in
database is 800), so it is like first entered value + second entered
value.
Here is what i want:
Whenever user edit the Quantity in DataGridView, it should goes to this
formula valueOfQuantityInDatabase - valueOfQuantityInSystem ------ (So,
whenever user change the Quantity value in DataGridView, let's say it
change to 150 from 50, the Quantity in Database should recognized it and
minus with current value of Quantity in DataGridView (150), not the older
one (50)
Here is my solution that i came with:
Get the first value of Quantity in Database before it was changed (1000)
Get how many value of Quantity that has been added from user by formula
Quantity in DataGridView after changes - Quantity in DataGridView before
changes and plus it with the formula Quantity in DataGridView after
changes - Quantity in DataGridView before changes
But i don't know how to get the solution 1 nor 2. Could anyone help me?
Thank you very much! Your answer i appreciate so much!

Friday, 27 September 2013

checkbox state and other attributes

checkbox state and other attributes

What would be the best way to get the checked or unchecked state of a
checkbox + any other relevant data like data-id etc
So far I have
$(".checkbox").each(function(){
var $checked = $(":checked");
});
I have a var checkbox that is set as an array. My ideal result would be
data-id state

Querying google maps for time between A & B

Querying google maps for time between A & B

how do I query google maps to tell me how much time it takes to reach from
point A to point B? I want to build an app which alerts me what's the
right time to leave from office to home. I don't want to check every 5
minutes how the traffic pattern is.

How to bind data to a control's Visibility property

How to bind data to a control's Visibility property

I understand that the Visibility property of a control cannot be bound to
data in the same way that other properties can. It needs some kind of
converter(?). In trying to implement the solution from this question I run
into a compiler error that says: The resource "BoolToVisible" could not be
resolved. I'm guessing that I have to create a ResourceKey named
BoolToVisible, I just don't know how.
I'm requesting that someone show me the right way to Bind to the
Visibility property of a control.
*The control that I am adding this to is a radio button. * I have a bool
property for isVisible in my Data Model that will be bound to this radio
button.
Data Model Property:
private bool _isVisible = true;
public bool IsVisible
{
get { return _isVisible; }
set
{
_isVisible = value;
NotifyPropertyChange(() => IsVisible);
}
}
XAML:
<RadioButton Visibility="{Binding
DataModel.IsVisible,Converter={StaticResource
ResourceKey=BoolToVisible},RelativeSource={RelativeSource
TemplatedParent}}" ... />
Thank you.

How to tell 0/1 from false/true with NSJSONSerialization?

How to tell 0/1 from false/true with NSJSONSerialization?

I need to deal with JSON data with arbitrary structures in iOS.
However, NSJSONSerialization convert true/false value into NSNumber.
So my question is, how can I tell when a NSNumber is converted from a
boolean value true/false, as apposed to actual number 0/1?
Note: I am aware of [NSNumber numberWithBool], but here, I want to figure
out when it's appropriate to call it. I'm also aware that writing my own
parser solves this problem, but I want to make sure there isn't a easier
solution before I go done that route.

Causing underflow in ieee-754 floating point format using subtraction

Causing underflow in ieee-754 floating point format using subtraction

This seems basic but I am having a lot of trouble answering the following
question:
Give two numbers X and Y represented in the IEEE754 format such that
computing X-Y will result in underflow.
To my understanding every operation can potentially result in underflow
but for the life of mine I cant find an example for subtraction.
PLEASE HELP!!! thanks

Error uploading build to Testflight Android

Error uploading build to Testflight Android

I tried to upload an APK to Testflight today and got this error:
I found this question: Uploading build to Testflight IOS
Apparently it's a Testflight issue, can someone confirm this?

How to use Struct with a *variable name?

How to use Struct with a *variable name?

private:
// data containing character strings
// shared by Strings when copying/assigning
struct SharedData
{
char *data; // 0-terminated char array
size_t n; // number of non-0 characters in string
size_t count; // reference count, how many Strings share this object?
};
SharedData *shared; //here i don't understand how to use.
How do I use n?
do I just do this
shared -> n = 3;
I keep getting segmentation faults so i don't know what i am doing. I want
to grab the length of a string and then pass it to n to be stored

Thursday, 26 September 2013

Getting mutual funds financial data through gate-way

Getting mutual funds financial data through gate-way

One of my client is mutual fund, insurance broker. He needs a web-app
which showing all records of customers like policy no, premium, how many
premium paid etc. Is there any gate-way to get this all information for
developing purpose. I would like to develop web-app in java.

Wednesday, 25 September 2013

Please help me cURL website in PHP

Please help me cURL website in PHP


http://24sms.net is a website for sending free sms to 190 countries.
Any body can cURL website http://24sms.net in PHP language.
I really want to use 24sms.net as SMS Gateway for sending my customers'
order information
Please help me.
Thanks a lot.

Thursday, 19 September 2013

C++ strTok implementation returning weird characters

C++ strTok implementation returning weird characters

I'm currently working on a string tokenizer in C++ and am getting a
strange result. char *mystrtok(char *str, const char *delim) { char *
LeftOver; bool lastToken; int i=0;
if(str != NULL)
{
LeftOver = str;
lastToken = false;
}else
{
str = LeftOver;
}
for(i = 0; str[i] != '\0'; i++)
{
for(int j=0; delim[j] != '\0'; j++)
{
//If I take out this line then it returns weird characters
cout << "\tstr[" << i <<" ]" << "=" << str[i] << endl;
if(LeftOver[i] == delim[j])
{
str[i] = '\0';
LeftOver = str + i+1;
return str;
}
}
}
if(LeftOver[i] == '\0' && !lastToken)
{
lastToken = true;
return str;
}
return NULL;
}
What's really weird is that if I take out the cout then it returns weird
characters Any idea what could be causing this?
Here's a sample output //input "ls -l -a | wc -c >> myfile"
returned: ls
¢ÆM.¢Æ

Strange @PrePersist @PreUpdate behavior

Strange @PrePersist @PreUpdate behavior

I'm trying to add some auditing information to my records. My plan is as
follows:
@Temporal(TemporalType.TIMESTAMP)
@Column(updatable = false)
private Date created;
@Temporal(TemporalType.TIMESTAMP)
private Date updated;
@PrePersist
private void onCreate() {
created = new Date();
}
@PreUpdate
private void onUpdate() {
updated = new Date();
}
Using different versions of Hibernate, I'm observing the need to add the
following to the update:
@PreUpdate
private void onUpdate() {
if (created == null) {
created = new Date();
}
updated = new Date();
}
I.e. @PrePersist seems to not stick for my inserts. Is my attempt
conceptually wrong? If so, why? If not, what can we do to debug the
problem? The onCreate does get called, though, upon first insertion.

convert date from numeric value to date valid format

convert date from numeric value to date valid format

I need to filter all dates which greater than, say 01 january 2011.
select * from table_name where date > '01/01/2011';
the problem is that date field store int values, here is an example:
1339011098
1336717439
1339010538
How to convert the date field on the sql query (from the int format to
date format), I need to convert it to a valid date so that I can compare
it towards the above date.
Thanx.

Kendo Grid - Won't bind to remote data MVC

Kendo Grid - Won't bind to remote data MVC

Maddening... Trying to utilize AJAX reads with a Kendo Grid. I've done
quite a few binding to data passed down from the model. I copy the code
straight from the KendoUI site and tweak to meet my demands:
@(Html.Kendo().Grid<FaultReport2.Models.usp_CMC_TopIssues_Result>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(p => p.description).Title("Description");
columns.Bound(p => p.responsible).Title("Responsibility");
columns.Bound(p => p.charged_time).Title("Time");
columns.Bound(p => p.responsible).Title("Responsible");
columns.Bound(p => p.root_cause).Title("Root Cause");
columns.Bound(p => p.counter_measure).Title("Countermeasure");
columns.Bound(p => p.status).Title("Status");
})
.Pageable()
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(10)
.Read(read => read
.Action("cmcTopIssues", "FaultInfo", new { equipment_id =
Model.area_id, start_date = Model.start_date })
)
)
)
Controller code for the read.Action():
public ActionResult cmcTopIssues(int equipment_id, DateTime
start_date)
{
var db = new Models.FAULTEntities1();
var top_issues = db.usp_CMC_TopIssues(equipment_id,
start_date).ToList();
return Json(top_issues, JsonRequestBehavior.AllowGet);
}
Does not work. I verify that my cmcTopIssues method is being called and
that the top_issues var is being filled. It just does not populate the
grid.
When I switch over to local and pass the data down through the model, it
works fine.
Any help would be appreciated.

Loading and modifying an excel file

Loading and modifying an excel file

Hy everyone i would like to have some opinion about how to modify a xls
file. Basicly i imported a txt file into excel with the openText method
from the office.interop.excel class. And it convert the file very well
into excel . But i want to add 2 extra columns at the fist 2 position. And
after all sort one of them. shuld i load back the xls file after the
conversion and open up for modifying?
I'm stucked here so pls if anyone has some idea!
Text export
xlApp.Workbooks.OpenText(openFile.FileName, Excel.XlPlatform.xlWindows, 1,
Excel.XlTextParsingType.xlDelimited,
Excel.XlTextQualifier.xlTextQualifierSingleQuote, false, false, false,
true, false, false, missing, oFieldInfo, missing, missing, missing,
missing, missing);
Best regards!
Smith

A formula to copy the values from a formula to another column

A formula to copy the values from a formula to another column

I have a column of values created from a formula, I know I can copy the
values over to another column by using the clipboard. BUT...I want my
spreadsheet to be automatic whilst avoiding the use of VBA coding, so it
would be ideal if I could create a formula for the next column which
copies the VALUES over to the next column. Maybe an INDEX/MATCH kind of
method but one that copies ONLY the values rather than the formulas.
So in essence I want a formula to copy the values from a formula....

Wednesday, 18 September 2013

user role editor - restoring admin capabilities

user role editor - restoring admin capabilities

Can anyone help me with a problem I'm having after using the User Role
Editor plugin on my wordpress site. It's restricted my admin account so I
am locked out of any theme/user/appearance/plugins areas of the dashboard.
The plugin support suggested deleting the plugin via FTP, which I have
done, but it's made no difference. I tried reinstalling the plugin and
editing the role again, but am unable to find options to restore the super
admin capabilities. Does anyone have any ideas on how restore the
super-admin capabilities to my admin login? many thanks, Louise

Transfering Lists between winform

Transfering Lists between winform

Normally i use something like
public List<Item> itemList = new List<Item>();
public Total(List<Item> i)
{
itemList = i;
InitializeComponent();
}
but now im getting
Error 1 Inconsistent accessibility: parameter type
'System.Collections.Generic.List<Budgeting_Program.Item>' is less
accessible than method
'Budgeting_Program.Total.Total(System.Collections.Generic.List<Budgeting_Program.Item>)'
C:\Users\Mika\Documents\Visual Studio 2012\Projects\Budgeting
Program\Budgeting Program\Total.cs 22 16 Budgeting Program
I'm not quite sure what this means. Can anyone help please!

Microsoft Excel: Is there a symbol that represents the value of the row or column and can be used in defining functions?

Microsoft Excel: Is there a symbol that represents the value of the row or
column and can be used in defining functions?

I am dealing with an incredibly large stack of data (close to a 1000
rows). I want to write a function for all of the cells in a column that
takes the value from one cell in each row, divides it by the value from
another cell in the same row, and writes the result on a third cell in the
same row. In other words, as to row X, it takes AX, divides it by BX, and
writes it on CX; and as to row Y, it takes the value in AY, divides it by
BY, and writes on CY.
As I said, I am dealing with a large stack of data and I really would like
to be able to write one function for the entire column, rather than having
to write one function for each cell in the column. Conceptually, it is
clear to me that I need some way of using the row number as the variable
in defining the function and apply that to the entire column. I do not
know how to bring that to application though.
Thanks in advance for your help.
P

Detect unused AMD dependencies

Detect unused AMD dependencies

Is there any tool that can analyze my files for unused AMD modules so that
I can clean up my code if I remove a previously used dependency?
I know to a certain degree jshint can do this with the unused option, but
setting it to true ignores unused deps followed by a used one. As well as
it does not actually analyze the deps array, just the function arguments.
Also setting it to strict isn't really practical for other parts of my
code as I need that.

Android layout not displaying in app

Android layout not displaying in app

Hi I am trying to develop an app with menu bar on the top and display
buttons in the layout i have four layouts for four different
purposes..When i edit the XML its displaying properly in graphical layout
but when i install and view the app in phone it does not show those
buttons or any extra addition like edit text in the tabs of menu bar..Can
anyone please help me with this. Here is my xml layout
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/username"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_x="1dp"
android:layout_y="236dp"
android:clickable="true"
android:ems="10" />
<Button
android:id="@+id/signUp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_x="4dp"
android:layout_y="154dp"
android:text="Sign up!" />
</AbsoluteLayout>
This is my XML layout which integrates the layouts
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="5dp">
<TabWidget
android:id="@android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="5dp" />
</LinearLayout>
</TabHost>

Webview email link (mailto)

Webview email link (mailto)

I have a view and view the site has malito code to send email. When I open
the link opens in a error. I want that when I open the link opens Gmail
app or another email application.

SaxParser Eception while reading from dozer-mapping.xml

SaxParser Eception while reading from dozer-mapping.xml

I am trying to implemet DOZER in my project. I am getting SAX Exception.
PFB, the details
org.dozer.MappingException: org.xml.sax.SAXException: Parsing Error Line:
4 URI: null Message: cvc-elt.1: Cannot find the declaration of element
'mappings'. at
org.dozer.util.MappingUtils.throwMappingException(MappingUtils.java:82) at
org.dozer.loader.xml.MappingStreamReader.read(MappingStreamReader.java:55)
at org.dozer.loader.xml.MappingFileReader.read(MappingFileReader.java:58)
at org.dozer.DozerBeanMapper.loadFromFiles(DozerBeanMapper.java:227) at
org.dozer.DozerBeanMapper.loadCustomMappings(DozerBeanMapper.java:209) at
org.dozer.DozerBeanMapper.initMappings(DozerBeanMapper.java:315) at
org.dozer.DozerBeanMapper.getMappingProcessor(DozerBeanMapper.java:192) at
org.dozer.DozerBeanMapper.map(DozerBeanMapper.java:120)
My dozer-mapping.xml
<?xml version="1.0" encoding="UTF-8"?>
<mappings xmlns:ns="http://dozer.sourceforge.net"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://dozer.sourceforge.net
http://dozer.sourceforge.net/schema/beanmapping.xsd">
<mapping>
<class-a>org.esb.ClassA</class-a>
<class-b>org.esb.ClassB</class-b>
<field>
<a>status</a>
<b>statusCode</b>
</field>
</mapping>
</mappings>
My java code:
destinationObj= dozerBeanMapper.map(sourceObj, DestinationClass.class);
Jars Used:
Dozer 5.4.0.jar, commons-beanutils-1.8.3.jar, commons-lang-2.6.jar,
jcl-over-slf4j-1.6.6.jar, log4j-1.2.15.jar, slf4j-api-1.6.6.jar,
slf4j-log4j12-1.6.6.jar

No RuntimeException in stack trace when implementing HttpHandler.handle() in Java

No RuntimeException in stack trace when implementing HttpHandler.handle()
in Java

I am developing an application which has to serve some XML file through
HTTP. For the HTTP server implementaion I use the
com.sun.net.httpserver.HttpServer and I created a handler class which
implements HttpHandler. The very weird thing is that I cannot get any
RuntimeException from the MyHandler.handle() method. I put together a
sample code to reproduce the case I am struggling with:
Server code:
public class HttpServerTest {
public static void main(String[] args) {
HttpServer server;
try {
server = HttpServer.create(new InetSocketAddress(8080),0);
server.createContext("/", new MyHandler());
server.start();
} catch (IOException ex) {
Logger.getLogger(HttpServerTest.class.getName()).log(Level.SEVERE,
null, ex);
}
throw new RuntimeException("Very Important Exception from main");
}
}
And the handler:
class MyHandler implements HttpHandler {
public MyHandler() {
}
@Override
public void handle(HttpExchange he) throws IOException {
System.out.println("hello");
throw new RuntimeException("Very Important Exception from
MyHandler.handle");
}
}
Output:
Exception in thread "main" java.lang.RuntimeException: Very Important
Exception from main
at httpservertest.HttpServerTest.main(HttpServerTest.java:26)
hello
hello
hello
hello
hello
hello
So as you can see, I can get the exception from the main class main
method, but I do not get anything from the handler method. Has anyone seen
something like this before? Runtime exceptions should be in the stack
track trace always.
Thanks, Zoltan

Tuesday, 17 September 2013

ping works,http works but https does not work for my local jboss server

ping works,http works but https does not work for my local jboss server

I am using 64 bit ubuntu 12.04LTS. My JBOSS server is running. I can ping
my ip address well. I can access my project using [http://localhost:8080]
well but when i want to use [https://localhost:8080], it shows error in
firefox as
The connection to localhost:8080 was interrupted while the page was loading.
i have also checked my hosts file as
127.0.0.1 localhost
127.0.1.1 someone-pc
192.168.18.75 localhost
I have also tried google chrome,IE,that also gives error message.
When anyone wants to use my pc using my ip address he can access using
http but can not using https.
please help me.Advance thanks to u.

Converting a fraction into a decimal with integers in C++

Converting a fraction into a decimal with integers in C++

Yes. It's an assignment, that is quite a brain teaser for me to be
honest.. The goal of the program, or "problem" (if you want to look at it
in math terms) is dividing two numbers against each other. You are able to
divide whole numbers, and fractions against each other. The function
definition looks like this:
bool divide(int c1, int n1, int d1, int c2, int n2, int d2, char result[],
int len)
c1, c2 - Whole numbers
n1, n2 - Numerator 1, Numerator 2
d1, d2 - Denominator 1, Denominator 2
result[ ] - The character array that is to display the answer
len - The number of characters allowed in result []



I would simply use long division and find my answer this way but since
there is a restriction to not use double, float, or string I am more
limited in my options towards my approach.
The good news is I've gotten a far ways towards the end solution and would
like to ask for advice as what my next move might be. This is my process
thus far:
1) Convert each number to an improper fraction
2) Take result 1 * (1 / result 2 )
3) Find the whole number part of the solution (if there is one)
4) (From the improper fraction) Take the numerator % denominator to find
my new numerator for the mixed fraction I have
5) I am now here, trying to find a base 10 multiple for the denominator so
I can represent the mixed fraction in decimal format.. Any pointers would
be helpful!

HTMLUnit : Send AJAX Post request

HTMLUnit : Send AJAX Post request

I'm using HTMLUnit to get a webpage that contains javascript. In this
webpage, I have a form, that help user input some information, and will
send ajax to server and change some contents of page. For example. The
Form is :
<form name="ajaxform" method="post" onsubmit="return checkDate();">
<label>Data1</label>
<input name="data1" id="data_1" readonly="readonly" / type ="text"
value="">
<label>Data2</label>
<input name="data2" id="data_2" readonly="readonly"/ type ="text"
value="">
<input name="getData" value="Get All Data From Server" / type
="submit" value="">
</form >
So my question is : How can I send a post request for this form to server.
(use pure java or HTMLUnit), and how can I get modified page, after server
return data again back to client.
Thanks :)

How to know WCF progress transmission?

How to know WCF progress transmission?

I have a WP8 app and use WCF-service with it. All is nice, but I do not
know - how can I quess about progress of transmission huge amount of data?
It 5 mb about.
I have only *async() and *completed() methods. Is there a way?
Thanks.

Rebind knockout js when I need to redraw html with bindings

Rebind knockout js when I need to redraw html with bindings

I have a situation where I build a div container dynamically that has
other html elements inside bonded to my knockout view model. It works up
to the point where I call a method on my knockout view model that needs to
redraw the whole div. After the redraw knockout stops working.
for example:
calendar += ('<div class="month-nav-container"><div class="nav-prev"
data-bind="click: $root.showPreviousMonthOnPrevMonthBtnClick"
><<<</div><span class="month-name-calendar">' + monthNames[month] +
'</span><div class="nav-next" data-bind="click:
$root.showNextMonthOnNextMonthBtnClick" >>>></div></div>');
I build my calendar control like so of course this is just part of it, but
I hope you get the general Idea.
my knockout view model method:
self.showPreviousMonthOnPrevMonthBtnClick = function () {
alert("prev");
var $calendar = $("#calendar");
$calendar.empty();
////// previous month
if (self.calendarDisplayDate.month == 0) {
$calendar.calendarWidget({ month: 12, year:
self.calendarDisplayDate.year - 1 });
} else {
$calendar.calendarWidget({ month: self.calendarDisplayDate.month -
1, year: self.calendarDisplayDate.year});
}
}
On my page load I build my calendar div, then I call ko.applyBindings() to
my view model and it works. But when I click on the btn that calles my
previous month method which needs to redraw calendar according to the
right month, knockout stops working. I redraw the whole parent div that
holds all the knockout bindings. Does anyone know solution to my problem.
I need to redraw the div that has KO bindings inside so maybe what i'm
looking for is some kind of bindings refresh method of Knockout ?

Jquery .on not working corectly

Jquery .on not working corectly

Im playing around with pagination and jquery, my code first looked like this:
$(function() {
$(".pagination a").live("click", function(){
$.get(this.href, null, null, "script");
return false;
});
});
Then i noticed that live is not supported in jquery 1.9 so i changed my code:
$(function() {
$(".pagination").on("click", 'a', function(){
$.get(this.href, null, null, "script");
return false;
});
});
But somehow this also wont work! The problem is that can navigate from the
first ajax page to the second but then form the second back to the first
page or to the third page my ajax is not working. I supose because my code
does not regognice the new added .pagination a!

Sunday, 15 September 2013

UITableView reloads data while scrolling

UITableView reloads data while scrolling

I've create an app that uses some maps functionality. I've added an
MKMapView to the UITableViewCell and WebView to another uiTableviewcell (I
need this, because it look elegant). I've created my custom cells. My
uitableview delegate and datasource methods:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 2;
}
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSInteger section = indexPath.section;
switch (section)
{
case 0:
return [self cellForMapView];
case 1:
return [self cellForUIWebView];
}
return nil;
}
-(UITableViewCell *)cellForMapView
{
//if (_mapViewCell)
// return _mapViewCell;
// if not cached, setup the map view...
CGFloat cellWidth = self.view.bounds.size.width - 20;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
cellWidth = self.view.bounds.size.width - 90;
}
CGRect frame = CGRectMake(0, 0, cellWidth, 241);
_mapView = [[MKMapView alloc] initWithFrame:frame];
_mapView.showsUserLocation = YES;
_mapView.userLocation.title = @"Òåêóùåå ìåñòîïîëîæåíèå";
_mapView.mapType = MKMapTypeStandard;
_mapView.zoomEnabled = YES;
NSString * cellID = @"Cell";
UITableViewCell *cell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID]
autorelease];
[cell.contentView addSubview:_mapView];
_mapViewCell = cell;
return cell;
}
/*
- (CGFloat)tableView:(UITableView *)tableView
heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 50.0f;
} */
-(UITableViewCell *)cellForUIWebView
{
//if (_webViewCell)
// return _webViewCell;
CGFloat cellWidth = self.view.bounds.size.width - 20 ;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
cellWidth = self.view.bounds.size.width - 90;
}
CGRect frame = CGRectMake(0, 0, cellWidth, 241);
_webView = [[UIWebView alloc] initWithFrame:frame];
NSString * cellID = @"Cell";
UITableViewCell *cell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleValue1
reuseIdentifier:cellID]autorelease];
[cell.contentView addSubview:_webView];
_webViewCell = cell;
return cell;
}
I'm downloading some data to the webview and to display some annotations
on the map. The problem is that when the user is changing orientation and
scrolling the tableview data, table view reloads the data automatically (I
have my webview and Map being recreated and displaying nothing). How to
fix this problem? Maybe I can save the tableviewcell's state?? But how to
do it?

Java version of Plural Sight?

Java version of Plural Sight?

this one was closed with a very very weak reason behind it. Java ecosystem
videos like Pluralsight-training?
before anyone could post any links or sites. The reason being that
opinions could be posted, well thats what were looking for, a list of
sites, something to go one that people might know off. I have the EXACT
question, and was very very dissapointed that it was closed before it
attracted any responses except one. Whats the harm? i think people were
just too trigger happy, so can it PLEASE be re opened, and people get
information to their question??



Does anyone know of any training (commercial) sites where I can learn
about Java and all the frameworks/technologies related to JVM? Sites
similar to pluralsight.com/training?
Thanks JD

Get an array from Server/Client app (Java)

Get an array from Server/Client app (Java)

So I have a Server/Client layer app running between my application and
database. I would like to get an array from the Server. I will paste some
pieces of code which I think is enough to give you an idea of what is
going on:
I send to the server the keyword for search in database (user and his
password)
fromUser = Musername + "," + Password;
out.println(fromUser);
Here is the code of the Server:
public class Server {
public static String[] theOutput;
public static String inputLine;
public static String[] string_array;
public static String output = "";
public static String[] process(String Input) throws Exception {
String[] data = Input.split(",");
// Call database class to get the results and store them into the
array
load_login pridobi = new load_login();
theOutput = pridobi.nalozi(data[0], data[1]);
return theOutput;
}
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(4444);
} catch (IOException e) {
System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.exit(1);
}
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
true);
BufferedReader in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
// get the username and password
inputLine = in.readLine();
if (inputLine.length() != 0) {
string_array = process(inputLine);
}
// And here I would like to do something like that :/
out.println(string_array);
}
}
PS: NOTE that some array elements are actually long text.

Call shadowbox inside gallery.js

Call shadowbox inside gallery.js

i have an image gallery and i want to add a shadowbox when i click on the
large image. The shadowbox is working on the HTML page, but when i try to
call him trough the gallery, it doesn't answer!
This .js script is called to be able to show the large image on the image
gallery.
// shows the large image that is associated to the $item
var $loader = $rgGallery.find('div.rg-loading').show();
$items.removeClass('selected');
$item.addClass('selected');
var $thumb = $item.find('img'),
largesrc = $thumb.data('large'),
title = $thumb.data('description');
$('<img/>').load( function() {
$rgGallery.find('div.rg-image').empty().append('<a
href="' + largesrc + '" rel="shadowbox" ><img src="' +
largesrc + '"/></a>');
if( title )
$rgGallery.find('div.rg-caption').show().children('p').empty().text(
title );
$loader.hide();
What should i do??

Design pattern for handling a server response

Design pattern for handling a server response

I've an observer pattern on the UI that checks what's the status of an
object that handles a server connection that's trying to update a certain
field on a database.
The UI's update method receives an object containing data pairs containing
the information of what's happening with the connection. The problem is
that I'm getting tangled with a lot of ifs checking for different
possibilities.
- (void) update:(Bundle *)arg
{
if ([[arg getData:@"updatee"] isEqualToString:@"email"]){
UITableViewCell *emailCell = [[self tableView]
cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0
inSection:0]];
if ([[arg getData:@"connecting"] isEqualToString:@"true"]) {
//Email is being posted
[_emailLabel_email setText:@"Connecting..."];
[_emailLabel_set setHidden:YES];
emailCell.accessoryType = UITableViewCellAccessoryNone;
[_emailActivityIndicator startAnimating];
}else{
if ([[arg getData:@"succesfull"] isEqualToString: @"false"])
//Email was posted unsuccesfully
[[[UIAlertView alloc] initWithTitle:@"Taken Email Address"
message:@"The email address that you
entered is already in use, please
double check it"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil] show];
else{
//Email was posted succesfully.
[_emailLabel_set setText:@"Change"];
}
[_emailActivityIndicator stopAnimating];
[_emailLabel_email setText:[mng getEmail]];
[_emailLabel_set setHidden:NO];
emailCell.accessoryType =
UITableViewCellAccessoryDisclosureIndicator;
}
}
//Password cases
}
}
As the server responds with a string I'm finding difficult to avoid this
spaggetti of code.
Which would be the smarter object to send on the update method?

Search and Replace in a variable string with Shell scripts

Search and Replace in a variable string with Shell scripts

I am in dilemma about how could I search and replace a particular
character in a variable of a shell script.
e.g. I have a condition where I need to pass '~' to the java program but I
should pass it as '/~' to avoid it being intercepted as $HOME. I have a
shell variable e.g. $1 = '.-~' and I am passing it directly to the Java
program as an argument. So how could I modify this variable in such a way
that it searches for '~' and if it finds then changes $1 = '.-/~' so as to
avoid the error in Java program.

Sinatra: Helper method won't "translate" a variable

Sinatra: Helper method won't "translate" a variable

I'm writing this helper:
helpers do
def css(*stylesheets)
stylesheets.map do |stylesheet|
'<link href="/#{stylesheet}.css" media="screen, projection"
rel="stylesheet" />'
end.join
end
end
Problem is, when I add it to the views (using the slim templating engine)
with:
==css :styles
and look at the HTML, I see:
<link href="/#{stylesheet}.css" media="screen, projection"
rel="stylesheet" />
Why doesn't this helper method translate #{stylesheet} into the
appropriate file? I tried restarting the server and everything, but
nothing worked so far.

Saturday, 14 September 2013

Where can I find the function definition in atomicity.h?

Where can I find the function definition in atomicity.h?

atomicity.h is part of c++ stl. In its source file, it declares two
functions about atomic operation. Here is the whole source code. Where can
I find the definition of these functions. I don't find it in stl source
code.
#ifndef _GLIBCXX_ATOMICITY_H
#define _GLIBCXX_ATOMICITY_H 1
#include <bits/atomic_word.h>
namespace __gnu_cxx
{
_Atomic_word
__attribute__ ((__unused__))
__exchange_and_add(volatile _Atomic_word* __mem, int __val);
void
__attribute__ ((__unused__))
__atomic_add(volatile _Atomic_word* __mem, int __val);
} // namespace __gnu_cxx

Unable to set the type of the image from Xcode to PHP

Unable to set the type of the image from Xcode to PHP

I'm trying to upload an image, taken from photo library, from Xcode to PHP.
When I send it to the server, the server outputs the details of the file
as follows:
[userfile] => Array
(
[name] => 001file.jpg
[type] =>
[tmp_name] => /tmp/php5VSe1V
[error] => 0
[size] => 9530
)
However, the 'type' section is always empty, and I can't figure out why.
When I changed multipart/form-data; to application/octet-stream, the
output array was NULL.
Any ideas? Thanks in advance.
ViewController.m
-(void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info{
[self dismissViewControllerAnimated:YES completion:NULL];
fileURL = [info objectForKey:UIImagePickerControllerReferenceURL];
NSLog(@"fileurl %@",fileURL);
NSData * data = [NSData dataWithContentsOfURL:fileURL];
NSLog(@"bites %d",[data length]);
UIImage * originalImage = (UIImage *) [info objectForKey:
UIImagePickerControllerOriginalImage];
[imageView setImage:originalImage];
NSString * photoFile = [[NSString alloc]init];
ALAssetsLibrary *assetLibrary=[[ALAssetsLibrary alloc] init];
[assetLibrary assetForURL:fileURL resultBlock:^(ALAsset *asset) {
NSLog(@"asset %@",asset);
ALAssetRepresentation *rep = [asset defaultRepresentation];
Byte *buffer = (Byte*)malloc(rep.size);
NSUInteger buffered = [rep getBytes:buffer fromOffset:0.0
length:rep.size error:nil];
theImageData = [NSData dataWithBytesNoCopy:buffer length:buffered
freeWhenDone:YES];//this is NSData may be what you want
NSLog(@"data bytesss a z%d",[theImageData length]);
//[data writeToFile:photoFile atomically:YES];//you can save image
later
} failureBlock:^(NSError *err) {
NSLog(@"Error: %@",[err localizedDescription]);
}];
NSLog(@"data bytesss %d",[theImageData length]);
}
- (void)sendImage{
[[EPUploader alloc] initWithURL:[NSURL
URLWithString:@"myurl.com/photoUploader.php"]
fileData:UIImageJPEGRepresentation(imageView.image,0.5)
delegate:self
doneSelector:@selector(onUploadDone:)
errorSelector:@selector(onUploadError:)];
}
EPUploader.m
#import "EPUploader.h"
#import <zlib.h>
static NSString * const BOUNDRY = @"0xKhTmLbOuNdArY";
static NSString * const FORM_FLE_INPUT = @"userfile";
#define ASSERT(x) NSAssert(x, @"NSASSERT ERROR")
@interface EPUploader (Private)
- (void)upload;
- (NSURLRequest *)postRequestWithURL: (NSURL *)url
boundry: (NSString *)boundry
data: (NSData *)data;
- (NSData *)compress: (NSData *)data;
- (void)uploadSucceeded: (BOOL)success;
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
@end
@implementation EPUploader
/*
*-----------------------------------------------------------------------------
*
* -[Uploader initWithURL:filePath:delegate:doneSelector:errorSelector:] --
*
* Initializer. Kicks off the upload. Note that upload will happen on a
* separate thread.
*
* Results:
* An instance of Uploader.
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
- (id)initWithURL: (NSURL *)aServerURL // IN
fileData: (NSData *)aFilePath // IN
delegate: (id)aDelegate // IN
doneSelector: (SEL)aDoneSelector // IN
errorSelector: (SEL)anErrorSelector // IN
{
if ((self = [super init])) {
NSLog(@"%@ databyte %d %@",aServerURL,[aFilePath length],aDelegate);
ASSERT(aServerURL);
ASSERT(aFilePath);
ASSERT(aDelegate);
ASSERT(aDoneSelector);
ASSERT(anErrorSelector);
serverURL = aServerURL;
fileData = aFilePath;
delegate = aDelegate;
doneSelector = aDoneSelector;
errorSelector = anErrorSelector;
[self upload];
}
return self;
}
/*
*-----------------------------------------------------------------------------
*
* -[Uploader dealloc] --
*
* Destructor.
*
* Results:
* None
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
- (void)dealloc
{
serverURL = nil;
fileData = nil;
delegate = nil;
doneSelector = NULL;
errorSelector = NULL;
}
/*
*-----------------------------------------------------------------------------
*
* -[Uploader filePath] --
*
* Gets the path of the file this object is uploading.
*
* Results:
* Path to the upload file.
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
- (NSData *)fileData
{
return fileData;
}
@end // Uploader
@implementation EPUploader (Private)
/*
*-----------------------------------------------------------------------------
*
* -[Uploader(Private) upload] --
*
* Uploads the given file. The file is compressed before beign uploaded.
* The data is uploaded using an HTTP POST command.
*
* Results:
* None
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
- (void)upload
{
NSData *data = fileData;
ASSERT(data);
if (!data) {
[self uploadSucceeded:NO];
return;
}
if ([data length] == 0) {
// There's no data, treat this the same as no file.
[self uploadSucceeded:YES];
return;
}
// NSData *compressedData = [self compress:data];
// ASSERT(compressedData && [compressedData length] != 0);
// if (!compressedData || [compressedData length] == 0) {
// [self uploadSucceeded:NO];
// return;
// }
NSURLRequest *urlRequest = [self postRequestWithURL:serverURL
boundry:BOUNDRY
data:data];
if (!urlRequest) {
[self uploadSucceeded:NO];
return;
}
NSURLConnection * connection = [[NSURLConnection alloc]
initWithRequest:urlRequest delegate:self];
if (!connection) {
[self uploadSucceeded:NO];
}
// Now wait for the URL connection to call us back.
}
/*
*-----------------------------------------------------------------------------
*
* -[Uploader(Private) postRequestWithURL:boundry:data:] --
*
* Creates a HTML POST request.
*
* Results:
* The HTML POST request.
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
- (NSURLRequest *)postRequestWithURL: (NSURL *)url // IN
boundry: (NSString *)boundry // IN
data: (NSData *)data // IN
{
// from http://www.cocoadev.com/index.pl?HTTPFileUpload
NSMutableURLRequest *urlRequest =
[NSMutableURLRequest requestWithURL:url];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setValue:
[NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundry]
forHTTPHeaderField:@"Content-Type"];
NSMutableData *postData =
[NSMutableData dataWithCapacity:[data length] + 512];
[postData appendData:
[[NSString stringWithFormat:@"--%@\r\n", boundry]
dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:
[[NSString stringWithFormat:
@"Content-Disposition: form-data; name=\"%@\";
filename=\"001file.jpg\"\r\n\r\n", FORM_FLE_INPUT]
dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:data];
[postData appendData:
[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundry]
dataUsingEncoding:NSUTF8StringEncoding]];
[urlRequest setHTTPBody:postData];
return urlRequest;
}
/*
*-----------------------------------------------------------------------------
*
* -[Uploader(Private) compress:] --
*
* Uses zlib to compress the given data.
*
* Results:
* The compressed data as a NSData object.
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
- (NSData *)compress: (NSData *)data // IN
{
if (!data || [data length] == 0)
return nil;
// zlib compress doc says destSize must be 1% + 12 bytes greater than
source.
uLong destSize = [data length] * 1.001 + 12;
NSMutableData *destData = [NSMutableData dataWithLength:destSize];
int error = compress([destData mutableBytes],
&destSize,
[data bytes],
[data length]);
if (error != Z_OK) {
NSLog(@"%s: self:0x%p, zlib error on compress:%d\n",__func__,
self, error);
return nil;
}
[destData setLength:destSize];
return destData;
}
/*
*-----------------------------------------------------------------------------
*
* -[Uploader(Private) uploadSucceeded:] --
*
* Used to notify the delegate that the upload did or did not succeed.
*
* Results:
* None
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
- (void)uploadSucceeded: (BOOL)success // IN
{
[delegate performSelector:success ? doneSelector : errorSelector
withObject:self];
}
/*
*-----------------------------------------------------------------------------
*
* -[Uploader(Private) connectionDidFinishLoading:] --
*
* Called when the upload is complete. We judge the success of the
upload
* based on the reply we get from the server.
*
* Results:
* None
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
- (void)connectionDidFinishLoading:(NSURLConnection *)connection // IN
{
NSLog(@"%s: self:0x%p\n", __func__, self);
[self uploadSucceeded:uploadDidSucceed];
}
/*
*-----------------------------------------------------------------------------
*
* -[Uploader(Private) connection:didFailWithError:] --
*
* Called when the upload failed (probably due to a lack of network
* connection).
*
* Results:
* None
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
- (void)connection:(NSURLConnection *)connection // IN
didFailWithError:(NSError *)error // IN
{
NSLog(@"%s: self:0x%p, connection error:%s\n",
__func__, self, [[error description] UTF8String]);
[self uploadSucceeded:NO];
}
/*
*-----------------------------------------------------------------------------
*
* -[Uploader(Private) connection:didReceiveResponse:] --
*
* Called as we get responses from the server.
*
* Results:
* None
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
-(void) connection:(NSURLConnection *)connection // IN
didReceiveResponse:(NSURLResponse *)response // IN
{
NSLog(@"%s: self:0x%p\n", __func__, self);
}
/*
*-----------------------------------------------------------------------------
*
* -[Uploader(Private) connection:didReceiveData:] --
*
* Called when we have data from the server. We expect the server to
reply
* with a "YES" if the upload succeeded or "NO" if it did not.
*
* Results:
* None
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
- (void)connection:(NSURLConnection *)connection // IN
didReceiveData:(NSData *)data // IN
{
NSLog(@"%s: self:0x%p\n", __func__, self);
NSString *reply = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding]
;
NSLog(@"%s: data: %s\n", __func__, [reply UTF8String]);
if ([reply hasPrefix:@"YES"]) {
uploadDidSucceed = YES;
}
}
@end

Problems with text/csv Content-Encoding = UTF-8 in Ruby Mechanize

Problems with text/csv Content-Encoding = UTF-8 in Ruby Mechanize

When attempting to load a page which is a CSV that has encoding of UTF-8,
using Mechanize V2.5.1, I used the following code:
a.content_encoding_hooks << lambda{|httpagent, uri, response, body_io|
response['Content-Encoding'] = 'none' if
response['Content-Encoding'].to_s == 'UTF-8'
}
p4 = a.get(redirect_url, nil, ['accept-encoding' => 'UTF-8'])
but I find that the content encoding hook is not being called and I get
the following error and traceback:
/Users/jackrg/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/mechanize-2.5.1/lib/mechanize/http/agent.rb:787:in
'response_content_encoding': unsupported content-encoding: UTF-8
(Mechanize::Error) from
/Users/jackrg/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/mechanize-2.5.1/lib/mechanize/http/agent.rb:274:in
'fetch' from
/Users/jackrg/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/mechanize-2.5.1/lib/mechanize/http/agent.rb:949:in
'response_redirect' from
/Users/jackrg/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/mechanize-2.5.1/lib/mechanize/http/agent.rb:299:in
'fetch' from
/Users/jackrg/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/mechanize-2.5.1/lib/mechanize/http/agent.rb:949:in
'response_redirect' from
/Users/jackrg/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/mechanize-2.5.1/lib/mechanize/http/agent.rb:299:in
'fetch' from
/Users/jackrg/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/mechanize-2.5.1/lib/mechanize.rb:407:in
'get' from prototype/test1.rb:307:in `'
Does anyone have an idea why the content hook code is not firing and why I
am getting the error?

how to using jCanvas for dynamic data

how to using jCanvas for dynamic data

Plugin : enter link description here
some time has many data like this
$("canvas")
.drawText({text1..}).drawText({text2..});
.drawLine({ data1..
}).drawLine({data2..}).drawLine({data3..}).drawLine({data3..});
or
$("canvas")
.drawText({text1..})
.drawLine({ data1.. });
how to add .drawXXX() to $("canvas") using loop or something for better

WPF, 3d camera won't rotate correctly

WPF, 3d camera won't rotate correctly

I'm trying to make my camera rotatable around the center point by holding
down the left button. Here's my code so far:
private void mouseWheel(object sender, MouseWheelEventArgs e)
{
if (e.Delta < 0) { _posZ = _posZ - 0.5; } else { _posZ = _posZ +
0.5; }
_perspectiveCamera.Position = new Point3D(_posX, _posY, _posZ);
}
private void mouseMove(object sender, MouseEventArgs e)
{
if ( e.LeftButton == MouseButtonState.Pressed )
{
if (isLeftDown == false)
{
isLeftDown = true;
tempMouseX = this.PointToScreen(Mouse.GetPosition(this)).X;
tempMouseY = this.PointToScreen(Mouse.GetPosition(this)).Y;
}
else
{
double currentDelataX = tempMouseX -
this.PointToScreen(Mouse.GetPosition(this)).X ;
double currentDelataY = tempMouseY -
this.PointToScreen(Mouse.GetPosition(this)).Y ;
_posX = _posX - currentDelataX / 1000;
_posY = _posY - currentDelataY / 1000;
_perspectiveCamera.Position = new Point3D(_posX, _posY,
_posZ);
Point3D objectPosition = new Point3D(0, 0, 0);
_perspectiveCamera.LookDirection = new
Vector3D(objectPosition.X - _perspectiveCamera.Position.X,
objectPosition.Y - _perspectiveCamera.Position.Y,
objectPosition.Z - _perspectiveCamera.Position.Z);
}
}
/////////////////////////////////////////
if (e.LeftButton == MouseButtonState.Released)
{
isLeftDown = false;
}
}
Yet the rotation itself doesn't seem to work right, looks like the camera
moves far away by the Z axe ( object moves away from the viewer ).
What do you think might be wrong?
Thanks

Make use of a value from a servlet to use it in a normal class

Make use of a value from a servlet to use it in a normal class

My Scenario : I have a servlet and two normal classes. X servlet y Class Z
Class.
X Servlet code :
Y y=new Y();
y.setMap(Map);//Value exists for Map[Found out by sysout]
Y Class :
public void setMap(HashMap<String,String> hash){
this.hash=hash;
System.out.println("Set:::"+this.hash.toString());
}
public HashMap<String, Boolean> getMap(){
System.out.println("Bean Class:::"+hash.toString());
return hash;
}
Z Class:
Bean bean=new Bean();
HashMap result=bean.getMap();
System.out.println(result);
It results to null. Can any one explain y it results in null.

Do PHP notices cause additional server load?

Do PHP notices cause additional server load?

I've got a few files which cause PHP notices to show if I have them
enabled. Everything works as it should, just the notices appear. I know
they should be corrected (undefined index and undefined variable) but at
the moment I need to get this done. Some pages have over 100, some are as
few as 10.
Are there any adverse performance effects to putting this code live, i.e.
additional server load?

C# MVC populating drop down value from DB

C# MVC populating drop down value from DB

I am struggling to understand MVC. I have created couple of pages that
work. Now I created a new page which has a dropdownlist which needs to
populate from a table called accounts(coloumn is called accountNumber)
However there is a relationship with that table and table called
customer(customerid).
In essence the user whose logged in has a customerid.
what is the easiest way of doing this? when I enter
@Html.DropDownListFor(u => u.
none of tables I need pop up

Friday, 13 September 2013

Authenticate API using digital signature

Authenticate API using digital signature

I am building an API solution to cater few enterprises who can share keys
with me privately. I want to build a secure API and following are the
requirements
1) If I get a request from any enterprise, I should have the proof that
only that enterprise have sent that request, so if any bad request is sent
by enterprise should have proof to show. - I plan to achieve to ask the
sender also put the signature of the request so that only they could have
sent the request as noone can create their signature.
2) Secure channel - I plan to use https
3) Other standard requirements which I plan to cater by requiring the
sender to include the Access key id created by me, date, time stamp.
I have mostly followed this using the standard ways to encrypt based on my
requirements and Amazon's way of securing the requests
(http://docs.aws.amazon.com/AmazonS3/latest/dev/S3_Authentication2.html).
curl -i -H "Content-Type: application/json \n "
-X POST -d '{ "key1": "value1", "key2":
"value2", "key3": "value3",
"key4": "value4", "accesskeyid":"sdfsd334s",
"timestamp":"35d345",
"signature":"sglfdkgjfldkgj"}'
http://localhost:5000/xyz
My intention is to only allow calls from known parties, and to prevent
calls from being reused verbatim.
Is this good enough? Underkill? Overkill?
Our server is located on amazon cloud.

logical interview question_ print foo for time of 3, boo for time of 5 and fooboo for both

logical interview question_ print foo for time of 3, boo for time of 5 and
fooboo for both

I have been asked logical question in interview. I have solved it but just
wondering how other programmers approach to same problem of let say which
is most efficient way. I have used C# but you can use any language.
question is print number from 1 to 100. if next number is time of 3 then
print foo. If next number in queue is time of 5, print boo and if next
number in queue is time of 3 and 5 both then print fooboo else print
number
I have used bool in my logic. lets see whats other audience come back with!!!
class Program
{
static void Main(string[] args)
{
MyClass_01 obj1 = new MyClass_01();
obj1.myFunction_01();
}
}
class MyClass_01
{
public void myFunction_01()
{
for (float i = 1; i <= 100; i++)
{
bool gate1 = false;
bool gate2 = false;
if (i % 3 == 0)
{
gate1 = true;
}
if (i % 5 == 0)
{
gate2 = true;
}
if (gate1 && !gate2)
{
Console.WriteLine(i + " foo");
}
else if (gate2 && !gate1)
{
Console.WriteLine(i + " boo");
}
else if (gate1 && gate2)
{
Console.WriteLine(i + " booFoo");
}
else
{
Console.WriteLine(i);
}
}
Console.ReadLine();
}
}

How would I print to an Epson TM-U210A receipt printer

How would I print to an Epson TM-U210A receipt printer

I have this Epson TM-U210A receipt printer that I'd like to make use of.
How would I make an application communicate with the printer? Preferably
I'd like this to happen through JavaScript client-side. Is there an API to
do this? Sorry if this has been asked before, but I'm quite new to
alternative printers and couldn't really understand any of the few
articles I've found.

OPL namespace printing output on the screen

OPL namespace printing output on the screen

i was looking at ILOG IBM help and came across below section. i am not
sure what the OPL namespace mean. how can run below example in my ibm ilog
screen?
length
Purpose OPL function to return the number of characters of a string.
Type:int
Syntax:length(string s)
Description: Returns the number of characters in the string s. You can use
this function within IBM® ILOG Script statements by specifying the OPL
namespace:
( Opl.xxx() )
Example
string s="Paris";
int l=length(s);
execute
{
writeln("length(\"",s,"\") gives ",l);
}
Result
length("Paris") gives 5

Is iterating over a Python file object thread safe?

Is iterating over a Python file object thread safe?

While searching for a neat solution to this problem I was wondering if
iterating over a Python file object is thread safe or not.
from concurrent.futures import ThreadPoolExecutor
import sys, time
f = open("big_file")
def worker():
running = True
while running:
try:
line = next(f)
except StopIteration:
return
# process line
time.sleep(3)
sys.stdout.write(line + "\n")
no_workers = 4
with ThreadPoolExecutor(max_workers=no_workers) as e:
for _ in range(no_workers):
e.submit(worker)
f.close()
My question is, if the example above is safe, or if not, what is an easy
way to get a thread-safe file object (for reading a file line by line,
writing is not required).

Thursday, 12 September 2013

When to use a HybridDictionary over other Dictionary types?

When to use a HybridDictionary over other Dictionary types?

I am looking at the Collection classes in MSDN for the .Net framework. I
ran into the HybridDictionary and it states
(http://msdn.microsoft.com/en-us/library/system.collections.specialized.hybriddictionary.aspx):
Implements IDictionary by using a ListDictionary while the collection is
small, and then switching to a Hashtable when the collection gets large.
So I wondered about the ListDictionary which states
(http://msdn.microsoft.com/en-us/library/system.collections.specialized.listdictionary.aspx)
Recommended for collections that typically include fewer than 10 items.
Now that seems like an arbitrary number (of items) to me. I can't find in
the documentation what the mechanism behind this would be, I suspected the
boundary of performance would have been related to a number of items like
2^N (2 to the power of N).
Now I do use the collection type of Dictionary often, and the collections
might contain 10 to 30 items, 50 tops, depending on the 'page size'.
But HybridDictionary and ListDictionary requires unboxing and there are no
generic type contructors for them.
I can't find a comparison anywhere about the performance of a
HybridDictionary vs Dictionary.
So when to actually use this HybridDictionary over other Dictonary types?
P.S. And if HybridDictionary switches to ListDictionary or HashTable when
the number of items grow to optimize its functioning. Why ever use a
ListDictionary? If some requirements in the software change, and suddenly
a maximum of 20 items must be put in the ListDictionary, instead of a
maximum number of 10 items, the code must be re-factored to HashTable to
maintain performance?

Cannot return value from main

Cannot return value from main

**static string Main(string[] args)
{
//IPAddress ipAddress = System.Net.IPAddress.Loopback;
IPAddress ipAddress = IPAddress.Parse("192.168.0.100");
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 1515);
Socket sock = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
Connect(localEndPoint, sock);
string packet;
packet = Console.ReadLine();
packet += "<EOF>";
Send(sock, packet);
Receive(sock);
return packet;
//connectDone.WaitOne();
}**
This is me Client mail section, when i try to return my string from my
server respond (packet variable) the compiler error Program '...\clie.exe'
does not contain a static 'Main' method suitable for an entry point

Set attribute on model callback with rails 4

Set attribute on model callback with rails 4

sorry for my english...
I am trying set the user id of my model usign the before_create callback,
but I am not getting it.
before_create :set_user_id
def set_user_id
self.user_id = 1
end
user_id is nil, Some help?

MySQL query not working after adding AND operator

MySQL query not working after adding AND operator

I'm pretty sure i messed up the quotes, but can't find where exactly. It
stopped working after adding the AND operator. Can anybody guide me to the
right direction?
$result = mysql_query("SELECT * FROM pl_table WHERE p_num=".$w[0] AND
l_num='.$w[0]);

Disk Cleaner App - How do they do it? [on hold]

Disk Cleaner App - How do they do it? [on hold]

There is an approved app in app store that claims to cleanup disk space on
your iDevice by removing temporary files. iClean
Now here are my questions regarding the technology
How do these apps figure out how much disk space is available when
technically they cannot access anything outside of their sandbox?
By the same token how does this app appear to cleanup disk space and
remove temporary files?
What is the underlying technology and api's that they are using? What ios
SDK documentation is available on this topic?
Are there any sample tutorials or explanation available? I for one
couldn't find anything even after hours of googling.

Hosting ruby on rails on Bluehost- installation of specific versions of ruby, rails

Hosting ruby on rails on Bluehost- installation of specific versions of
ruby, rails

I have logged into my Bluehost server through SSH and I am looking to
install ruby v1.9.3 and rails v3.2.13. The version of ruby by default
seems to be 1.8.7 and the rails 2.3.11.
I tried to upgrade rails using the following command in the terminal under
the SSH session:
gem install rails -v 3.2.13 --no-rdoc --no-ri
I get the following output:
Successfully installed rails-3.2.13
1 gem installed
I then tried running a check that it was installed:
rails -v
I get the following output:
Rails 2.3.11
Why does it not get upgraded? Additionally, what command should I be using
within bluehost SSH session to upgrade ruby?

php,javascript,mysql splitting big query to google maps

php,javascript,mysql splitting big query to google maps

first question here :)
I have a table with over million locations (id|address|longitude|latitude).
User can enter an address and he gets the nearest locations by 5km radius
in google map.
My select query :
$result = mysql_query("SELECT *, ( 6371 * acos( cos( radians(".$lat1.") )
* cos( radians( lat ) ) * cos( radians( lng ) - radians(".$lng1.") ) +
sin( radians(".$lat1.") ) * sin( radians( lat ) ) ) ) AS distance FROM
star HAVING distance < ".$rad." ORDER BY distance");
results on table, inside javascript <>
while ($row = mysql_fetch_array($result)) {
echo "
var marker".$row{'id'}." = new google.maps.Marker({
position: new google.maps.LatLng(".$row{'lat'}." , ".$row{'lng'}."),
map: map
});
var infowindow".$row{'id'}." = new google.maps.InfoWindow({
content: 'City : ".$row{'city'}.", Address : ".$row{'address'}." , Lat
: ".$row{'lat'}." , Lng : ".$row{'lng'}."'
});
google.maps.event.addListener(marker".$row{'id'}.", 'click', function() {
infowindow".$row{'id'}.".open(map, marker".$row{'id'}.");
});
";
}
My problem is when it gets over 10 locations, its doesn't show the google
map.. I dont want to use LIMIT 0,10, I wanna show all the results.
How do I split the query to search each time 10% from the big table?
Something lke putting the markers on runtime after the page loads.

Tomcat/Ubuntu not using correct JDK

Tomcat/Ubuntu not using correct JDK

I am trying to use an AMI created from ubuntu instance running on AWS. The
original instance had the java 1.7.0_21 installed and JAVA_HOME pointing
to it. I compile my classes with compatibility set to 1.7 as I need the
javax.net.ssl package. My application runs fine inside tomcat. But when I
try to run an instance created from AMI, I am getting the Unsupported
major.minor version 51.0 (unable to load class error. I do a ps on the
processes running and I see the tomcat has been started with jdk 1.7.0_21
as expected. I am not sure why I get this error.
ubuntu@XXXX:~$ ps aux | grep tomcat
tomcat6 2554 0.8 35.3 997460 213768 ? Sl 07:01 0:21
/usr/local/java/jdk1.7.0_21/bin/java
-Djava.util.logging.config.file=/var/lib/tomcat6/conf/logging.properties
-Djava.awt.headless=true -Xmx128m -XX:+UseConcMarkSweepGC
-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager
-Djava.endorsed.dirs=/usr/share/tomcat6/endorsed -classpath
/usr/share/tomcat6/bin/bootstrap.jar -Dcatalina.base=/var/lib/tomcat6
-Dcatalina.home=/usr/share/tomcat6
-Djava.io.tmpdir=/tmp/tomcat6-tomcat6-tmp
org.apache.catalina.startup.Bootstrap start