Monday, 30 September 2013

DNS Server, DHCP Client and Server works fine, but request time out occurs when using MikroTik as an access point for a modem

DNS Server, DHCP Client and Server works fine, but request time out occurs
when using MikroTik as an access point for a modem

I use 2 Mikrotik wireless router, the first one is connected to modem and
it works perfectly (SSID: server-one (hidden)).
Second router ID:
ether1: 192.168.1.1
wlan1: dhcp-client
wlan2: 192.168.2.1
SSID: skywifi
Then, i tried to configure the second router. I set wlan1 to connect to
server-one, as a station and dhcp client and received 192.168.50.124 as
its IP, 192.168.50.254 as its gateway.
I set wlan2 as an ap-bridge, and set it as dhcp server. Then I create a
static route to 0.0.0.0/0 through 192.168.50.254.
Connection OK, DNS to device connecting skywifi works perfectly, i can
nslookup google.com. The problem is, when i tried to ping google.com, it
always give request time out reply. (Note that I also tried to ping
another host too (Wikipedia,Yahoo, etc). The result is also request time
out.
Any idea why this things happened? Thanks,

Intertext like command in enumerate environment=?iso-8859-1?Q?=3F_=96_tex.stackexchange.com?=

Intertext like command in enumerate environment? – tex.stackexchange.com

I would like to insert some explanatory text between two items of a
numbered list. Is there a command that can do this in the same way as the
\intertext command in an align environment?

Fire a javascript function after jquery autosuggest selection made

Fire a javascript function after jquery autosuggest selection made

I have the jQuery autosuggest working. What i'd like to do though is after
the data is selected from the autosuggest, to be able to fire off a
javascript function. So the user selects the name John Smith and some
other info gets populated with ajax. I have the ajax working, I have the
autosuggest working but can't figure out how to get the autosuggest to
fire off the ajax.
I've tried putting a call in the select portion of the autosuggest.. that
didn't work. was almost as if it was getting ignored. Anyway.. I've looked
around and can't find the answer.
thanks for any help shannon

How to log the CPU and network utilization for Android

How to log the CPU and network utilization for Android

I want to get the CPU utilization over time and turn the records into plot
diagrams. I have surveyed some method for instant utilization, like shell
command top, dumpsys, and APPs TaskSpy.
Usage: top [ -m max_procs ] [ -n iterations ] [ -d delay ] [ -s
sort_column ] [ -t ] [ -h ]
-m num Maximum number of processes to display.
-n num Updates to show before exiting.
-d num Seconds to wait between updates.
-s col Column to sort by (cpu,vss,rss,thr).
-t Show threads instead of processes.
-h Display this help screen.
dumpsys
I want to customize the chart like TaskSpy and add some details to
analysis. It will be better to analysis on PC/MAC. Can I do these by adb
shell command?

Sunday, 29 September 2013

How to check out code from local git directory

How to check out code from local git directory

I downloaded a source code package. It is nearly 3GB. But it is a empty
directory and just contains a .git directory. How can I check out code
from it?

A call to PInvoke function has unbalanced the stack

A call to PInvoke function has unbalanced the stack

Making a function call to .NET 4 to native code is resulting in the
following exception:
A call to PInvoke function has unbalanced the stack. This is likely
because the managed PInvoke signature does not match the unmanaged target
signature. Check that the calling convention and parameters of the PInvoke
signature match the target unmanaged signature.
Here is my definition in Native Code:
typedef void ( CALLBACK* CB_DOWNLOADING )
(
ULONG, // secs elapsed
LPARAM, // custom callback param
LPBOOL // abort?
);
FETCH_API HttpFetchW
(
LPCWSTR url,
IStream** retval,
LPCWSTR usrname = NULL,
LPCWSTR pwd = NULL,
BOOL unzip = TRUE,
CB_DOWNLOADING cb = NULL,
LPARAM cb_param = 0,
LPWSTR ctype = NULL,
ULONG ctypelen = 0
);
Here is the .NET counterpart:
[DllImport(dllPath, CharSet = CharSet.Unicode, SetLastError = true,
CallingConvention = CallingConvention.Cdecl)]
internal static extern FETCH HttpFetchW
(
[MarshalAs(UnmanagedType.LPWStr)]
string url,
out System.Runtime.InteropServices.ComTypes.IStream retval,
[MarshalAs(UnmanagedType.LPWStr)]
string usrname,
[MarshalAs(UnmanagedType.LPWStr)]
string pwd,
bool unzip,
dlgDownloadingCB cb,
IntPtr cb_param,
[MarshalAs(UnmanagedType.LPWStr)]
string ctype,
ulong ctypelen
);
Where FETCH is an enum.
[UnmanagedFunctionPointerAttribute(CallingConvention.Cdecl)]
internal delegate void dlgDownloadingCB(ulong elapsedSec, IntPtr
lParam, bool abort);
internal static void DownloadingCB(ulong elapsedSec, IntPtr lParam, bool
abort)
{
// Console.WriteLine("elapsedSec = " + elapsedSec.ToString());
}
Can anyone suggest an alternative within the .NET 4?
Thank you very much for your help.

How to implement double indexing in a 2D sparse scipy matrix?

How to implement double indexing in a 2D sparse scipy matrix?

Suppose I have a 2D sparse matrix M representing the results of 2-on-2
basketball matches. I want to use address the elements of the matrix using
double-indexing : Element M[i,j][k,l] will represent the score of the game
played by a team of players i and j against team k and l. Thus, each
column/row is specified by two numbers instead of one. Note that this is
not a 4D matrix. I'm looking for a way to do this with a sparse SciPy
matrix in order to be able to perform various matrix-related calculations
(eigenvalues/vectors, etc).

converting [RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA] to [RRRRRGGGGGBBBBBA]

converting [RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA] to [RRRRRGGGGGBBBBBA]

I am writing an ImageEncoder that writes a TGA image. I have been able to
successfully write the TGA file, but instead of ending up with
[RRRRRGGGGGBBBBBA] I get [RGBBBBBA] here is the relevant code:
int lastRow = minY + height;
for (int row = minY; row < lastRow; row += 8) {
int rows = Math.min(8, lastRow - row);
int size = rows * width * numBands;
// Grab the pixels
Raster src = im.getData(new Rectangle(minX, row, width, rows));
src.getPixels(minX, row, width, rows, pixels);
for (int i = 0; i < size; i++) {
//output.write(pixels[i] & 0xFF);
short o = (short) pixels[i];
byte[] reo = new byte[2];
reo[0] = (byte) (o & 0xff);
reo[1] = (byte) ((o >> 8) & 0xff);
output.write(reo);
}
}

Saturday, 28 September 2013

convergence with a bounded sequence and a sequence that tends to zero

convergence with a bounded sequence and a sequence that tends to zero

how to prove that if $\sum k_n$ converges absolutely and $Lim_{n \to
+\infty}c_n = 0$ (where $c_n$ is a sequence) then $ \sum k_n c_n$
converges absolutely

Send recurring email based on date using PHP

Send recurring email based on date using PHP

I am not sure where to begin setting up an automatic recurring email
reminder app. I currently have a form that inserts data into a msyql
database.
<form method="post" action="save.php">
<p>
<label for="name">Full Name</label><br />
<input type="text" name="name" data-h5-errorid="error-name" required />
<span id="error-name" class="error">Please enter a full name</span>
</p>
<p>
<label for="address">Address (Street Address Only)</label><br />
<input type="text" name="address" data-h5-errorid="error-address"
required />
<span id="error-address" class="error">Please enter an address</span>
</p>
<p>
<label for="email">Email</label><br />
<input type="email" name="email" data-h5-errorid="error-email"
required />
<span id="error-email" class="error">Please enter a valid email
address</span>
</p>
<p>
<label for="date">Date of Service</label><br />
<input id="date" type="text" data-h5-errorid="error-service"
name="date" required />
<span id="error-service" class="error">Please choose a date</span>
</p>
<p>
<label for="reminder">Reminder</label><br />
<select name="reminder">
<option value="1">30 Days</option>
<option value="2">60 Days</option>
<option value="3">Semiannual</option>
<option value="4">Annual</option>
</select>
</p>
<p>
<label for="notes">Notes on Service</label><br />
<textarea name="notes" rows="15"></textarea>
</p>
<p>
<input type="submit" value="Submit" />
</p>
</form>
I am storing all fields in the database and have that working properly
using http://medoo.in/. How do I go about creating a PHP script to send a
recurring email based on the Service Date and the selected Reminder (every
30 days, 60 days, semianually, annually)? I was thinking of using PHP
mailer to send the actual emails and running a daily cron job.

Round a Value after While Loop in PHP

Round a Value after While Loop in PHP

Hey with the following code I am trying to round the variable $CelNum, and
since I am new to PHP I am unsure of how to do it correctly if you could
help me I would appreciate it.
<head>
<title>Temp Conversion</title>
<meta http-equiv="content-type" content="text/html;
charset=iso-8859-1" />
</head>
<body>
<?
$FarNum = 0;
$CelNum = 0;
while ($FarNum <= 100)
{
$CelNum = ($FarNum - 32)*5/9;
echo "<p>$FarNum = $CelNum</p>";
$FarNum++;
}

TreeView binding from XML by ID

TreeView binding from XML by ID

I'm using WPF.(MVVM pattern) I want to make hierarchical tree using
TreeView. Data from XML. But XML structure is not hierarchical actually.
Nodes binds by ID. XML looks like the following:
<root>
<node>
<Id>1</Id>
<ParentId>-1</ParentId>
<Name>ROOT</Name>
</node>
<node>
<Id>2</Id>
<ParentId>1</ParentId>
<Name>NODE</Name>
</node>
</root>
What should i use to do this? It will be great if you show me any simple
example.
And the second question. How can i get nodes dinamically? That is when i
run the application only root is loading.
Thanks in advance.

Friday, 27 September 2013

Use Python's `timeit` from a program but functioning the same way as the command line?

Use Python's `timeit` from a program but functioning the same way as the
command line?

For instance, documentation says:
Note however that timeit will automatically determine the number of
repetitions only when the command-line interface is used.
Is there a way to call it from within a Python script and have the number
of repetitions be determined automatically, with only the shortest number
returned?

jacob - Could not initialize class com.jacob.com.ComThread

jacob - Could not initialize class com.jacob.com.ComThread

I have jacob.jar in my class path and the jar also contains
ComThread.class but when I run the application I am getting the following
exception. Any idea how to resolve this?
java.lang.NoClassDefFoundError: Could not initialize class
com.jacob.com.ComThread
at
org.apache.jsp.WEB_002dINF.view.perc.jemrreport_jsp._jspService(jemrreport_jsp.java:226)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at
org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:749)
at
org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:487)
at
org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:412)
at
org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:339)
at
org.apache.struts2.dispatcher.ServletDispatcherResult.doExecute(ServletDispatcherResult.java:159)

