Saturday, 31 August 2013

get surface width in angle game engine

get surface width in angle game engine

how can i get width of surface (mGLSurfaceView) in angle android game engine?
i tried mGLSurfaceView.getWidth() but it return 0!!!
what should i use?
any help appreciated !

Delete Function of a Class

Delete Function of a Class

I'm having trouble with the delete function. I have everything working
except the delete function.
Any help would be appreciated. I've tried to change it a bit but it still
doesn't delete. I have no idea what the problem is with my remove
function.
public class Person
{
private string name;
private string phoneNumber;
public string Name
{
set { name = value; }
get { return name; }
}
public string PhoneNumber
{
set { phoneNumber = value; }
get { return phoneNumber; }
}
public void PrintInfo()
{
Console.WriteLine();
Console.WriteLine(" Name: {0}", name);
Console.WriteLine(" Phone Number: {0}", phoneNumber);
Console.WriteLine();
}
public void SaveASCII(ref StreamWriter output)
{
output.WriteLine(name);
output.WriteLine(phoneNumber);
}
public void LoadASCII(ref StreamReader input)
{
name = input.ReadLine();
phoneNumber = input.ReadLine();
}
}
public class membershipList
{
public Person[] ML = null;
public void AddMember(Person p)
{
if (ML == null)
{
ML = new Person[1];
ML[0] = p;
}
else
{
Person[] temp = ML;
ML = new Person[temp.Length + 1];
for (int i = 0; i < temp.Length; ++i)
{
ML[i] = new Person();
ML[i] = temp[i];
}
ML[temp.Length] = new Person();
ML[temp.Length] = p;
temp = null;
}
}
public void DeleteMember(string p)
{
if (ML != null)
{
foreach (Person pers in ML)
{
if (pers.Name.ToLower().CompareTo(p.ToLower()) == 0)
{
pers.Remove();
break;
}
}
}
else Console.WriteLine("Then list is empty.");
}
// {
// int memberIndex = Array.FindIndex(ML, p => p.Name
== name);
// if (memberIndex == -1)
// {
// Console.WriteLine(name + " had not been added
before.");
// return;
// }
// else
// {
// List<Person> tmp = new List<Person>(ML);
// tmp.RemoveAt(memberIndex);
// ML = tmp.ToArray();
// }
// }
// }
public void PrintAll()
{
if (ML != null)
foreach (Person pers in ML)
pers.PrintInfo();
else Console.WriteLine("Then list is empty");
}
public void Search(string p)
{
if (ML != null)
{
foreach (Person pers in ML)
{
if (pers.Name.ToLower().CompareTo(p.ToLower()) == 0)
{
Console.WriteLine("1 Record Found:");
pers.PrintInfo();
break;
}
}
}
else Console.WriteLine("Then list is empty.");
}
public void ReadASCIIFile()
{
StreamReader input = new StreamReader("memberlist.dat"); ;
try
{
int num = Convert.ToInt32(input.ReadLine());
ML = new Person[num];
for (int i = 0; i < num; ++i)
{
ML[i] = new Person();
ML[i].LoadASCII(ref input);
}
input.Close();
}
catch (FormatException e)
{
Console.WriteLine(e.Message);
input.Close();
}
}
public void SaveASCIIFile()
{
StreamWriter output = new StreamWriter("memberlist.dat");
output.WriteLine(ML.Length);
foreach (Person pers in ML)
{
pers.SaveASCII(ref output);
}
output.Close();
}
}
class Program
{
static void Main(string[] args)
{
membershipList ML = new membershipList();
ML.ReadASCIIFile();
string option;
do
{
// Console.Clear();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("MemberShip List MENU");
Console.WriteLine();
Console.WriteLine(" a. Add");
Console.WriteLine(" b. Seach");
Console.WriteLine(" c. Delete");
Console.WriteLine(" d. Print All");
Console.WriteLine(" e. Exit");
Console.WriteLine();
Console.Write("option: ");
option = Console.ReadLine().ToLower();
switch (option)
{
case "a":
Person np = new Person();
Console.Write("Enter Name: ");
np.Name = Console.ReadLine();
Console.Write("Enter PhoneNumber: ");
np.PhoneNumber = Console.ReadLine();
ML.AddMember(np);
break;
case "b":
Console.Write("Enter Name: ");
string name = Console.ReadLine();
ML.Search(name);
break;
case "c":
Console.Write("Enter Name to be Deleted:");
string pers = Console.ReadLine();
ML.DeleteMember(pers);
break;
case "d":
ML.PrintAll();
break;
case "e":
ML.SaveASCIIFile();
Console.WriteLine("BYE...... ");
break;
default:
Console.WriteLine("Invalid Option");
break;
}
} while (option.ToLower() != "d");
}
}

How to send form to URL?

How to send form to URL?

Here's the code I'm currently using for my form:
<form method="post" action="access.php" class="form-stacked">
<fieldset class="control-group">
<div class="control-group">
<div class="controls">
<input class="input-xlarge" name="s1" id="s1" type="text"
value="" />
</div>
</div>
<center>(click here if you need help finding your
username)</center>
</fieldset>
<fieldset class="control-group">
<div class="control-group">
<div class="controls">
<input class="input-xlarge" name="s2" id="s2" type="text"
value="" />
</div>
</div>
<center>(click here if you need help finding your
username)</center>
</fieldset>
</form>
When I click enter it takes people directly to http://mysite.com/access.php
But instead I'm trying to figure out how to make it take them to
http://mysite.com/access.php?s1=value&s2=value
Obviously the value would be replaced with the text they actually entered.
What's the easiest way for me to change this code to make it happen?
Thanks!

Jquery pagination - Applying class to items

Jquery pagination - Applying class to items

I am trying to design a pagination system in Jquery. The bit I am stuck on
is when I click on different page number links, I want it to move the
"active" class to the newly clicked page.
In the example page "1" has the active class. When I click "2" I want the
active class to move to "2" and be removed from "1".
http://jsfiddle.net/qKyNL/24/
$('a').click(function(event){
event.preventDefault();
var number = $(this).attr('href');
$.ajax({
url: "/ajax_json_echo/",
type: "GET",
dataType: "json",
timeout: 5000,
beforeSend: function () {
$('#content').fadeTo(500, 0.5);
},
success: function (data, textStatus) {
// TO DO: Load in new content
$('html, body').animate({
scrollTop: '0px'
}, 300);
// TO DO: Change URL
// TO DO: Set number as active class
},
error: function (x, t, m) {
if (t === "timeout") {
alert("Request timeout");
} else {
alert('Request error');
}
},
complete: function () {
$('#content').fadeTo(500, 1);
}
});
});
I'm quite new to Jqeury and could do with some help. Can anyone please
give me some guidance on how to do this?

Using jsoup how to get anchor tags that are within div tags with class that have display none style

Using jsoup how to get anchor tags that are within div tags with class
that have display none style

I have a document from which I am trying to extract the a tags. Some of
them are within tags that have the class attribute and the class has the
display:none property set. I want to eliminate those.

C# I need a algorithmic for Lock-by-value

C# I need a algorithmic for Lock-by-value

You have a function Foo(long x) which is called by many threads. You want
to prevent threads from executing the method simultaneously for the same
value of x. If two methods call it with x=10, one should block and wait
for the other to finish; but if one thread calls it with x=10 and another
with x=11, they should run in parallel. X can be any long value. You must
not keep in memory all the values with which the function was called in
the past, but free them once all threads with that value exit the function
(you may wait for GC to free them). Extra: if two threads, with different
values of X, do not contend for any shared lock (such as a static
management lock) when entering or leaving the function, and only threads
with the same values of X can ever block and wait.

How to recover LOST WORK resulting from the use of git?

How to recover LOST WORK resulting from the use of git?

I'm using SourceTree and what happened is that I clicked on "Commit", then
added all changed files, but before committing I wanted to remove one of
the files in order to commit it later.
I right-clicked on my file and was offering the following choices:
"Discard",
"Remove",
"Unstage from index",
"Stop tracking"

I was really confused by those choices, I clicked "Discard" and now all
the work done in this file was lost!!!
PANIC MODE! How can I recover my changes in this file?
Thank you!

What would you use JavaScript for in general on a web page?

What would you use JavaScript for in general on a web page?

What would you use JavaScript for in general on a web page?

Friday, 30 August 2013

Is there any world wide real estate api?

Is there any world wide real estate api?

Does anyone know world wide real estate api which I can get the list of
pricing of real estate for searching with location? I tried to look for
google api or yahoo api. Also, I checked Zillow api but it was only for
US.

Thursday, 29 August 2013

Best way to disable CSS rule (like Chrome does?)

Best way to disable CSS rule (like Chrome does?)

I have this situation. I'm using bootstrap and jquery-ui in my
application, included in this way:
<link href="bootstrap.min.css" rel="stylesheet" media="screen"/>
<link href="jquery-ui.css" rel="stylesheet" media="screen"/>
<!-- My custom stylesheet -->
<link href="style/style.css" rel="stylesheet" media="screen"/>
When use jquery-ui for open a modal window, I realized that the content
has it's "own" font-family and font-size, because of this rules:
.ui-widget input,
.ui-widget select,
.ui-widget textarea,
.ui-widget button {
font-family: Verdana,Arial,sans-serif/*{ffDefault}*/;
font-size: 1em;
}
When debugging in Chrome (F12) I can "disable" this rules and gets the
expected result. But I can't figure out how to do it in my custom
stylesheet. I know that this would do the trick:
.ui-widget input,
.ui-widget select,
.ui-widget textarea,
.ui-widget button {
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-size: 14px;
}
Or I can comment out the rules in the jquery-ui.css file. But I was
looking for a way that, if later I decide to change the "base" font, I
could make the change in one single place and don't modify the jquery-ui
and bootstrap css files How can achieve this? How does the mechanism to
"disable" rules in Chrome works?

Android functions simultaneously

