Saturday, 31 August 2013

Javascript return enclosing function

Javascript return enclosing function

I have a simple scenario in which I check if something exists before
adding it, if it does, I return the function (hence exiting). I use this
pattern many times and I would like to decouple it in another simple
function.
function onEvent(e){
if( this.has(e) )
return
this.add(e);
// More logic different on an event-basis
}
I would like to decouple it like so:
function safeAdd(e){
if( this.has(e) )
return
this.add(e);
}
function onEvent(e){
safeAdd(e);
// More logic
}
But obviously doing so just returns safeAdd and doesn't exit from onEvent,
and the rest of the logic gets executed anyways.
I know I could do something like:
function safeAdd(e){
if( this.has(e) )
return false
this.add(e);
return true
}
function onEvent(e){
if( !safeAdd(e) )
return
// More logic
}
But, since I repeat this a lot, I would like to be as concise as possible.

Jenkins: How to modify PATH environment variable for build steps?

Jenkins: How to modify PATH environment variable for build steps?

I'm trying to follow the instructions here to prepend a directory to path
for my build steps. However, the instructions reference the deprecated
SetEnv plugin. I tried playing with the new EnvInject plugin, setting
PATH=mydir:$PATH in Script Content field of the "Inject Build Environments
to the build process" section. However, the path is not updated when my
build step shell scripts execute.

Is there an efficient way to snapshot in-memory sqlite database with System.Data.Sqlite?

Is there an efficient way to snapshot in-memory sqlite database with
System.Data.Sqlite?

I want to be able to go to and from a byte[] representation of an
in-memory SQLite database. The only solution I know of right now is using
SQLiteConnection.BackupDatabase method, which can copy an active in-memory
database to another database on disk. I can then load that database with
File.ReadAllBytes, but I find this approach terribly inefficient for my
needs.

Perforce Server connection error in Mac OS X

Perforce Server connection error in Mac OS X

Good Day everyone!
I am trying to configure perforce server in OS X(10.8.4) . I tried to
follow instructions from here. In fact i am not sure if i am doing it
right ! Please check the commands below that i entered in Terminal.
Last login: Sun Sep 1 02:13:19 on ttys000
MDs-MacBook-Pro:~ Emon$ export PATH=~/perforce:$PATH export P4PORT=1666
MDs-MacBook-Pro:~ Emon$ cd ~/perforce chmod a+x p4d p4d -d
MDs-MacBook-Pro:perforce Emon$ chmod a+x p4
MDs-MacBook-Pro:perforce Emon$ mkdir ~/myws cd ~/myws p4 client myws
mkdir: /Users/Emon/myws: File exists
mkdir: p4: File exists
MDs-MacBook-Pro:perforce Emon$
After that i tried to to connect from p4v, but the following occurs !
In connection setup assistance i tried (as instructed in the link)
Host : localhost
Port : 1666
And the connection continues to refuse showing this...
Connect to server failed;check $P4PORT.
TCP Connection to localhost:1666 failed.
Connect: 127.0.0.1:1666 : Connection refused.
Please someone guide me in this regard. Thank you in advance. :)

How are views in CouchDB stored on disk?

How are views in CouchDB stored on disk?

I understand that CouchDB views are pre-computed, now I'm wondering what
the storage cost is per view. How can this be estimated? Is it the raw
JSON size of the emitted data?

What does session_destroy() do in PHP?

What does session_destroy() do in PHP?

In PHP manual, the description for session_destroy() function is :
session_destroy() destroys all of the data associated with the current
session. It does not unset any of the global variables associated with the
session, or unset the session cookie. To use the session variables again,
session_start() has to be called.
I am confused about this description. If this function destroys all
session data, then why the global variables associated with the session
are not unset? Why can we use the session variables again?

jquery mobile- swipe for the same page with different content

jquery mobile- swipe for the same page with different content

i am trying to swipe for the same page with different content but with the
slide animation? i am using jquery mobile. however, after the page is
changing the page disappear. What am i amissing
function swipeleftHandler( event ){
$.mobile.changePage.defaults.allowSamePageTransition = true;
$.mobile.changePage( '#MatchStats' , {
transition: "slide",
});
if (indexMathces==0)
indexMathces=listMatches.length;
indexMathces--;
getMatchStats(indexMathces,GroupID);
}
function swiperightHandler( event ){
indexMathces++;
if (indexMathces==listMatches.length)
indexMathces=0;
getMatchStats(indexMathces,GroupID);
$.mobile.changePage.defaults.allowSamePageTransition = true;
$.mobile.changePage( '#MatchStats' , {
transition: "slide",
});

Friday, 30 August 2013

Django Admin - Make previous inline forms uneditable

Django Admin - Make previous inline forms uneditable

I have an inline form in Django Admin. When the user edits the modelform
all previously filled inline forms are also listed. I just want to allow
users to view previously filled inline forms and make them uneditable. But
the user can add another form.
I tried using editable=False but this doesn't allow me to fill new form.

Redirect remove query

Redirect remove query

I want to redirect this page:
http://www.mydomain.com/mypage/subpage/
To:
http://www.mydomain.com/tempage/index.html
and this is my htaccess directive:
Redirect 302 /mypage/subpage/ /tempage/index.html
This redirects correctly but it adds a query string ?url=/mypage/subpage/
at the end of the URL, how can I remove it?

Thursday, 29 August 2013

Bash/command line - Count occurances of string in output from qstat

Bash/command line - Count occurances of string in output from qstat

I am trying to write a line of shell code that will tell me how many jobs
I have in a queue.
The command qstat will return a list of jobs with the following attribute
Job id, Name, User, Time Use Queue name
The command is labelled qstat(1B) in the man page.
My attempt to count how many jobs I have running uses grep:
grep -c my_username | qstat
As I understand it, this should count the number of occurrences of
my_username in the output from qstat. It doesn't work though. Any ideas
where I am going wrong?

why does simple_html_dom find('tr')[0] get table row 2 instead of table row 1?

why does simple_html_dom find('tr')[0] get table row 2 instead of table
row 1?

why does find('tr')[0]; get table row 2 instead of table row 1 ?
This is my html all tables have the same class and layout.
<table class="tablemenu">
<tbody>
<tr>
<td><b>hello</b></td>
<td><b>hi</b></td>
<tr>
<tr>
<td>hey</td>
<td>Alright</td>
<td>Good</td>
<td><a>Date</a></td>
<tr>
</tbody>
</table>
<table class="tablemenu">
<tbody>
<tr>
<td><b>hello</b></td>
<td><b>hi</b></td>
<tr>
<tr>
<td>hey</td>
<td>Alright</td>
<td>Good</td>
<td><a>Date</a></td>
<tr>
</tbody>
</table>
<table class="tablemenu">
<tbody>
<tr>
<td><b>hello</b></td>
<td><a>hi</a></td>
<tr>
<tr>
<td>hey</td>
<td>Alright</td>
<td>Good</td>
<td><a>LINK</a></td>
<tr>
</tbody>
</table>
This is my php
<?php
include("simpleHtmlDom/simple_html_dom.php");
$html = new simple_html_dom();
// Load a file
$html->load_file('http://mySite.net/');
foreach($html->find('table[class=tablemenu]') as $element){
$Link = $element->find('tr')[0]->find('td')[4]->find('a')[0];
echo($Link->text());
echo '<br />';
}
?>
although it works i now can't access table row 1. to grab the word hi.

Wednesday, 28 August 2013

Grails with Taggable crashes if deleting all but 1 tag

Grails with Taggable crashes if deleting all but 1 tag

I have a simple Grails application and one of the classes implements
Taggable. When testing with the Grails scaffolding and very basic user
interface for tags. When I delete a tag, everything is fine. When I delete
all the tags on an object, everything is fine. But if I try to delete all
but one, I get a Grails Runtime Error with the message, "Cannot cast
object 'groovytag' with class 'java.lang.String' to class
'java.util.List'" where groovytag was the single tag remaining. The error
sites this line:
objectInstance.tags = params.tags
Can anyone suggest what I need to do to get an object with only one tag?

(fscanf(file, "%lf", &num) > 0) and segmentation fault in C

(fscanf(file, "%lf", &num) > 0) and segmentation fault in C

I'm modifying a piece of the source code of bind, specifically the random
order section of the rdataset.c file, which is below:
for (i = 0; i < count; i++) {
dns_rdata_t rdata;
isc_uint32_t val;
isc_random_get(&val);
choice = i + (val % (count - i));
rdata = shuffled[i];
shuffled[i] = shuffled[choice];
shuffled[choice] = rdata;
if (order != NULL)
sorted[i].key = (*order)(&shuffled[i], order_arg);
else
sorted[i].key = 0; /* Unused */
sorted[i].rdata = &shuffled[i];
}
I change the line with choice and let that variable be taken from a
function like this
choice=weightCal();
and the code of function is
unsigned int weightCal() {
FILE *file = fopen("weight.txt", "r");
double integers[10],prob[10];
unsigned int i=0,j=0,k=0;
double sum=0,subSum=0,num;
unsigned int result=0;
while(fscanf(file, "%lf", &num) > 0) {
integers[i] =num;
sum+=num;
i++;
}
rewind(file);
while(fscanf(file, "%lf", &num) > 0){
subSum=subSum+num;
prob[j]= subSum / sum;
j++;
}
srand(time(NULL));
double r = rand() / (double)RAND_MAX;
for(k=0;k<sizeof(prob)/sizeof(double);k++) {
if (r < prob[k]) {
result=k;
break;
}
}
fclose(file);
return result;
}
then I recompile bind. The compilation works but when I use the command :
dig www.example.com. @127.0.0.1
it returns the error "Segmentation fault (core dumped)." I tried to debug
it and the debugger told me that the error is in the line
while(fscanf(file, "%lf", &num) > 0)
How can I fix this error?

Outputting \n as a line break when returning string as a file

Outputting \n as a line break when returning string as a file

This is hopefully very simple one and I think it lies in the encoding.
I have a string which contains \n for new lines
public ActionResult DownloadText(int id)
{
var text =
"BB2B-XX2A-F2CR-2MMQ-K79A\n3AP2-PH3H-M2QE-2DRH-D73A\nGPD3-AU3Q-P2DN-2FEX-P86A";
return File(new
System.Text.ASCIIEncoding().GetBytes(tempKeys.ToString()),
"text/plain", "Key"+ id.ToString() + ".txt");
}
I would like to display each item on a different line when output in the
text file. BB2B-XX2A-F2CR-2MMQ-K79A 3AP2-PH3H-M2QE-2DRH-D73A
GPD3-AU3Q-P2DN-2FEX-P86A

How to verify power provided to processors is clean

How to verify power provided to processors is clean

Once in a blue moon, I am seeing a blue screen of death on a shiny new
Dell R7610 with a single 1100 Watt Dell-provided power supply on a beefy
UPS. BCode is 101 (A clock interrupt was not received...), which some say
is caused by under-volting a CPU.
Naturally, I would have to contact Dell support, and their natural
reaction would be to replace a motherboard, a power supply, or CPU, or a
mixture of the above components.
In synthetic benchmarks, system memory and CPU, as well as graphics memory
and CPU perform admirably, staying up for hours and days.
My questions are:
Is power supply good enough for the application? Does it provide clean
enough power to VRMs on the motherboard?
Are VRMs good enough for dual Xeon E5-2665?
Does C-states logic work correctly?
Is there sufficient current provided to PCIe peripherals, such as disk
controllers?
P.S. Recently, I've gone through the ordeal with HP. They were nice and
professional about it, but root cause was not established, and the HP
machine still is less than 100%, giving me a blue screen of death once in
a couple of months.

Which architecture Should be use for my project(jax-ws , play frameork or other)

Which architecture Should be use for my project(jax-ws , play frameork or
other)

I have design a proje but I cant decide about project architecture.
in my project have service data to web , mobile applications . Also my
project call mutiple web service as asynchrous at same time ( least 5 web
service calling) for some request.
For that , firstly , I think jax-ws and play framework. but I cant decide
which should be. OR there can be different architecture for this

Battery graph in android using GraphView library?

Battery graph in android using GraphView library?

i found i great library to draw graphs. I want to create one that displays
in the x axis the time and in y the battery percentage. My goal is create
a graph like this:
You can see the percentage on the left and the date/time on bottom.
Starting from this example code :
https://github.com/jjoe64/GraphView-Demos/blob/master/src/com/jjoe64/graphviewdemos/AdvancedGraph.java
i want insert the correct data but i never used graphs. This is the
activity
public class AdvancedGraph extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.graphs);
// draw sin curve
int num = 150;
GraphViewData[] data = new GraphViewData[num];
double v=0;
for (int i=0; i<num; i++) {
v += 0.2;
data[i] = new GraphViewData(i, Math.sin(v));
}
// graph with dynamically genereated horizontal and vertical labels
GraphView graphView;
if (getIntent().getStringExtra("type").equals("bar")) {
graphView = new BarGraphView(
this
, "GraphViewDemo"
);
} else {
graphView = new LineGraphView(
this
, "GraphViewDemo"
);
}
// add data
graphView.addSeries(new GraphViewSeries(data));
// set view port, start=2, size=40
graphView.setViewPort(2, 40);
graphView.setScrollable(true);
LinearLayout layout = (LinearLayout) findViewById(R.id.graph1);
layout.addView(graphView);
// draw random curve
num = 1000;
data = new GraphViewData[num];
v=0;
for (int i=0; i<num; i++) {
v += 0.2;
data[i] = new GraphViewData(i, Math.sin(Math.random()*v));
}
// graph with dynamically genereated horizontal and vertical labels
if (getIntent().getStringExtra("type").equals("bar")) {
graphView = new BarGraphView(
this
, "GraphViewDemo"
);
} else {
graphView = new LineGraphView(
this
, "GraphViewDemo"
);
((LineGraphView) graphView).setDrawBackground(true);
}
// add data
graphView.addSeries(new GraphViewSeries(data));
// set view port, start=2, size=10
graphView.setViewPort(2, 10);
graphView.setScalable(true);
// set manual Y axis bounds
graphView.setManualYAxisBounds(2, -1);
layout = (LinearLayout) findViewById(R.id.graph2);
layout.addView(graphView);
}
}
What have i to change?How can i create what i want?Anyone can help me?
Thank you.