Using column name when using SqlDataReader.IsDBNull

Using column name when using SqlDataReader.IsDBNull

Hello I have got this code which reads data from SQL DB.
I don't know how should I edit it so I can use original column name and
not column index.
string query = "SELECT * FROM zajezd WHERE event='" +
thisrow+ "' AND year='" + klientClass.Year() + "'";
SqlCommand cmd= new SqlCommand(query, spojeni);
spojeni.Open();
SqlDataReader read= cmd.ExecuteReader();
if (read.Read())
{
maskedTextBox2.Text = read.IsDBNull(24) ? string.Empty :
read.GetDateTime(24).ToString("MM/dd/yyyy");
Thanks in advance.

PHP & SQL - get results from db where date is today

PHP & SQL - get results from db where date is today

i'm trying to do the following thing: In my Database, I have rows with
time in each one (using time() function). For example: 1380300397. Now,
I'd like to build a query that gets the rows from the current day. I've
tried this query with no success:
SELECT `id`,DATE_FORMAT(`time`, '%Y-%m-%d') FROM `facts`
WHERE `app` = 1 AND DATE(`time`) = CURDATE()
What am I doing wrong? Thanks!

Data Source SQL Command from Variable using default value instead of updated value

Data Source SQL Command from Variable using default value instead of
updated value

I have four dynamically assigned variables in my package. Each one is
populated using a query similar to this:
select 'SELECT * FROM SHARE_DM.MDM_ORG_CLASSIFICATIONS WHERE LAST_UPD_DATE
>= '''
+ (select convert(nvarchar(50), coalesce(max(last_upd_date),
cast('1/1/1900' as datetime)), 106) from MDM_ORG_CLASSIFICATIONS)
+ '''' sql
The default queries are defined like this:
SELECT * FROM SHARE_DM.MDM_ORG_CLASSIFICATIONS WHERE LAST_UPD_DATE >= '01
Jan 1900'
(I'm building the sql like this because I'm using Oracle data connections
and the parameter parsing doesn't work properly, where this technique has
worked before)
The output sql comes out like this:
SELECT * FROM SHARE_DM.MDM_ORG_CLASSIFICATIONS WHERE LAST_UPD_DATE >= '26
Sep 2013'
I have validated that my variables are being updated using message boxes
in script components. When I run the queries manually against Oracle, I
get very small result sets, as expected. However, when I run the package,
I get full result sets as if the default value of 1/1/1900 was being used
instead of the updated variable.
Each variable is set to EvaluateAsExpression False.
Comparing the operation in this package vs. a different package where I do
the same kind of operation, I'm not seeing any obvious differences -
except for one thing - in the other package I list each column in the
select statement, whereas in here I use select *.
Why isn't my OLE DB Source updating with the updated SQL from the variable?
Edit: Thinking maybe the select * was the issue, I updated one of them to
use explicit column names. No change.

java.lang.IllegalStateException: System services not available to Activities before onCreate() with ArrayAdapter

java.lang.IllegalStateException: System services not available to
Activities before onCreate() with ArrayAdapter

I am trying to run a ListActivity, which takes an array of filenames,
which are to be inserted into the database. This is done by insert() in
the following code. I am getting IllegalStateException at
ArrayAdapter<String>. If I am calling the insert() function from another
class. So, I am unable to define ArrayAdapter in the onCreate() method.
Please see the following code, which is defining insert() method -
public class FileEvent extends ListActivity implements ObserverActivity{
public static final String PREFS_NAME = "MyPreferencesFile";
public String filename;
public String path;
MyFileObserver myFileObserver;
public adapter info = new adapter(this);
ArrayAdapter<String> adapter;
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
listView = (ListView) findViewById(android.R.id.list);
setContentView(R.layout.fileeventlist);
Bundle bundle = getIntent().getExtras();
myFileObserver = new
MyFileObserver("/storage/sdcard/DCIM/SAMPLE_IMAGES/");
myFileObserver.registerObserver(this);
myFileObserver.startWatching();
/* String var_from_prev_intent = bundle.getString("path");
insert(var_from_prev_intent);
SharedPreferences settings = getSharedPreferences (PREFS_NAME,0);
String newpath = "";
this.path = settings.getString("name",newpath);
Log.v("New path in FileEvent : ",this.path);*/
}
protected void onPause(){
myFileObserver.stopWatching();
myFileObserver.unregisterObserver(this);
}
protected void onResume(){
myFileObserver.registerObserver(this);
myFileObserver.startWatching();
}
public void insert(String path) {
// TODO Auto-generated method stub
//try{
Log.v("FileName to insert : ",path);
Log.v("a3","a3");
this.filename = path;
Log.v("a4","a4");
int rowcount = info.getrowcountofpersons();
Log.v("a5","a5");
Log.v("rowcount in new list onCreate: ",
""+info.getrowcountofpersons()+"");
Log.v("a6","a6");
String[] values = new String[rowcount];
Log.v("a7","a7");
for(int i =1;i<=rowcount;i++)
{
values[i-1]=info.getPersonList(i);
//Toast.makeText(getApplicationContext(), values[i-1],
Toast.LENGTH_LONG).show();
System.out.println("in for loop now"+values[i-1]);
}
Log.v("a8","a8");
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, values);
Log.v("a9","a9");
Log.v("a10","a10");
listView.setItemsCanFocus(false);
Log.v("a11","a11");
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
Log.v("a12","a12");
// Assign adapter to List
setListAdapter(adapter);
// new Bullet(info).execute((Void)null);
Log.v("a13","a13");
/*}
catch (Exception e)
{
Log.v("Error in insert() definition FileEvent.java :
",e.toString());
}*/
}
protected void onListItemClick(ListView l, View v, int position, long id) {
// try{
Log.v("a14","a14");
super.onListItemClick(l, v, position, id);
Log.v("a15","a15");
// ListView Clicked item index
int itemPosition = position;
Log.v("a16","a16");
// ListView Clicked item value
String itemValue = (String) l.getItemAtPosition(position);
Log.v("a17","a17");
// content.setText("Click : \n Position :"+itemPosition+" \n
ListItem : " +itemValue);
String personname = itemValue;
Log.v("a18","a18");
try
{
System.out.println("paths in FileEvent : "+filename);
info.insert(filename,personname);
Log.v("a19","a19");
}
catch(Exception e)
{
Log.v("a20","a20");
e.printStackTrace();
Log.v("a21","a21");
}
Log.v("a22","a22");
/* }
catch (Exception e)
{
Log.v("Error in insert() definition FileEvent.java :
",e.toString());
}
*/
}
And the following logcat I am getting, when I run the code -
09-27 06:37:23.269: A/FileObserver(2284): Unhandled exception in
FileObserver com.example.sample_fileobserver.MyFileObserver@b11955a0
09-27 06:37:23.269: A/FileObserver(2284): java.lang.IllegalStateException:
System services not available to Activities before onCreate()
09-27 06:37:23.269: A/FileObserver(2284): at
android.app.Activity.getSystemService(Activity.java:4492)
09-27 06:37:23.269: A/FileObserver(2284): at
android.widget.ArrayAdapter.init(ArrayAdapter.java:310)
09-27 06:37:23.269: A/FileObserver(2284): at
android.widget.ArrayAdapter.<init>(ArrayAdapter.java:128)
09-27 06:37:23.269: A/FileObserver(2284): at
com.example.sample_fileobserver.FileEvent.insert(FileEvent.java:76)
09-27 06:37:23.269: A/FileObserver(2284): at
com.example.sample_fileobserver.MyFileObserver.onEvent(MyFileObserver.java:59)
09-27 06:37:23.269: A/FileObserver(2284): at
android.os.FileObserver$ObserverThread.onEvent(FileObserver.java:125)
09-27 06:37:23.269: A/FileObserver(2284): at
android.os.FileObserver$ObserverThread.observe(Native Method)
09-27 06:37:23.269: A/FileObserver(2284): at
android.os.FileObserver$ObserverThread.run(FileObserver.java:88)
Please tell me where I made mistake.
Thanks in advance.

Thursday, 26 September 2013

how can I check which submit button was pressed?

how can I check which submit button was pressed?

I have a two submit buttons set up for form submission. I'd like to know
which submit button was clicked without applying a .click() event to each
one. One more thing I am using ASP.NET MVC 3 and want to get the clicked
button name in Controller.
Here's the setup:
<a class="anchorbutton">
<input type="submit" value="Save" id="Save" class="hrbutton"/>
</a>
<input type="submit" value="Save & Next" id="SaveNext" class="hrbutton
anchorbutton"/>
$('#form').live('submit', function (e)
{
e.preventDefault();
var form = $('#form');
$.ajax({
cache: false,
async: true,
type: "POST",
url: form.attr('action'),
data: form.serialize(),
success: function (data) {
$.ajax({
url: 'url',
dataType: "html",
success: function (data) {
$("#div").html(data);
}
});
}
});
return false;
});
[HttpPost]
public JsonResult Post(FormCollection form, string submitButton)
{
}

Wednesday, 25 September 2013

In angularjs ng-change="chk(query)" call function when space is hit after typing word

In angularjs ng-change="chk(query)" call function when space is hit after
typing word

I am using following code to take input from user and search the term
the problem is that if I press any word function gets called but when I
press spacebar it is not calling the function so I want if user enters
space then also the function should get called
<input ng-model="query" ng-change="chk(query)" placeholder="Search..">
so please can anyone suggest me with the solution please
Thank you
I tried to use ng-trim="false" but not working

Thursday, 19 September 2013

Calling C++ method in QML Error "Cannot Call Method 'x' of null"