Android functions simultaneously

This is my code:
protected void loadvide(Chan channel) {
Rtmpdump dump = new Rtmpdump();
dump.parseString(channel.getUrl());
startActivity(new Intent(this,VideoViewDemo.class));
}
The code works, but I have a problem.
The problem is, when I execute the aplication, first execute this part to
my code:
Rtmpdump dump = new Rtmpdump();
dump.parseString(channel.getUrl());
and the second part: startActivity(new Intent(this,VideoViewDemo.class));
not work, because the second part begin work when finish the first part.
But I would like that when I start the application, the first and second
parts of the code are executed simultaneously.

Wednesday, 28 August 2013

Count and IN Clause Issue

Count and IN Clause Issue

I have a table named as employee history and its structure is as follows.
tbl_employee_history Structure id|history_nr|history_value|employee_id 1
82 83 1 2 86 84 1 3 87 85 1 4 603 1 5 82 83 2 6 86 83 2 7 87 83 2 8 603 83
2
This is the dummy data for my table. Now I want to count all those
employees whose history_nr is in 82,86,87,603 AND history_value should not
be empty like in the above example the count should be 1 as for employee
id 2 all the values are not empty. This is my query for implementing the
count.
SELECT count(employee_id) FROM tbl_employee_history where history_nr
IN(82,86,87,603) AND history_value!=''
But what happens is the count returns me two values. Thanks in advance.

Calling C++ from Fortran (linking issue?)

Calling C++ from Fortran (linking issue?)

I really need your help! I'm on a deadline and I'm trying to learn just
enough to get some work done. It's been well over a week now that I'm
dealing with what appears to be a straightforward issue but I haven't been
able to successfully implement solutions online.
Long story short: I need to call C++ code from F77. I'm compiling with g++
and gfortran. I'm a complete newb to makefiles. When these codes are
compiled as part of their respective programs, they are bug free (I'm
taking a function from my C++ code, not main(), and trying to use it with
the fortran code). Here's what I've got:
C++ Code:
#include <cmath>
#include <vector>
using namespace std;
extern"C" double ShtObFun(double x[], int &tp)
{
return //double precision awesomeness
}
Fortran Code:
subroutine objfun(nv, var, f, impass)
implicit real(8) (a-h,o-z), integer (i-n)
c initializations including tp, used below
f = ShtObFun(var, tp)
return
end
Makefile (shows only files listed above):
all:
g++ -c Objective_Functions.cpp
gfortran -c -O3 opcase1.f
gfortran opcase1.o Objective_Functions.o -fbounds-check -lstdc++ -g -o
Program.out
rm *.o
Error:
opcase1.o: In function 'objfun_':
opcase1.f:(.text+0xbd): undefined reference to 'shtobfun_'
collect2: ld returned 1 exit status
I have tried this a variety of other ways and they did not work. I can
list those later if requested. Does anyone see the issue here?
The sites I've checked:
calling C++ function from fortran not C, Linking fortran and c++ binaries
using gcc, , Calling C Code from FORTRAN, Cookbook - Calling C from
Fortran, YoLinux - Using C/C++ and Fortran together

How can I Generate a time series with Hadoop?

How can I Generate a time series with Hadoop?

What's the easiest way to generate a time series with Hadoop (or pig or
Hive)?, Or where can I get information on the proper functions?
For example I want to generate a 1sec sequence from 00:00:00 01/01/2000 to
23:59:59 31/12/2010.
With other programs, such as R, is quite simple because they have many
functions to work with dates and times.
Regards

GCM Push Notification adobe air

GCM Push Notification adobe air

I m developing a push notification service for my app in android i came to
some tutorials to achieve my goal. I struck to 2 things that i can't
figure out. I need some help.
PushNotifications.init( "*DEV_KE*Y" )&#894;
<permission android:name="*application ID*.permission.C2D_MESSAGE"
Now i want to know about this 2 things. Dev_key and application
id.Secondly is PushNotifications.init()&#894; necessary to call? what if i
call it without dev_key param?

Tuesday, 27 August 2013

Skype won't let me edit/delete other people's messages

Skype won't let me edit/delete other people's messages

In an old version (5.x, I don't remember the exact version) of skype, I
was able to right click someone else's IM and have the option to modify or
edit it, like I can do to my own IMs:

However, now I can only see this when I right-click someone else's IM:

I created the group and my role is CREATOR (that's what it said after I
did /get role)

jcarousel with 100% li item width?

jcarousel with 100% li item width?

I'm trying to get jcarousel to work with an li width of 100%. i.e.
whatever width the browser window has, that's the width of the visible li
item.
When I make the ul wide enough for all the items (20000em like the demo)
and set the li width to 100%, naturally it becomes 20000em too, where as I
want it the width of the container
#slider {
height:500px;
position:relative;
overflow:hidden;
width:100%;
}
#slider ul {
height:500px;
list-style:none;
list-style-type:none;
position:absolute;
width:20000em;
}
#slider ul li {
height:500px;
width:100%;
float:left;
}
// HTML
<div id="slider">
<ul>
<li>As wide as the window, not 20000em like the parent ul</li>
</ul>
</div>

Heroku Rails app not loading pages

Heroku Rails app not loading pages