Tuesday, 27 August 2013

Software packages to create graphs or charts from a database full of numbers?

Software packages to create graphs or charts from a database full of numbers?

I have a device which generates a bunch of statistics once per second. All
of the statistics are stored in a PostgreSQL database on a Ubuntu server.
I'd like to create a web interface to prompt the user for a time range and
which values to graph. I'm also thinking this kind of thing is common when
people have databases full of numbers, so it must already exist. Problem
is I don't know what terms to google to find relevant software packages.
So far, the only 2 I've found are php5-rrd, and Carbon/Graphite.
The PHP5-RRD solution seems simple enough, though I'm worried I'll be
needlessly re-inventing the wheel. Can anyone recommend other similar
software packages that can help generate a bunch of "live" charts or
graphs with a web front-end?

Use a symbol for multiplication operator in sympy output in ipython notebook

Use a symbol for multiplication operator in sympy output in ipython notebook

In ipython notebook I would like to be able to use a symbol (\times or
\cdot) for the multiplication operator in the latex/mathjax output of an
expression. Is this possible?
sympy.latex() has an option mul_symbol but I can't see how to use it to
change the latex in an output cell.

SVM for ECG signal feature classification?

SVM for ECG signal feature classification?

I am new to using Matlab and I am trying to follow the example
function [ corr ] = svfit( InPop,chck)[m,n]=
size(InPop);corr=zeros(m,n);for i=1:n for j=1:n if j==i j=j+1;end
sum=0;data=[InPop(:,[i,j])];groups=ismember(chck,'arth');
[train,test]=crossvalind('holdOut',groups);cp=classperf(groups);
svmStruct=svmtrain(data(train,:),groups(train), 'showplot',true);
classes=svmclassify(svmStruct,data(test,:), 'showplot',true);
classperf(cp,classes,test);sum=sum+ cp.CorrectRate;j=j+1;end
corr(i)=sum/17;i=i+1;
to handle a classification problem.
However, I am not able to understand why it isn't running . Is the code
true or not? What is the best code to classify ECG signal ? How can i
initialize the input of support vector machine from genetic algorithm ? I
hope to help me and please don't delete my question ..

Liverpool vs Notts County live stream

Liverpool vs Notts County live stream

live-Liverpool-vs-Notts-County-Live-Stream-match starts\now
Click Here to watch -http://sportshdtv.dimitapapers.com/category/home/
Click Here to watch -http://sportshdtv.dimitapapers.com/category/home/
Liverpool don't have any contemporary injury issues for his or her League
Cup second-round tie against League One Notts County at Anfield. The match
can return timely for defender Martin Skrtel, however, with the defender
still combating a knee injury. Uruguayan centre-back Sebastian Coates may
be a long casualty – expected to be out for many of the season - with
frontman Luis Suarez still serving his suspension. Fabio Borini, United
Nations agency spent abundant of last season outharmed with a broken foot,
may create the team with urban center manager Brendan Rodgers expected to
create changes.
Notts County manager Chris Kiwomya can check on variety of players
previous the League Cup clash. Captain Dean humourist may be a doubt,
though Kiwomya are going to be keen to own his most-experienced defender
play against the Reds. Fellow defender Alan Sheehan, United Nations agency
has been suffering with a hamstring strain, and forwards Enoch Showunmi
and Danny Haynes incomprehensible the house league defeat to Stevenage on
Sat however are going to be checkedprevious the visit to Anfield

Add placeholder in wordpress editor of admin section

Add placeholder in wordpress editor of admin section

I want to add place holder for word-press default editor as like title.
When you create new post then the title field show "Enter Title Here"
exactly same like editor.I have used one filter for add text in editor but
the behaviour of the filter is not like same as title field means when i
click on title field then "enter title here" is replace to blank
space.below is my code.Please check
add_filter( 'default_content', 'my_editor_content' ); function
my_editor_content( $content ) { $content .= 'Enter Description Here';
return $content; }
I have used this code but i want same as like title field. Is this
possible. Please help me.

A subclass type as parameter type in superclass constructor java

A subclass type as parameter type in superclass constructor java

So I have a node class and I haven't learned Linked List yet, so I can't
use that. To construct a node object I want the parameters to be like
this:
Node(int numberOfNode, type complex or simpel)
I have two subclasses of node called Simpelnode and complexNode and so a
node object can be either one of them. What do I need to do so that the
parameter can be of both types?

Monday, 26 August 2013

Can I add a column with a value calculated from joined table?

Can I add a column with a value calculated from joined table?