Calling C++ method in QML Error "Cannot Call Method 'x' of null"

I'm having some difficuly calling a method from a C++ class in QML. I keep
getting a "Cannot call method 'x' of null" error. Here is my code:
QML:
import QtQuick 2.0
import QtQuick.Controls 1.0
import QtQuick.Window 2.0
import Jane 1.0
ApplicationWindow
{
property MainWindowModel m_Model
...
Button {
id: m_PluralizeButton
text: "Pluralize"
anchors.left: parent.left
anchors.leftMargin: 10
anchors.top: m_OutputRow.bottom
anchors.topMargin: 10
onClicked: m_OutputText.text = m_Model.getPluralization();
}
}
MainWindowModel.h
class MainWindowModel : public QObject
{
Q_OBJECT
public:
MainWindowModel();
~MainWindowModel() {}
Q_INVOKABLE QString getPluralization() const;
private:
};
MainWindoModel.cpp
MainWindowModel::MainWindowModel() :
QObject()
{
}
QString MainWindowModel::getPluralization() const
{
return "Test";
}
Main.cpp
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
// Need to register types prior to loading the file.
qmlRegisterType<MainWindowModel>("Jane", 1, 0, "MainWindowModel");
QQmlApplicationEngine engine(QUrl("qrc:/root/QML/MainWindowView.qml"));
QObject* topLevel = engine.rootObjects().value(0);
QQuickWindow* win = qobject_cast<QQuickWindow*>(topLevel);
if (!win)
{
qWarning("Error: not a valid window.");
return -1;
}
win->show();
return a.exec();
}
Any help will be appreciated, thanks.

keep the first part and delete the rest on a specified line using sed

keep the first part and delete the rest on a specified line using sed

I know a line number in a file, wherein I want to keep the first word and
delete the rest till the end of the line. How do I do this using sed ? So
lets say, I want to go to line no 10 in a file, which looks like this -
goodword "blah blah"\
and what i want is
goodword
I have tried this - sed 's/([a-z])./\1/'
But this does it on all the lines in a file. I want it only on one
specified line.

"This version of JustMock has expired!" after purchasing a license

"This version of JustMock has expired!" after purchasing a license

I recently purchased a license for Telerik JustMock. The Telerik Control
Panel shows JustMock under my list of Purchased products. When I attempt
to run my tests in Visual Studio's Test Explorer with the JustMock Visual
Studio extension enabled I receive an exception saying:
Telerik.JustMockExpiredException : This version of JustMock has expired!
I have uninstalled all the Telerik Visual Studio extensions, uninstalled
everything Telerik via Windows Programs/Features, then re-installed the
control panel and then JustMock yet the problem persists. Of note, when I
re-installed the control panel it remembered my username/password so I'm
guessing there is a configuration file somewhere caching my information
incorrectly.
A possible root cause of this problem is that I was trialing JustMock
under my personal email address but it was purchased by my company and
assigned to my work email address. I am currently logging into the control
panel with my work address and see no other place to change that.

NullPointerException when trying to send a message to a Client Socket

NullPointerException when trying to send a message to a Client Socket

I have a ServerHandler class, which creates a new PrintWriter and stores
it into a PrintWriter array, The message gets sent by giving the
selectedId integer the ID number of the client that should receive the
message. When i call the SendMessage() method inside the ServerHandler
class it sends the message without a problem, but when i try to call the
SendMessage("some message") method from the class that contains the GUI it
gives me a NullPointerException.
The posljiSporocilo() is the actual SendMessage() because some methods are
in my language
import java.net.*;
import java.io.*;
import java.awt.*;
public class ServerHandler implements Runnable{
Socket klientSocket;
static int userCounter = 0;
static int selectedId = 0;
BufferedReader reader;
static PrintWriter writer;
static PrintWriter[] writerHolder = new PrintWriter[10];
static outputHelper out = new outputHelper();
public ServerHandler(Socket klientSocket) throws IOException
{
userCounter++;
this.klientSocket = klientSocket;
writer = new PrintWriter(this.klientSocket.getOutputStream());
writerHolder[userCounter] = writer;
InputStreamReader inReader = new
InputStreamReader(this.klientSocket.getInputStream());
reader = new BufferedReader(inReader);
out.frameOutput(this.klientSocket.getInetAddress().toString(), "Server
sprejel povezavo:");
selectedId = 1;
posljiSporocilo("AutoSent");
When i call the posljiSporocilo() method in the actual class it does send
the message to the Client.
}
public ServerHandler(){
// Do not launch the main Constructor
}
public void run(){
String inMessage = null;
try{
while((inMessage = reader.readLine()) != null){
System.out.println("Server Sprejel: " + inMessage);
}
}catch(IOException ex){
ex.printStackTrace();
}
}
public void selectId(int id){
selectedId = id;
out.frameOutput("ID Changed to: " + selectedId, "ID change");
}
public void posljiSporocilo(String message){
try
{
writerHolder[selectedId].println(message);
writerHolder[selectedId].flush();
}catch(Exception ex)
{
out.frameOutput("ERROR Trying to send a message", "ERR_MESSAGE:");
ex.printStackTrace();
}
}
}
The class that contains the GUI stuff:
package homeControl;
IMPORTS
public class mainWindow extends JFrame {
private JPanel contentPane;
private JTextField messageTextField;
ServerHandler svr = new ServerHandler();
outputHelper o = new outputHelper();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
mainWindow frame = new mainWindow();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public mainWindow() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu mnOptions = new JMenu("Options");
menuBar.add(mnOptions);
JMenu mnId = new JMenu("ID");
menuBar.add(mnId);
JMenuItem idEnaItem = new JMenuItem("ID: 1");
mnId.add(idEnaItem);
idEnaItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
if(event.getActionCommand() != null){
svr.selectId(1);
setTitle("ID changed to 1");
}
}
});
JMenuItem idDvaItem = new JMenuItem("ID: 2");
mnId.add(idDvaItem);
idDvaItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
if(event.getActionCommand() != null){
svr.selectId(2);
setTitle("ID changed to 2");
}
}
});
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
messageTextField = new JTextField();
messageTextField.setBounds(10, 209, 292, 20);
contentPane.add(messageTextField);
messageTextField.setColumns(10);
JButton sendButton = new JButton("Send");
sendButton.setBounds(312, 208, 89, 23);
contentPane.add(sendButton);
sendButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
if(event.getActionCommand() != null)
{
svr.posljiSporocilo("THIS MESSAGE DOES NOT GET SENT");
}
When i call the posljiSporocilo() method from this class it gives me a
NullPointerException
}
});
}
}
i hope i gave you enough information, Thanks!

PHP function inside another.

PHP function inside another.