I'm publishing a Rails app on Heroku for the first time, and am running
into an error. Everything works great, except only the landing page loads.
From the landing page, there are sign-up and log-in buttons for Devise,
but they just throw 500 error pages. I opened up the Heroku logs and see
these:
2013-08-27T19:00:55.036186+00:00 app[web.1]: Processing by
Devise::SessionsController#new as HTML
2013-08-27T19:00:55.035363+00:00 heroku[router]: at=info method=GET
path=/users/sign_in host=infinite-escarpment-6269.herokuapp.com
fwd="98.245.21.165" dyno=web.1 connect=3ms service=20ms status=500
bytes=643
2013-08-27T19:00:55.773025+00:00 heroku[router]: at=info method=GET
path=/favicon.ico host=infinite-escarpment-6269.herokuapp.com
fwd="98.245.21.165" dyno=web.1 connect=2ms service=14ms status=304 bytes=0
2013-08-27T19:00:01.630144+00:00 heroku[router]: at=info method=GET
path=/users/sign_up host=infinite-escarpment-6269.herokuapp.com
fwd="98.245.21.165" dyno=web.1 connect=5ms service=150ms status=500
bytes=643
I don't see any error codes in here. My app is using PostgreSQL and the
only commands I ran on the database were heroku run rake db:create:all and
heroku run rake db:migrate. Do I need to make any changes in my
database.yml file to get the site working on Heroku? Do I need to write
any migrations to get the site working on Heroku? I'm new to all of this,
so I'm not sure. I've just been following the getting started instructions
on Heroku.
UPDATE I tailed the logs and see this error message relating to PostgreSQL:
ActiveRecord::StatementInvalid (PG::Error: ERROR: relation "users" does
not exist
This error message is familar to me, but I can't remember what to do about
it.

Is there a better way to map Objects from a database query to an object?

Is there a better way to map Objects from a database query to an object?

I would like to know if there is a better way to solve this problem that I
am overlooking. (I'm looking for a second opinion)
I want to create a generic and easy way to bind objects to database reader
queries using "Oracle.DataAccess.Client".
In order to do this I initially wanted to create an object which inherited
from OracleCommand; however, OracleCommand is a sealed object.
To deal with this I decided to create an extension method which attempts
to map objects to generic columns in the database for each row.
EDIT : In my scenario, I know what the database will look like; however, I
will not know where the database is before run time. i.e. The database may
have been transferred ahead of time and the end user will specify the
credentials for the database at run time.
Here is the implementation:
public static T[] Bind<T>(this OracleCommand oe, Binding binding,
CommandBehavior Behavior = CommandBehavior.Default)
{
List<T> ret = new List<T>();
using (var reader = oe.ExecuteReader(Behavior))
{
while (reader.Read())
{
T unknownObj = (T)Activator.CreateInstance(typeof(T));
for (int i = 0; i < binding.GetBindCount(); i++)
{
var propinfo =
unknownObj.GetType().GetProperties().ToList();
var prop = propinfo.Find((p) => p.Name ==
binding.GetBindValue(i, true));
prop.SetValue(unknownObj,
reader[binding.GetBindValue(i, false)]);
}
ret.Add(unknownObj);
}
}
return ret.ToArray();
}
}
public class Binding
{
List<BindingMap> _map = new List<BindingMap>();
public void AddBind(String VariableName, String ColumnName)
{
_map.Add(new BindingMap(VariableName, ColumnName));
}
public String GetBindValue(int index, bool IsVariable = true)
{
var a = _map.ToArray();
return (IsVariable) ? a[index].Variable : a[index].Column;
}
public int GetBindCount()
{
return _map.Count;
}
}
public class BindingMap
{
public String Column;
public String Variable;
public BindingMap(String v, String c)
{
Variable = v;
Column = c;
}
}
Is there a better way to do this that I've overlooked, or is this a sound?
The way it would be used in real code is like this :
static void Main()
{
Binding b = new Binding();
b.AddBind("CreatedBy", "Create_by");
using (var Conn = new OracleConnection())
{
Conn.ConnectionString = od.Options.GetConnectionString();
using (var Command = new OracleCommand())
{
Command.Connection = Conn;
Command.CommandText = "Select * From Accounts";
Conn.Open();
var a = Command.Bind<Account>(b);
foreach (Account e in a)
{
Console.WriteLine(e.CreatedBy);
}
}
}
Console.Read();
}
public class Account
{
public String CreatedBy
{
get;
set;
}
}

compare between different kind of engineering research methodology

compare between different kind of engineering research methodology

Base on engineering perspective of research methodology what is the
different between Theoretical studies,Numerical methodology and
Empirical/experimental methods.

Monday, 26 August 2013

DI with Unity when multiple instances of the same type is needed

DI with Unity when multiple instances of the same type is needed

I need help with this. I'm using Unity as my container and I want to
inject two different instances of the same type into my constructor.
class Example
{
Example(IQueue receiveQueue, IQueue sendQueue) {}
}
....and IQueue is implemented in my MessageQueue class....
class MessageQueue : IQueue
{
MessageQueue(string path) {}
}
How can I inject two different instances of MessageQueue into my Example
class? Each of the MessageQueue instances to be created with different
path.

Why is Entity Framework significantly slower when running in a different AppDomain?

Why is Entity Framework significantly slower when running in a different
AppDomain?

We have a Windows service that loads a bunch of plugins (assemblies) in to
their own AppDomain. Each plugin is aligned to a "service boundary" in the
SOA sense, and so is responsible for accessing its own database. We have
noticed that EF is 3 to 5 times slower when in a separate AppDomain.
I know that the first time EF creates a DbContext and hits the database,
it has to do some setup work which has to be repeated per AppDomain (i.e.
not cached across AppDomains). Considering that the EF code is entirely
self-contained to the plugin (and hence self-contained to the AppDomain),
I would have expected the timings to be comparable to the timings from the
parent AppDomain. Why are they different?
Have tried targeting both .NET 4/EF 4.4 and .NET 4.5/EF 5.
Sample code
EF.csproj
Program.cs
class Program
{
static void Main(string[] args)
{
var watch = Stopwatch.StartNew();
var context = new Plugin.MyContext();
watch.Stop();
Console.WriteLine("outside plugin - new MyContext() : " +
watch.ElapsedMilliseconds);
watch = Stopwatch.StartNew();
var posts = context.Posts.FirstOrDefault();
watch.Stop();
Console.WriteLine("outside plugin - FirstOrDefault(): " +
watch.ElapsedMilliseconds);
var pluginDll =
Path.GetFullPath(AppDomain.CurrentDomain.BaseDirectory +
@"..\..\..\EF.Plugin\bin\Debug\EF.Plugin.dll");
var domain = AppDomain.CreateDomain("other");
var plugin = (IPlugin)
domain.CreateInstanceFromAndUnwrap(pluginDll,
"EF.Plugin.SamplePlugin");
plugin.FirstPost();
Console.ReadLine();
}
}
EF.Interfaces.csproj
IPlugin.cs
public interface IPlugin
{
void FirstPost();
}
EF.Plugin.csproj
MyContext.cs
public class MyContext : DbContext
{
public IDbSet<Post> Posts { get; set; }
}
Post.cs
public class Post
{
public int Id { get; set; }
}
SamplePlugin.cs
public class SamplePlugin : MarshalByRefObject, IPlugin
{
public void FirstPost()
{
var watch = Stopwatch.StartNew();
var context = new MyContext();
watch.Stop();
Console.WriteLine(" inside plugin - new MyContext() : " +
watch.ElapsedMilliseconds);
watch = Stopwatch.StartNew();
var posts = context.Posts.FirstOrDefault();
watch.Stop();
Console.WriteLine(" inside plugin - FirstOrDefault(): " +
watch.ElapsedMilliseconds);
}
}
Sample timings
Note: This is querying against an empty database table - 0 rows.
Run 1
outside plugin - new MyContext() : 55
outside plugin - FirstOrDefault(): 783
inside plugin - new MyContext() : 352
inside plugin - FirstOrDefault(): 2675
Run 2
outside plugin - new MyContext() : 53
outside plugin - FirstOrDefault(): 798
inside plugin - new MyContext() : 355
inside plugin - FirstOrDefault(): 2687
Run 3
outside plugin - new MyContext() : 45
outside plugin - FirstOrDefault(): 778
inside plugin - new MyContext() : 355
inside plugin - FirstOrDefault(): 2683
AppDomain research
After some further research in to the cost of AppDomains, there seems to
be a suggestion that subsequent AppDomains have to re-JIT system DLLs and
so there is an inherent start-up cost in creating an AppDomain. Is that
what is happening here? I would have expected that the JIT-ing would have
been on AppDomain creation, but perhaps it is EF JIT-ing when it is
called?
Reference for re-JIT:
http://msdn.microsoft.com/en-us/magazine/cc163655.aspx#S8
Timings sounds similar, but not sure if related: First WCF connection made
in new AppDomain is very slow

memcache - searching key names containing multiple identifiers

memcache - searching key names containing multiple identifiers

I'm new to memcache (via Amazon ElastiCache) and I'm using it to store
data to offload some work from the database.
Currently I store 2 identical values where the key is a different lookup key.
For example:
// each key represents the user email address with the value a json dump
of the user record
'email@email.com': {
id: 1,
name: 'John Doe',
email: 'email@email.com'
}
// each key represents the user id with the value a json dump of the user
record
1: {
id: 1,
name: 'John Doe',
email: 'email@email.com'
}
Is it possible to store both the id/email in one key thus eliminating the
need for 2 separate records stored in memory?
Any example in either Python or PHP would be most helpful!

Resource path is not callable in Custom Magento Module

Resource path is not callable in Custom Magento Module

Sei que tem alguns topicos relacionado aqui no Stackoverflow, mas nenhum
conseguiu me atender devidamente. Segue minha API.XML
<?xml version="1.0"?>
<config>
<api>
<resources>
<verificaintegrador_api translate="title"
module="verificaintegrador">
<title>Myapi</title>
<acl>verificaintegrador/api</acl>
<model>verificaintegrador/api</model>
<methods>
<verificarintegradoron translate="title"
module="verificaintegrador">
<title>verificarintegradoron</title>
<acl>verificaintegrador/verificarintegradoron</acl>
</verificarintegradoron>
<alterarstatusintegrador translate="title"
module="verificaintegrador">
<title>alterarstatusintegrador</title>
<acl>verificaintegrador/alterarstatusintegrador</acl>
</alterarstatusintegrador>
</methods>
</verificaintegrador_api>
</resources>
<acl>
<resources>
<verificaintegrador translate="title"
module="verificaintegrador">
<title>VerificaIntegrador</title>
<sort_order>2000</sort_order>
<verificarintegradoron translate="title"
module="verificaintegrador">
<title>verificarintegradoron</title>
</verificarintegradoron>
<alterarstatusintegrador translate="title"
module="verificaintegrador">
<title>alterarstatusintegrador</title>
</alterarstatusintegrador>
</verificaintegrador>
</resources>
</acl>
</api>
</config>

Instantiating Null Objects with Null-Coalescing Operator – programmers.stackexchange.com

Instantiating Null Objects with Null-Coalescing Operator –
programmers.stackexchange.com

Consider the following typical scenario: if(myObject == null) { myObject =
new myClass(); } I'm wondering what is thought of the following
replacement using the null-coalescing operator: ...

insert data into table using the today() function

insert data into table using the today() function

I have a silly question... for some reason I just can't get it work...
I want to insert a row into an empty table using the today(function).
This is what I do:
insert into gal_risk_factor (RISK_FACTOR_ID, VALID_FROM_DTTM,
RISK_FACTOR_NM, EFFECTIVE_FROM_DTTM, EFFECTIVE_TO_DTTM)
values ("1",today(),
"GGG",
"01JAN1901:00:00:00"dt, "01JAN2999:00:00:00"dt
)
This is the error I get:
today(),
_____
22
202
ERROR 22-322: Syntax error, expecting one of the following: a quoted
string, a numeric constant, a datetime constant,
a missing value, ), +, ',', -, MISSING, NULL, USER.
ERROR 202-322: The option or parameter is not recognized and will be
ignored.
What am I missing here...?
Thank you in advance, Gal.

Sunday, 25 August 2013

Display tree structure on a jsp using Recursion and JSTL

Display tree structure on a jsp using Recursion and JSTL

I would like to implement a tree structure in my JSP baised
web-application using recursion and JSTL.The values of tree is populated
from database using java(using some list or map..).I know this question
may be asked by some peoples.but i didn't get any idea from those
resources.Please help me..
Here is my Table Structure for company table.
Column Type
Company_id int
Company_parent_id int
Company_name varchar(50)
Class Company
public Class Company{
private int companyId;
private int companyParantId;
private String companyName;
//getters&setters
}
Sample tree structure that i watnt to implement.
1
1.1
1.2
1.2.1
1.2.1.1
2
2.1
3
3.1
3.1.1
.....
n
n.1
....
My question is How can i implement Recursion in jsp with the help of JSTL?.
Thanks,

[ Fashion & Accessories ] Open Question : Where can I find this backpack?

[ Fashion & Accessories ] Open Question : Where can I find this backpack?