I am trying to populate a column on my transactions table using the
difference between a timestamp in the transaction table and a timestamp in
the user table. The idea is to normalize the dates to reflect at what
point of a user experience the transactions happened (i.e. how many days
after a user joined was the transaction processed), as such:
update transactions
set days = ceil(extract(days from T.tdate - U.created_at)) +1
from transactions T join users U on T.user_id=U.id
For some reason, all the rows get the same number (262) in the "days"
field after running the query.

Height more than 100% of browser height

Height more than 100% of browser height

I'm building responsive webiste. I don't want to set a default height in
px, but I want to to something like this. This will be only top of layout.
E.g. prowly.com.

And my fiddle:
http://jsfiddle.net/QVxW8/1/
html, body {
margin: 0;
padding:0;
}
div#handler {
width: 100%;
height: 110%;
display:block;
}
div#content {
width: 100%;
height:100%;
background: red;
}
div#content2 {
width: 100%;
height: 10%;
background: blue;
}
HTML
<body>
<div id="handler">
<div id="content">I want to 100% height of browser</div>
<div id="content2">I want 10% of height browser</div>
</div>
</body>
Ps. As I also saw, 100% of height it's buggy on Safari iPhone and Opera
Mobile so I don't know what should I do. Of course I can use JS but I want
to know is there other way?

How can I connect latex and and excel to postgres?

How can I connect latex and and excel to postgres?

Is it possible to run a postgres query from excel and get the results in
excel?
Is it possible to run postgres query from latex and get the results in the
place of the query?

Server returned HTTP response code: 407

Server returned HTTP response code: 407

I am using WGet to access the content of few webpages as below:
String inputLine;
StringBuffer buffer = new StringBuffer();
System.setProperty("http.proxyHost", "myproxy.company.com");
System.setProperty("http.proxyPort", "8080");
System.setProperty("http.proxyUser", "username");
System.setProperty("http.proxyPassword", "password");
URL srcURL = new URL("http://www.example.com");
URLConnection connection = srcURL.openConnection();
connection.setConnectTimeout(60000);
connection.setReadTimeout(60000);
BufferedReader reader = new BufferedReader(new
InputStreamReader(connection.getInputStream()));
while ((inputLine = reader.readLine()) != null) {
buffer.append(inputLine + System.getProperty("line.separator").toString());
}
reader.close();
return (buffer.toString().length() > 0) ? buffer.toString() : "";
While executing this code in Ubuntu machine, I get the below error:
java.io.IOException: Server returned HTTP response code: 407 for URL:
http://www.example.com/
at
sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1459)
How to resolve this error?

Getting type of file request

Getting type of file request

I have this example code:
<img src="e.php"/>
<link href="e.php" rel="stylesheet"/>
<script src="e.php"></script>
There is a way to know if e.php is loaded on the window or if is called by
those document elements?

Sending mail using classic asp

Sending mail using classic asp

I am new for classic asp. I have written simple code to send mail using
classic asp as follows :
HTML Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<form method="post" action="ASPformEmailResults.asp">
<p><input type="submit" name="submit" value="Submit"/></p>
</form>
</body>
</html>
ASP page:
<%
Set myMail=CreateObject("CDO.Message")
myMail.Subject="Sending email with CDO"
myMail.From="a@gmail.com"
myMail.To="b@gmail.com"
myMail.TextBody="This is a message."
myMail.Send
set myMail=nothing
%>
<html>
<head>
<title>My First ASP Page</title>
</head>
<body bgcolor="white" text="black">
</body>
</html>
but whenever open html page & click on submit button then mail should sent
to given id but it displays asp page content. Please help me to solve this
problem.
Thank You.

Sunday, 25 August 2013

MKDIR 3 levels above using php

MKDIR 3 levels above using php

level1/level2/level3/CWD/mkdir.php
Name of Level1 is not known; is user specified & can be anything. Name of
level2 & level3 is known and will remain static. Current Working Directory
contains mkdir.php file that is required to create a directory in level1
with user provided name. The mkdir.php file below does the job, but don't
know whether it's the correct way. Want experts to approve and advice.
Thanks in advance.
<?php
if (isset($_POST['Name']))
{
$newdir = $_POST['Name'];
$dirname = "..\\$newdir";
$step1 = "..\\CWD";
$step2 = "..\\$step1";
$step3 = "..\\$step2\\$dirname";
if (mkdir($step3, 0777, true))
{
echo "dir created successfully";
}
else
{
echo "dir not created";
}
}
?>

Typekit with Wordpress loads Font Styles/Selectors but not font?

Typekit with Wordpress loads Font Styles/Selectors but not font?

I'm trying to get Typekit to activate for the font, Abril, on my Wordpress.
I have the code in my tag which they tell me to embed:
<script type="text/javascript" src="//use.typekit.net/gir7uqk.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
Here is the styling on Firebug:
http://prntscr.com/1ngbub
So the script is clearly activating, but the font is not loading, and the
stack reverts to serif.
Yes, everything is published. Is this just a problem with Typekit? I've
tried it with several other fonts to no avail.
Also tried it on a webpage on my local machine with the same results - so
it's not a Wordpress thing.
Any help is appreciated. Thank you.

Equation formatting\Alinging

Equation formatting\Alinging

According the question I have written the file but I got wrong somewhere.
Can you please check?
\documentclass{article}
\usepackage{amsmath}
\begin{document}
\begin{align}
&\begin{aligned}
& \ddot\phi_3&+\phi_3+2g_2p_1 \cos(\tau+\alpha)[p_2\cos(\tau + \alpha) +
q_2\sin(\tau + \alpha)\\
& + \frac{g_2}{6}p_1^2[\cos(2\tau + 2\alpha) -
3]]+g_3p^3_1\cos^3(\tau+\alpha)-\cos(\tau+\alpha) [-p_1 (\nabla
\alpha)^2+\Delta p_1]\\
&-\sin(\tau+\alpha) [p_1\Delta \alpha+2\nabla \alpha \nabla
p_1]\qquad+\omega_2p_1\cos(\tau+\alpha)=0
\end{aligned}\nonumber\\
&\begin{aligned}
& \ddot\phi_3&+\phi_3+g_2p_1 p_2 [1+\cos2(\tau+\alpha)] + g_2p_1
q_2\sin2(\tau+\alpha) \\
& + \frac{2 g_2^2 p_1^3}{6} \cos(\tau +\alpha)[2\cos^2(\tau+\alpha)-4] \\
& + g_3p_1^3[\frac{1}{4}(3\cos(\tau +\alpha)+\cos3(\tau+\alpha))]\\
& -\cos(\tau+\alpha)\left[\Delta p_1--p_1 (\nabla \alpha)^2\right] \\
& +\sin(\tau+\alpha)\left[p_1\Delta \alpha+2 \nabla p_1 \nabla
\alpha\right]\\
& + \omega_2p_1\cos(\tau+\alpha) =0
\end{aligned}\nonumber\\
&\begin{aligned}
& \ddot\phi_3&+\phi_3+g_2p_1 p_2 + g_2p_1 p_2 \cos2(\tau+\alpha)] +
g_2p_1 q_2\sin2(\tau+\alpha)\\
& + \frac{2 g_2^2 p_1^3}{3} \cos^3(\tau +\alpha)-\frac{8 g_2^2 p_1^3}{6}
\cos(\tau +\alpha) \\
& +g_3p_1^3[\frac{1}{4}(3\cos(\tau +\alpha)+\cos3(\tau+\alpha))]\\
& -\cos(\tau+\alpha)[\Delta p_1--p_1 (\nabla \alpha)^2] \\
& +\sin(\tau+\alpha)\left[p_1\Delta \alpha+2 \nabla p_1 \nabla
\alpha\right]+\omega_2p_1\cos(\tau+\alpha)=0
\end{aligned}\\
&\begin{aligned}
& \ddot\phi_3&+\phi_3+g_2p_1 p_2 + g_2p_1 p_2 \cos2(\tau+\alpha)] +
g_2p_1 q_2\sin2(\tau+\alpha) \\
& + \frac{2 g_2^2 p_1^3}{3}[\frac{1}{4}(3\cos(\tau
+\alpha)+cos3(\tau+\alpha))] -\frac{8 g_2^2 p_1^3}{6} \cos(\tau +\alpha)
\\
& +g_3p_1^3[\frac{1}{4}(3\cos(\tau +\alpha)+\cos3(\tau+\alpha))] \\
& -\cos(\tau+\alpha)[\Delta p_1-p_1 (\nabla \alpha)^2] \\
&+\sin(\tau+\alpha)[p_1\Delta \alpha+2 \nabla p_1 \nabla
\alpha]+\omega_2p_1\cos(\tau+\alpha)=0
\end{aligned} \\
&\begin{aligned}
&\ddot\phi_3&+\phi_3+\sin(\tau+\alpha)[p_1\Delta \alpha+2 \nabla p_1
\nabla \alpha] \\
& -\cos(\tau+ \alpha)\left[\Delta p_1 -p_1 (\nabla
\alpha)^2+\frac{5}{6}g_2^2p_1^3- \frac{3}{4}g_3p_1^3-p_1 +\omega_2
p_1\right] \\
& +\frac{ p_1^3}{12}(2g_2^2+3g_3)\cos3(\tau + \alpha) \\
& +g_2 p_1 [p_2+ p_2 \cos2(\tau +\alpha)+q_2 \sin2(\tau+\alpha)] =0
\end{aligned}\nonumber\\
&\begin{aligned}\label{eq10}
& \ddot\phi_3&+\phi_3+\sin(\tau+\alpha)[p_1\Delta \alpha+2 \nabla p_1
\nabla \alpha] \\
& -\cos(\tau+ \alpha)[\Delta p_1-p_1 (\nabla \alpha)^2 + \lambda
p_1^3-p_1+\omega_2 p_1] \\
& +\frac{p_1^3}{12}(2g_2^2+3g_3)\cos3(\tau + \alpha) \\
& +g_2 p_1 [p_2+ p_2 \cos2(\tau +\alpha)+q_2 \sin2(\tau+\alpha)]=0
\end{aligned}
\end{align}
\end{document}