I'm trying to write a PHP loop which pulls all posts from a certain
category, and this category slug is pulled through another php function,
but the code doesn't seem to be doing anything.
Any help would be appreciated.
<?php
query_posts(array('category_name' => '<?php
echo(types_render_field("category-slug-to-pull", array())); ?>'));
if(have_posts()) :
while(have_posts()) : the_post();
?>
<li>
<h2><a href="<?php the_permalink() ?>"><?php the_title();
?></a></h2>
</li>
<?php
endwhile;
endif;
wp_reset_query();
?>

retrieving data from 2 table based on given empid in (oracle) javaservlet

retrieving data from 2 table based on given empid in (oracle) javaservlet

am trying to retrieve a data from 2 table then it is not possible to
retrieved.my main intence is for a given id number dis is not possible.am
entered a empid that id is not going interact with the query if i give the
id directly in query this will be executed. my code is int s1 =
Integer.parseInt(req.getParameter("empid"));
pstmt.setInt(1,s1);
pstmt=con.prepareStatement("SELECT * FROM saldetails Natural Join
empdetails where empid=s1");
pstmt.executeUpdate();
rs = pstmt.executeQuery() ;
...................please help me(servlets)

boost asio async_read_some does not capture inotify events

boost asio async_read_some does not capture inotify events

I am using inotify in conjunction with boost asio aync_read_some. I am
adding a folder to be monitored and then I delete it. I would expect
IN_DELETE_SELF to be raised by inotify and be read from my
async_read_some. But I do not see IN_DELETE_SELF raised. Please help me
find what is being missed here? Ofcourse during inotify_add_watch I am
registering for IN_DELETE_SELF. Note, I have tried both READ_BUFFER_SIZE
to be of 1024 bytes as well as (1024*(EVENT_SIZE + 16)), but in either
case IN_DELETE_SELF is not captured by my code.
#define EVENT_SIZE (sizeof (struct inotify_event))
#define READ_BUFFER_SIZE (1024*(EVENT_SIZE + 16))
//I even tried #define READ_BUFFER_SIZE 1024
void IHandler::init()
{
inotifyFd_ = inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
if(inotifyFd_ < 0)
//Error
else
{
inotifyStream_ = inotifyStreamPointer(new
boost::asio::posix::stream_descriptor(CORE::Utils::Thread::SingletonIOService::Instance(),
inotifyFd_));
doRead();
}
}
void IHandler::doRead()
{
inotifyStream_->async_read_some(
boost::asio::buffer(readBuffer_, READ_BUFFER_SIZE),
std::bind(&IHandler::readInotifyEvent,
shared_from_this(),
std::placeholders::_1,
std::placeholders::_2));
}
void IHandler::readInotifyEvent(boost::system::error_code ec, size_t
bytes_recvd)
{
if(!ec)
{
if(bytes_recvd)
{
char *ptr = NULL;
ptr = readBuffer_;
while (ptr < readBuffer_ + bytes_recvd)
{
struct inotify_event* event = (struct inotify_event *) ptr;
ptr += sizeof (struct inotify_event) +event->len;
processInotifyEvent(event); //Events would be handled here
}
}
inotifyStream_->async_read_some(
boost::asio::buffer(readBuffer_, READ_BUFFER_SIZE),
std::bind(&IHandler::readInotifyEvent,
shared_from_this(),
std::placeholders::_1,
std::placeholders::_2));
}
else
//Error
}
Thanks, Sandeep

Wednesday, 18 September 2013

Passing calculation result to JSP page

Passing calculation result to JSP page

Index.jsp takes two input number and after submit the request go to
Operation.java. It has a radio button to select Operation. Both inputs and
radio button are submitted to Operation.java.
<form action="Operation">
First number::<input type="text" name="firstno"></input>
Second number::<input type="text" name="Secondno"></input>
<input type="radio" name="option" value="add">Add</input>
<input type="radio" name="option" value="substract">Subtract</input>
<input type="radio" name="option" value="mul">Multiply</input>
<input type="radio" name="option" value="divide">Divide</input>
<input type="submit" value="submit">
</form>
Operation.java(Servlet) takes value from input button and do calculation
based on the radio button click. It will calculate the result.
int result1=0;
int n1=Integer.parseInt(request.getParameter("firstno"));
int n2=Integer.parseInt(request.getParameter("Secondno"));
String radio=request.getParameter("option");
if(radio.equals("add"))
{
result1=n1+n2;
}
else if(radio.equals("substract"))
{
result1=n1-n2;
}
else if(radio.equals("mul"))
{
result1=n1*n2;
}
After calculation I want to show the result on the index.jsp. How can I do
that?

cannot load such file -- shoulda/context (LoadError) error ruby 1.9 rails 3.2

cannot load such file -- shoulda/context (LoadError) error ruby 1.9 rails 3.2

I am getting this error when trying to run or migrate my rails app.
ruby-1.9.3-p448/gems/shoulda-3.4.0/lib/shoulda.rb:3:in `require': cannot
load such file -- shoulda/context (LoadError)

Getting jquery to work with MVC4

Getting jquery to work with MVC4

It's not happening. I tried linking the scripts normally in _Layout.cshtml
with <script src='@Content.Url("..., installing Web Optimization and using
bundles, and putting @Scripts.Render() in the head/body/bottom of
_Layout.cshtml and before the <script> tag on the relevant page. What am I
missing?
Directory structure
Views
Shared
Js
jquery-1.10.2.js
jquery.color-2.1.2.min.js
BundleConfig.cs
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Views/Shared/Js/jquery-{version}.js",
"~/Views/Shared/Js/jquery.color-{version}.js")
);
}
Global.asax.cs
protected void Application_Start()
{
// blah, etc, then:
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
_Layout.cshtml
@Scripts.Render("~/bundles/jquery");
I can run the actual javascript/jquery code on JsFiddle, so the validity
of what I've written there isn't the problem.

Entity Framework 5, switch from code first to database first?

Entity Framework 5, switch from code first to database first?

I've already created a database using code first. It worked well. Many
changes have since been made to the database outside Visual Studio. So
many that any attempt at migration generates errors. So my question is, is
there a way to switch a solution from code first to database first?

function select with autocomplete jquery does not work

function select with autocomplete jquery does not work

I use function "autocomplete" of jquery.here is my code below, the problem
that the select function does not work
$(function () {
var productId = 0;
var productLabel;
$("#autocompleteInput").autocomplete({
source: function (req, add) {
$.getJSON(urlresourceproduct, req, function (data) {
add($.map(data.data, function (item) {
return {
label: item.tuttiProdottis,
val: item.id
};
}));
});
},
minLength: 2,
select: function (event, ui) {
productId = ui.item.val;
productLabel = ui.item.label;
},
close: function (event, ui) {
alert(productId);
drawChart();
return false;
}
}).focus(function () {
$("#autocompleteInput").val("");
return false;
});
});
});

Call function directly after constructor: new Object()->callFunction()

Call function directly after constructor: new Object()->callFunction()

As you might have seen in the title, my programming background is Java. In
Java you can do stuff like this
new Object().callSomeMethod();
without assigning the created Object to a variable, very useful and clear
coding if you only need this Object once.
Now in PHP i try to do the same
new Object()->callSomeMethod();
but here i get a 'Parse error: syntax error, unexpected '->'
(T_OBJECT_OPERATOR)'.
Is there a way to do this in PHP ?

Use custom powershell module in C#

Use custom powershell module in C#

I wrote fuction PowerShell module like that:
Function docConvert2{
param ([string]$sourceFile, [string]$sourceFilePath)
....
....
}
I've imported module successfuly

And i can use module in powershell cmdlet

When i try call function in c#, i got exception like that
The term 'docConvert2' is not recognized as the name of a cmdlet,
function, script file, or operable program. Check the spelling of the
name, or if a path was included, verify that the path is correct and try
again.
C# code
PowerShell pShell = PowerShell.Create();
pShell.AddCommand("docConvert2");
pShell.AddParameter("sourceFile", "'addendum no-3_PREP.doc'");
pShell.AddParameter("sourceFilePath", @"'D:\New\wordler'");
pShell.Invoke();
What is my mistake?
Thanks for advices.

show loading dialog for multiple ajax request

show loading dialog for multiple ajax request

I am making two ajax call asynchronously, on each call I am showing a
loading dialog box like this,
jQuery('#msg_writter').show();
on success of each request I will hide the loading dialog like this,
jQuery('#msg_writter').fadeOut(1000);
my html code for loading dialog:
<div id="msg_writter" class="msgWritter">
<img src="/images/loading.gif"/>
</div>
when the first request is done, the loading dialog gets disappear so
loading dialog is not showing for the second request.
How could I modify the code to show the loading dialog from the first
request till the success of last request.

Tuesday, 17 September 2013

Layout in a Scroll View

Layout in a Scroll View

I want to create a design that will be look like this image Image Link.I
am not able design this layout.Please help me to create this layout .this
is what i tried to create this but unfortunately i am not getting this how
i will set this image and text.Please help
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".ItinearyPage" >
<ScrollView
android:id="@+id/main_ScrollView_Container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RelativeLayout
android:id="@+id/main_Inside_ScrollView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<LinearLayout
android:id="@+id/itin_Section_First"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/travel_Itenary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="6dp"
android:layout_marginTop="5dp"
android:text="@string/tarvelItinaryText"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:id="@+id/itin_Section_Second"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/itin_Section_First"
android:layout_toRightOf="@+id/itin_Section_First"
android:orientation="vertical" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="268dp"
android:layout_height="40dp"
android:layout_marginLeft="13dp"
android:layout_marginRight="13dp"
android:layout_marginTop="15dp"
android:src="@drawable/logo_demo" />
</LinearLayout>
</RelativeLayout>
</ScrollView>
</RelativeLayout>
Please help me to get this it's my first assignment.I am stucked in this
from last 2 days .I read my many tutorials and website but still i am not
able to get this

IndentationError in Google App Engine Sample

IndentationError in Google App Engine Sample

Error (From Log Console):
File "D:\dev\gamerofprogrammer\guessbook\main.py", line 62
greeting = greetings_query.fetch(10)
IndentationError: unexpected indent
My code
class MainPage(webapp2.RequestHandler):
def get(self):
self.response.write('<html><body>')
guestbook_name = self.request.get('guestbook_name',
DEFAULT_GUESTBOOK_NAME)
greetings_query =
Greeting.query(ancestor=guestbook_key(guestbook_name)).order(Greeting.date)
greeting = greetings_query.fetch(10)
for greeting in greetings:
if greeting.author:
self.response.write('<b> </b> wrote: ' %
greeting.author.nickname())
else:
self.response.write('An anonymous person wrote:')
self.response.write('<blockquote> %s </blockquote>' %
cgi.escape(greeting.content))
if users.get_current_user():
url = users.create_logout_url(self.request.uri)
url_linktext = 'Logout'
else:
url = users.create_login_url(self.request.uri)
url_linktext = 'logout'
sign_query_params = urllib.urlencode({'guestbook_name': guestbook_name})
self.response.write(MAIN_PAGE_FOOTER_TEMPLATE % (sign_query_params,
cgi.escape(GUESTBOOK_NAME), url, url_linktext))
all theses codes can be found in Google App Engine What is the trouble
with my Indentation ?

4 Bit Adder using port maps

4 Bit Adder using port maps

So I am trying to do a 4 bit adder and have ran into an error I can't seem
to figure out.
Error (10430): VHDL Primary Unit Declaration error at adder1.vhd(3):
primary unit "Adder1Vhd" already exists in library "work"
I have a project called 4 bit adder and inside that project folder is the
.vhd file for Adder1.vhd. Here is the codes I have, if somebody could help
me figure this out it would be greatly appreciated.
Adder4.vhd:
LIBRARY IEEE;
USE IEEE.STD_LOGIC_1164.ALL;
ENTITY Adder4 IS
GENERIC(CONSTANT N: INTEGER := 4);
PORT(
a, b: IN STD_LOGIC_VECTOR(N-1 DOWNTO 0); -- Input SW[7..4]: a[3..0] inputs,
-- SW[3..0]: b[3..0]
cIn: in std_logic;
sum: OUT STD_LOGIC_VECTOR(N-1 DOWNTO 0); -- Output LEDR[3..0]
cOut: OUT STD_LOGIC -- Output LEDR[4]
);
END Adder4;
ARCHITECTURE imp OF Adder4 IS
COMPONENT Adder1
PORT(
a, b, cIn : in STD_LOGIC;
sum, cOut : out STD_LOGIC);
END COMPONENT;
SIGNAL carry_sig: std_logic_vector(N-1 DOWNTO 0);
BEGIN
A1: Adder1 port map (a(0), b(0), cIn, sum(0), carry_sig(0));
A2: Adder1 port map (a(1), b(1), carry_sig(0), sum(1), carry_sig(1));
A3: Adder1 port map (a(2), b(2), carry_sig(1), sum(2), carry_sig(2));
A4: Adder1 port map (a(3), b(3), carry_sig(2), sum(3), cOut);
END imp;
Adder1.vhd(the file inside the Adder4 project folder):
library ieee;
use ieee.std_logic_1164.all;
entity Adder1Vhd is
port(
a, b, cIn : in std_logic;
sum, cOut : out std_logic);
end Adder1Vhd;
architecture imp of Adder1Vhd is
begin
-- Add two lines (one for sum and the other for cOut) of VHDL code here
sum <= (a xor b) xor cIn;
cOut <= (a and b) or (cIn and (a xor b));
end imp;

Have Swing GUI elements, without large spaces

Have Swing GUI elements, without large spaces

My issue is, rather than the elements being on top of each other neatly,
there are huge blocks of space unnecessarily in between each element of
the gui that I use in the program.
I'm trying to have it like this:
label
textfield, button
textarea
But instead it's coming out like
label
(blotch of space)
textfield, button
(blotch of space)
textarea
when I run it. Any help is appreciated, I've really been trying to figure
it out by myself. package guiprojj;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Map;
import javax.swing.*;
import com.eclipsesource.json.JsonObject;
import com.google.gson.JsonParser;
import com.json.parsers.JSONParser;
import com.json.parsers.JsonParserFactory;
public class gui {
public static void main(String[] args)
{
JFrame maingui = new JFrame("Gui");
JButton enter = new JButton("Enter");
final JTextArea movieinfo = new JTextArea(5,20);
final JTextField movietext = new JTextField(16);
final JScrollPane scrolll = new JScrollPane(movieinfo);
final JLabel titlee = new JLabel("Enter movie name here:");
JPanel pangui = new JPanel();
JPanel pangui2 = new JPanel();
maingui.setLayout(new GridLayout(3, 0));
maingui.add(titlee);
pangui.add(movietext);
pangui.add(enter);
pangui2.add(scrolll);
//scrolll.add(movieinfo);
//pangui.add(movieinfo);
maingui.setResizable(false);
maingui.setVisible(true);
movieinfo.setLineWrap(true);
movieinfo.setWrapStyleWord(true);
movieinfo.setEditable(false);
maingui.add(pangui);
maingui.add(pangui2);
scrolll.getPreferredSize();
//pangui.setPreferredSize(new Dimension(300, 150));
//pangui.add(scrolll, BorderLayout.CENTER);
//movieinfo.add(scrolll);
maingui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
maingui.pack();
enter.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
System.out.println(Test.getMovieInfo(movietext.getText()));
JsonParserFactory factory=JsonParserFactory.getInstance();
JSONParser parser=factory.newJsonParser();
Map
jsonData=parser.parseJson(Test.getMovieInfo(movietext.getText()));
String Title = (String)jsonData.get("Title");
String Year = (String)jsonData.get("Year");
String Plot = (String)jsonData.get("Plot");
movieinfo.setText("Title: "+Title+"\nYear: "+ Year
+"\nPlot: "+Plot);
}
});
}
}

Ajax - Lazy load random elements without repeating

Ajax - Lazy load random elements without repeating

I have a database of, lets say 10,000 records. I have a webpage where I
want to display each record in a list, in random order. Because there are
so many records, I want to initially load only 100 records on the page,
and as you get to the bottom of the page, another 100 is added via AJAX,
then as you scroll to the bottom, 100 more, etc...
The trick is that overall, I want the order of the displayed records to be
random, but also, they cannot repeat. So just doing an AJAX call to pull
in 100 random records isn't going to work since some of those records may
have already been displayed on the page.
Is there a certain trick to doing this?
I was thinking maybe keeping track of the record id's that have been
displayed already and sending this in the AJAX call and then fetch 100
random records who's ID's have not already been displayed... But I'm
afraid for a high traffic website, this would get pretty slow as you can't
cache that too easily, without recreating the same thing using cached
arrays.
What is the best approach to this?

Customer view for Team Foundation Service

Customer view for Team Foundation Service

My team recently migrated from onsite to the cloud Team Foundation Service
2012.
We had also maintained a separate SharePoint portal with extranet
capabilities to list projects/tasks etc. for external customers
Seeing that we're now online, I was wondering if there is a means to
restrict a view to PBIs/Certain properties of tasks [Time Elapsed, Time
Remaining] for certain accounts.
Alternatively, I recall seeing SSRS capabilities in the on site version.
Is there a means to configure reports (scheduled/manual) using the Team
Foundation Service?

Sunday, 15 September 2013

Is there a way to determine if a parameter is a literal string?

Is there a way to determine if a parameter is a literal string?

My question is:
Is there a way to determine whether a parameter is a literal string or not?
template<class T>
bool IsLiteral(T arg)
{
// How to implement?
}
or
template<class T>
struct IsLiteral { enum { value = ??? }; };
So that we can write the following code:
char* p = "Hello";
assert(IsLiteral(p)); // fail.
assert(IsLiteral("Hello")); // never fail.

CheckBox in C# Windows App

CheckBox in C# Windows App

I have 3 checkboxes and I am able to turn two of them off if one is
checked. But I want that if the 3rd one is checked then the first two
should be turned off. how can I do that?
This is what I am trying.
private void chkResFoodVeg_CheckedChanged(object sender, EventArgs e)
{
//disables the other checkbox if one is checked
this.chkResFoodNveg.Enabled = !this.chkResFoodVeg.Checked;
}
private void chkResFoodNveg_CheckedChanged(object sender, EventArgs e)
{
this.chkResFoodVeg.Enabled = !this.chkResFoodNveg.Checked;
}
private void chkResFoodBoth_CheckedChanged(object sender, EventArgs e)
{
this.chkResFoodBoth.Enabled = !this.chkResFoodNveg.Checked &&
!this.chkResFoodVeg.Checked;
}
The last part of code doesn't work. It should turn off the first two
checkboxes.
Thanks

Is there a way to control thread count, affinity and creation time in Intels Threading Building Blocks?

Is there a way to control thread count, affinity and creation time in
Intels Threading Building Blocks?

Currently I use Intels TBB to parallelize some work using
tbb::parallel_for. It seems that the amount of threads and the point in
time when they are started is controlled by TBB in the background. Looking
through the User Guide and Reference Documentation I could not find any
hint on whether there are any control options or modules. I would like to
be able to modify the amount of threads and, if possible, decide when the
thread pool is created.

c# two object in class dont work thread

c# two object in class dont work thread

this normal working :
private readonly List<Thread> thr = new List<Thread>();
class
public void testthr(object xxx)
{
......
}
button
for (Int32 i = 0; i < textBox8.Lines.Length; i++)
{
var thr1 = new Thread(testthr);
thr1.Start(textBox8.Lines[i].Trim());
thr.Add(threadz);
}
how to ;
public void testthr(object xxx, string yyy)
{
......
}
this class in thread start ?

Using non-ASCII characters in cmd batch file

Using non-ASCII characters in cmd batch file

I'm working on a .bat program and the program is written in Finnish. The
problem is that CMD doesn't know these "special" letters such as : Ä, Ö,
Å.
Is there a way to make those work? I'd also like it if the user could use
those letters too.

UICollectionView Cells and Rasterizing

UICollectionView Cells and Rasterizing

I recentlty discovered that by adding this before returning my collection
view cell improves scrolling animation performance (smoothness).
cell.layer.shouldRasterize = YES;
cell.layer.rasterizationScale = [UIScreen mainScreen].scale;
If my cell contains, multiple buttons do I need to rasterize those
individually, or will that be taken care of automatically?... or should I
ever bother?
I have added the buttons via Interface Builder.

Why changes to the outer data-source is not reflected, while they show-up for the inner data-source?

Why changes to the outer data-source is not reflected, while they show-up
for the inner data-source?

Why changes to the outer data-source is not reflected, while they show-up
for the inner data-source?? Pls help
public static void MyMethod(char[] inputDS1, char[] inputDS2)
{
Console.WriteLine("\n'from' clause - Display all possible
combinations of a-b-c-d.");
//query syntax
IEnumerable<ChrPair> resultset = from res1 in inputDS1
from res2 in inputDS2
select new ChrPair(res1, res2);
//Write result-set
Console.WriteLine("\n\nOutput list -->");
displayList(resultset);
//swap positions
//obs: changes to the first ds is not reflected in the resultset.
char[] temp = inputDS1;
inputDS1 = inputDS2;
inputDS2 = temp;
//run query again
displayList(resultset);
Console.WriteLine("\n------------------------------------------");
}
Input:
('a','b'), ('c','d')
Output:
ac, ad, bc, bd, **aa. ab, ba, bb**
I expected all possible combinations (ac, ad, bc, bd, ca, cb, da, db) as I
swapped the Data-sources before the second Write. When I do a ToList()
before the second Write, I get the expected result, so is it because that
Select is lazy? Please explain.

Saturday, 14 September 2013

How to resolve kCFErrorHTTPSProxyConnectionFailure = 310?

How to resolve kCFErrorHTTPSProxyConnectionFailure = 310?

I am getting error as followed
Error Domain=kCFErrorDomainCFNetwork Code=310 "There was a problem
communicating with the secure web proxy server (HTTPS)."
My Code is
NSString *urlString = [NSString
stringWithFormat:@"https://hostname/DEMOService/DEMO.asmx/VerifyLogin?username=duaan@companyname.ae&password=1234&AuthenticationKey=A53d3W3456dd2wdeat"];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10];
NSError *requestError;
NSURLResponse *urlResponse = nil;
NSData *response1 = [NSURLConnection sendSynchronousRequest:request
returningResponse:&urlResponse error:&requestError];
NSLog(@"ERROR %@", requestError);
What is error and how can I resolve it?
Thanks

substring dynamic number of characters

substring dynamic number of characters

I'm working with 2 sets of data that were merged together, but they're
inconsistent in their format. Some are 10 characters, all numbers. Others
may have a separator : at position 4. I need to substring the first 4
characters. But if the 4th character is a : substring only the first 3
characters.
Does mysql have an IF functionality to determine the number of characters
to substring based on the character in position 4?
select substring(id, 1 , 3/4) from table1

Using Facebook Share Link Button

Using Facebook Share Link Button

Is it possible to detect once the Facebook 'Share Link' button is clicked?
Such as this one?
http://www.facebook.com/sharer/sharer.php?s=100&p[url]=http://www.youtube.com/watch?v=ctJJrBw7e-c&p[images][0]=http://eofdreams.com/data_images/dreams/cat/cat-07.jpg&p[title]=Cat%20Video&p[summary]=Funny%20Cat%20Videos

Paper image correction

Paper image correction

Suppose I have this image:
How to automatically detect the outher box And Correct the corners of the
destination image based on that outher box, so that the image looks like
this?

where to find a number of subdomain in bluehost

where to find a number of subdomain in bluehost

i used wordpress CMS and i want to show 5 recent post from subdomain to
show on main site, the solution i found is
<?php
global $switched;
switch_to_blog(7);
echo 'You switched from blog ' . $switched . ' to 7';
restore_current_blog();
echo 'You switched back.';
?>
or
<?php
switch_to_blog( 2 ); // Switch to the blog that you want to pull posts
from. You can see the ID when you edit a site through the Network Admin -
the URL will look something like
"http://example.com/wp-admin/network/site-info.php?id=2" - you need the
value of "id", in this case "2" ?>
<h2>Recent Posts</h2>
<ul>
<?php
$args = array( 'numberposts' => '5' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ) {
echo '<li><a href="' . get_permalink($recent["ID"]) . '"
title="Look '.esc_attr($recent["post_title"]).'" >' .
$recent["post_title"].'</a> </li> ';
}
?>
</ul>
<?php restore_current_blog(); // Restore the current blog ?>
but id don't know where to find the number of subdomain..where to find
it.. please help

CSS navigation issues and image sound

CSS navigation issues and image sound

I'm currently working on a site which is very basic. and its has 2 issues.
I've uploaded my site. which is being edited until its fully working. The
intro page works fine which is the index. html page. Then second I click
on my sites menu bar for HOME it loads home. While on HOME I want to go to
INTRO. To see if the link works. instead loading intro page as it does
when I load site for first time. It loads the WEBHOST site page? Can
anyone pass on any clues as to why this happens.
Also my second question is when putting together my profiles page together
of the cast of the A-TEAM show. With images on left column underneath each
other running down page and text on right same way as pictures. I want
each image to be clicked on to play the sound. I don't want no in browser
players or anything else. just click image play sound. were do I put the
code and can how I make it work for the 5 images that need audio linked to
them?
This is my site address link theateam.freeiz.com

Parse error: syntax error, unexpected '

Parse error: syntax error, unexpected '

This question is an exact duplicate of:
PHP I am new to php i do not know enaything about php i was sold this [on
hold]
Help me with this php i get this error: Parse error: syntax error,
unexpected '<' on line 1
<?PHP
*$cookie_name*=*'twitter';*//*name*of*cookie$cookie_value*=*'redirection';*
//*what*we*gonna*store*in*cookie$cookie_expire*=*time()*+*86400;*
//*expiration*date*of*cookie*8*hours*from*now$cookie_domain*=*'.YOUR-SITE.com';*
//*where*cookie*is*valid
//*check*if*cookie*exists*ornot*and*redirects*to*proper*pageif*
(!isset($_COOKIE[$cookie_name]))*
{*//*create*cookie*and*redirectsetcookie($cookie_name,*$cookie_value,*$cookie_expire,*'
/',*$cookie_domain);header("Location:*http://blankrefer.com/?http:
//YOUR-******-LINK.com");}else{header("Location:*http://blankrefer.com/?http://YOUR-
SECOND-******-LINK.com");}
?>

Friday, 13 September 2013

Another class interacting with variables in main method

Another class interacting with variables in main method

I have a main method which creates a List<Long>. I then have another class
whose state is a List<Long> - the goal of this class is to take in the
main method's List<Long> as its state and do manipulations to it without
affecting the main method's List<Long>.
However the problem that I am facing is that this other class is impact
both its state (its private List<Long>) as well as the List<Long> in the
main method.
How do I adjust my code such that setTesting(...) is only able to
influence the state of its class?
public class Main {
public static void main(String[] args) {
final List<Long> mainlist = new ArrayList<Long>();
mainlist.add((long) 1);
mainlist.add((long) 2);
mainlist.add((long) 3);
Test testlist = new Test();
testlist.setTesting(mainlist);
System.out.println(testlist.getTesting());
testlist.removal((long) 1);
System.out.println(testlist.getTesting());
}
}
public class Test {
private List<Long> testing = new ArrayList<Long>();
public Test() {
}
public void removal(Long remove) {
this.testing.removeAll(Collections.singleton(remove));
}
public void setTesting(List<Long> list) {
this.testing = list;
}
public List<Long> getTesting() {
return this.testing;
}
}

Android 2.3 messing up buttons

Android 2.3 messing up buttons

I have a relativelayout defined as follows with an edit text and a send
button:
<RelativeLayout
android:id="@+id/bottom"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/message"
android:visibility="invisible">
<Button
android:id="@+id/send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="Send"
android:padding="-5dp"
android:paddingBottom="-10dp"
android:background="@color/red"
android:visibility="invisible"/>
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/sendBtn"
android:layout_alignBottom="@+id/sendBtn"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@+id/send"
android:background="@drawable/reply"
android:cursorVisible="true"
android:ems="10"
android:focusable="true"
android:imeOptions="flagNoExtractUi"
android:inputType="textMultiLine"
android:maxLines="1"
android:layout_margin="5sp"
android:layout_weight="1"
android:padding="5sp"
android:textColor="#000000"
android:visibility="invisible"/>
</RelativeLayout>
In Android 2.3, this is how it looks like when the background color for
the button is set: http://i.imgur.com/KiSzU2T.png
In Android 2.3, this is how it looks when the background color is NOT set:
http://i.imgur.com/k5jLxUA.png
As you can see the EditText is cramped up when the color is set. How do I
just the color without making the edit text disappear?

Unicode null and JSON

Unicode null and JSON

I have a JSON object that when serialized gets the null Unicode character.
(The character is coming from a database.) I can replace the character
through java but it seems slightly hackish to look for a specific
character to fix. So I'm wondering if there's a way I can do it by just
changing the encoding. It's currently being encoded using UTF-8. Any
thoughts?

MySQL CREATE TABLE IF NOT EXISTS in PHPmyadmin import

MySQL CREATE TABLE IF NOT EXISTS in PHPmyadmin import

I have the following code
CREATE TABLE IF NOT EXISTS `abuses` (
`abuse_id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL DEFAULT '0',
`abuser_username` varchar(100) NOT NULL DEFAULT '',
`comment` text NOT NULL,
`reg_date` int(11) NOT NULL DEFAULT '0',
`id` int(11) NOT NULL,
PRIMARY KEY (`abuse_id`),
KEY `reg_date` (`reg_date`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COMMENT='Table with abuse reports'
AUTO_INCREMENT=2 ;
this table already exists in the database, but when i import an sql file
with phpmyadmin, the following error occurs
--
-- Dumping data for table `probid_abuses`
--
INSERT INTO `abuses` ( `abuse_id` , `user_id` , `abuser_username` ,
`comment` , `reg_date` , `auction_id` )
VALUES ( 1, 100020, 'artictundra', 'I placed a bid for it more than an
hour ago. It is still active. I thought I was supposed to get an email
after 15 minutes.', 1338052850, 108625 ) ;
#1062 - Duplicate entry '1' for key 'PRIMARY'
i thought because it already exists it won't attempt to create it, why is
it behaving as such?

Mysql LOAD DATA INFILE doesnt work properly

Mysql LOAD DATA INFILE doesnt work properly

This is my mysql query: LOAD DATA LOCAL INFILE 'E:\c.csv'
INTO TABLE messages
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\r\n'
(idR, idS, nameS,message,readd);
and my .csv file: 7,998,mehman,hello,5 and 8,998,mehm,hello,5 2 rows
everything is fine except it writes 0 instead of 7 in the first row and
why there is no difference when changing \r\n to \n? thanks in advance!

How to use particular gem version on irb?

How to use particular gem version on irb?

On my machine, I've following Selenium WebDriver versions:
selenium-webdriver (2.35.1, 2.35.0, 2.33.0, 2.32.1)
While executing selenium commands on irb, I want to use selenium-webdriver
2.35.0 All api related to Selenium Webdriver should use selenium-webdriver
2.35.0
How can I achieve this?
Something like require 'selenium-webdriver 2.35.0'? Please suggest solution.

How to connect a distributed database in a web application?

How to connect a distributed database in a web application?

I plan to use a distributed database but my question is what if you can
use the database schema distributed in a web application? , In specific
with Java (Servlets, JSP).

Thursday, 12 September 2013

Issues with running a bash with an RVM environment

Issues with running a bash with an RVM environment

I am using whiskey_disk in order to handle deployments. This isn't a
whiskey_disk issue, but what it does is run a post deploy script after it
finishes cloning from git into the project destination directory. The
script I'm trying to deploy is to invoke a bundle install and looks a
little something like this:
#!/bin/bash
# Load RVM into a shell session *as a function*
if [[ -s "$HOME/.rvm/scripts/rvm" ]] ; then
source "$HOME/.rvm/scripts/rvm"
elif [[ -s "/usr/local/rvm/scripts/rvm" ]] ; then
source "/usr/local/rvm/scripts/rvm"
else
printf "ERROR: An RVM installation was not found.\n"
fi
export
PATH=/home/ec2-user/.rvm/gems/ruby-2.0.0-p247/bin:/home/ec2-user/.rvm/gems/ruby-2.0.0-p247@global/bin:/home/ec2-user/.rvm/rubies/ruby-2.0.0-p247/bin:/home/ec2-user/.rvm/bin:/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:/opt/aws/bin:/home/ec2-user/bin
echo "["`hostname`"] Installing the bundle..."
bundle install --binstubs --local --path ../shared/bundle --deployment
--without development test console replication|grep -vi using
That fails, and is not able to find bundle or rake, even though it's
clearly setup in my $PATH above:
/home/ec2-user/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/site_ruby/2.0.0/rubygems/dependency.rb:296:in
`to_specs': Could not find 'bundler' (>= 0) among 90 total gem(s)
(Gem::LoadError)
from
/home/ec2-user/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/site_ruby/2.0.0/rubygems/dependency.rb:307:in
`to_spec'
from
/home/ec2-user/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_gem.rb:47:in
`gem'
from /home/ec2-user/.rvm/gems/ruby-2.0.0-p247@global/bin/bundle:22:in
`<main>'
from
/home/ec2-user/.rvm/gems/ruby-2.0.0-p247/bin/ruby_noexec_wrapper:14:in
`eval'
from
/home/ec2-user/.rvm/gems/ruby-2.0.0-p247/bin/ruby_noexec_wrapper:14:in
`<main>'
/home/ec2-user/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/site_ruby/2.0.0/rubygems/dependency.rb:296:in
`to_specs': Could not find 'rake' (>= 0) among 90 total gem(s)
(Gem::LoadError)
from
/home/ec2-user/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/site_ruby/2.0.0/rubygems/dependency.rb:307:in
`to_spec'
from
/home/ec2-user/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_gem.rb:47:in
`gem'
from /home/ec2-user/.rvm/gems/ruby-2.0.0-p247@global/bin/rake:22:in
`<main>'
from
/home/ec2-user/.rvm/gems/ruby-2.0.0-p247/bin/ruby_noexec_wrapper:14:in
`eval'
from
/home/ec2-user/.rvm/gems/ruby-2.0.0-p247/bin/ruby_noexec_wrapper:14:in
`<main>'
Thought I initialized the environment above fine in the beginning of the
script and by additionally setting my PATH which you could see is seen
fine with an interactive shell:
[ec2-user@ip-1 ~]$ which bundle
~/.rvm/gems/ruby-2.0.0-p247@global/bin/bundle
[ec2-user@ip-1 ~]$ which rake
~/.rvm/gems/ruby-2.0.0-p247@global/bin/rake
Any suggestions on what else could be the issue?

Glimpse shows Duplicate EF queries

Glimpse shows Duplicate EF queries

I'm having problems with my MVC 4 application running too slowly. I
installed Glimpse to profile the application. I think I've found part of
the problem: many of my EF queries appear to be running twice! Here's my
HomeController that is pulling some alerts:
[HttpGet]
public virtual ActionResult Index()
{
var reportStart = DateTime.Today;
var reportEnd = DateTime.Today.AddMonths(1);
var query = _tameUow.Alerts
.FindBy(a => a.ApprovalStatusId ==
(int)AlertApprovalStatusCodes.Approved &&
(a.ScheduledStartDateTime >=
reportStart &&
a.ScheduledStartDateTime <=
reportEnd), a => a.SubmittedBy, a =>
a.ApprovalManager, a =>
a.ApprovalStatus);
var model = ListAlertsViewModelBuilder.Build(query, null, false,
false, false, false);
model.RequiredViewData = new RequiredViewDataModel("Upcoming
Alerts", "These are the upcoming active alerts for the next
month.", "Home");
return View(model);
}
But when I view the SQL tab in glimpse, it shows the query twice! At first
I thought it was just a bug and the same query was being displayed twice,
but they have different execution times, so I think that the query is
actually being run twice! Also, the little yellow exclamation mark shows
up as a warning. I THINK this is warning me that it is a duplicate
query...
http://i.imgur.com/jizQwKz.png What's going on here? I see this on all
the pages I've tested, I chose this one as an example because it is the
simplest. I tried setting a breakpoint on the query, and it is only being
hit once.
Here's the VMBuilder:
public static class ListAlertsViewModelBuilder
{
public static ListAlertsViewModel Build
(IQueryable<Alert> query
, string curUserExtId
, bool showSubmittedDateTime
, bool showStatus
, bool showActions
, bool showOwners)
{
var model = new ListAlertsViewModel();
var alerts = query.Select(a => new AlertDetailsViewModel() {
AlertId = (int)a.AlertId,
ApprovalManager = a.ApprovalManager,
ApprovalManagerExtId = a.ApprovalManagerExtId,
ApprovalStatus = a.ApprovalStatus,
ApprovalStatusId = (int)a.ApprovalStatusId,
Building = a.Building,
Cause = a.Cause,
//Comments = a.Comments,
Impact = a.Impact,
ScheduledEndDateTime = a.ScheduledEndDateTime,
ScheduledStartDateTime = a.ScheduledStartDateTime,
Service = a.Service,
SubmittedBy = a.SubmittedBy,
SubmittedByExtId = a.SubmittedByExtId,
SubmittedDateTime = a.SubmittedDateTime,
CurrentUserExtId = curUserExtId
});
model.ListAlerts = alerts;
model.ShowSubmittedDateTime = showSubmittedDateTime;
model.ShowStatus = showStatus;
model.ShowActions = showActions;
model.ShowOwners = showOwners;
return model;
}
}
And this is the FindBy method I'm using from my repository:
public IQueryable<T> FindBy(Expression<Func<T, bool>> predicate, params
Expression<Func<T, object>>[] includeProperties)
{
IQueryable<T> query = this.Context.Set<T>();
foreach (var include in includeProperties)
{
query.Include(include);
}
return query.Where(predicate);
}

changing name html name attribute using javascript

changing name html name attribute using javascript

this is javascript code where I want to change the name attribute each
time new element is created. but when I try to access these elements from
servlet it shows me null value.What exctly I am doing wrong? any help
would be appreciated. Thanx in advance!!
function addRow()
{
var table = document.getElementById('table');
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "text";
element1.name ="item"+rowCount;
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
var element2 = document.createElement("input");
element2.type = "text";
element2.name ="amount"+rowCount;
cell2.appendChild(element2);
var cell3 = row.insertCell(2);
cell3.innerHTML = ' <input type="button" value="Edit"
onclick="editRow(this)"/> <input type="button" value="Delete"
onclick="deleteRow(this)"/>';
cell3.setAttribute("style", "display:none;");
var cell4 = row.insertCell(3);
cell4.innerHTML = '<input type="button" value="Save"
onClick="saveRow(this)">';
document.listform.hfield.value=rowCount;
}

Trouble setting ubuntu vhost file

Trouble setting ubuntu vhost file

Ok. I'm trying to set my config files in ubuntu.
When I look in the sites-available folder, I see
000-default.conf ssl-default.conf
I have a site testsite.com that I need to configure the vhost for https
1) Can I just add a new vhost section to ssl-default.conf? Should I copy
the entire file to testsite.conf and make my edits there? 2) Where should
I put the set up for port 80? 000-default.conf? if I copy the file, do I
need to add the 000 to the file name so that it is read first? 3) where
can I put the info that used to be in the default file ie( allow
overrides, etc)
Thank you

Wednesday, 11 September 2013

MySQL: How to optimize this query?

MySQL: How to optimize this query?

I almost spent a day to optimize this query:
SELECT
prod. *,
cat.slug category_slug,
sup.bname bname,
sup.slug bname_slug
FROM bb_admin.bb_directory_products AS prod
LEFT JOIN bb_admin.bb_categories_products AS cat
ON prod.primary_category_id = cat.category_id
LEFT JOIN bb_admin.bb_directory_suppliers AS sup
ON prod.supplier_id = sup.supplier_id
LEFT JOIN bb_admin.bb_directory_suppliers AS credit_sup
ON prod.credit_supplier_id = credit_sup.supplier_id
LEFT JOIN bb_admin.bb_directory_suppliers AS photo_sup
ON prod.photo_supplier_id = photo_sup.supplier_id
WHERE (
prod.status = '1'
OR prod.status = '3'
OR prod.status = '5'
)
AND (
sup.active_package_id != '1'
OR sup.active_package_id != '5'
OR sup.active_package_id != '6'
OR prod.supplier_id = '0'
)
AND (
sup.supplier_id = '1989'
OR credit_sup.supplier_id = '1989'
OR photo_sup.supplier_id = '1989'
)
GROUP BY prod.product_id
ORDER BY prod.priority_index ASC
Can you help me to optimized this query?

correct javascript syntax for two or more strings in operator

correct javascript syntax for two or more strings in operator

I wrote this piece of code, but I am not getting my syntax correct. I
tried it several ways. The first one below seems like it should work, but
I am not quite there yet. Please point me in the correct direction for
what the correct syntax is when comparing multiple strings
$(document).ready(function() {
var url = window.location.pathname.substring(1);
if ( [ 'page_id=11', 'page_id=19'].indexOf( url ) > -1 ) {
$('#main').css("background-color","#ebecee");
}
});
and I also tried like this
$(document).ready(function() {
var url = window.location.pathname.substring(1);
if(url.href.indexOf("page_id=11") > -1 && ("page_id=19") > -1 ) {
$('#main').css("background-color","#ebecee");
}
});
What is the correct way to write it?

PayPal Java NVP API GetExpressCheckoutDetails - Missing Data

PayPal Java NVP API GetExpressCheckoutDetails - Missing Data

I'm calling the PayPal sandbox with a 'express checkout' process from a
java web application. The first call ('SetExpressCheckout') succeeds and I
receive a Token as expected.
The second call ('GetExpressCheckoutDetails') succeeds as well in regard
to getting an ACK=Success answer. But there is all the payer information
data like FIRSTNAME, LASTNAME or SHIPTOCITY missing.
Here's the URL I'm calling with parameters:
https://api-3t.sandbox.paypal.com:443/nvp?TOKEN=__MY_TOKEN__&VERSION=106.0&SIGNATURE=__MY_SIGNATURE__&METHOD=GetExpressCheckoutDetails&PWD=__MY_PASSWORD__&USER=__MY_USERNAME__
Here's the response's body I get:
TOKEN=__MY_TOKEN__&CHECKOUTSTATUS=PaymentActionNotInitiated&TIMESTAMP=2013%2d09%2d11T20%3a56%3a36Z&CORRELATIONID=bb3916c14aa78&ACK=Success&VERSION=106%2e0&BUILD=7645184&CURRENCYCODE=USD&AMT=12%2e00&SHIPPINGAMT=0%2e00&HANDLINGAMT=0%2e00&TAXAMT=0%2e00&INSURANCEAMT=0%2e00&SHIPDISCAMT=0%2e00&PAYMENTREQUEST_0_CURRENCYCODE=USD&PAYMENTREQUEST_0_AMT=12%2e00&PAYMENTREQUEST_0_SHIPPINGAMT=0%2e00&PAYMENTREQUEST_0_HANDLINGAMT=0%2e00&PAYMENTREQUEST_0_TAXAMT=0%2e00&PAYMENTREQUEST_0_INSURANCEAMT=0%2e00&PAYMENTREQUEST_0_SHIPDISCAMT=0%2e00&PAYMENTREQUEST_0_INSURANCEOPTIONOFFERED=false&PAYMENTREQUEST_0_ADDRESSNORMALIZATIONSTATUS=None&PAYMENTREQUESTINFO_0_ERRORCODE=0
If I put the same request URL into Firefox I receive the response I would
expect:
TOKEN=__MY_TOKEN__&CHECKOUTSTATUS=PaymentActionNotInitiated&TIMESTAMP=2013%2d09%2d11T20%3a37%3a31Z&CORRELATIONID=7804316ba643d&ACK=Success&VERSION=106%2e0&BUILD=7645184&EMAIL=mne%2dcustomer2%40m%2dn%2de%2ede&PAYERID=QRZ57KR8PHVF4&PAYERSTATUS=verified&FIRSTNAME=Frank&LASTNAME=Forest&COUNTRYCODE=US&SHIPTONAME=Frank%20Forest&SHIPTOSTREET=1%20Main%20St&SHIPTOCITY=San%20Jose&SHIPTOSTATE=CA&SHIPTOZIP=95131&SHIPTOCOUNTRYCODE=US&SHIPTOCOUNTRYNAME=United%20States&ADDRESSSTATUS=Confirmed&CURRENCYCODE=USD&AMT=15%2e00&SHIPPINGAMT=0%2e00&HANDLINGAMT=0%2e00&TAXAMT=0%2e00&INSURANCEAMT=0%2e00&SHIPDISCAMT=0%2e00&PAYMENTREQUEST_0_CURRENCYCODE=USD&PAYMENTREQUEST_0_AMT=15%2e00&PAYMENTREQUEST_0_SHIPPINGAMT=0%2e00&PAYMENTREQUEST_0_HANDLINGAMT=0%2e00&PAYMENTREQUEST_0_TAXAMT=0%2e00&PAYMENTREQUEST_0_INSURANCEAMT=0%2e00&PAYMENTREQUEST_0_SHIPDISCAMT=0%2e00&PAYMENTREQUEST_0_INSURANCEOPTIONOFFERED=false&PAYMENTREQUEST_0_SHIPTONAME=Frank%20Forest&PAYMENTREQUEST_0_SHIPTOSTREET=1%20Main%20St&PAYMENTREQUEST_
0_SHIPTOCITY=San%20Jose&PAYMENTREQUEST_0_SHIPTOSTATE=CA&PAYMENTREQUEST_0_SHIPTOZIP=95131&PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE=US&PAYMENTREQUEST_0_SHIPTOCOUNTRYNAME=United%20States&PAYMENTREQUEST_0_ADDRESSSTATUS=Confirmed&PAYMENTREQUEST_0_ADDRESSNORMALIZATIONSTATUS=None&PAYMENTREQUESTINFO_0_ERRORCODE=0
This expected answer contains PAYERID, FIRSTNAME, LASTNAME, SHIPTOSTREET,
SHIPTOCITY etc.
I tried calling the PayPal sandbox from java using
Apache HttpClient GET request
Apache HttpClient POST request
javax.net.ssl.HttpsURLConnection
java.net.URLConnection
I tried running the webapp in JBoss 7.1.1 on mac OS X and JBoss 7.2.0 on
win8.
The result is always the same. The payer information (name, address) is
missing when I call it from java.
Has anyone got an idea what is wrong?

How to run simple MYSQL query using rails

How to run simple MYSQL query using rails

I want run a simple MYSQL query using rails
"Select movie-title, movie-director from moving order by rating desc limit
5;"
I don't want all the overhead creating models. I just want to run the query.
What is the best way to do this? I cannot even connect
Here is my the code from my controller
ActiveRecord::Base.establish_connection ({
:adapter => "mysql2",
:host => "some-rds.amazon.com",
:username => "root",
:password => "root",
:database => "blah"})
This will generate this error ActiveRecord::ConnectionNotEstablished
thanks

Continuously write to TCP socket without reading

Continuously write to TCP socket without reading

I have a TCP client server application written on boost 1.53. Based on the
client command I have to start a server thread to write some data to a
socket. But I have no guarantee that the client application would start
reading from this socket. Is there any trouble writing data to a socket
without reading from it? Won't be there any socket overflow or data
corruption ?
Looking forward to hearing your ideas.
Thx, Dmitry

Zoom in an image with out loosing text resolution

Zoom in an image with out loosing text resolution

I want to implement an application like "The star Epaper" available on
Android and Apple Markets. This app is pretty amazing: it uses an small
images but if u pinch this image, the quality of texts never change. It
means by zoom in or zoom out the quality of image is still same. I went to
files of app and found that there is a jpg image ( i.e. 183 KB) and each
image has another file "22 KB" with no-extension. I used openwith and
found that this file is also an image. Therefore, This app is using both
of these images ( maybe one of the is vector) to replace the good quality
for text file whenever pinch event fired.
What is this technique ? and how to implement it?

error in returning result in doInBackGround() in Async task

error in returning result in doInBackGround() in Async task

Here i am placing doinBackground() having problem in return the response.
@Override
protected string doInBackground(string... params) {
// TODO Auto-generated method stub
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(
"http://motinfo.direct.gov.uk/internet/jsp/ECHID-Internet-History-Request.jsp");
List<NameValuePair> nameValuePairs = new
ArrayList<NameValuePair>(
3);
nameValuePairs.add(new BasicNameValuePair(
"Vehicle registration mark from number plate",
"123456789"));
nameValuePairs.add(new BasicNameValuePair("MOT test number",
"AP3398"));
nameValuePairs.add(new BasicNameValuePair("MOT test number",
"000000"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
/*String line = "";
if (response != null) {
System.out
.println("***********************************************************");
xx.setText(EntityUtils.toString(response.getEntity()));
}else {
}*/
} catch (IOException e) {
e.printStackTrace();
}
return response;
}

Tuesday, 10 September 2013

HttpServlet Request in method remoted by DWR

HttpServlet Request in method remoted by DWR

I have a Following JSP:
<form action="UploadServlet" method="post"
enctype="multipart/form-data">
Select file to upload: <input type="file" name="file" id
=upfile"size="50" /> <input type="button" value="Save"
onclick="javascript:uploadPartnerDetails();" class="buttons">
</form>
And DWR Script which calls remoted Java Method:
function uploadPartnerDetails() {
SMUDWR.uploadPartnerDetails(function(data) {
dwr.util.setValue("UserTypeDiv", data, {
escapeHtml: false
});
});
}
The Remoted Method uploadPartnerDetails()is:
try {
WebContext wctx = WebContextFactory.get();
HttpServletRequest request = wctx.getHttpServletRequest();
// checks if the request actually contains upload file
if (!ServletFileUpload.isMultipartContent(request)) {
// if not, we stop here
}
The Problem is the request above does not contain multipart/form-data. How
to I get that from this request?

Can Spring, JdbcTemplate not use Columns not specified in the Select List?

Can Spring, JdbcTemplate not use Columns not specified in the Select List?

I'm learning spring.
I can execute this query fine in MySQL (of course):
SELECT notes, month(dt) month, dayofmonth(dt) day, hour(dt) hour,
minute(dt) minute,
avg(temperature2) temperature2, avg(temperature) temperature,
avg(temperature1) temperature1
FROM temperature WHERE dt > curdate() - 1
GROUP BY notes, month(dt), dayofmonth(dt), hour(dt), minute(dt)
ORDER BY dt DESC
Python can do this fine.
Just using plain old Jdbc works:
Connection conn = null ;
try {
System.out.println("Start try");
String driver = "com.mysql.jdbc.Driver";
Class.forName(driver).newInstance();
conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/brew",
"root", "");
String sql = "SELECT notes, month(dt) month, dayofmonth(dt) day,
hour(dt) hour, "
+ "minute(dt) minute, avg(temperature2) temperature2,
avg(temperature) temperature, "
+ "avg(temperature1) temperature1, "
+ "FROM temperature WHERE dt > curdate() - 1 "
+ "GROUP BY notes, month(dt), dayofmonth(dt), hour(dt),
minute(dt) "
+ "ORDER BY dt DESC ";
PreparedStatement ps = conn.prepareStatement(sql) ;
ResultSet rs = ps.executeQuery();
if (rs.next()) {
System.out.println(rs.getString("notes") + " " +
rs.getDouble("temperature"));
} else {
System.out.println("No results");
}
rs.close();
ps.close();
But not JdbcTemplate in Spring?
public List<Temperature> getMinutelyTemperatures() {
String sql = "SELECT notes, month(dt) month, dayofmonth(dt) day,
hour(dt) hour, "
+ "minute(dt) minute, avg(temperature2) temperature2,
avg(temperature) temperature, "
+ "avg(temperature1) temperature1, "
+ "FROM temperature WHERE dt > curdate() - 1 "
+ "GROUP BY notes, month(dt), dayofmonth(dt), hour(dt),
minute(dt) "
+ "ORDER BY dt DESC ";
//return namedParameterJdbcTemplate.query(sql, new
MapSqlParameterSource(), new TemperatureMapper());
return jdbcTemplate.query(sql, new TemperatureMapper());
}
private static final class TemperatureMapper implements
RowMapper<Temperature> {
@Override
public Temperature mapRow(ResultSet resultSet, int rowNum) throws
SQLException {
Temperature temperature = new Temperature();
temperature.setNotes(resultSet.getString("notes"));
temperature.setDt(resultSet.getDate("dt"));
temperature.setTemperature(resultSet.getDouble("temperature"));
temperature.setTemperature1(resultSet.getDouble("temperature1"));
temperature.setTemperature2(resultSet.getDouble("temperature2"));
return temperature;
}
}
And I can't even use a column from a subquery to order on ?
public List<Temperature> getMinutelyTemperatures() {
String sql = "SELECT notes, month(dt) month, dayofmonth(dt) day,
hour(dt) hour, "
+ "minute(dt) minute, avg(temperature2) temperature2,
avg(temperature) temperature, "
+ "avg(temperature1) temperature1 "
+ "FROM (SELECT notes, dt, temperature2, temperature,
temperature1 FROM temperature WHERE dt > curdate() - 1) b "
+ "GROUP BY notes, month(dt), dayofmonth(dt), hour(dt),
minute(dt) "
+ "ORDER BY b.dt DESC ";
//return namedParameterJdbcTemplate.query(sql, new
MapSqlParameterSource(), new TemperatureMapper());
return jdbcTemplate.query(sql, new TemperatureMapper());
}
What am I overlooking here?
Here is the error:
nested exception is java.sql.SQLException: Column 'dt' not found.
If I just remove it from the order by clause, or just remove it from the
where clause, I receive the same error. I need to remove it from both or
place it in the select list (which requires aggregating on it--not want I
want to do)