Does anyone know where I can find this backpack? On all the sites I
checked they are all sold out :( Its called 'Roxy Lately Pearl Crochet
Backpack' and it looks like this:
http://www.zumiez.com/roxy-lately-pearl-crochet-backpack.html Thanks!

Indexer causes MySQL to hang

Indexer causes MySQL to hang

Not sure what's going on. I run indexer --all --rotate When it finishes
mysql hangs and not accepting new connections.
*mysql tables are not corrupt
*i'm using mysql 5.6.12-56
*table in Innodb type
indexer --all --rotate
Sphinx 2.1.1-beta (rel21-r3701)
Copyright (c) 2001-2013, Andrew Aksyonoff
Copyright (c) 2008-2013, Sphinx Technologies Inc (http://sphinxsearch.com)
using config file '/etc/sphinx/sphinx.conf'...
indexing index 'online'...
collected 27114 docs, 99.0 MB
sorted 258.8 Mhits, 100.0% done
total 27114 docs, 98993190 bytes
total 119.609 sec, 827633 bytes/sec, 226.68 docs/sec
total 21 reads, 4.497 sec, 53362.9 kb/call avg, 214.1 msec/call avg
total 2510 writes, 3.210 sec, 968.1 kb/call avg, 1.2 msec/call avg
rotating indices: successfully sent SIGHUP to searchd (pid=12773).
from my observation as soon as indexer finishes, all queries status become
query end
processlist when it hangs:
Id User Host db Command Time State Info Rows_sent
Rows_examined
31891 forum_DB localhost forum_DB Query 346
query end INSERT INTO ibf_sessions (`id`,`member_name`,`member_id$
31905 forum_DB localhost forum_DB Query 346
query end DELETE FROM ibf_sessions WHERE (id='yandex=95108240250_$
31964 forum_DB localhost forum_DB Query 345
query end INSERT INTO ibf_sessions (`id`,`member_name`,`member_id$
32062 forum_DB localhost forum_DB Query 343
query end INSERT INTO ibf_topic_views (`views_tid`) VALUES(599181$
32077 forum_DB localhost forum_DB Query 343
query end INSERT INTO ibf_topic_views (`views_tid`) VALUES(599181$
32353 forum_DB localhost forum_DB Query 338
query end INSERT INTO ibf_core_like_cache (`like_cache_id`,`like_$
32443 forum_DB localhost forum_DB Query 336
query end INSERT INTO ibf_core_like_cache (`like_cache_id`,`like_$
32450 forum_DB localhost forum_DB Query 336
query end INSERT INTO ibf_sessions (`id`,`member_name`,`member_id$
32518 forum_DB localhost forum_DB Query 335
query end INSERT INTO ibf_sessions (`id`,`member_name`,`member_id$
32617 forum_DB localhost forum_DB Query 333
query end INSERT INTO ibf_core_like_cache (`like_cache_id`,`like_$
32642 forum_DB localhost forum_DB Query 332
query end INSERT INTO ibf_sessions (`id`,`member_name`,`member_i
...
37207 online localhost online Query 247 Waiting for query
cache lock SELECT id, short_story, title, date, alt_name, category$
37216 forum_DB localhost forum_DB Query 247 query
end INSERT INTO ibf_sessions (`id`,`member_name`,`member_id$
37228 online localhost online Query 247 Waiting for query
cache lock SELECT id, short_story, title, date, alt_name, category$
37232 online localhost online Query 247 System lock SELECT
id, autor, date, short_story, SUBSTRING(full_story, 1, 15) as fu$
37239 online localhost online Query 247 FULLTEXT
initialization SELECT id, short_story, title, date, alt_name, category,
flag F$
37243 music localhost music Query 247 Waiting for query
cache lock TRUNCATE TABLE dle_login_log 0 0
37250 online localhost online Query 246 Sending data SELECT
COUNT(*) as count FROM dle_post WHERE approve=1 AND allow_main=1$
37253 files localhost files Query 246 Waiting for query
cache lock TRUNCATE TABLE dle_views 0 0
37264 music localhost music Query 246 Waiting for table
metadata lock TRUNCATE TABLE dle_login_log 0 0
37271 files localhost files Query 245 Waiting for table
metadata lock SELECT COUNT(*) as count, news_id FROM dle_views GROUP $
37279 online localhost online Query 245 Sending data SELECT
COUNT(*) as count FROM dle_post WHERE approve=1 AND allow_main=1$
37288 files localhost files Query 244 Waiting for table
metadata lock SELECT COUNT(*) as count, news_id FROM dle_views GROUP $
37289 online localhost online Query 244 FULLTEXT
initialization SELECT id, short_story, title, date, alt_name, category,
flag F$
37291 files localhost files Query 244 Waiting for table
metadata lock SELECT COUNT(*) as count, news_id FROM dle_views GROUP $
37292 online localhost online Query 244 Waiting for query
cache lock TRUNCATE TABLE dle_login_log 0 0
37296 online localhost online Query 244 Sending data SELECT
COUNT(*) as count FROM dle_post WHERE approve=1 AND
...
cat processlist-2013-08-25-11-52.log | wc -l 352
sphinx.conf
source online_posts
{
type = mysql
sql_host =
sql_user =
sql_pass =
sql_db = online_test
sql_port = 3306 # optional, default is 3306
sql_query = \
SELECT * FROM post
#sql_attr_uint = group_id
sql_attr_timestamp = date
sql_query_pre = SET NAMES utf8
sql_query_pre = SET CHARACTER SET utf8
sql_query_pre = SET SESSION query_cache_type=OFF
sql_query_info = SELECT * FROM post WHERE id=$id
}
index online
{
source = online_posts
path = /var/lib/sphinx/online
docinfo = extern
charset_type = utf-8
morphology = stem_enru
min_word_len = 2
min_prefix_len = 0
min_infix_len = 2
charset_table = 0..9, A..Z->a..z, _, a..z,
U+410..U+42F->U+430..U+44F, U+430..U+44F
enable_star = 1
}
indexer
{
mem_limit = 512M
}
searchd
{
listen = 9312
listen = 9306:mysql41
log = /var/log/sphinx/searchd.log
query_log = /var/log/sphinx/query.log
read_timeout = 5
max_children = 30
pid_file = /var/run/sphinx/searchd.pid
max_matches = 1000
seamless_rotate = 1
preopen_indexes = 1
unlink_old = 1
workers = threads # for RT to work
binlog_path = /var/lib/sphinx/
}
Looks like others have this problem as well, but I don't understand how he
solved that http://sphinxsearch.com/forum/view.html?id=11072

Images on admin backend not showing up

Images on admin backend not showing up

It was going alright with images a week ago! But recently when I noticed I
found that image thumbnails in media library and in post editor were
either not showing up or were just showing there file-names. I need to do
a lot of work with images, so I have a custom column on post admin page
that shows featured images of the post is showing that same behavior as
media library. Here is Media library
and in Post editor
It is very important requirement to have images for site working. Can
anyone provide suggestions, how to resolve this?

Saturday, 24 August 2013

Nutch 1.3 and Solr 4.4.0 integration Job failed

Nutch 1.3 and Solr 4.4.0 integration Job failed

I am trying to crawl the web using nutch and I followed the documentation
steps in the nutch's official web site (run the crawl successfully, copy
the scheme-solr4.xml into solr directory). but when I run the
bin/nutch solrindex http://localhost:8983/solr/ crawl/crawldb -linkdb
crawl/linkdb crawl/segments/*
I get the following error:
Indexer: starting at 2013-08-25 09:17:35
Indexer: deleting gone documents: false
Indexer: URL filtering: false
Indexer: URL normalizing: false
Active IndexWriters :
SOLRIndexWriter
solr.server.url : URL of the SOLR instance (mandatory)
solr.commit.size : buffer size when sending to SOLR (default 1000)
solr.mapping.file : name of the mapping file for fields (default
solrindex-mapping.xml)
solr.auth : use authentication (default false)
solr.auth.username : use authentication (default false)
solr.auth : username for authentication
solr.auth.password : password for authentication
Indexer: java.io.IOException: Job failed!
at org.apache.hadoop.mapred.JobClient.runJob(JobClient.java:1357)
at org.apache.nutch.indexer.IndexingJob.index(IndexingJob.java:123)
at org.apache.nutch.indexer.IndexingJob.run(IndexingJob.java:185)
at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:65)
at org.apache.nutch.indexer.IndexingJob.main(IndexingJob.java:195)
I have to mention that the solr is running but I cannot browse
http://localhost:8983/solr/admin (it redirects me to
http://localhost:8983/solr/#).
On the other hand, when I stop the solr, I get the same error! Does
anybody have any idea about what is wrong with my setting?
P.S. the url that I crawl is: http://localhost/NORC

Parsing HTML with Jsoup issue in Android Application

Parsing HTML with Jsoup issue in Android Application

I am new to android development. I am using Jsoup to parse an URL to get
the file location.
Below is the code I have for parsing the URL, It works for most of the URL
I inserted. For example, www.baidu.com/ or www.nba.com/, the title Logged
is exactly same as shown in the page source.
However,
1) for http://music.baidu.com/ the title displayed in the Eclipse Log is
different from the page resource. Eclipse shows °Ù¶ÈÒôÀÖ Page Resource
shows °Ù¶ÈÒôÀÖ-ÖйúµÚÒ»ÒôÀÖÃÅ»§
/* This is the most important one I want to solve */. 2) For
http://music.baidu.com/search?key=%E5%86%8D%E8%A7%81%E7%8E%8B%E5%AD%90+%E6%A3%89%E8%8A%B1%E7%B3%96
Eclipse again shows °Ù¶ÈÒôÀÖ again, Page Resource shows ËÑË÷º¬ÓÐ"ÔÙ¼ûÍõ×Ó
ÃÞ»¨ÌÇ"µÄÒôÀÖ_°Ù¶ÈÒôÀÖ-ÖйúµÚÒ»ÒôÀÖÃÅ»§
Also, for those 2 webpage, nothing is in Element links, so the
Log.d("text", link.text()); never returns anything.
I notice that the 2 webpages source does not have in HTML like other HTML
has.
package com.example.htmlparser;
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
//set layout view
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread downloadThread = new Thread() {
public void run() {
Document doc;
try {
String url = "";
doc = Jsoup.connect(url).get();
//doc = Jsoup.parse(new URL(url).openStream(),
"UTF-8", url);
String title = doc.title();
Log.d("title", title);
Elements links = doc.select("a[href]");
for (Element link : links) {
//Log.d("link", link.attr("href").toString());
Log.d("text", link.text());
}
} catch (IOException e) {
Log.d("exception", e.toString());
}
}
};
downloadThread.start();
}
}
Can someone help me to solve this problem?

Android JSON Object getDouble only working in Debug

Android JSON Object getDouble only working in Debug

I have researched my problem and so far no one is experiencing this. I am
developing an app for Android, my code is throwing a JSON Exception with
the message "No Value For TotalProductCount" but only if I do not debug
it. If I put a break point in anywhere the code should go, it works. Here
is my code:
InternetServices class:
public static ArrayList<ShoppingCart> GetItemFromBarcode(String barcode,
String sessionKey, String shop) throws ClientProtocolException,
IOException, JSONException {
ArrayList<ShoppingCart> shoppingCart = new ArrayList<ShoppingCart>();
if (shop.equals("Tesco")) {
String URL =
"https://secure.techfortesco.com/groceryapi/restservice.aspx?command=PRODUCTSEARCH&page=1&sessionkey="
+ sessionKey + "&searchtext=" + barcode;
_client = new DefaultHttpClient();
HttpGet get = new HttpGet(URL);
HttpResponse r = _client.execute(get);
int status = r.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONObject items = new JSONObject(data);
if (items.getDouble("TotalProductCount") == 1) {
JSONArray products = items.getJSONArray("Products");
JSONObject item = products.getJSONObject(0);
shoppingCart.add(ConvertJSONtoShoppingCart(item));
}
else if (items.getDouble("TotalProductCount") == 0) {
//No product found
ShoppingCart error = new ShoppingCart();
error.setFailure(R.string.ShoppingItemReviewDialog_barcodeMessage);
shoppingCart.add(error);
}
else {
//More than one item found
int productCount = (int)
items.getDouble("PageProductCount");
JSONArray products = items.getJSONArray("Products");
for (int i=0; i < productCount; i++) {
JSONObject item = products.getJSONObject(i);
shoppingCart.add(ConvertJSONtoShoppingCart(item));
}
}
}
else {
//connecting to internet failed
ShoppingCart error = new ShoppingCart();
error.setFailure(R.string.ShoppingItemReviewDialog_loginMessage);
shoppingCart.add(error);
}
}
return shoppingCart;
}
public static ShoppingCart ConvertJSONtoShoppingCart(JSONObject item)
throws ClientProtocolException, IOException, JSONException {
ShoppingCart shoppingCart = new ShoppingCart();
shoppingCart.setItem(item.getString("Name"));
shoppingCart.setImage(item.getString("ImagePath"));
shoppingCart.setPrice(item.getDouble("Price"));
String temp = item.getString("OfferPromotion");
String offerString = temp.replaceAll("£", "£");
shoppingCart.setOffer(offerString);
//TODO find out how to receive the offer ID from the Tesco API
//shoppingCart.setOfferID(item.getString("OfferID"));
shoppingCart.setOfferID(item.getString("Name"));
String offer = item.getString("OfferValidity");
if (!offer.equals("") && !offer.equals(null)){
shoppingCart.setOfferStart(GetStartDateFromString(offer));
shoppingCart.setOfferEnd(GetEndDateFromString(offer));
}
return shoppingCart;
}
Activity Class: this is the runnable that is being executed on another thread
public void run() {
synchronized (t) {
if (sessionKey != null && sessionKey != "") {
try {
potentialItems =
InternetServices.GetItemFromBarcode(barcodeValue,
sessionKey, theShoppingTrip.getShop());
} catch (ClientProtocolException e) {
ErrorOnThread errorOnThread = new
ErrorOnThread(e.getMessage(), this);
handler.post(errorOnThread);
e.printStackTrace();
} catch (IOException e) {
ErrorOnThread errorOnThread = new
ErrorOnThread(e.getMessage(), this);
handler.post(errorOnThread);
e.printStackTrace();
} catch (JSONException e) {
ErrorOnThread errorOnThread = new
ErrorOnThread(e.getMessage(), this);
handler.post(errorOnThread);
e.printStackTrace();
}
}
else {
}
}
handler.post(returnRes);
synchronized (t)
{
t.interrupt();
}
}
and this is the runnable being posted to the UI thread when an error occurs:
private static class ErrorOnThread implements Runnable {
private final String errorMessage;
private final Context context;
ErrorOnThread(final String message, Context context) {
this.errorMessage = message;
this.context = context;
}
public void run() {
Toast toast = Toast.makeText(context, errorMessage,
Toast.LENGTH_LONG);
toast.show();
}
}
Here is an example JSON Object
{ "StatusCode": 0, "StatusInfo": "Processed and Logged OK", "PageNumber":
1, "TotalPageCount": 1, "TotalProductCount": 1, "PageProductCount": 1,
"Products": [ { "BaseProductId": "51644502", "EANBarcode":
"5000462001015", "CheaperAlternativeProductId": "",
"HealthierAlternativeProductId": "", "ImagePath":
"http://img.tesco.com/Groceries/pi/015/5000462001015/IDShot_90x90.jpg",
"MaximumPurchaseQuantity": 99, "Name": "Tesco Still Water 2Ltr",
"OfferPromotion": "", "OfferValidity": "", "OfferLabelImagePath": "",
"Price": 0.45, "PriceDescription": "£0.02 each", "ProductId": "258016425",
"ProductType": "QuantityOnlyProduct", "UnitPrice": 0.023, "UnitType":
"100ml" } ] }
Again this all works perfectly fine if I follow it in debug so it is
impossible to see what is going wrong. I am hoping that I am just being
blind and am missing something obvious.
I hope this makes sense. Any help or suggestions is appreciated. Thank you

How do I catch a UNIX TERM Signal so I can gracefully terminate a PHP process?

How do I catch a UNIX TERM Signal so I can gracefully terminate a PHP
process?

I'm running many PHP processes via Supervisord. Sometimes I need to shut
Supervisord down. When I do so, I have it set to send a TERM signal to all
the PHP processes it has spawned. I'd like to intercept that TERM Signal
and gracefully terminate the PHP process. Can this be done?
I've added this code to my PHP program to try and do this:
declare( ticks = 1 );
function gracefully_terminate() {
echo "\n\ngracefully terminating\n\n";
}
pcntl_signal( SIGTERM, "gracefully_terminate" );
Also ... how to I send a TERM signal to a PHP process via the CLI? I've
tried using Kill -s TERM #####. Perhaps this is sending the TERM signal,
but it's not terminating the PHP process.

What to look for when purchasing a blender?

What to look for when purchasing a blender?

I currently don't have a blender after purchasing my own home and am
looking to get one for making smoothies primarily, but also for pureeing
for soups, etc.
I had a smoothie maker that I won as a prize; it was very obviously a
cheap unit. It barely handled frozen fruit and yogurt. Ice cream and
frozen fruit burned up the motor.
I am aware of the extreme "Home Improvement"-style "Binford-3000" Blendtec
blenders (also as proposed in this question) but they are extremely
expensive and I don't plan on incorporating cell phones or garden rakes
into my smoothies.
What should I look for to get a quality blender? I don't want to purchase
an inexpensive one three or four times in the next few years. I'd prefer
one that will last a long time and prove to be a good kitchen tool.
Edit:
In shopping for blenders, it seems that most seem to be between $30 and
$150. Obviously there are some questionably cheap ones and many that
exceed that range. So for the purposes of this question, assume that range
to be the budget.

Copy fileto SD Card from Raw folder after context-menu selection?

Copy fileto SD Card from Raw folder after context-menu selection?

I'm (slowly) making an app which displays a list of tones and lets the
user "long press" a certain one which then brings up a context menu asking
if you'd like to copy it to SD card. Only problem is that last part, I
need help. Basically the tones are stored in the Raw folder, and I need it
that it copies the selected tone file to the SD card, preferably in the
notifications folder.
Just wondering if someone could give me an example of how I would go about
this because I'm absolutely lost?
Here's my code
import java.util.ArrayList;
import android.app.ListActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
private ArrayList<Sound> mSounds = null;
private SoundAdapter mAdapter = null;
static MediaPlayer mMediaPlayer = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerForContextMenu(getListView());
this.getListView().setSelector(R.drawable.selector);
//create a simple list
mSounds = new ArrayList<Sound>();
Sound s = new Sound();
s.setDescription("Anjels");
s.setSoundResourceId(R.raw.anjels);
mSounds.add(s);
s = new Sound();
s.setDescription("Fizz");
s.setSoundResourceId(R.raw.fizz);
mSounds.add(s);
s = new Sound();
s.setDescription("Flipper");
s.setSoundResourceId(R.raw.flipper);
mSounds.add(s);
s = new Sound();
s.setDescription("Glass Key");
s.setSoundResourceId(R.raw.glasskey);
mSounds.add(s);
s = new Sound();
s.setDescription("Halo");
s.setSoundResourceId(R.raw.halo);
mSounds.add(s);
mAdapter = new SoundAdapter(this, R.layout.list_row, mSounds);
setListAdapter(mAdapter);
}
@Override
public void onListItemClick(ListView parent, View v, int position, long id){
Sound s = (Sound) mSounds.get(position);
MediaPlayer mp = MediaPlayer.create(this, s.getSoundResourceId());
mp.start();
}@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo
menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo)
item.getMenuInfo();
int length = mSounds.size(); // get the length of mSounds object
String[] names = new String[length]; // creates a fixed array with
strings
for(int i = 0; i < length; i++) {
// add sound name to string array
names[i] = mSounds.get(i).getDescription(); // returns the string
name
}
switch(item.getItemId()) {
case R.id.copytosd:
Toast.makeText(this, "Applying " +
getResources().getString(R.string.copy) +
" for " + names[(int)info.id],
Toast.LENGTH_SHORT).show();
return true;
default:
return super.onContextItemSelected(item);
}
}}

Text validation on ajax autocomplete extender

Text validation on ajax autocomplete extender

I'm having a text-box with AJAX auto-complete extender. Some times when
user type some characters and presses tab key in that case web-service is
not working. How can i stop user to leave control without completion of
service method.
.aspx Code
<asp:TextBox runat="server" ID="ddlOrg" CssClass="tb10" autocomplete="off" />
<ajaxToolkit:AutoCompleteExtender
TargetControlID="ddlOrg" UseContextKey="true"
runat="server" BehaviorID="AutoCompleteEx"
ID="autoComplete1"
ServicePath="AutoComplete.asmx"
ServiceMethod="GetResellerList"
MinimumPrefixLength="1"
CompletionInterval="1000" EnableCaching="true"
FirstRowSelected="true"
CompletionSetCount="20"
CompletionListCssClass="cssList"
DelimiterCharacters=""
ShowOnlyCurrentWordInCompletionListItem="true" >
</ajaxToolkit:AutoCompleteExtender>
Service Code
[WebMethod]
public string[] GetResellerList(string prefixText, int count, string
contextKey)
{
DataSet ds = new DataSet();
ds = clsTransaction.Select("SELECT nm AS Name FROM tblReseller WHERE
nm LIKE '" + prefixText + "%' AND wsid = '" + contextKey + "'",
DataSendBSSWEB.ServerDbEnum.MainSqlServer,
false);
//Then return List of string(txtItems) as result
List<string> txtItems = new List<string>();
String dbValues;
foreach (DataRow row in ds.Tables[0].Rows)
{
dbValues = row["Name"].ToString();
txtItems.Add(dbValues);
}
return txtItems.ToArray();
}
Can any one help me to do this.

Friday, 23 August 2013

Rails How to output negative numbers from Postgress

Rails How to output negative numbers from Postgress

I am having a small problem. outputting the minus sing from the database.
I cheeked the field and the value is "Solid Door -10°F Freezers"
When i go to out put the value it comes out like "Solid Door 10°F
Freezers" i think its funny how the ° but not the - Now i am not doing
anything special just
<%= model.field %>
I tried to do
<%= raw model.field %>
but nothing is its not really html
Thanks for the help

Twitter Sentimental Analysis

Twitter Sentimental Analysis

I would like to know, if I have 3 labels (positive,negative, and neutral )
for sentimental analysis for twitter , and this dataset (Dataset1) is
unbalanced 1000 records for neutral, 570 for positive, and 450 for
negative.. I combined it with another dataset Dataset2 to get balanced,
For example, 1000 neutral from Dataset1 1000 positive from Dataset2 1000
negative from Dataset2
and make classification ,I tested it and I found that the accuracy is low,
so my question is : Does merging/combining dataset like mentioned before
affect the classifier ?, or I have to investigate in another direction..
Also if anyone knows where I can find balanced database for twitter
sentimental analysis including (pos,neg, neutral), it will be better to
use it once.

Where can i find towitoko library?

Where can i find towitoko library?

I tried to install the gem ctapi:
gem install ctapi
Fetching: ctapi-0.2.3.gem (100%)
Temporarily enhancing PATH to include DevKit...
Building native extensions. This could take a while...
ERROR: Error installing ctapi:
ERROR: Failed to build gem native extension.
C:/RailsInstaller/Ruby1.9.3/bin/ruby.exe extconf.rb
Using default library towitoko!
checking for main() in -ltowitoko... no
On the site of the gem it says:
You need to install a driver library, that supports the CTAPI interface
for this extension to link against. The newest version of the towitoko
library, that is required to drive the Towitoko Chipdrive Micro, Extern,
Extern II, Intern, Twin, and the "Kartenzwerg", can be download at this
URL: http://www.geocities.com/cprados
The problem is that the url is not avaible! Does somebody know antoher
place where i can find this libaries?

Faster way for this mysql_query

Faster way for this mysql_query

$handle = fopen("stock.csv", "r");
while (($data = fgetcsv($handle, 1000, ";")) !== false) {
$model = mysql_real_escape_string ($data[0]);
$quantity = mysql_real_escape_string ($data[7]);
mysql_select_db("verradt33_xoho", $link);
$quantity = str_replace("JA", "10", $quantity);
$quantity = str_replace("NEE", "0", $quantity);
$result = mysql_query("UPDATE dev_product
SET quantity = $quantity
WHERE model = '$model'")
or die(mysql_error());
Even tho the code works, it takes a long time to process the 7000+ lines
in the CSV. Due to having to replace JA or NEE with 10 or 0 every single
line.
Is there a way to make this faster? I can't touch the csv file, that's the
hard part of course.
Current load time is 40 minutes.

xslt: sum up just a for of an integer array

xslt: sum up just a for of an integer array

So, I have an array of integers. And I want to sum it up. But not the
whole array but just till a position in the array specified by another
variable.
For example. This beeing my array:
<xsl:variable name="myArray" as="xs:int*">
<Item>11</Item>
<Item>22</Item>
<Item>33</Item>
<Item>44</Item>
<Item>55</Item>
<Item>66</Item>
<Item>77</Item>
<Item>88</Item>
</xsl:variable>
And this beeing my position variable:
<xsl:variable name="myPosition" as="xs:int*">3</xsl:variable>
I expect the result 66. (Because: $myArray[1] + $myArray[2] + $myArray[3]
= 11 + 22 + 33 = 66)
Sounds rather simple but I can't find a solution.
I guess, I need the "sum" function and the "for" and "return" expressions.
But I must admit didn't understand any of the examples and instructions I
found corncerning these.

How to remove keyboard. Normal method not working. objective-c

How to remove keyboard. Normal method not working. objective-c

I have this code.
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
//If user presses next go to next textfield
if (textField == self.emailTextField) {
[textField resignFirstResponder];
[self.passwordTextField becomeFirstResponder];
}
else if (textField == self.passwordTextField) {
[self.passwordTextField resignFirstResponder];
}
return YES;
}
This line below runs but all it does is make the textfield inactive and
leaves the keyboard there. Then if you tap on the keys on keyboard then it
does nothing.
[self.passwordTextField resignFirstResponder];
This is not a duplicate question because the normal method is not working
for some reason.

Thursday, 22 August 2013

isolate l2tp vpn client traffic

isolate l2tp vpn client traffic

I have successfully set up an L2TP/IPSec server under Server 12.04 LTS,
following info from here with a few tweaks from here. I can connect on my
iPhone, get an internal address, and browse the internet as if I'm sitting
at my desk at home. One thing I'd like to do is isolate VPN traffic so
that VPN clients can't access anything else in my home network. (Yeah, it
sounds strange, but this is strictly for iOS devices only, and really only
for when I'm traveling and need my home IP address while on the internet.
I have other ways to get to my home computer or file shares.) The setup
is, my home network DHCP range is 192.168.1.0/24; the VPN range is
192.168.2.0/24. So in /etc/ipsec.conf I have the following, which, based
on the comments in the file, I thought should limit accessible subnets to
just what's on this line:
virtual_private=%v4:192.168.2.0/24
Additionally, in the [lns default] section of /etc/xl2tpd/xl2tpd.conf I
have the following:
ip range = 192.168.2.1-192.168.2.254
However when I connect with my phone, I can browse my Plex Media Manager,
which is located in my DHCP range. It's that kind of access I'm looking to
restrict.
In talking with some friends the first off-the-cuff idea was to use VLANs.
But the server is running as a virtual (vbox) on my desktop PC with one
NIC so I don't think I can use VLANs here.
The next-best suggestion was to put up some iptables rules to drop traffic
not going to 192.168.2.0/24 but I can't seem to get the rule(s) right -
I've been using -A OUTPUT ! -d 192.168.2.0/24 -j DROP but it seems like
there needs to be an exception to that rule and I confess my fluency in
iptables is kinda terrible. As soon as I enter that rule by itself, I can
no longer make a VPN connection.
I also experimented with using two NICs, one with a static IP of
192.168.2.1 and another with a static IP of 192.168.1.xxx, then change
over the conf files to use the .2.1 address; but even after changing the
confs and adjusting the port forwarding, I wasn't able to connect. On my
router, I did verify that the router itself had access to 192.168.2.1 and
that the router's subnet mask was 255.255.0.0. I could ping both NICs from
my laptop as well.
I'm kinda bumping into all the walls here. Can anyone give me some
pointers on how to isolate VPN traffic from the rest of my network
(basically internet only, no intranet), given a virtual installation
running in vbox with bridged networking?

What is the correct way to cast a std::unique_ptr to a std::unique_ptr to a superclass?

What is the correct way to cast a std::unique_ptr to a std::unique_ptr to
a superclass?

Suppose I have a class called foo which inherits from a class called bar.
I have a std::unique_ptr to an instance of foo and I want to pass it to a
function that only takes std::unique_ptr<bar>. How can I cast the pointer
so it works in my function?

Prevent user from coming back to log-in page after logging-in in an Android Application

Prevent user from coming back to log-in page after logging-in in an
Android Application

I am making an Application which has Log-in form, so what i need is to
make user enter His username and password only once means after entering
all details once there will be no need to re-enter details again else he
log-out.

PHP Get default printer via comand line in windows 7

PHP Get default printer via comand line in windows 7

i have a script go get defaul printer via cmd
cscript C:\Windows\System32\Printing_Admin_Scripts\en-US\prnmngr.vbs -g >
C:\xampp\htdocs\photo\printer.txt
and the result printer.txt is
Microsoft (R) Windows Script Host Version 5.8
Copyright (C) Microsoft Corporation. All rights reserved.
The default printer is Canon SELPHY CP780
but when i run and execute in php with this script
<?php
exec('C:\WINDOWS\system32\cmd.exe cscript
C:\Windows\System32\Printing_Admin_Scripts\en-US\prnmngr.vbs -g >
C:\xampp\htdocs\photo\printer.txt');
?>
the result is
Microsoft (R) Windows Script Host Version 5.8 Copyright (C) Microsoft
Corporation. All rights reserved.
where is the printer name? is there someting wrong with my code? is there
any solution?
php ver 5.4.4 and os win 7 64bit.

raycast a 3D pointcloud to an 2D image from a given viewpoint

raycast a 3D pointcloud to an 2D image from a given viewpoint

what i want to do is to raycast a pointcloud to an 2D image. What I have
is a 3D PointCloud and a Viewpoint which is different to the general world
coordinate system. I would like to do a raycasting from this Viewpoint to
generate a 2D image of the point cloud. So, i just need a method like
getintersectedvoxel which is doing the casting for the whole area and not
only for a single ray.

Binding to a property within a static class instance

Binding to a property within a static class instance

What I am trying to achieve
I have a WPF application (it's just for testing) and I want to bind the
text (Content) of a label to a property somewhere. The idea is that this
property value will be changed when the user chooses a different language.
When the property changes, I want the label text to update with the new
value.
What I have tried
I tried to create a static class with a static property for the label
value. For example:
public static class Language
{
public static string Name = "Name";
}
I then was able to bind this value to my label using XAML like so:
Content="{Binding Source={x:Static lang:Language.Name}}"
And this worked fine for showing the initial value of "Name". The problem
is, when the Name property changes the label value doesn't change.
So, back to the drawing board (Google). Then I found this answer which
sounded exactly like what I needed. So here was my new attempt at this:
public class Language
{
public static Language Instance { get; private set; }
static Language() { Instance = new Language(); }
private Language() { }
public string Name = "Name";
}
With my binding changed it this:
Content="{Binding Source={x:Static lang:Language.Instance}, Path=Name}"
The problem I have now though is that despite not having any compile
errors/warnings, the label is just blank, there appears to be no content
at all.
Questions
What am I missing with my latest attempt? Why is the label blank? Am I
going in completely the wrong direction trying to solve this problem?

Turn this code into a Task to run Asynchronously on another thread

Turn this code into a Task to run Asynchronously on another thread

I am starting to toy with Tasks and async await. So that I get a better
handle on how to convert my existing code, I thought I would try to try
changing a current method which is run synchronously:
private bool PutFile(FileStream source, string destRemoteFilename, bool
overwrite)
{
if (string.IsNullOrEmpty(destRemoteFilename)) return false;
string path = Path.GetDirectoryName(destRemoteFilename);
if (path == null) return false;
if (!Directory.Exists(path)) Directory.CreateDirectory(path);
if (overwrite)
{
if (File.Exists(destRemoteFilename)) //delete file if it exists,
because we are going to write a new one
File.Delete(destRemoteFilename);
}
else if (File.Exists(destRemoteFilename)) return false;
using (FileStream dest = File.OpenWrite(destRemoteFilename))
{
source.Seek(0, SeekOrigin.Begin);
source.CopyTo(dest);
}
return true;
}
I have tried to simply change the method to async, and dabbled with
Task<bool> but I'm obviously missing something here as neither of them
seem to work. I have experienced Type System.Threading.Task<bool> is not
awaitable.

Wednesday, 21 August 2013

Collection was modified; enumeration operation may not execute. VB.Net

Collection was modified; enumeration operation may not execute. VB.Net

There are a lot of questions that are a duplicate of this question, but
none of them seem to actually answer my specific problem.
I am writing an IRC bot, and i am adding users to a List(Of String) as you
can see in the below code. However, when i want to go through a foreach
loop of the users on another thread, i get the error in the title. I have
even put a boolean in place to stop it from adding users, yet it still
says it is being modified somehow. Any help would be greatly appreciated.
(Before you read the code, keep in mind i am new to VB.net, and even if it
messy, i'd prefer to not be bashed for it as i am new)
Sub Handler()
handlerActive = True
Dim list As New List(Of String)
query = "SELECT * FROM " & channel.Substring(1)
Try
connHost.Close()
Catch
End Try
connHost.Open()
Dim cmd As MySqlCommand = New MySqlCommand(query, connHost)
Dim dataReader As MySqlDataReader = cmd.ExecuteReader()
While (dataReader.Read())
list.Add(dataReader.GetString(1))
End While
dataReader.Close()
If (users.Count > 0) Then
For Each user2 In users
Try
connHost.Close()
Catch ex As Exception
End Try
connHost.Open()
query = ("UPDATE `" & channel.Substring(1) & "` SET `Amount` =
Amount + 1 WHERE `Username`='" & user2 & "'")
cmd = New MySqlCommand(query, connHost)
Try
cmd.ExecuteNonQuery()
Catch
Console.WriteLine("Failed to update user - " & user2)
End Try
Next
End If
connHost.Close()
handlerActive = False
End Sub
Below here is where i add users to my List called "users"
If (handlerActive = False And users.Contains(user) = False And
user.Trim().CompareTo("") <> 0 Or user.Trim().CompareTo("jtv") <> 0 Or
user.Trim().Contains(" ") = False Or user.Trim().Contains(".") = False)
Then
users.Add(user)
End If

Line input level, iMac. Mountain Lion - can I change sensitivity? (as opposed to setting the volume)

Line input level, iMac. Mountain Lion - can I change sensitivity? (as
opposed to setting the volume)

Connecting a standard stereo tape output to iMac line input socket,
setting input level in System Prefs > Sound > Input > Line In requires the
slider to be barely "off the stop" before the blue level meter hits hard
right. Can I lower the line input sensitivity somehow? There's no output
level control on the tape output.

UNION ALL and NOT IN together

UNION ALL and NOT IN together

I have 3 simple tables (Fname, Lname and Exceptions) with one column each
called Name. I want my end result to look like: (Everybody in Fname +
Everybody in LName) - (Everybody in Exceptions).
FName:
Name
A
B
LName:
Name
Y
Z
Exceptions:
Name
A
Z
Expected Query Result Set:
B
Y
Current SQL Query:
Select Name from Fname
UNION ALL
Select Name from Lname
WHERE Name NOT IN
(Select Name from Exceptions)
The SQL query only works on removing data which appears in LName but not
in Fname. Can somebody please help.

GCD on UITableView where NSURL is implemented

GCD on UITableView where NSURL is implemented

i been trying to implement a GCD on my project which shows the fetch data
from an XML, even though its my first time doing it i've
succesfully(maybe) implemented in on nameLabel and detailLabel which are
both string, but the imageLabel(commented part of the code) doesn't give
anything when i try to implement the same GCD as both strings, i dont know
whats happening but when i run the project it gives an unknown exception,
i would like to know if how to implement a GCD on the commented part of
the code so i will be able to show the image in the imageView.
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = @"CustomCell";
dataFileHolder *currentData = [[xmlParser listPopulated]
objectAtIndex:indexPath.row];
CustomCellXMLClass *cell = [tableView
dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil) {
cell = [[CustomCellXMLClass
alloc]initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:@"cell"];
NSArray *nib = [[NSBundle mainBundle]
loadNibNamed:@"CustomCellXMLSample" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
myQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(myQueue, ^{
NSString *nameLabel = [currentData nameOfCat];
NSString *dataToCacheLabel = [myCache objectForKey:nameLabel];
if(nameLabel != nil){
dataToCacheLabel = [NSString stringWithString:nameLabel];
if (dataToCacheLabel != nil) {
[myCache setObject:dataToCacheLabel forKey:nameLabel];
dispatch_async(dispatch_get_main_queue(), ^{
[cell.nameLabel setText:dataToCacheLabel];
});
}
}
NSString *detailLabel = [currentData descriptionOfCat];
NSString *stringToCache = [myCache objectForKey:detailLabel];
if (detailLabel != nil) {
stringToCache = [NSString stringWithString:detailLabel];
if (stringToCache != nil) {
[myCache setObject:stringToCache forKey:detailLabel];
dispatch_async(dispatch_get_main_queue(), ^{
[cell.detailLabel setText:stringToCache];
});
}
}
// NSString *imageURL = [currentData imageLink];
// NSData *dataToCache;
// if (imageURL != nil) {
//
// dataToCache = [NSData dataWithContentsOfURL:[NSURL
URLWithString:imageURL]];
// if (dataToCache != nil) {
//
// [myCache setObject:dataToCache forKey:imageURL];
// [cell.imageShow setImage:[UIImage
imageWithData:dataToCache]];
//
// }
// else {
//
// NSURL *imageURL = [NSURL
URLWithString:@"http://i178.photobucket.com/albums/w255/ace003_album/190579604m.jpg"];
// dataToCache = [NSData dataWithContentsOfURL:imageURL];
// [myCache setObject:dataToCache forKey:imageURL];
// [cell.imageShow setImage:[UIImage
imageWithData:dataToCache]];
// }
//
// }
[self.activityIndicator
performSelectorOnMainThread:@selector(stopAnimating)
withObject:nil waitUntilDone:YES];
});
return cell;
}

Find the value of $a^2b$ .

Find the value of $a^2b$ .

If a variable tangent to the curve $x^2y = c^3$ makes intercepts $a$ and
$b$ on the $x$ and $y$ axis respectively then find the value of $a^2b$.
The answer is $\frac{27}{4}c^3$ but how? Please show the solution steps.

Multiple Clients in Client Server app in C#

Multiple Clients in Client Server app in C#

using resources at http://www.developerfusion.com i came up with the
following server code. It works well for single client. How can i make it
for multiple clients. I tried adding array and different instances of the
beiginreceive but was unable to. The server code:
class Program
{
public static AsyncCallback pfnWorkerCallBack;
public static Socket m_socListener;
public static Socket m_socWorker;
static void Main(string[] args)
{
try
{
//create the listening socket...
m_socListener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, 8221);
//bind to local IP Address...
m_socListener.Bind(ipLocal);
Console.WriteLine("UCManager Started");
//start listening...
m_socListener.Listen(4);
// create the call back for any client connections...
m_socListener.BeginAccept(new AsyncCallback(OnClientConnect),
null);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
public static void OnClientConnect(IAsyncResult asyn)
{
try
{
m_socWorker = m_socListener.EndAccept(asyn);
WaitForData(m_socWorker);
}
catch (Exception se)
{
Console.WriteLine(se.Message);
}
}
public class CSocketPacket
{
public System.Net.Sockets.Socket thisSocket;
public byte[] dataBuffer = new byte[1];
}
public static void WaitForData(System.Net.Sockets.Socket soc)
{
try
{
if (pfnWorkerCallBack == null)
{
pfnWorkerCallBack = new AsyncCallback(OnDataReceived);
}
CSocketPacket theSocPkt = new CSocketPacket();
theSocPkt.thisSocket = soc;
// now start to listen for any data...
soc.BeginReceive(theSocPkt.dataBuffer, 0,
theSocPkt.dataBuffer.Length, SocketFlags.None,
pfnWorkerCallBack, theSocPkt);
}
catch (SocketException se)
{
Console.WriteLine(se.Message);
}
}
public static void OnDataReceived(IAsyncResult asyn)
{
try
{
CSocketPacket theSockId = (CSocketPacket)asyn.AsyncState;
//end receive...
int iRx = 0;
iRx = theSockId.thisSocket.EndReceive(asyn);
char[] chars = new char[iRx + 1];
Decoder d = Encoding.UTF8.GetDecoder();
int charLen = d.GetChars(theSockId.dataBuffer, 0, iRx, chars, 0);
String szData = new String(chars);
Console.WriteLine(szData);
int code = Convert.ToInt32(szData);
WaitForData(m_socWorker);
}
catch (Exception se)
{
Console.WriteLine(se.Message);
}
}
}
}

Tuesday, 20 August 2013

delay in pinging www.google.com but faster with its actual ip

delay in pinging www.google.com but faster with its actual ip

When I try pinging www.google.com, its dead slow. It takes 4-8 seconds for
the first packet to be sent. But when i ping its actual ip its really
fast. I feel it has something to do with the dns. Can anyone help me how
to resolve this issue?
PING www.google.com (173.194.126.49) 56(84) bytes of data.
64 bytes from 173.194.126.49: icmp_req=1 ttl=63 time=2.34 ms
64 bytes from 173.194.126.49: icmp_req=2 ttl=63 time=2.76 ms
64 bytes from 173.194.126.49: icmp_req=3 ttl=63 time=2.50 ms
64 bytes from 173.194.126.49: icmp_req=4 ttl=63 time=3.00 ms
64 bytes from 173.194.126.49: icmp_req=5 ttl=63 time=2.82 ms
64 bytes from 173.194.126.49: icmp_req=6 ttl=63 time=3.34 ms
64 bytes from 173.194.126.49: icmp_req=7 ttl=63 time=3.02 ms
8 packets transmitted, 8 received, 0% packet loss, time 99656ms
While pinging the actual ip
PING 173.194.126.49 (173.194.126.49) 56(84) bytes of data.
64 bytes from 173.194.126.49: icmp_req=1 ttl=63 time=2.75 ms
64 bytes from 173.194.126.49: icmp_req=2 ttl=63 time=3.38 ms
64 bytes from 173.194.126.49: icmp_req=3 ttl=63 time=4.45 ms
64 bytes from 173.194.126.49: icmp_req=4 ttl=63 time=4.91 ms
64 bytes from 173.194.126.49: icmp_req=5 ttl=63 time=4.21 ms
64 bytes from 173.194.126.49: icmp_req=6 ttl=63 time=3.89 ms
64 bytes from 173.194.126.49: icmp_req=7 ttl=63 time=2.98 ms
64 bytes from 173.194.126.49: icmp_req=8 ttl=63 time=3.90 ms
--- 173.194.126.49 ping statistics ---
8 packets transmitted, 8 received, 0% packet loss, time 7011ms

Elegant way to code drag and drop

Elegant way to code drag and drop

I have a game in which I want all the windows and the items in the
inventory window to be drag and droppable. However the event handling is
event driven. I have it working to a point, but it's getting convoluted
fast. I was trying to find information on coding guis bottom up in a
canvas, or at least a less convoluted way to do window input (such as drag
and drop), but I can't figure out how to Google these things efficiently.
This is in java by the way.

How do I resolve the dependencies when building git plugin for Jenkins?

How do I resolve the dependencies when building git plugin for Jenkins?

I am trying to build and install the git plugin for Jenkins.
Unfortunately, there aren't any instructions and I am new to Jenkins and
Maven.
I have found these instructions but when I get to this step mvn install it
fails on some dependencies. I've attempted many different ways to make
Maven find the jars it's looking for, but without success. Here are the
key output lines indicating the missing libraries:
Running InjectedTest
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.369 sec
<<< FAILURE!
initializationError(InjectedTest) Time elapsed: 0.017 sec <<< ERROR!
java.lang.UnsatisfiedLinkError: com.sun.jna.Native.open(Ljava/lang/String;)J
...
Running hudson.plugins.git.RevisionParameterActionTest
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.012 sec
<<< FAILURE!
init ializationError(hudson.plugins.git.RevisionParameterActionTest) Time
elapsed: 0 sec <<< ERROR!
java.lang.NoClassDefFoundError: org.jvnet.hudson.test.HudsonTestCase

Faralda isn't at her post to allow me entrance to the College of Winterhold

Faralda isn't at her post to allow me entrance to the College of Winterhold

When I was attempting to get into the College of Winterhold, a dragon
appeared while I was talking with her. She went to fight it, and ever
since then, she hasn't been at the front entrance of the college.
I'm on a mission where I have to get inside of the college grounds and
can't get in. How can I get her to man her post again?

Help with definitions

Help with definitions

I need the definitions of 2 following things:
What is a characteristic function of the unit disc in $\mathbb{R}^{2}$?
What is a distribution is obtained by integrating a function over the unit
sphere?
Thanks a lot!

Styling an android activty with html?

Styling an android activty with html?

I am trying to add a "help" screen to my application. I inserted all of my
text in, but I can't make it look how I want. Is it possible to use html
to style and organise my text?

Monday, 19 August 2013

Need help in protocol buffer in client server using java

Need help in protocol buffer in client server using java

I am new to google protocol buffer . I am writing a client server
application where client send request object to server and server return
response. Currently when i send object to server neither the server
respond nor throw any exception. Probably it stuck on line
Request request = Request.parseFrom(bytes);
where Request and Response are my message classes generated by protocol
buffer.
My code samples are as follows
public class TCPServer {
final static Logger logger = Logger.getLogger(TCPServer.class.getName());
static int PORT = 6789;
public static void main(String argv[]) throws Exception
{
ServerSocket socket = new ServerSocket(PORT);
Socket connectionSocket = null;
while(true)
{
try{
connectionSocket = socket.accept();
}catch (IOException e) {
System.out.println("Could not listen on port:" + PORT);
System.exit(-1);
}
Thread thread = new Thread(new
ServerConnection(connectionSocket));
thread.start();
}
}
}
public class ServerConnection implements Runnable{
static final Logger logger =
Logger.getLogger(ServerConnection.class.getName());
String clientInput;
String serverOutput = null;
Socket connectionSocket = null;
ServerConnection(Socket connectionSocket){
this.connectionSocket = connectionSocket;
}
public void run() {
try {
InputStream input = connectionSocket.getInputStream();
ObjectInputStream inFromClient = new ObjectInputStream(input);
ObjectOutputStream outToClient = new
ObjectOutputStream(connectionSocket.getOutputStream());
serveRequest(inFromClient , outToClient);
outToClient.flush();
} catch (IOException ex) {
logger.log(Level.SEVERE, null, ex);
System.out.println("Exception occured in ServerConnection
run() method");
}
}
public void serveRequest(InputStream inFromClient, OutputStream outToClient){
try {
System.out.println("Recieving data from client");
ResponseReciever response = new ResponseReciever();
ObjectInputStream input = (ObjectInputStream) inFromClient;
byte size = input.readByte();
byte []bytes = new byte[size];
input.readFully(bytes);
Request request = Request.parseFrom(bytes);
System.out.println("Request recieved");
response.createResponse(request.getId(),request.getMessage(),true).writeTo(outToClient);
System.out.println("Response send");
} catch (Exception ex) {
logger.log(Level.SEVERE, null, ex);
System.out.println("Exception occured in ServerConnection
serverRequest() method");
}
}
And my client look like this
public class TCPClient {
final static Logger logger = Logger.getLogger(TCPClient.class.getName());
private static int PORT = 6789;
private static String HOST_NAME = "localhost";
private static boolean isOpen = true;
private Socket openConnection(final String hostName,final int port){
Socket clientSocket = null;
try {
clientSocket = new Socket(HOST_NAME, PORT);
} catch (IOException e) {
logger.log(Level.SEVERE, "Exception occured while connecting to
server", e);
}
return clientSocket;
}
private void closeConnection(Socket clientSocket){
try {
logger.log(Level.INFO, "Closing the connection");
clientSocket.close();
isOpen = false;
} catch (IOException e) {
logger.log(Level.SEVERE, "Exception occured while closing the
connection", e);
}
}
public void sendToServer(OutputStream output){
try {
System.out.println("Sending data to server");
RequestSender requestSender = new RequestSender();
Request request =
requestSender.getRequest(1,"param1","param2",23L,"Its
message",true);
ObjectOutputStream outputStream = (ObjectOutputStream)output;
request.writeTo(outputStream);
} catch (IOException ex) {
logger.log(Level.SEVERE, null, ex);
}
}
public void recieveFromServer(InputStream input){
try {
System.out.println("Recieving data from server");
Response response = Response.parseFrom(input);
System.out.println(response.getId());
System.out.println(response.getResponse());
System.out.println(response.getError());
} catch (IOException ex) {
logger.log(Level.SEVERE, null, ex);
}
}
public static void main(String argv[]) throws Exception
{
ObjectOutputStream outToServer = null;
InputStream inFromServer = null;
TCPClient client = new TCPClient();
try {
while(isOpen)
{
Socket clientSocket = client.openConnection(HOST_NAME, PORT);
outToServer = new ObjectOutputStream(clientSocket.getOutputStream());
inFromServer = new ObjectInputStream(clientSocket.getInputStream());
client.sendToServer(outToServer);
client.recieveFromServer(inFromServer);
}
}catch (Exception e) {
logger.log(Level.SEVERE, "Exception occured ", e);
System.out.println("Exception occured in TCPClient main() method");
System.exit(1);
}
}
}
I am unable to find what is wrong in the code. Please let me know if you
find something missing.