[ Singles & Dating ] Open Question : why he ask if i am dating now?

[ Singles & Dating ] Open Question : why he ask if i am dating now?

he told me he wants to be friends and we broke up mutually because he
doesnt have feeling for me all along. he said we are now at friends phase
and there is no need to define friendship as i can just wait and see. i
rejected his friendship once and now just talked with him because he kept
texting. but i never say i am friends with him. so why he wants to be
friends? and he told me he has feelings for a few but can be suppressed as
he wants to focus on studies now and not want to be into a relationship. I
dont want to get back together with him, however why he still saying these
to me and wants us to be friends?how would he respond to my no response as
i blocked him on facebook and he texted just now asking why my profile
disappear?why he want to be my friend still? what to do with him?because
these two days he texted again asking if i am around and also he asked
today if i am very busy to return his text.So i ended up replying on this
weekend, asking him what's up. however the next day he replied and expect
me to answer him, asking me if i am still busy even on weekends. I was out
with my friends today, so should i continue to reply?why he seem to want
to talk to me everyday?? Also he asked just now if I do check the texts on
my phone Also, he asked if i am seeing anyone now. why he asked?

Logging insertion to Database on Android

Logging insertion to Database on Android

I'm currently needing to log the insertions/updates/deletes from my
database but i don't get what i can call a great result.
I've just implemented SQLiteDatabase.CursorFactory but that is just for
queries, and not data modification.
What i've done so far is to simply log what i am inserting calling a
function that receives the parameters and the table ta it will insert.
I have a general function inside SQLiteOpenHelper to insert:
public void insertToTable(ContentValues cv, String table){
status = dBase.insert(table,null,cv);
if(status != -1){
logInsert(cv,table);
}
}
public void logInsert(ContentValues cv, String tabela) {
StringBuilder raw = new StringBuilder();
Set<String> keys = cv.keySet();
String[] columns = keys.toArray(new String[keys.size()]);
int i;
raw.append("INSERT INTO " + tabela + "(");
for (i = 0; i < columns.length-1; i++) {
raw.append(columns[i] + ",");
}
raw.append(columns[i] + ") VALUES(");
for (i = 0; i < cv.size()-1; i++) {
raw.append("'" + cv.get(columns[i]) + "',");
}
raw.append("'" + cv.get(columns[i]) + "');");
Log.v("SQL",raw.toString());
}
This is working pretty well but don't think is the best way to do as i am
iterating over the same ContentValues three times (one time to insert and
other two just for logging).
What can i do to improve it? There's a good way to fit this also to
update/delete ?
Thanks in advance!

Saturday, 24 August 2013

Calling Jquery function from .Net, with parameters

Calling Jquery function from .Net, with parameters

I have a .Net method which does some validation on an object, and then, I
need to display the issues to the user.
I am trying to use a jquery message box I found:
The jquery function:
function ShowPopup() {
$.msgBox({
title: "Unable to save",
content: "An error has occured while saving the object."
});
}
I need to call that from a .Net method, passing it a List of strings. Is
that possible? And then set the content property to be the list of errors?
My .Net saving method, which may trigger this popup, looks like this:
protected void btnSave_Click(object sender, EventArgs e)
{
var o = new UserDto
{
DisplayName = txtName.Text,
Email = txtEmail.Text,
Username = txtUsername.Text,
Password = txtPassword.Text,
TimeZoneId = ddZones.SelectedValue,
Id = Session["SelectedUserId"] == null ? 0 :
int.Parse(Session["SelectedUserId"].ToString())
};
var result = new UserService(Common.CurrentUserId()).SaveUser(o);
if (result.Success == false)
{
// Show an error.
return;
}
Response.Redirect("users.aspx");
}
If, if success is false, I want to pass it a list of errors, and show that
popup.
The jquery function is from here.

How to use xcasset

How to use xcasset

I started developing for ios 7 with xcode 5 and I want to use xcassets for
my images. The problem is, when I try to set the image for my
navigationBar it doesnt work. I tried the folowing :
[self.navigationController.navigationBar setBackgroundImage:[UIImage
imageNamed:@"navigationBar.png"] forBarMetrics:UIBarMetricsDefault]; but
it didnt set it to anything. What is the method for setting images with
xcassets?

What are the consequences of omitting @autoreleasepool { } in main()?

What are the consequences of omitting @autoreleasepool { } in main()?

What are the practical consequences of omitting @autoreleasepool { ... }
in main() of a command line program?
These two pieces of code compile and seem to work equivalently:
1.
int main(int argc, const char * argv[])
{
@autoreleasepool {
NSLog(@"Hello, World!");
}
return 0;
}
2.
int main(int argc, const char * argv[])
{
NSLog(@"Hello, World!");
return 0;
}
I suspect that the theoretical consequences are that the second version
can leak memory. I want to know why.

code for how to send username and password to their email in ios after registering account

code for how to send username and password to their email in ios after
registering account

IN .xib file i will have
First Name :----------- Last Name :------------ email id :------------
pincode :------------
-----------------
register button
-----------------
After clicking registration button the user name and password should be
send to the given email id in the form.
I need code for this please.

Best way to implement Kleen star (closure) operation in C or C++?

Best way to implement Kleen star (closure) operation in C or C++?

Assume that I have a string "AAAB" and a pattern "A*B". How do I check
that the string matches with pattern?

Friday, 23 August 2013

Using PhantomJS in webdriver, what are ways to improve navigation in sites using JavaScript templates?

Using PhantomJS in webdriver, what are ways to improve navigation in sites
using JavaScript templates?

To start off with the simplest example, I have a Python script that uses
selenium/webdriver and includes Ghost Driver/PhantomJS() as it's
webdriver.
from selenium import webdriver
driver = webdriver.PhantomJS()
driver.get("http://shaneofalltrades.com")
driver.find_element_by_id("navbar-contact").click()
print driver.current_url
driver.quit
I opted to test in this site as it is using JavaScript templating to
create new pages and happens to do the funky stuff I get errors in when
scraping other similar sites. This is my site, so I can add anything to
help debug if any ideas. So far I can use this script on some other sites
and I can process the test on shaneofalltrades using Firefox...
driver = webdriver.Firefox()
Am I missing something about using a headless webdriver or is it always
going to be more difficult? Also, because it is "headless", I take it many
UI features are missing, so maybe I need specific selectors?
The reason I would rather use phantom.js over Firefox is the speed.

ng-repeat does not seem to rebind ng-click on a re-rendering

ng-repeat does not seem to rebind ng-click on a re-rendering

I have an ng-repeat assigned to a row in a table as shown below. When the
user selects a down arrow in the row, the method moveDown gets executed,
which reorders the list (see code).
When I look at the DOM, everything looks right - The rows are reordered,
and the ng-click sees the newly assigned seqNbr.
Better explanation:
Initially first row shows data-ng-click='moveDown(0);' second
data-ng-click='moveDown(1);'
After selecting the first one, the first and second row trade places. The
seqNbr are swapped in the objects and list is reordered, then the
ng-repeate is reexecuted.
Now the DOM shows that the NEW first row has: data-ng-click='moveDown(0);'
and the old first row, now the second row, has
data-ng-click='moveDown(1);'
However if I select the new first row, what gets executed is moveDown(1)
(the old method associated with that row). Its as if the DOM is updated,
but not the method binding.
HTML:
<tr class='evidencerow' data-ng-repeat="e in data.evidence">
<td><div class='assertion webdiv' style='height:4em;'
data-ng-dblclick='openReference(e);'>
<span data-ng-bind-html-unsafe='e.assertion'></span>
</div>
</td>
<td>
<img src='img/UpArrow16x16.png' data-ng-hide='$first'
data-ng-click='moveUp({{e.seqNbr}});'
style='width:32px;'>
<img src='img/DownArrow16x16.png' data-ng-hide='$last'
data-ng-click='moveDown({{e.seqNbr}});'
style='width:32px;'>
</td>
</tr>
controller code:
$scope.moveUp = function(seq) {
var recs = $scope.data.evidence.slice(0);
recs[seq].seqNbr = seq - 1;
if (_ev.notEmpty(recs[seq - 1])) {
var s2 = seq - 1;
recs[s2].seqNbr = seq;
}
recs.sort(_ev.compareSeqNbr);
$scope.data.evidence = recs;
};
$scope.moveDown = function(seq) {
var recs = $scope.data.evidence.slice(0);
recs[seq].seqNbr = seq + 1;
if (_ev.notEmpty(recs[seq + 1])) {
var s2 = seq +1;
recs[s2].seqNbr = seq;
}
recs.sort(_ev.compareSeqNbr);
$scope.data.evidence = recs;
};
This behavior doesn't seem right to me. The result is instead of the rows
moving up and down, they toggle back and forth.

Unexpected results when casting dword to byte [4] (endianity swap?)

Unexpected results when casting dword to byte [4] (endianity swap?)

Im trying to cast a dword into an array of 4 bytes. When i do this, the
bytes seem to flip around (change endianness)
As i understand it a dword equaling 0x11223344 on little endian systems
will look like this:
0000_1011___0001_0110___0010_0001____0010_1100
but when i do this:

typedef unsigned long dword;
typedef unsigned char byte;
int main(void)
{
dword a = 0x11223344;
byte b[4];
memcpy(b, &a, 4);
printf("%x %x %x %x\n", b[0], b[1], b[2], b[3]);
}
I get 44 33 22 11.
I expected it to be 11 22 33 44.

The same thing happens when i use reinterpret_cast or
union
{
dword a;
byte b[4];
} foo;
Im guessing Im wrong and not the compiler/processor, but what am i missing
here? Also how would this look on a big endian system?

Sending information to a library

Sending information to a library

I'm working with OSMF, the StrobeMediaPlayback and FlashBuilder/Eclipse.
I have a variable that I've captured from a flashvar, and stored in a
singleton class. I want it to be accessible to another package that I'm
using as a library for this project.
I can't import the class directly, because it would cause a cycle, nor can
I seem to access it with a static reference, because it's in a different
package.
How can I do this?



Here's what I want to send:
StrobeMediaPlayback > src > SessionFlashVars.as
Here's where I want to send it:
OSMF > org.osmf > net > NetNegotiator.as

Expense and Balance Mismatch

Expense and Balance Mismatch

I searched and couldn't find a post in stack exchange for this. I recently
saw a calculation for rupee spend and having balance in yahoo, but i am
not quiet convinced with the answer given...
the question goes like this....
If i have 50 Rupees
Spend -- Balance
0---------50
20--------30
15--------15
9---------6
6---------0
If we see the sum of amount spend it gives 50 Rupees.
But if we calculate the balance amount (30+15+6) it gives 51 rupee instead
of 50 rupees.
How could this be possible....
If this question is mentioned somewhere else in this forum please refer
that too...

Wish + tense agreement + subordinate clause

Wish + tense agreement + subordinate clause

I wish I knew what he did/does for a living
I wish I knew what he had/has bought her
I wish I knew what he would/will do in this case



I wish I'd known what he had done for a living
I wish I'd known what he did for a living
I wish I'd known what he would do in this case
Are they correct and what the situations are like when hear them?

Thursday, 22 August 2013

Mongodb Emulator to simulate real nosql transactions

Mongodb Emulator to simulate real nosql transactions

I'm trying to develop and application a "database builder" or a designer
that will enable the users to experiment on using mongodb as well as
produce them json databases.
Question is:
I wanted to do this because of I am afraid that the users of the
application will have actual interaction on the database and let them do
what they want, am I right on this one, is providing the user real mongodb
interaction will have security risk?
Are there javascript libraries to do what I wanted?

Ruby: Can I get an instance by its ID?

Ruby: Can I get an instance by its ID?

In Ruby, if I have the ID of an object instance as a string, such as
"#<Meeting:0x4531860>", can I get the instance its self by this ID?
# what I want
meeting = SOME_MAGIC_HERE "#<Meeting:0x4531860>"
# and then I can handle the meeting itself
meeting.name # => 'BLABLABLA'

How do I access flashvars if I can't access the stage?

How do I access flashvars if I can't access the stage?

How do I access flashvars if I can't access the stage?
I'm fiddling with the Open Source Media Framework's Strobe Media Playback
player, and I'm trying to take a flashvar and put it in the package
org.osmf.net.NetNegotiator.
But the netNegotiator class can't access the stage, so I can't do
stage.loaderInfo.parameters to get the flashvar.



Alternately, I can get the flashvar from StrobeMediaPlayback.as, but I
can't figure out how to send it over there.
I've tried to import the package in the StrobeMediaPlayback.as, but not
only does NetNegotiator show up on the predictive typing thing, I get an
undefined error when I try to use it.

How to add elements in List when used Arrays.asList()

How to add elements in List when used Arrays.asList()

We cannot perform <Collection>.add or <Collection>.addAll operation on
collections we have obtained from Arrays.asList .. only remove operation
is permitted.
So What if I come across a scenario where I require to add new Element in
List without deleting previous elements in List?. How can I achieve this?

gradle building: class, interface, or enum expected

gradle building: class, interface, or enum expected

I need to build apk file by using Gradle. Here's build.gradle code:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.5+'
}
}
apply plugin: 'android'
dependencies {
compile files('libs/android-support-v4.jar')
}
android {
buildToolsVersion "17.0"
compileSdkVersion 10
testBuildType = "debug"
defaultConfig {
versionCode = 1
versionName = "0.1"
minSdkVersion = 9
targetSdkVersion = 10
buildConfig "private final static boolean DEFAULT = true;", \
"private final static String FOO = \"foo\";"
}
buildTypes {
debug {
packageNameSuffix = ".debug"
buildConfig "private final static boolean DEBUG2 = false;"
}
}
aaptOptions {
noCompress "txt"
}
sourceSets {
main {
manifest {
srcFile 'AndroidManifest.xml'
}
java {
srcDir 'src'
}
res {
srcDir 'res'
}
assets {
srcDir 'assets'
}
resources {
srcDir 'src'
}
}
}
}
And here's class code:
final package com.tecomgroup.handifox.bin;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuInflater;
import android.view.View;
import android.widget.AdapterView;
import com.tecomgroup.handifox.ActivityHandifox;
import com.tecomgroup.handifox.Datastore;
import com.tecomgroup.handifox.GeneralFunc;
import com.tecomgroup.handifox.R;
public abstract class BinEditWindow extends ActivityHandifox {
public static Datastore idw_items;
public static Datastore ids_id_changed_items;
public static Datastore dw_bin;
protected final List<String> deletedItems = new LinkedList<String>();
protected void deleteItem(final String idColumnName) {
if (DS.Rowcount() > 1) {
if (!GeneralFunc.Empty(DS.get(DS.CurrentRow, "Parent"))) {
removeItem(idColumnName);
} else {
removeItem(idColumnName);
setParentForItems(chooseNewParentAndGetLineId());
}
}
}
public abstract String getItemLineId(final int row);
private String chooseNewParentAndGetLineId() {
DS.set(0, "Parent", "");
return getItemLineId(0);
}
private void removeItem(final String idColumnName) {
final String listId = DS.get(DS.CurrentRow, idColumnName);
deletedItems.add(listId);
DS.DeleteRow(DS.CurrentRow);
ib_changed = true;
}
private void setParentForItems(final String lineId) {
final int rowCount = DS.RowCount();
for (int row = 0; row < rowCount; row++) {
if (!GeneralFunc.Empty(DS.get(row, "Parent"))) {
DS.set(row, "Parent", lineId);
}
}
}
@Override
protected boolean onPostCreate() {
deletedItems.clear();
return super.onPostCreate();
}
@Override
protected void onPause() {
super.onPause();
if (isFinishing()) {
removeStaticDatastores();
}
}
@Override
protected void onDestroy() {
removeStaticDatastores();
super.onDestroy();
}
protected void removeStaticDatastores() {
idw_items = null;
ids_id_changed_items = null;
dw_bin = null;
}
@Override
public void onCreateContextMenu(final ContextMenu menu, final View v,
final ContextMenuInfo menuInfo) {
clearFocusEditText();
final AdapterView.AdapterContextMenuInfo info =
(AdapterView.AdapterContextMenuInfo) menuInfo;
if (info.position != DS.CurrentRow) {
DS.isClicked = true;
DS.ScrolltoRow(info.position);
}
final MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.salesreceipt_edit_menu, menu);
menu.getItem(1).setVisible(DS.RowCount() > 1);
super.onCreateContextMenu(menu, v, menuInfo);
}
protected ArrayList<String> getParentRow() {
ArrayList<String> result = null;
final int rowCount = DS.RowCount();
for (int row = 0; row < rowCount; row++) {
if (GeneralFunc.Empty(DS.get(DS.CurrentRow, "Parent"))) {
result = DS.getRow(row);
break;
}
}
return result;
}
protected void removeDeletedItems(final Datastore removeItemsFrom,
final String idColumnName) {
for (final String deletedItemId : deletedItems) {
final int deletedRowIndex =
removeItemsFrom.Find(idColumnName,
deletedItemId, "equal", false);
if (deletedRowIndex >= 0) {
removeItemsFrom.DeleteRow(deletedRowIndex);
}
}
}
}
While building i get the following error:
...src\com\tecomgroup\handifox\bin\BinEditWindow.java :1: error: class,
interface, or enum expected final package com.tecomgroup.handifox.bin;
Where was I wrong?

How can i if function with value?

How can i if function with value?

My function
function Random() {
var length = 6,
charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
retVal = "";
for (var i = 0, n = charset.length; i < length; ++i) {
retVal += charset.charAt(Math.floor(Math.random() * n));
}
return retVal;
}
I want like this if but does not work I want to make them equal but i
couldn't thanks
$('#rand').bind('keypress keyup change', function () {
if ($(this).val() !== Random()) { //etc }
});

generate SOAP classes for iPhone from WSDL

generate SOAP classes for iPhone from WSDL

in my application I need to communicate with server and I have an WSDL
file, how can I generate SOAP classes for iPhone?

Wednesday, 21 August 2013

Error when enterting this command ALTER TABLE `report` AUTO_INCREMENT = 1

Error when enterting this command ALTER TABLE `report` AUTO_INCREMENT = 1

I get an error when using this command to alter my SQL table
Error message: #1064 - You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right syntax
to use near 'ALTER TABLEreportAUTO_INCREMENT = 1, 30' at line 2 Any idea
of that?

Hey guys, i'm new to javascript I hope you can help me out

Hey guys, i'm new to javascript I hope you can help me out

I looked up to google on this one but no luck I hope you can help me out,
I got no codes to present here or something I just would like to ask what
is the use of Calc.Input.value function in JavaScript? I'm kinda confused
of what's the use of that one. Thank you in advance guys! Much love :))

When overriding Object.Equals, is it appropriate to use the passed in object's Equals(MyType)?

When overriding Object.Equals, is it appropriate to use the passed in
object's Equals(MyType)?

For a simple example, assume you have two classes that are different in
many ways, but can still be considered "equateable":
class WholeNumber: IEquatable<WholeNumber> {
int value;
public override bool Equals(object obj) {
if (obj is IEquatable<WholeNumber>) {
IEquatable<WholeNumber> other = (IEquatable<WholeNumber>) obj;
return other.Equals(this);
} else {
return false;
}
}
public bool Equals(WholeNumber other) {
return this.value == other.value;
}
}
class Fraction : IEquateable<WholeNumber > {
WholeNumber numerator;
WholeNumber denominator;
public bool Equals(WholeNumber other) {
if (denominator != 1) {
// Assume fraction is already reduced
return false;
} else {
return this.numerator.Equals(other);
}
}
}
This will allow any object that claims to be equateable to WholeNumber to
be passed into the WholeNumber's Equals(object) function and get the
desired result without WholeNumber needed to know about any other class.
Is this pattern a good idea? Is using IEquatable with other classes a
common (where it makes sence) thing to do?

Reading xml from rss feed

Reading xml from rss feed

package com.example.nasadailyimage;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.ImageView;
import android.widget.TextView;
public class NasaDailyImage extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nasa_daily_image);
IotdHandler handler = new IotdHandler();
System.out.println("handler object created");
Log.d("NasaDailyImage","handler object created");
new ConfigParser().execute();//here i have called execute on my
AsyncTaskclass
// handler.processFeed();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is
present.
getMenuInflater().inflate(R.menu.nasa_daily_image, menu);
return true;
}
}
and my ConfigParser class
import java.io.InputStream;
import java.net.URL;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.os.AsyncTask;
import android.util.Log;
public class ConfigParser extends AsyncTask<Void, Void,Void > {
private String url="http://www.nasa.gov/rss/dyn/image_of_the_day.rss";
@Override
protected Void doInBackground(Void... params) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader reader = parser.getXMLReader();
IotdHandler handler=new IotdHandler();
reader.setContentHandler(handler);
InputStream inputStream = new URL(url).openStream();
reader.parse(new InputSource(inputStream));
}
catch (Exception e)
{
Log.d("IotdHandler", "Exception");
e.printStackTrace();
}
return null;
}
}
and my IotdHandler Class
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
public class IotdHandler extends DefaultHandler {
private String url="http://www.nasa.gov/rss/dyn/image_of_the_day.rss";
private boolean inUrl = false;
private boolean inTitle = false;
private boolean inDescription = false;
private boolean inItem = false;
private boolean inDate = false;
private Bitmap image = null;
private String title = null;
private StringBuffer description = new StringBuffer();
private String date = null;
private String imageUrl;
private Bitmap getBitmap(String url) {
try {
HttpURLConnection connection = (HttpURLConnection)new
URL(url).openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(input);
input.close();
return bitmap;
}
catch (IOException ioe)
{ ioe.printStackTrace(); }
return null;
}
public void startElement(String uri, String localName, String
qName,Attributes attributes) throws SAXException {
if (localName.equals("enclosure"))
{ inUrl = true;
imageUrl=attributes.getValue("url");
System.out.println(imageUrl);
}
else { inUrl = false; }
if (localName.startsWith("item"))
{ inItem = true; }
else if (inItem) {
if (localName.equals("title"))
{ inTitle = true;
System.out.println("invtitle");}
else { inTitle = false; }
if (localName.equals("description"))
{ inDescription = true;
System.out.println("indiscription");}
else { inDescription = false; }
if (localName.equals("pubDate"))
{ inDate = true;
System.out.println("dtae");}
else { inDate = false; }
}
}
public void characters(char ch[], int start, int length) {
String chars = new String(ch).substring(start, start + length);
if (inUrl && url == null) { image = getBitmap(imageUrl); }
if (inTitle && title == null) { title = chars; }
if (inDescription) { description.append(chars); }
if (inDate && date == null) { date = chars; }
}
public Bitmap getImage() { return image; }
public String getTitle() { return title; }
public StringBuffer getDescription() { return description; }
public String getDate() { return date; }
}
So basically I want to get daily image updates from NASA, but in my
program everything is returning null I don't know what I am trying wrong,
my xml file is not parsing to avoid the NetworkOnMainTHread I have also
used Async class, any help.

Regex for matching anything after particular directory

Regex for matching anything after particular directory

I have a page set up on my wordpress install called /forum.
I want anything that comes after forum e.g. /forum/login.asp?helloworld=hi
etc to be put as a query string to forum so it goes to the forum page and
I can obtain this 'login.asp?helloworld=hi' as a variable.
I've created a rule on my IIS server which is above the default wordpress
rule.
I used this regex:
/forum/(.*)$
to rewrite to this /forum/?test={R:1}
and made it so it stops processing any other rules if we get a match.
All I seem to get is the Wordpress 404 page. Im absolutely useless at
redirects/rewrites/regex etc so any help would be awesome!

how to modify date format in wordpress list comments

how to modify date format in wordpress list comments

I want to modify my comments list detail date showing replay button and
etc in my wordpress theme i saw this code and i use it but i need to
modify the date format and the lable and titles and etc i use this code
<?php /*----------------------------------- Template for Comments
---------------------------------------*/ ?>
<div id="comments">
<?php if ( post_password_required() ) : ?>
<p class="text-error"><?php _e( 'This post is password protected.
Enter the password to view any comments.', 'cusmagazines' ); ?></p>
</div>
<?php
return;
endif;
?>
<?php if ( have_comments() ) : ?>
<h2 id="comments-title">
<?php
printf( _n( 'One Comment', '%1$s Comments',
get_comments_number(), 'cusmagazines' ), number_format_i18n(
get_comments_number() ) );
?>
<a class="goto goto-respond" href="#respond" title="Add Your
Comment">( Add Comment )</a>
</h2>
<?php if ( get_comment_pages_count() > 1 && get_option(
'page_comments' ) ) : ?>
<div id="comment-nav-above">
<h1 class="assistive-text"><?php _e( 'Comment navigation',
'cusmagazines' ); ?></h1>
<div class="nav-previous"><?php previous_comments_link( __(
'&larr; Older Comments', 'cusmagazines' ) ); ?></div>
<div class="nav-next"><?php next_comments_link( __( 'Newer
Comments &rarr;', 'cusmagazines' ) ); ?></div>
</div>
<?php endif; ?>
<div class="commentlist">
<?php
$args = array(
'walker' => null,
'max_depth' => 3,
'style' => 'div',
'callback' => 'custhemes_comment',
'end-callback' => null,
'type' => 'all',
'page' => null,
'per_page' => null,
'avatar_size' => 45,
'reverse_top_level' => null,
'reverse_children' => null );
wp_list_comments($args);
?>
</div>
<?php if ( get_comment_pages_count() > 1 && get_option(
'page_comments' ) ) : ?>
<div id="comment-nav-below">
<h1 class="assistive-text"><?php _e( 'Comment navigation',
'cusmagazines' ); ?></h1>
<div class="nav-previous"><?php previous_comments_link( __(
'&larr; Older Comments', 'cusmagazines' ) ); ?></div>
<div class="nav-next"><?php next_comments_link( __( 'Newer
Comments &rarr;', 'cusmagazines' ) ); ?></div>
</div>
<?php endif; ?>
<?php
elseif ( ! comments_open() && ! is_page() && post_type_supports(
get_post_type(), 'comments' ) ) :
?>
<p class="nocomments"><?php _e( 'Comments are closed.', 'cusmagazines'
); ?></p>
<?php endif; ?>
and i add this code to function.php
<?php function custhemes_comment($comment, $args, $depth) {
$GLOBALS['comment'] = $comment;
extract($args, EXTR_SKIP);
if ( 'div' == $args['style'] ) {
$tag = 'div';
$add_below = 'comment';
} else {
$tag = 'li';
$add_below = 'div-comment';
}
?>
<<?php echo $tag ?> <?php comment_class(empty( $args['has_children'] )
? '' : 'parent') ?> id="comment-<?php comment_ID() ?>">
<?php if ( 'div' != $args['style'] ) : ?>
<div id="div-comment-<?php comment_ID() ?>" class="comment-body">
<?php endif; ?>
<div class="comment-author vcard">
<?php if ($args['avatar_size'] != 0) echo get_avatar( $comment,
$args['avatar_size'] ); ?>
</div>
<?php if ($comment->comment_approved == '0') : ?>
<em class="comment-awaiting-moderation"><?php _e('Your comment is
awaiting moderation.') ?></em>
<br />
<?php endif; ?>
<div class="comment-meta commentmetadata">
<?php printf(__('<span class="author-name">%s</span>'),
get_comment_author_link()); ?>
<a href="<?php echo htmlspecialchars( get_comment_link(
$comment->comment_ID ) ) ?>">
<?php printf( __('%1$s - %2$s'), get_comment_date('d.m.Y'),
get_comment_time()); ?>
</a>
<?php edit_comment_link(__('(Edit)'),' ','' );
?>
</div>
<div class="comment-text"><?php comment_text(); ?></div>
<div class="reply">
<?php comment_reply_link(array_merge( $args, array('add_below' =>
$add_below, 'depth' => $depth, 'max_depth' =>
$args['max_depth']))) ?>
</div>
<?php if ( 'div' != $args['style'] ) : ?>
</div>
<?php endif; ?>
<?php } ?>
now i need to modify date format and the lable of the comments how can i
do that

Tuesday, 20 August 2013

how to use variable with the String in Python

how to use variable with the String in Python

I want to include file name 'main.txt' in the subject for that I am
passing file name from command line. but getting error in doing so
python sample.py main.txt #running python with argument
msg['Subject'] = "Auto Hella Restart Report "sys.argv[1] #line where i am
using that passed argument

How can I let my clients subdomain my Ruby On Rails / Heroku app?

How can I let my clients subdomain my Ruby On Rails / Heroku app?

I have an app that I want my clients to be able to subdomain. Right now it
works like this
www.mydomain.com/clientname/
www.mydomain.com/clientname/page1
www.mydomain.com/clientname/page2
How can I structure the app so that my clients can subdomain it like:
dashboard.client1.com -> www.mydomain.com/clientname/
dashboard.client1.com/page1 -> www.mydomain.com/clientname/page1
etc
Can I use wildcard subdomains?
I can't figure out the terminology for what I want to do, but any
references you can provide would be helpful!

Efficient strategy to creative a UIView which is the size of device's screen

Efficient strategy to creative a UIView which is the size of device's screen

Context
I'm creating a UIView to act as the "container view" (let's call it
containerView) for a UIScrollView, this UIScrollView will then house a
UIWebView. See this question for more context. Matching subview's width to
it's superview using autolayout
Goal
Have the containerView, when created, be "full screen", i.e. take up the
whole screen. I can then tie the containerView's size, through auto-layout
constraints to the UIWebView and make the UIWebView, be full width of the
screen.
Questions
What is the best strategy for this? Using [[UIScreen mainScreen]
applicationFrame];

Refactoring fat controllers and handling validation and logging in the service layer

Refactoring fat controllers and handling validation and logging in the
service layer

I currently have an application which suffers from Fat Controllers. I am
trying to pull out the business logic into a service layer and am hoping
to clarify my approach.
For raising Model errors I had planned on using an approach like described
here:
http://www.asp.net/mvc/tutorials/older-versions/models-%28data%29/validating-with-a-service-layer-cs
- about 1/2 of the way down using the IValidationDictionary approach.
But I see this approach is not discussed in newer versions of the
documentation. The validation in the service layer section is completely
removed in the newer versions.
I hope that is enough context for the following questions / validation of
my approach:
I believe that the approach in the link above is outdated and should not
be used in favor of DataAnnotations (and overriding possibly overriding
IsValid - this may be naive, I don't fully understand the workflow of
validating the ModelState.IsValid yet). Am I understanding correctly or
are these somewhat separate concerns?
I would expect to have a mix of strongly typed views to both Entities (on
simple forms that have a 1-1 mapping of fields to the entity) and DTO's
(on forms with a less simple mapping to entities). Is it possible to have
the entity validations bubble up to the DTO's to avoid duplicating
non-business requirement validations? On entity's which could be strongly
typed without a DTO should I be including business logic validations on
the entity (this seems wrong)? Am I even thinking about/approaching this
correctly?
The site is using a repository approach - can I skip the service layer and
have my business logic spread across data annotations and the repository?
Again am I asking the right question?

JSF Backing Component - Composite Component - Stackoverflow Exception

JSF Backing Component - Composite Component - Stackoverflow Exception

I want to use a backing component as a layer for accessing the attributes
of my composite component (as defined in its interface). What I wanted to
achieve was reading the attributes of my componentent via my backing
component class where i give back the property value of the attribute
provided.
public String getName() {
if (this.name == null) {
this.name = getAttributes().get("name");
}
return this.name;
}
But when setting a new value e.g. via an input field I wanted to store the
value only within my backing bean properties not updating the values of
the original properties passed as attribute arguments to my composite
component.
public void setName(final String name) {
this.name = name;
}
My problem now is when the getter of my backing component is called the
first time or at some early stage of his life the code of the getter as
shown above results in a Stackoverflow exception as
getAttributes.get("name") calls the getter of my backing component
(itself) instead fetching the property/attribute provided to my composite
component. Fun part is using a simple getter only returning this.name
instead of calling getAttributes() I can set a breakpoint there and then
calling getAttributes.get("name") gives me not this.name but instead the
attribute provided to my composite component.
I guess it has something to do with the coupling betweend the backing
component and the composite component. That when the getter gets called
for the first time no coupling between them is given and therefor the call
of getAttributes.get("name") results in calling the getter of my backing
component whereas later the call does not invoke its own getter but
instead fetches the attribute provided to my comp component.
Anyone have any idea how to solve this issue? Thnx in advance.

Using an IF() based on a query result

Using an IF() based on a query result

I'm trying to use an IF() is mySQL where the structure looks something
like this:
if(
phone_number LIKE '%992%' (SELECT phone_number FROM db.phonebook WHERE
country='UK'),
SELECT xxx FROM xxx WHERE xxx,
SELECT xxx FROM xxx WHERE xxx
)
I'm trying to achieve:
IF (if you manage to find a phone number in the 'UK' phonebook that
looks like '992'),
THEN (run the following XXX query),
ELSE (run the following YYY query)
This doesn't work, the syntax is obviously wrong. Would appreciate you
advice.

Form does not submit any params

Form does not submit any params

Form does not submit any parameters. How can I fix it?
<form action="{{ path('search') }}" method="POST">
<div class="block-17">
<div class="block-17_1">
Êàòàëîã àâòîìîáèëåé
</div>
<div class="block-17_2">
<div class="block-17_2_1">
<span>Ïîèñê àâòîìîáèëåé</span>
<a href="">Ñðàâíèòü àâòîìîáèëè</a>
</div>
<div class="block-17_2_2">
<div>
<span class="block-17_2-name">Ìàðêà</span>
<div class="block-17_select-v1">
<select>
<option value="">Ëþáàÿ</option>
{% for manufacturer in manufacturers %}
<option value="{{ manufacturer.manufacturer }}">{{
manufacturer.manufacturer }}</option>
{% endfor %}
</select>
</div>
</div>
<div>
<span class="block-17_2-name">Ìîäåëü</span>
<div class="block-17_select-v1">
<select style="width: 100px">
<option value="">Ëþáàÿ</option>
</select>
</div>
</div>
<div>
<span class="block-17_2-name">Öåíà (ðóá.)</span>
<div class="block-17_select-v2_outer">
<div class="block-17_select-v2">
<select>
{% for value in [500, 1000, 2000, 3000, 4000,
5000, 6000, 7000, 8000, 9000, 10000, 15000, 20000,
25000, 50000, 100000, 200000] %}
<option value="{{ value }}">{{ value }}</option>
{% endfor %}
</select>
</div>
<div class="block-17_2-tire">
-
</div>
<div class="block-17_select-v2">
<select >
{% for value in [500, 1000, 2000, 3000, 4000,
5000, 6000, 7000, 8000, 9000, 10000, 15000, 20000,
25000, 50000, 100000, 200000] %}
<option value="{{ value }}">{{ value }}</option>
{% endfor %}
</select>
</div>
<div class="clearboth">
</div>
</div>
</div>
<div class="clearboth">
</div>
</div>
<div class="clearboth">
</div>
</div>
<div class="block-17_3" id="block-17_3" style="overflow: hidden;">
<div class="block-17-hide">
<div class="block-17_3_1">
<span class="block-17_2-name">Îáúåì äâèãàòåëÿ (ë.)</span>
<div class="block-17_select-v2_outer">
<div class="block-17_select-v2">
<select>
{% for value in [0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4,
5, 6, 7] %}
<option value="{{ value }}">{{ value }}</option>
{% endfor %}
</select>
</div>
<div class="block-17_2-tire">-</div>
<div class="block-17_select-v2">
<select>
{% for value in [0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4,
5, 6, 7] %}
<option value="{{ value }}">{{ value }}</option>
{% endfor %}
</select>
</div>
<div class="clearboth">
</div>
</div>
</div>
<div class="block-17_3_1">
<span class="block-17_2-name">Ìîùíîñòü äâèãàòåëÿ (ë. ñ.)</span>
<div class="block-17_select-v2_outer">
<div class="block-17_select-v2">
<select>
{% for value in [50, 100, 150, 200, 250, 300, 400,
500, 600, 700] %}
<option value="{{ value }}">{{ value }}</option>
{% endfor %}
</select>
</div>
<div class="block-17_2-tire">-</div>
<div class="block-17_select-v2">
<select>
{% for value in [50, 100, 150, 200, 250, 300, 400,
500, 600, 700] %}
<option value="{{ value }}">{{ value }}</option>
{% endfor %}
</select>
</div>
<div class="clearboth">
</div>
</div>
</div>
<div class="block-17_3_1">
<span class="block-17_2-name">Êîðîáêà ïåðåäà÷</span>
<div class="block-17_select-v2_outer">
<div class="block-17_select-v2">
<select>
{% for transmission in transmissions %}
<option value="{{ transmission.transmission
}}">{{ transmission.transmission }}</option>
{% endfor %}
</select>
</div>
</div>
</div>
<div class="block-17_3_1">
<span class="block-17_2-name">Òèï äâèãàòåëÿ</span>
<div class="block-17_select-v2_outer">
<div class="block-17_select-v2">
<select>
{% for engineType in engineTypes %}
<option value="{{ engineType.type }}">{{
engineType.type }}</option>
{% endfor %}
</select>
</div>
</div>
</div>
<div class="clearboth clearboth-block-17_3">
</div>
<div class="block-17_3_1">
<span class="block-17_2-name">Òèï êóçîâà</span>
<div class="block-17_select-v2_outer">
<div class="block-17_select-v2">
<select>
{% for body in bodies %}
<option value="{{ body.body }}">{{ body.body
}}</option>
{% endfor %}
</select>
</div>
</div>
</div>
<div class="block-17_3_1">
<span class="block-17_2-name">Ïðèâîä</span>
<div class="block-17_select-v2_outer">
<div class="block-17_select-v2">
<select>
{% for transferCase in transferCases %}
<option value="{{ transferCase.transferCase
}}">{{ transferCase.transferCase }}</option>
{% endfor %}
</select>
</div>
</div>
</div>
<div class="block-17_3_1" style="width: 145px">
<span class="block-17_2-name">Îïöèè</span>
<div class="block-17_select-v2_outer">
<div class="block-17_select-v2">
<select style="width: 145px">
{% for option in options %}
<option value="{{ option.equipment }}">{{
option.equipment }}</option>
{% endfor %}
</select>
</div>
</div>
</div>
<div class="block-17_3_1" >
<span class="block-17_2-name">Ñòðàíà ïðèíàäëåæíîñòè</span>
<div class="block-17_select-v2_outer">
<div class="block-17_select-v2">
<select>
{% for transferCase in transferCases %}
<option value="{{ transferCase.transferCase
}}">{{ transferCase.transferCase }}</option>
{% endfor %}
</select>
</div>
</div>
</div>
<div class="clearboth">
</div>
<div></div>
<div class="block-17_hide_button_open">
<a onclick="openboxhidden('block-17_3'); return false"
href="#">Ñêðûòü äîïîëíèòåëüíûå ïàðàìåòðû</a>
</div>
</div>
</div>
<div class="clearboth">
</div>
<div class="block-17_4">
<input type="submit" value="Ïîèñê" name="" />
<a onclick="openboxhidden('block-17_3'); return false"
href="#">Ïîêàçàòü äîïîëíèòåëüíûå ïàðàìåòðû</a>
</div>
</div>
</form>

Monday, 19 August 2013

Creating a PHP PDO database class, trouble with the OOP

Creating a PHP PDO database class, trouble with the OOP

this is my current Database class:
class Database {
private $db;
function Connect() {
$db_host = "localhost";
$db_name = "database1";
$db_user = "root";
$db_pass = "root";
try {
$this->db = new PDO("mysql:host=" . $db_host . ";dbname=" .
$db_name, $db_user, $db_pass);
} catch(PDOException $e) {
die($e);
}
}
public function getColumn($tableName, $unknownColumnName,
$columnOneName, $columnOneValue, $columnTwoName = "1", $columnTwoValue
= "1") {
$stmt = $this->db->query("SELECT $tableName FROM
$unknownColumnName WHERE $columnOneName='$columnOneValue' AND
$columnTwoName='$columnTwoValue'");
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $results[0][$unknownColumnName];
}
}
I'm trying to run it using the following code:
$db = new Database();
$db->Connect();
echo $db->getColumn("Sessions", "token", "uid", 1);
And i get the following error:
PHP Fatal error: Call to a member function fetchAll() on a non-object in
/Users/RETRACTED/RETRACTED/root/includes/Database.php on line 19
Any idea what's up? Thanks

Navigating the Vertices on a Sphere Made of Triangles

Navigating the Vertices on a Sphere Made of Triangles

Pretty simple question: if I have a sphere made of triangles, how could I
differentiate the vertices and find the neighbors of a specific vertice?

forced preemption on windows (occurs or not here)

forced preemption on windows (occurs or not here)

Sorry for my weak english, by preemption I mean forced context (process)
switch applied to my process.
My question is:
If I wrote and run my own program game in such way that it is 20
millisecond period work, then 5 millisecond sleep, and then windows pump
(peek message/dispatch message) in loop again and again - Is it ever
preempted by force in windows or no, this preemption doeas not occur ?
I suppose that this preemption would occur if i would not volountairy give
control back to system by sleep or peek/dispatch in by larger amount of
time - but here it will occur or no?
tnx for the answer

Returning view from jQuery AJAX get operation

Returning view from jQuery AJAX get operation

I'm trying to make an asynchronous jQuery get to an MVC Action to return a
view. For some reason, although it accesses the action, it does not render
the view.
This is the jQuery:
function showArchive(url) {
var moreRecentThanDate = $("#chooseDate").val();
$.get(url, { moreRecentThan: moreRecentThanDate });
}
and this is the action :
[HttpGet]
public ActionResult ShowArchive(DateTime moreRecentThan)
{
List<NewIndexViewModel> model = Service.GetArchives(moreRecentThan);
ViewBag.IsArchive = true;
return View("Index", model);
}
PS: I call this jQuery from an ad-hoc modal popup;

Sunday, 18 August 2013

Error Upgrade Jquery.min into Jquery.1.9

Error Upgrade Jquery.min into Jquery.1.9

I try this code in jqueri.min1.2.js Work but in Jquery.1.9.js not Work
//SubmitComment
$('a.comment').livequery("click", function(e){
var getpID = $(this).parent().attr('id').replace('commentBox-','');
var comment_text = $("#commentMark-"+getpID).val();
if(comment_text != "Write a comment...")
{
$.post("add_comment.php?comment_text="+comment_text+"&post_id="+getpID,
{
}, function(data){
$('#CommentPosted'+getpID).append($(data).fadeIn('slow'));
$("#commentMark-"+getpID).val("Write a comment...");
});
}
});
Ouput on console "Uncaught Error: Syntax error, unrecognized expression:"
Help me please...

Android: How to set a custom view for single choice alertdialog?

Android: How to set a custom view for single choice alertdialog?

You are the droids I have been looking for!
Fellow droids..
I'd like to change the title in a Single choice alertdialog to a custom
title. I know I can use dialog.setCustomTitle(View view) but that doesn't
seem to have any effect.
Also, I'd like to replace the radiobuttons with a custom button that I
created.
How can I do this? I'd rather use an alertdialog because of it's
simplicity, than create my own listview or gridlayout.
Help is much appreciated. Thanks!

Why .slice always delete the last element

Why .slice always delete the last element

In the javascript, there are two arrays:tags[] and tags_java[]. I use
.splice to delete certain items, which of the same index in the two
arrays. The tags[] works fine, but tags_java doesn't, it seems always
delete the last item. here is the javascript and the jsfiddle link.
var tag = $(this).text();
var index = $.inArray(tag, tags);
tags.splice(index,1);
tags_java.splice(index,1);

SocketServer no modules are getting import

SocketServer no modules are getting import

I want to create a SocketServer on my mac.
However it seems to be some problem with the packages. When I try this
sampling code found here it raises attributeerror.
import SocketServer
class MyTCPHandler(SocketServer.BaseRequestHandler):
"""
The RequestHandler class for our server.
It is instantiated once per connection to the server, and must
override the handle() method to implement communication to the
client.
"""
def handle(self):
# self.request is the TCP socket connected to the client
self.data = self.request.recv(1024).strip()
print "{} wrote:".format(self.client_address[0])
print self.data
# just send back the same data, but upper-cased
self.request.sendall(self.data.upper())
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
# Create the server, binding to localhost on port 9999
server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
server.serve_forever()
The error :
Traceback (most recent call last):
File "/Users/ddl449/Projects/visualization/SocketServer.py", line 1, in
<module>
import SocketServer
File "/Users/ddl449/Projects/visualization/SocketServer.py", line 3, in
<module>
class MyTCPHandler(SocketServer.BaseRequestHandler):
AttributeError: 'module' object has no attribute 'BaseRequestHandler'
I do not know if that has to do that I am running on Mac. My python
version is:
2.7.5 (v2.7.5:ab05e7dd2788, May 13 2013, 13:18:45)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)]

Javascript debugging: pause on click event

Javascript debugging: pause on click event

I'm debugging a web page and want a way to pause the JS execution of an
oonclick handler of an element, where I don't really know who is the
handler or when is the handler being registered.
Is there something like a pause button (such as in Visual Studio) on any
of the browsers debuggers that pauses the JS execution once a user event
is triggered?
Thanks

Consecutive uppercase letters regex

Consecutive uppercase letters regex

I'm trying to use regex to find 3 consecutive uppercase letters within a
string.
I've tried using
\b([A-Z]){3}\b
as my regex which works to an extent.
However this only returns strings by themselves. I also want it to find 3
consecutive uppercase letters nested within a string. i.e thisISAtest
Any help would be appreciated. Thanks

Saturday, 17 August 2013

Where two or more values match condition?

Where two or more values match condition?

I have been asked this question;
You list county names and the surnames of the representatives if the
representatives in the counties have the same surname.
and I have the following tables;
***REPRESENTATIVE***
REPI SURNAME FIRSTNAME COUNTY CONS
---- ---------- ---------- ---------- ----
R100 Gorege Larry kent CON1
R101 shneebly john kent CON2
R102 shneebly steve kent CON3
I cant seem to figure out the correct way to ask Orical to display a
surname that exists more then twice and the surnames are in the same
country.
I know how to ask WHERE something = something, but that's doesn't ask what
I want to know.