Monday, 30 September 2013

EC2 instances - more than one startup mode (maintenance / production)

EC2 instances - more than one startup mode (maintenance / production)

It is my understanding that in order to make use of EC2 spot instances,
the AMI for the instances must be configured to start doing whatever it's
supposed to do immediately upon bootup, and continue doing it until it's
done or the instance is terminated.
That's not a problem in itself, but I will be needing periodically to
update the AMI with new software and/or configuration scripts, so I'll
occasionally need to bring up a regular instance that I can ssh into and
tinker, which won't play nice with boot scripts that immediately start
trying to Do Stuff (for instance, while I am updating the AMI for a bunch
of compute workers, the associated control server will probably be down).
Is there a way to configure two (or more) boot modes for the same AMI?
Sort of like good old-fashioned SysV run levels ... which would work fine
for this application, in fact, except I don't see any way to control the
kernel command line from the EC2 web or CLI interfaces.
(Operating system inside the AMI is Linux, if that matters.)

Coupon collector's problem worst case time?

Coupon collector's problem worst case time?

The expected time is $n Hn$. So for 9 coupons we get ~26 trials. But what
is the probability that all coupons have been collected after 26 trials?
How do we know the number of trials required to collect all with arbitrary
certainty?

JPA - Optional columns

JPA - Optional columns

We have many customers data in separate databases per customer which
should have the same schema/table structures. However there is a table
that has extra columns in some databases compared to others.
For example for customer A there is a table X with columns a, b, c, d. For
customer B there is a table X with columns a, c, d. I need to capture b if
it exists but can ignore it if not.
Is there a way to tell JPA to ignore those columns if they don't exist?
@Basic(optional=true) reads exactly like what I want but the documentation
indicates it is for another purpose.
Currently I get, as expected, Unknown column 'table.field' in 'field list'
P.S. I can't just add the columns to the databases that don't have them
unfortunately.

mysql query : How to join multiple table with statment

mysql query : How to join multiple table with statment

I have mysql query below. but it not work.
Select CASE
WHEN isLevel = '1' THEN 'Mahasiswa'
WHEN isLevel = '2' THEN 'Dosen'
WHEN isLevel = '3' THEN 'Karyawan'
ELSE 'Admin'
END as level from mhs left join if(isLevel=1,'mahasiswa','dosen') on
username=iduser where blabala.
if "isLevel=1" join with mahasiswa table and if "isLevel=2" join dosen
table,.. How to the query?
please help me. thanks.

Sunday, 29 September 2013

Optimize multiple JOINs in MySQL

Optimize multiple JOINs in MySQL

I have this MySQL which should be correct syntax:
select c.cat_id,c.cat_name as cat_name,
c.cat_desc, c.cat_image, mi.filename,
l.link_id, l.user_id, l.address,l.city,
l.country,l.link_created,l.link_desc,
l.email,l.fax,l.link_hits, l.link_modified,
l.link_name,l.postcode, l.price,l.link_rating,
l.state,l.telephone,l.link_votes,
l.website, l.link_id, l.link_visited, cf.value
from j25_mt_cats as c,
j25_mt_links as l
LEFT OUTER JOIN j25_mt_cfvalues AS cf ON (cf.link_id = l.link_id),
j25_mt_images AS mi,
j25_mt_cl as cl
UNION ALL
select c.cat_id,c.cat_name as cat_name,
c.cat_desc, c.cat_image, mi.filename,
l.link_id, l.user_id, l.address,l.city,
l.country,l.link_created,l.link_desc,
l.email,l.fax,l.link_hits, l.link_modified,
l.link_name,l.postcode, l.price,l.link_rating,
l.state,l.telephone,l.link_votes,
l.website, l.link_id, l.link_visited, cf.value
FROM j25_mt_cats as c,
j25_mt_links as l
RIGHT OUTER JOIN j25_mt_cfvalues AS cf ON cf.link_id = l.link_id,
j25_mt_images AS mi,
j25_mt_cl as cl
where cf.cf_id = 40 and cl.link_id = l.link_id
AND mi.link_id = l.link_id AND mi.ordering < 2
AND c.cat_id = cl.cat_id and c.cat_published = 1
AND c.cat_approved = 1 and l.link_published = 1 and l.link_approved = 1
AND cf.link_id IS NULL
ORDER BY RAND() DESC;
The query eats up 3GB+ in the tmp directory and ends up timing out. I'm
missing something here, how can I increase the efficiency? My goal here
was just adding onto an existing query to grab a value from an additional
table (j25_mt_cfvalues).

Computing the inverse of function in MATLAB

Computing the inverse of function in MATLAB

How do you compute the inverse of a function in MATLAB? Say you want to
compute the inverse of f(x)=e^x, what would be the code?

Getting rows from a data frame which satisfy a condition in pandas

Getting rows from a data frame which satisfy a condition in pandas

I have a data frame and I have a range of numbers. I want to find the rows
where values in a particular column lie in that range.
This seems like a trivial job. I tried with the techniques given here -
http://pandas.pydata.org/pandas-docs/dev/indexing.html#indexing-boolean
I took a simple example:
In [6]: df_s
Out[6]:
time value
0 1 3
1 2 4
2 3 3
3 4 4
4 5 3
5 6 2
6 7 2
7 8 3
8 9 3
In [7]: df_s[df_s.time.isin(range(1,8))]
Out[7]:
time value
0 1 3
1 2 4
2 3 3
3 4 4
4 5 3
5 6 2
6 7 2
Then, I tried with a sample from the data set I am working with which has
timestamp and value as columns:
In [8]: df_s = pd.DataFrame({'time': range(1379945743841,1379945743850),
'value': [3,4,3,4,3,2,2,3,3]})
In [9]: df_s
Out[9]:
time value
0 1379945743841 3
1 1379945743842 4
2 1379945743843 3
3 1379945743844 4
4 1379945743845 3
5 1379945743846 2
6 1379945743847 2
7 1379945743848 3
8 1379945743849 3
In [10]: df_s[df_s.time.isin(range(1379945743843,1379945743845))]
Out[10]:
Empty DataFrame
Columns: [time, value]
Index: []
Why doesn't the same technique work in this case? What am I doing wrong?
I tried another approach:
In [11]: df_s[df_s.time >= 1379945743843 and df_s.time <=1379945743845]
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-11-45c44def41b4> in <module>()
----> 1 df_s[df_s.time >= 1379945743843 and df_s.time <=1379945743845]
ValueError: The truth value of an array with more than one element is
ambiguous. Use a.any() or a.all()
Then, I tried with a bit more complex approach:
In [13]: df_s.ix[[idx for idx in df_s.index if df_s.ix[idx]['time'] in
range(1379945743843, 1379945743845)]]
Out[13]:
time value
2 1379945743843 3
3 1379945743844 4
This gives the desired result but it takes way too much time to give any
result on my original data set. It has 209920 rows and it is expected that
the number of rows will increase when I actually put my code to test.
Can anyone direct to me towards the right approach?
I am using python 2.7.3 and pandas 0.12.0
Update:
Jeff's answer worked.
But I find the isin approach more simple, intuitive and less cluttered.
Please comment if anyone has any idea why it failed.
Thanks!

Java - Actionlistener showing error for a reason I can't see

Java - Actionlistener showing error for a reason I can't see

In the if statement, it is failing to find launchBtn. I'm probably doing
something stupidly obvious. Can anyone see what's wrong? The errors are in
bold (or highlighted with two **, Here is my code:
package launcher;
import java.awt.event.*;
import javax.swing.*;
@SuppressWarnings("serial")
class Window extends JFrame implements ActionListener
{
JPanel panel = new JPanel();
public Window()
{
//Creates the blank panel
super("Launcher");
setSize(500, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(panel);
setVisible(true);
//Create the button variables
JButton launchBtn = new JButton("Launch Game");
JButton optionsBtn = new JButton("Launcher Options");
//Add the buttons to the launcher
panel.add(launchBtn);
panel.add(optionsBtn);
//Add the buttons to the action listener
launchBtn.addActionListener(this);
optionsBtn.addActionListener(this);
}
public void actionPerformed(ActionEvent event)
{
if(event.getSource() == **launchBtn**)
{
**launchBtn**.setEnabled(true);
}
}
}

Saturday, 28 September 2013

In PHP would this be deemed correct?

In PHP would this be deemed correct?

I already wrote a post about an issue I had before about this but I had
that issue taken care of. Like my last post I have a form, text-box and a
button. I have everything done with this including Printing the original
word, Printing the number of characters in the word, Printing the word in
all caps and Printing the word in reverse order. My only issue I'm having
is trying to get whatever text I enter and then click the button to output
to Print the first letter of the word and Print the last letter of the
word. I've been doing a lot of looking around of PHP.net and I found that
substr is used to return a part of a string that I could use. The only
issue is when I write the code for it and try to execute my program it
errors out on that specific line. I'm not looking for the answer but could
someone just take a look and see what I'm doing wrong because I understand
everything completely but this is the only thing I'm hung up on.
$first = substr($_POST['entertext']);
echo "The first letter of the word is " . $first. "<br />\n";
$last = substr($_POST['entertext']);
echo "The first letter of the word is " . $last. "<br />\n";

continuous write on a pipe from 2 child processes and continuous read, from parent

continuous write on a pipe from 2 child processes and continuous read,
from parent

Problem to generate 10 random numbers (In two child), send it to parent
(one by one) and find the maximum among them
PS: Parent reads twice (one stream of random numbers from one child, does
the calculation to take the maximum, and then from the other another
child)
My question is: What is the mechanism of Read and Write system calls. How
does the control moves within the two system calls?
Problem to generate 10 random numbers (In two child), send it to parent
and finf the maximim among them. Do not use more than 4 variables to do
that. Parent reads twice (one stream of random numbers from one child,
takes the maximum, and then from another child)
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#define READ_END 0
#define WRITE_END 1
int main(int argc, char *argv[]){
pid_t child1, child2, pid, child1Pid, child2Pid;
int pipe1[2],status, bufChild1,bufChild2;
int maxChild1, minChild1, maxChild2, minChild2;
char Array1,Array2;
//create a pipe
if (pipe(pipe1) == -1)
{
fprintf(stderr, "Pipe failed");
}
//child1 created
child1 = fork();
//if creation failed
if (child1 < 0) {
fprintf(stderr, "Fork Failed");
return 1;
}
// child1 processes being created
else if (child1 == 0) {
printf("Inside child 1 with pid %d\n", getpid());
printf("The Parent pid is %d\n", getppid());
srand(456);
//Work of child1
for (int i=0;i<10;i++) //10 Random numbers for child 1 and
contunuous streaming to parent
{
bufChild1 = rand()%1000;
fprintf(stdout, "written value from child 1 is: %d\n",
bufChild1);
close(pipe1[READ_END]);
write(pipe1[WRITE_END],&bufChild1,sizeof(bufChild1));
//write into the Parent
close(pipe1[WRITE_END]);
}
usleep(1000);
exit(0);
}``
//Child2 created
child2 = fork();
//if creation failed
if (child2 < 0) {
fprintf(stderr, "Fork Failed");
return 1;
}
// child2 gets created
else if (child2 == 0) {
printf("\ninside child2 with pid %d\n", getpid());
printf("\nThe Parent pid is %d\n", getppid());
srand(789);
//Work of child2
for (int j=0;j<20;j++)////20 Random numbers for child 2,
continuously write to the pipe while generating random numbers
{
bufChild2 = rand()%1000;
fprintf(stdout, "written value from child 2 is: %d\n",
bufChild2);
close(pipe1[READ_END]);
write(pipe1[WRITE_END],&bufChild2,sizeof(maxChild2));
//write into the Parent
close(pipe1[WRITE_END]);
}
usleep(1000);
exit(0);
}
// Parent Process...Wait for children to exit.
pid = wait(&status);
printf("Inside Parent Process\n");
close(pipe1[WRITE_END]);
//Reading from Child 1 (keep reading and comparing till the loop pf
child 1 continues
// I AM STUCK HERE. HOW CAN I DO THE COMPARISION.
//I intend to compare the new coming number with the previous one,
and if its greater, it should be saved else get the new number
//if (read(pipe1[READ_END],&Array1,sizeof(Array1)) > maxChild1);
printf("Maximum number received from child2 : \%d\n",maxChild2);
//Similar Logic for child 2 ...
//``if (read(pipe1[READ_END],&Array2,sizeof(Array1)) > maxChild2);
return (1);
}

Making EntityFramework Connection String dynamic

Making EntityFramework Connection String dynamic

I'm using this code for connect to my database over the network :
// Specify the provider name, server and database.
string providerName = "System.Data.SqlClient";
string serverName = "VENUS-PC";
string databaseName = "Cheque";
// Initialize the connection string builder for the
// underlying provider.
SqlConnectionStringBuilder sqlBuilder =
new SqlConnectionStringBuilder();
// Set the properties for the data source.
sqlBuilder.DataSource = serverName;
sqlBuilder.InitialCatalog = databaseName;
//sqlBuilder.IntegratedSecurity = true;
sqlBuilder.UserID = "sa";
sqlBuilder.Password = "123";
sqlBuilder.MultipleActiveResultSets = true;
// Build the SqlConnection connection string.
string providerString = sqlBuilder.ToString();
// Initialize the EntityConnectionStringBuilder.
EntityConnectionStringBuilder entityBuilder =
new EntityConnectionStringBuilder();
//Set the provider name.
entityBuilder.Provider = providerName;
// Set the provider-specific connection string.
entityBuilder.ProviderConnectionString = providerString;
// Set the Metadata location.
entityBuilder.Metadata = @"res://*/Cheque.csdl|
res://*/Cheque.ssdl|
res://*/Cheque.msl";
//Console.WriteLine(entityBuilder.ToString());
System.Windows.Forms.MessageBox.Show(entityBuilder.ToString());
using (EntityConnection conn =
new EntityConnection(entityBuilder.ToString()))
{
conn.Open();
//Console.WriteLine("Just testing the connection.");
System.Windows.Forms.MessageBox.Show("Connection is Ok");
conn.Close();
}
But this exception Thrown : The underlying provider failed on open.Login
Failed for user 'sa'. And I test the user name ,password ,server name and
database name in Sql Server Managment Studio and it's working. How can i
fix my code?

Friday, 27 September 2013

Detour hook send/recv winsock

Detour hook send/recv winsock

Im trying to hook the send/recv functions from Ultima Online client usinf
MS Detour. I've found a c++ dll/injector source out there, but it is not
working. The dll is injected but the functions is not being hooked. When
the injector start the client, the dll throw 3 box saying that it was
injected and hooked both recv/send, but nothing happens when the client
start the comminication
injector.cpp
#include <windows.h>
#include <detours.h>
#include <cstdio>
#pragma comment(lib,"detours.lib")
int main(int argc, char *argv[])
{
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
ZeroMemory(&pi, sizeof(pi));
si.cb = sizeof(si);
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_SHOW;
if(!DetourCreateProcessWithDllEx("D:\\UO\\UO Game\\client.exe",
NULL, NULL, NULL, TRUE,
CREATE_DEFAULT_ERROR_MODE |
CREATE_SUSPENDED,
NULL, "D:\\UO\\UO Game\\", &si, &pi,
"C:\\Users\\Felipe\\Desktop\\mydll\\Debug\\mydll.dll",
NULL))
printf("Failed");
else
printf("Success");
ResumeThread(pi.hThread);
//WaitForSingleObject(pi.hProcess, INFINITE);
//CloseHandle(&si);
//CloseHandle(&pi);
return EXIT_SUCCESS;
}
dll.cpp
#include <cstdio>
#include <windows.h>
#include <detours.h>
#pragma comment(lib,"detours.lib")
#pragma comment(lib,"ws2_32.lib")
int (WINAPI *pSend)(SOCKET s, const char* buf, int len, int flags) = send;
int WINAPI MySend(SOCKET s, const char* buf, int len, int flags);
int (WINAPI *pRecv)(SOCKET s, char* buf, int len, int flags) = recv;
int WINAPI MyRecv(SOCKET s, char* buf, int len, int flags);
FILE* pSendLogFile;
FILE* pRecvLogFile;
BOOL msg_once = false;
int WINAPI MySend(SOCKET s, const char* buf, int len, int flags)
{
MessageBoxA(0,"MyRecv",0,0);
return pSend(s, buf, len, flags);
}
int WINAPI MyRecv(SOCKET s, char* buf, int len, int flags)
{
MessageBoxA(0,"MyRecv",0,0);
return pRecv(s, buf, len, flags);
}
extern "C" __declspec(dllexport) void dummy(void){
return;
}
BOOL WINAPI DllMain(HINSTANCE hinst, DWORD dwReason, LPVOID reserved)
{
if (!msg_once)
{
MessageBoxA(0,"loaded",0,0);
msg_once = true;
}
if (DetourIsHelperProcess()) {
return TRUE;
}
if (dwReason == DLL_PROCESS_ATTACH) {
DetourRestoreAfterWith();
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourAttach(&(PVOID&)pSend, MySend);
if(DetourTransactionCommit() == NO_ERROR)
MessageBox(0,"send() detoured successfully","asd",MB_OK);
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourAttach(&(PVOID&)pRecv, MyRecv);
if(DetourTransactionCommit() == NO_ERROR)
MessageBox(0,"recv() detoured successfully","asd",MB_OK);
}
else if (dwReason == DLL_PROCESS_DETACH) {
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourDetach(&(PVOID&)pSend, MySend);
DetourTransactionCommit();
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourDetach(&(PVOID&)pRecv, MyRecv);
DetourTransactionCommit();
}
return TRUE;
}

How to select nested UL element without class in JavaScript

How to select nested UL element without class in JavaScript

In my Joomla template I've created a vertical menu including a dropdown
which should "push" the elements below away when opening a submenu
onclick. Somehow I don't get it to work..
I am trying to grab the UL inside an LI, but how can I do this in
JavaScript without the UL's having a class or ID.
I've come to this yet:
function getElements(){
var listitems = {};
for(var i = 0; i< arguments.length; i++){
var id = arguments[i];
var item = content.getElementsByTagName("li");
if (item == null)
throw new Error ("No list items found.");
listitems[id] = item;
}
return listitems;
}
Now I should get something like: (I now the following code is impossible,
but it describes what I am trying)
var nav = document.getElementById("navigation");
var nestedList = nav ul li ul.onclick(nav ul li ul.style = "display:
block";);
Thanks!

How to make last page in ViewPager completely inaccessible

How to make last page in ViewPager completely inaccessible

In an App that I am working on, I implement a ViewPager. At some point, I
want to make the last page in the ViewPager completely inaccessible. To do
that I set up the getCount() method in my SectionsPagerAdapter like this:
@Override
public int getCount() {
return mPageCount;
}
When I want to make the last page inaccessible, I just subtract 1 from
mPageCount (which is a global variable) and the user can't access it
anymore. This works but the problem is that the user still can see the
last page if he flings the ViewPager in the second-to-last page. The
ViewPager will bounce back, so he can't stay at the last page, but he can
see it. Also there is no edge effect. Basically my question is: "How do I
remove the last page from the ViewPager such that it is COMPLETELY gone
(it should appear as if that is the end of the ViewPager)?"

Including all files within a directory with Combres

Including all files within a directory with Combres

I'm using Combres to bundle a variety of JavaScript libraries, like that:
<resourceSet name="libraryScripts" type="js">
<resource path="~/Scripts/Libraries/jquery-2.0.3.min.js" />
<resource path="~/Scripts/Libraries/underscore-min.js" />
<resource path="~/Scripts/Libraries/angular.min.js" />
<!-- Omitted for brevity ... -->
</resourceSet>
Is there any way to specify an entire folder to include (here:
~/Scripts/Libraries/) without having to list all JavaScript files
explicitly, one by one?

Thursday, 26 September 2013

Grab specific data using C++ with MySQL

Grab specific data using C++ with MySQL

I am trying to grab specific information from a MySQL database in C++.
Lets assume I can connect and have my MySQL package working just fine. The
below picture is a database. I want to retrieve the name LISA and insert
it into a variable to be used later. Anyone have any idea how to do so?
The below code works too.
DATABASE:
ID NAME
1 Rico
2 John
6 Lisa
7 Max
This is my current output with the below code. I just want LISA and be
able to place in a variable.
Input id: 6
name:
6Lisa
CODE:
string id_query;
string outstr;
string str8 = "Select * From users WHERE id=";
cout << "Input id: ";
cin >> id_query;
outstr = str8.c_str() + id_query;
if (mysql_query(conn, outstr.c_str()))
{
cerr << mysql_error(conn) << endl;
cout << "Press any key to continue. . . ";
cin.get();
exit(1);
}
res = mysql_use_result(conn);
cout << "name: " << endl;
while ((row = mysql_fetch_row(res)) != NULL)
cout << "\t" << row [0] << row[1] << endl;
cin.get();

Wednesday, 25 September 2013

filtering text input javascript

filtering text input javascript

Im looking for filtering text input the combo box is working but the text
box is working into age. I want is to filter the name but i don`t have a
idea to do.
combo box is for age and the text field is for name.

Thursday, 19 September 2013

How to help Scalaz with type inference and 2 type parameters

How to help Scalaz with type inference and 2 type parameters

I have something called a Generator:
trait Generator[A, B] { def generate(in: Seq[A]): Seq[B] }
I can provide a Bind instance for this generator:
object Generator {
implicit def generatorBind[T]: Bind[({type l[B] = Generator[T, B]})#l] =
new Bind[({type l[B] = Generator[T, B]})#l] {
def map[A, B](generator: Generator[T, A])(f: A => B): Generator[T, B]
= new Generator[T, B] {
def generate(in: Seq[T]): Seq[B] = generator.generate(in).map(f)
}
def bind[A, B](generator: Generator[T, A])(f: A =>Generator[T, B]):
Generator[T, B] = new Generator[T, B] {
def generate(in: Seq[T]): Seq[B] = generator.generate(in).flatMap(v
=> f(v).generate(in))
}
}
}
Unfortunately, type inference is completely lost if I try to use my
generators as applicative instances:
val g1 = new Generator[Int, Int] { def generate(seq: Seq[Int]) = seq.map(_
+ 1) }
val g2 = new Generator[Int, Int] { def generate(seq: Seq[Int]) = seq.map(_
+ 10) }
// doesn't compile
// can make it compile with ugly type annotations
val g3 = ^(g1, g2)(_ / _)
My only workaround for now has been to add a specialised method to the
Generator object:
def ^[T, A, B, C](g1: Generator[T, A], g2: Generator[T, B])(f: (A, B) => C) =
generatorBind[T].apply2(g1, g2)(f)
Then this compiles:
val g4 = Generator.^(g1, g2)(_ / _)
Is there a workaround for this problem? I suppose there is because using
State[S, A] as a Monad poses the same kind of issue (but in Scalaz there
seems to be a special treatment for State).

What is a simple way I can position images in html5

What is a simple way I can position images in html5

Hey I have been trying to use the
style="position:absolute;TOP;55px right;170px"
format to position images but it does not seem to be working.
This is my code
I was wondering if anyone who could tell me a simple way to position it on
the screen. It is preferred no css but if there is I think I could handle
it.
Cheers

Find All Radio Buttons in ASP Table

Find All Radio Buttons in ASP Table

I have an ASP table which contains a large number of radio buttons. I want
to loop through them all quickly and set the checked property to false:
<asp:Table runat=Server ID=tblSchedule>
<asp:TableRow>
<asp:TableCell>
<asp:RadioButton runat=Server ID=rdb1/>
</asp:TableCell>
</asp:TableRow>
</asp:table>
The following code never returns any results though.
foreach (RadioButton rdb in tblSchedule.Controls.OfType<RadioButton>())
{
rdb.Checked = false;
}

Bootstrap and Reveal.js

Bootstrap and Reveal.js

I'm using Bootstrap and Reveal.js to create a slide style web page for a
small portfolio. Everything is working well together but what I'm noticing
is that when my navbar collapses and I click the navbar toggle button, my
webpape/slide show will scroll back to the top while the menu expands.


So what I'm guessing is that the javascript that controls the navbar
collapse and expand is conflicting with Reveal.js. So what I want to know
is if someone has come across anything like this and how they resolved it.

What I thinking is that somewhere in bootstraps javascript is that there
is a bit to set the scroll (0,0) Is this true or is the problem with
Reveal.js?
Any help is appreciated

Remove autosuggest text when clicking off field

Remove autosuggest text when clicking off field

I have just finished adding a search bar into my page. It pretty much all
works fine, however, I would like the autosuggestions to disappear after
clicking outside of the field. How would I do this? I am using HTML5 and
my codes are:
$(document) .ready(function() {
$('.autosuggest').keyup(function() {
var search_term = $(this).val();
$.post('search.php', {search_term:search_term}, function(data) {
$(".result").html(data);
$('.result li').click(function() {
var result_value = $(this).text();
$('.autosuggest').val(result_value);
$('.result').html('');
});
});
});
});
<input type="text" id="autosuggest" class="autosuggest"
onBlur="removeSuggestion();"> <input type="submit" value="search">
<div class="dropdown">
<ul class="result"></ul>
</div>
Not too sure my php is needed but just in case...
<?php
require_once 'connect.php';
if (isset($_POST['search_term']) == true && empty($_POST['search_term'])
== false) {
$search_term = mysql_real_escape_string($_POST['search_term']);
$query = mysql_query("SELECT town FROM `boroughs` WHERE town LIKE
'$search_term%'");
while (($row = mysql_fetch_assoc($query)) !== false) {
echo '<li>', $row['town'], '</li>';
}
}
?>

PHP | MYSQL Combine 2 arrays into one array for while loop

PHP | MYSQL Combine 2 arrays into one array for while loop

I am sure it is simple but i just cant get my head around it...
I have one table of images:
'mc_comps_IMAGES'
and a second which is prize images
'mc_prizes_IMAGES'
How can i join the 2 queries to create 1 while loop to use as a slideshow?

Error in connecting with mysql using android

Error in connecting with mysql using android

I'm developing an app which will retrieve some data from mysql database. I
needed to connect my app with mysql directly to do this. I know, that i
have to use an ip address instead of localhost in getconnection method.
here is the code :
Class.forName("com.mysql.jdbc.Driver");
Log.i("output","class");
con =
DriverManager.getConnection("jdbc:mysql://192.168.1.1:3306/outsidelaundry",
"root", "");
Log.i("output","connection");
Statement stmt = con.createStatement();
String query = "select Name from nonmember";
ResultSet rs = stmt.executeQuery(query);
while(rs.next())
{
val = val + rs.getString(1) + "\n";
}
Log.i("output",val);
con.close();
Manifest.xml
<uses-permission
android:name="android.permission.SEND_SMS"></uses-permission>
<uses-permission
android:name="android.permission.RECEIVE_SMS"></uses-permission>
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera" />
To be honest i don't know what is the ip address i want to use to get
connection with mysql database. Above i used ip address is not working
too. Please help me with this.

Maven - activate profile based on project property

Maven - activate profile based on project property

Hi I am trying to achieve something like this:
In a parent pom, I have
<profile>
<activation>
<property>
<name>Compile</name>
<value>${project.artifactId}</value>
...
so that if I run mvn -DCompile=mod1 install under the parent pom, it will
only apply the profile settings to module 1, but not the others.
Similarly, if I have
<profile>
<activation>
<property>
<name>Compile</name>
<value>${project.packaging}</value>
...
then running mvn -DCompile=war install under the parent pom, it will only
apply the profile settings to those to be packed as war but not jar nor
pom.
I tried but it didnt work as expected. Did I miss anything? Please help.
P.S. no need to suggest workarounds as I am only interested on this
method. Simply answer it is not possible with reason if thats the case.
Thank you

Wednesday, 18 September 2013

After Postback make atleast 1 out of 5 textbox required

After Postback make atleast 1 out of 5 textbox required

I have 1 checkbox and 5 textboxes,
When I checked the checkbox, atleast 1 out of 5 textboxes(either of 5)
should be required.
Please help :(
Thank you.

Amazon RDS instance in EBS: Access Denied when trying from Java application in Tomcat

Amazon RDS instance in EBS: Access Denied when trying from Java
application in Tomcat

I created an EBS instance including the RDS instance based on MySQL.
I have access to the EC2 instance using SSH via PuTTY and using the MySQL
Workbench I've got access to the RDS instance as well and I can create
tables and insert data in them.
I developed a Java application using Netbeans 7.3.1 and when I run the
application locally while connecting to the MySQL instance on RDS the
application shows the same problem although I can connect to MySQL from
within Netbeans without a problem, ie I can connect to the database. But
as soon as I deploy my simple application onto EBS and run the same
application I get the error "Access denied for user ''@'' (using password:
YES)"
I added the IP to the Security Group of my RDS instance as well as the EBS
instance. Just to be sure.
Still I got the Access Denied error. The JDBC_CONNECTION_STRING
environment variable I've set up is
"jdbc:mysql://.cdydcnmtkkhw.us-west-1.rds.amazonaws.com:3306/ebdb?user=&password="
When I use any of the tools to connect to this database with that
information all works, when I try to connect from my Java application
running in Tomcat, I get the Access Denied message.
The Java call I'm using is:
private java.sql.Connection connect =
DriverManager.getConnection(jdbcConnect);
Any help would be appreciated as I'm totally stuck here.
Iwan*strong text*

How to transpose a small file with text spread over multiple lines in java?

How to transpose a small file with text spread over multiple lines in java?

for ex: From:
ab ch as asd lk
ere lk oi qw
weq aa q uro ppp lkj
To:
ab ere weq
ch lk aa
as oi q
asd qw uro
lk - ppp
- - lkj
assuming a - for missing items, for ex: (5,2) place
I have recently started with java and wanted to know what would be the
best way to manage such transpose conversion in java? Should I use an
Arraylist of arraylist, keeping in mind varying length of each line?
I have seen some of the existing questions on in-situ transposition, but,
as I will be working on small files, if someone could help me with an
easier to understand and implement solution, that would be really helpful.

Where max-wiidth (@media) css come from?

Where max-wiidth (@media) css come from?

I have this problem, there are 2 pages, that some part of the code is
repeated, to this part of code, I apply this css:
@media (max-width: 767px){
.sliderContent{
width:100%;
}
}
When I check one page in iphone, it loads this css, but when I check the
other does not use this style.
I have added an alert with the screen size in both pages, and both have
the same width.
Do you know where the max-width is taken? that could be making the
difference between the two pages?
Can the html somehow affect the size of the min-width??
Thanks in advance

iis and asp.net mvc compilation

iis and asp.net mvc compilation

as project is in developing state uploaded Files has not been compiled for
easy editing and other reason , when i edit model and add property to view
, iis say that your model has no that because of old compilation files ,
solution that Tested :
Deleted Temp folder in windows\microsoft.net
<compilation batch="false" debug="true" targetFramework="4.5" />
add new line to webconfig to force new compile
yet it run old compiled files

Git - deploying by replacing old files new ones

Git - deploying by replacing old files new ones

I already have files in project folder on server. I initialize there git:
git init
then i set up remote origin
git remote add origin git@bitbucket.org:xxxx
and ssh keys. Now i want to replace that old files by new files in remote
repository. Which command i should use?
I tried
git pull origin master
but its not making any changes, and when i making:
git checkout master
its says:
error: The following untracked working tree files would be overwritten by
checkout:

can anyone finds me some amazing free Jquery sliders?

can anyone finds me some amazing free Jquery sliders?

Google search result can produce millions of result but can anyone share
some personal favorites and some good blog articles about JQuery slider
which does't indexed top on searches.

C# variable contents altered when using a debugger

C# variable contents altered when using a debugger

In my C# program, I parse an XML file, which has been created before with
XSLT. When I normally run the program, variable extraClasses contains 3
nodes. The problem is that the selector I am using must return 2 nodes
when applied to this specific XML.
Trying to find the bug in my code, I used a debugger. When I examined the
value of variable extraClasses, the node count was 2, and the result was
the expected. When the variable is not examined, node count is 3 and the
results are wrong.
Furthermore, when I add an if statement to check if the extraClasses count
is more than 2, after the assignment, my program works fine
(extraClasses.Count = 2).
Why is this happening? Why the value examination alters the contents of
the variable? I am using C# and .NET Framework 4.
var extraClasses = xml.SelectNodes("//Class[@level='2']");
foreach (XmlElement extraClass in extraClasses) {
/* create some new nodes and append to the xml */
}

Tuesday, 17 September 2013

how to secure data in sharepoint custom list

how to secure data in sharepoint custom list

I have stored database connection string in a column of SharePoint custom
list. Through c# code i used to fetch the value from that column and my
application gets connected to specified database. But that connection
string is visible to everyone having access to the list. How we can
encrypt that value so that it cannot be visible to everyone but my
application can be connected to the database with minimum or no change in
code?

Cygwin gcc c++ c99 libraries error stod not recognized used strtod instead

Cygwin gcc c++ c99 libraries error stod not recognized used strtod instead

This question follows on from : c++ reading in text file into
vector<vector> then writing to vector or array depending on first word in
internal vector . Im editing this question because the first issue was
simply a typo error (couldn't ask seperate becaus eIve tried that before
and gow down voted for duplicate??, also couldnt delete Q because has
answers..), and the more important question is about the cygwin c++
compiler not having access to c99 libraries. When using stod instead of
strtod i get an compilation error. The issue is _GLIB_CXX_USE_C99 is
undefined??
Code so far:
#include <algorithm>
#include <fstream>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>
#include <cstdlib>
#if __cplusplus < 201103L
#warning No C++11 support

My jenkins build seems to be terminating with the message "channel stopped". Why?

My jenkins build seems to be terminating with the message "channel
stopped". Why?

I am trying to build a java maven project and I am seeing this problem.
Can't seem to tie it to any code changes that were made.
I simply see maven downloading artifacts and then the following messages,
channel stopped
Archiving artifacts
Sending e-mails to: xxx@yyy.orf
Finished: FAILURE

Does copy also transfers the retain counts?

Does copy also transfers the retain counts?

I am new to objectiveC. Suppose I have an object NSString (or perhaps
another object) with retain count 5 when I call copy on its pointer I get
a new cloned object, does this new object has retain count of its original
object ?

Issue with collecting AspectJ pointcut context and avoiding mentioning all arguments of the advised method

Issue with collecting AspectJ pointcut context and avoiding mentioning all
arguments of the advised method

I use AspectJ in order to check whether an object does belong to the
current user. The advised method is actually a Spring MVC controller
method. I use an annotation placed on that controller method in order to
apply the crosscutting security advice.
The issue I have is that the controller method has quite a few arguments.
I would like to avoid mentioning all arguments in the aspectJ source
because those can change (argument name, type, etc.) but I still have to
collect the pointcut context.
To sum up of the N arguments present in the method, I only need to use two
(member and advertisementId). How can I avoid mentioning the N arguments?
My pointcut:
public pointcut
advertisementBelongsToMemberControllerCheck(FamilyAdvertisementInfo
familyAdvertisementInfo, long advertisementId, Model model, Member member)
: execution(@AdvertisementExistsAndBelongsToMemberCheck * * (..))
&& args(familyAdvertisementInfo,advertisementId, model, member);
My advice:
before(FamilyAdvertisementInfo familyAdvertisementInfo, long
advertisementId, Model model, Member member) :
advertisementBelongsToMemberControllerCheck(familyAdvertisementInfo,advertisementId,
model, member) {
if
(!advertisementService.advertisementExistsAndBelongsToMember(advertisementId,
member)) {
throw new AccessDeniedException("Advertisement does not belong
to member!");
}
}
The annotation:
@Retention(RetentionPolicy.RUNTIME)
public @interface AdvertisementExistsAndBelongsToMemberCheck {
}
And finally, the advised controller method:
@RequestMapping(value = "/family/edit/{advertisementId}", method =
RequestMethod.GET, produces = "text/html")
@AdvertisementExistsAndBelongsToMemberCheck
public String editFamilyAdvertisementForm(@ModelAttribute
FamilyAdvertisementInfo familyAdvertisementInfo, @PathVariable long
advertisementId, Model model, @CurrentMember Member member/* the currently
logged in user */) {
FamilyAdvertisement advertisement =
advertisementService.findFamilyAdvertisement(advertisementId);
familyAdvertisementInfo.setFamilyAdvertisement(advertisement);
populateFamilyAdvertisementModel(model, familyAdvertisementInfo,
member);
return "advertisement/family/edit";
}

How can i launch a class from an actionlistener?

How can i launch a class from an actionlistener?

i have a basic gui class with a frame, a table, and a button. i want to
make it launch from the actilnlistener af another one of my basic gui
frames located in a different class
this is my main class:
public class IA {
public static void main(String[] args) {
MainFrame m1 = new MainFrame();
m1.setVisible(true);
}enter code here
public static void vts1 () {
ViewTeamStatistics v1 = new ViewTeamStatistics();
v1.setVisible(true);
}
}
it innitiates my main menu. and from the main menu i want to innitiate
another class named ViewTeamStatistics
this is the actionperformed. this is what is supposed to tell the program
to open the frame after i press the button
private void vtsActionPerformed(java.awt.event.ActionEvent evt) {
ViewTeamStatistics v1 = new ViewTeamStatistics();
v1.setVisible(true);
}
--------
the compiler comes back with no errors but when i run the program and
press the button nothing happens

Sunday, 15 September 2013

Why the function pointer pointing to different function works than it is defined

Why the function pointer pointing to different function works than it is
defined

In the following program the function pointer is defined to point to a
function which accepts no argument and returns void yet the function
pointer works here. Why?
#include<stdio.h>
int mul(int*,int*);
void main()
{ int a=10,b=20;
int(*p)();
p=&mul;
printf("%d ", (*p)(&a,&b));
}
int mul(int*a,int*b)
{
return (*a * *b);
}

How to get video status with C# or VB.NET Youtube API?

How to get video status with C# or VB.NET Youtube API?

I don't get video status (fail,processing,rejected etc..) How to fix this
problem? Thanks for help!!
settings = new YouTubeRequestSettings("app", devkey, "accountname",
"password");
request = new YouTubeRequest(settings);
string feedUrl = "http://gdata.youtube.com/feeds/api/videos/xxxxxx";
videoFeed = request.Get<Video>(new Uri(feedUrl));
foreach (Video entry in videoFeed.Entries)
{
listBox1.Items.Add("Status:" + entry.Status.Value);
}

Get end of string as const char * in C++

Get end of string as const char * in C++

Is it correct that in order to get a char pointer to the end of a string
in C++ i have to do this:
std::string str = ...
const char * end_ptr = &*str.cend();
Like dereferencing, then getting the address of the expression. Is there a
more elegant way to do this?

Click action from cloned element

Click action from cloned element

Click action won't work on any cloned element. See it on:
http://jsfiddle.net/Q9m4t/
HTML
<ul>
<li>hello <a class="del" href="#">del</a></li>
<li>new <a class="add" href="#">add</a></li>
</ul>
JS
$(".add").click( function() {
$(this.parentNode).prev("li")
.clone()
.insertBefore(this.parentNode);
return false;
});
$(".del").click( function() {
$(this).closest("li").remove();
return false;
});
Can anyone help please?

Facebook word press plugin - Featured post image does not display in facebook post

Facebook word press plugin - Featured post image does not display in
facebook post

I managed to integrate the Facebook plugin into Wordpress. Now when I post
on Wordpress my post shows up on my Facebook business page.
I noticed that the featured image is not being displayed on my Facebook
page. Can someone explain to why I am not seeing the featured Wordpress
post image in the Facebook post?
Please take a look at my Facebook site:
http://www.facebook.com/awesomelowcarb
See the first post which is a recipe. The image that I would expect is not
displayed.
I have seen others who have experienced similar problems but haven't seen
any solutions that are applicable to me.
Let me know if you need more info.
Thanks in advance, Andrew

How to disallow google maps to use internet?

How to disallow google maps to use internet?

How to disallow google maps to use internet (use traffic) ? Something like
go offline mode. Is it possible ?

Saturday, 14 September 2013

C# getting "string length can not be zero" inside dialog InitializeComponent

C# getting "string length can not be zero" inside dialog InitializeComponent

I moved few dialog froms from one class library to another (drag and drop)
in the same solution (Both are c# class librarians) Then at run time I
start getting get the error inside the InitializeComponent method of
myform.Designer.cs of moved and previously exists forms in that target dll
at line similar to
this.pictureBox1.Image = global::mydll.Properties.Resources.Webster;
The exception is "string length can not be zero".
Sometimes the form will load correctly the first time but not after that.
Do you ever have issues moving forms from one project to another?
I did updated all namespaces to use the target dll namespace.
Thank you for your help.

C++ error: declaration of ‘~Destructor’ as member of ‘Class’

C++ error: declaration of '~Destructor' as member of 'Class'

I compile using g++ -Wall -Werror *.cpp and get the error:
ConcreteCharArray.h:21:15: error: declaration of '~CharArray' as member of
'ConcreteCharArray'
Concrete implementation:
class ConcreteCharArray: public CharArray
{
private:
char * charArray;
public:
~CharArray() {
delete[] string;
}
};
Virtual class:
class CharArray
{
public:
virtual ~CharArray() {};
};

ASP.NET Export - Response not ending?

ASP.NET Export - Response not ending?

I'm trying to export some text to a text file, and that part works fine.
The trouble is that the text files get a bunch of HTML/.NET output at the
bottom of them... In other words, it's like the response isn't ending and
the page is trying to write the rest of the page. Here's the code:
Private Sub WriteData(ByRef Context As System.Web.HttpContext,
Data As List(of String), fileName as String)
With Context.Response
.Clear()
.ClearHeaders()
.ClearContent()
.AddHeader("content-disposition", String.Format("attachment;
filename={0}", fileName))
.ContentType = contentType
End With
For Each curValue in Data
Context.Response.Write(curValue)
Context.Response.Write(Environment.NewLine)
Next
Context.ApplicationInstance.CompleteRequest()
Context.Response.End()
End Sub
To call this, I just pass the HttpContext.Current and a list of data.
Does anybody know why this might happen? I'm not sure how to interpret it,
and I've looked all over without much luck. My assumption was that the
response wasn't actually ending with "Response.End()"...
Thanks,
Mike

How can I perform operation in SQL query?

How can I perform operation in SQL query?

Im making a command that will compute for fine if the books overdue. this
is my code
if (duedate.Value < DateTime.Now)
{
cmd.CommandText = ("UPDATE Penalty SET Penalty = '"+
(dateTimePicker1.Text - duedate.Value)*50 +"' WHERE Title =
'" + textBox3.Text + "'");
This code is not running because it has an error on dateTimePicker1.Text -
duedate.Value)

Google Apps Script - How To Publish / Install A Container-Bound Script

Google Apps Script - How To Publish / Install A Container-Bound Script

I have a document container-bound script, that I would like to publish, I
would like to make it available to people in my google apps organization.
I know the script gallery is only available to spreadsheet apps, so how do
I publish it. Or, more specifically, currently the script is bound to one
document, how do I make it run on all documents? My user base is fairly
small, about 300 people, and I can have each one of them install it if
need be.
Thanks, Ari

@OneToMany with @JoinTable and @Embedded

@OneToMany with @JoinTable and @Embedded

I have 3 tables representing a container-containee relationship like this:
create table Containee(id int, name varchar(100), primary key(id));
create table Container(id int, name varchar(100), sourceId int, sourceType
varchar(100), primary key(id));
create table JoinTable(containeeId int, resourceId int, resourceType
varchar(100), primary key(containeeId, resourceId, resourceType));
The hibernate entities are mapped as follows
@Entity
public class Containee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Basic
private String name;
}
@Entity
public class Container implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Basic
private String name;
@Embedded
@AttributeOverrides({
@AttributeOverride(name = "id", column = @Column(name = "sourceId")),
@AttributeOverride(name = "type", column = @Column(name = "sourceType"))
})
private DomainObject domainObject;
@OneToMany(fetch = FetchType.LAZY)
@JoinTable(name = "JoinTable",
joinColumns = {
@JoinColumn(name="resourceId", referencedColumnName = "sourceId"),
@JoinColumn(name="resourceType", referencedColumnName = "sourceType")
},
inverseJoinColumns = @JoinColumn(name = "containeeId")
)
private Collection<Containee> containees;
}
The embedded class is declared as
@Embeddable
public class DomainObject {
private int id;
private String type;
public int getId() {
return id;
}
public String getType() {
return type;
}
}
The above code doesn't work and I get the following error:
referencedColumnNames(sourceId, sourceType) of containees referencing
Container not mapped to a single property.
If I however remove @Embedded domainObject field and replace it with 2
@Basic sourceId and sourceType, the same code works like a charm. I have
tried numerous things but nothing seems to work with the @Embedded field
too. Any help is appreciated!

overloaded operators keeping variables updated instead of keeping the original variables

overloaded operators keeping variables updated instead of keeping the
original variables

I am trying to do some arithmetic operations with arrays. such as array
[1,2,3] + [1,2,3] should return [2,4,6]. However when I tried to do the
next arithmetic [1,2,3] * [1,2,3] = it returns [4,16,36] instead of
[1,4,9] that I want. It looks to me that the original array got
permanently updated to the result of the first arithmetic operation.
Please help a bit deeper than conceptual support, such as providing me
some alternative coding suggestions, since I am learning C++ and this has
been the toughest chapter that I encountered. Thank you very much.
#include <iostream>
using namespace std;
#include <string>
#include <fstream>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <vector>
#include <windows.h>
#include <cstring>
#include <cctype>
#include <iomanip>
#include <algorithm>
#include<sstream>
class TwoD
{
private:
int MaxCols;
double* outerArray;
double constant;
public:
TwoD(int size)
{
MaxCols = size;
outerArray = new double[MaxCols];
}
TwoD(int size, double constantInput)
{
MaxCols = size;
outerArray = new double[MaxCols];
for (int k = 0; k < size; k++)
outerArray[k] = constantInput;
}
TwoD(const TwoD& other): MaxCols(other.MaxCols)
{
outerArray = new double[MaxCols];
for (int i = 0; i < MaxCols; i++)
outerArray[i] = other.outerArray[i];
}
const TwoD& operator =(const TwoD& rightSide)
{
if(MaxCols != rightSide.MaxCols)
{
delete [] outerArray;
outerArray = new double [rightSide.MaxCols];
}
MaxCols = rightSide.MaxCols;
for (int i = 0; i < MaxCols; i++)
outerArray[i] = rightSide.outerArray[i];
return *this;
}
void input(int size)
{
for (int k = 0; k < size; k++)
cin >> outerArray[k];
}
void outPut(int size)
{
for (int l = 0; l < size; l++)
{
cout << outerArray[l]<< ", ";
}
cout << endl;
}
const TwoD operator + (const TwoD& rightSide)
{
for (int l = 0; l < MaxCols; l++)
{
outerArray[l] = outerArray[l] + rightSide.outerArray[l];
cout << endl;
}
return *this;
}
const TwoD operator * (const TwoD& rightSide)
{
for (int l = 0; l < MaxCols; l++)
{
outerArray[l] = outerArray[l] * rightSide.outerArray[l];
cout << endl;
}
return *this;
}
~TwoD()
{
delete[] outerArray;
}
};
int main()
{
int size;
double constantInput;
cout << "Please enter a size of an array" << endl;
cin >> size;
TwoD example1(size);
cout << "input example1" << endl;
example1.input(size);
example1.outPut(size);
cout << "Please enter a constant to work with: "<< endl;
cin >> constantInput;
TwoD constant1(size, constantInput);
constant1.outPut(size);
cout << "polynomial + polynomial" << endl;
TwoD result1 = example1 + example1;
result1.outPut(size);
cout << "polynomial * polynomial" << endl;
TwoD result2 = example1 * example1;
result2.outPut(size);
return 0;
}

Friday, 13 September 2013

Random 100 empty files based on inode number of ext4 on linux

Random 100 empty files based on inode number of ext4 on linux

Does anyone know how I can get 100 random files from random inode numbers
on a /dev/sda2 using php?
random file by inode number, is that possible?
e.g. 56, 1093, 321, 1231, 4231, 512... these numbers are inode numbers
pointing to file location randomly. and getting them using php

Parsing a paragraph: detecting lists

Parsing a paragraph: detecting lists

Let's say I have the following text:
Steps toward this goal include: Increasing efficiency of mobile networks,
data centers, data transmission, and spectrum allocation Reducing the
amount of data apps have to pull from networks through caching,
compression, and futuristic technologies like peer-to-peer data transfer
Making investments in accessibility profitable by educating people about
the uses of data, creating business models that thrive when free data
access is offered initially, and building out credit card infrastructure
so carriers can move from pre-paid to post-paid models that facilitate
investment If the plan works, mobile operators will gain more customers
and invest more in accessibility; phone makers will see people wanting
better devices; Internet providers will get to connect more people; and
people will receive affordable Internet so they can join the knowledge
economy and connect with the people they care about.
As you can tell by reading the text, these are multiple sentences (a list
of points). How can I split this text into sentences? I've tried using
python NLTK but no luck. Checking for uppercase letters won't work either,
as it isn't very reliable.
Any ideas on how to solve this problem?
Thanks.

Attributes: @property for Java

Attributes: @property for Java

Is there an @property attribute in Java like there is in Objective-C?
If there were, could I name the object, then access it's properties
through objectName.propertyName?
Thanks.

How to avoid checking for empty value in Haskell?

How to avoid checking for empty value in Haskell?

I'm trying to grasp how Haskell programs can avoid testing for "empty
value". I am struggling to get rid of case expression in this program:
main = do url:outputPath:[] <- getArgs
let maybeUri = parseURI url
case maybeUri of
Just uri -> download uri outputPath
Nothing -> return ()
My very rough understanding is that I should use monad transformer so that
I can use single mappend on Maybe value within IO monad and 'do' syntax
should be able to support it. How can I achieve this?

Is there a way to insert new data into any location in a C# list?

Is there a way to insert new data into any location in a C# list?

I'm writing a program that basically creates a list of items. It first
stores all the item numbers in a List of strings. After that, after each
item, I want the program to store multiple lines of descriptions. Is there
a way to add new data between two pre-existing points of data in the List
without destroying any pre-existing data? I know in C++ you could push
back a Vector, but I'm not sure if you can or how to do the same in C#.

Twig - Automatically insert templatename as html comment

Twig - Automatically insert templatename as html comment

I am working on a php project and using twig as template engine and
wondering if there is a possibility to automatically add the used template
filename/path into a twig template as html-comment?
That would be great for debugging, since I could have a look at the html
code and find out, in which twig file I have to look, if I want to change
something.
For example, the result should look like this:
<!-- start tpl/layout.twig -->
<html>
<head></head>
<body>
<!-- start tpl/header.twig -->
<header>My header</header>
<!-- end tpl/layout.twig -->
<!-- start tpl/content.twig -->
<section>
<!-- start tpl/article.twig -->
<article>blabla1</article>
<!-- end tpl/article.twig -->
<!-- start tpl/article.twig -->
<article>xyz</article>
<!-- end tpl/article.twig -->
</section>
<!-- end tpl/content.twig -->
</body>
</html>
<!-- end tpl/layout.twig -->

Can I handle an event with another way on visual studio 2012?

Can I handle an event with another way on visual studio 2012?

Now I'm work in a windows form application with visual studio 2012 and in
a part of that the program must execute some codes when an event
happens.One way is writing the code in an scope.Can you introducing
another way please?(I work on a windows form app and c#)

Thursday, 12 September 2013

jQuery Facebox restrict closing

jQuery Facebox restrict closing

I am using jQuery Facebox to show a list of possible currencies a user can
customise the site to however Facebox allows closing when clicking outside
the popup (dark area). I would like to force the user to select a currency
and click a button and then close facebox so my question is, is there a
way to stop the default close actions (click outside and the cross) so I
force the user to click an 'OK' (or whatever) button?
I can then close Facebox programatically (which I already know how).

How do I open/close ports in iptables based on a network service status?

How do I open/close ports in iptables based on a network service status?

I would like to have iptables dynamically open ports as a network service
is enabled and close ports as they are disabled.
Is there an established way to do this? Should I be mucking around with
iptables, /etc/init.d/* files, or clobber together my own ./script?
I don't think it provides much in added security, but it would be useful
for deployments where a full iptables configuration can be copied over for
many services, exposing ports only as those services are configured and
activated.
I am specifically using CentOS 6.2 on a Linode VPS, but I would also like
to be able to use this on an Ubuntu Server VM (12.04 LTS) or another other
Debian variant.

Responsive table design by cell

Responsive table design by cell

I have this table with three cells in the first row. I'm trying to create
a design that will bring down the last cell if there is no space. So
something like 2 on top, 1 below. And as the window gets even small 1 on
each row. I'm having trouble finding anything like this.
I was able to get a responsive design to stack all cells on top of each
other depending on size but if I could find a better solution that would
be nicer.
HTML:
<table id="dashboard" cellpadding="0" cellspacing="0">
<tr>
<td id="TopLeft"><div class='chartLoadingOverlay'>Loading chart
please be patient...</div></td>
<td id="TopRight"><div class='chartLoadingOverlay'>Loading chart
please be patient...</div></td>
<td id="BottomLeft"><div class='chartLoadingOverlay'>Loading chart
please be patient...</div></td>
</tr>
</table>
CSS:
#dashboard{
border-collapse: separate;
border-spacing: 5px 5px;
border: 5px solid red;
background-color: blue;
}
div.chartLoadingOverlay{
font-style:italic;
color:gray;
border:1px silver solid;
background-color:#F5F5F5;
line-height:250px;
height:250px;
width:500px;
text-align:center;
margin:2px;
}
@media only screen and (max-width: 1000px){
/* Force table to not be like tables anymore */
#dashboard table{
width: 100%;
border-collapse: collapse;
border-spacing: 0;
display: block;
position: relative;
width: 100%;
}
#dashboard tbody {
/*display: block;*/
width: auto; position: relative;
overflow-x: auto;
white-space: nowrap;
}
#dashboard tbody tr {
display: inline-block;
vertical-align: top;
}
#dashboard td {
display: block;
}
}

Get added/removed/changes key=>value pairs between two arrays

Get added/removed/changes key=>value pairs between two arrays

I have two multidimensional arrays called $old and $new. I want to compare
the two arrays and see what k=>v's were added, removed, or changed between
the two.
These are the arrays:
$old = array(
'ONE' => array('a' => 1, 'b' => 2, 'c' => 3),
'TWO' => array('a' => 4, 'b' => 5, 'c' => 6),
'THREE' => array('a' => 7, 'b' => 8, 'c' => 9)
);
$new = array(
'TWO' => array('a' => 5, 'b' => 5, 'c' => 6),
'THREE' => array('a' => 7, 'b' => 8, 'c' => 9),
'FOUR' => array('a' => 1, 'b' => 2, 'c' => 3)
);
Notice that in the $new array I have removed 'ONE', added 'FOUR', and
changed the value of 'TWO'=>'a' from 4 to 5.
This is my current (working) solution, but I feel that I don't need to
write this much code and I'm unsure if it will be slow on much larger
arrays.
$added = array();
$removed = array();
$changed = array();
foreach ($old as $old_key => $old_value) {
if (!in_array($old_key, array_keys($new))) {
$removed[] = $old_value;
unset($old[$old_key]);
}
}
foreach ($new as $new_key => $new_value) {
if (!in_array($new_key, array_keys($old))) {
$added[] = $new_value;
unset($new[$new_key]);
}
}
$changed = array_udiff($new, $old, create_function(
'$a,$b',
'return strcmp(implode("", $a), implode("", $b));'
));

Wednesday, 11 September 2013

Detect when exe is started vb.net

Detect when exe is started vb.net

Dose anybody know how I can make my VB.net application wait until a
process is detected as running?
I can find example of how to detect once an exe has finished running but
none that detect when an exe is started?

CKEditor multiple style class not working

CKEditor multiple style class not working

I have a custom CMS which using CKEditor. There is a big problem when I am
adding multiple classes to a class attribute.
<p class="abc xyz">
//
</p>
I am adding like this, but it renders as,
<p>
//
</p>
Can I solve this using config.js or something else?

PHP isset method

PHP isset method

I am building a website where a login and register link is displayed. If
the user logs in the login link changes to a logout link which will unset
a variable. I am wondering if there is a better way to do this then
setting and unsetting a variable to be checked with isset()? I am
relatively new to this is why I ask I want to make sure my code is safe,
effective and efficient. Any insight on this would be greatly appreciated.

Apache Tomcat + JSF + Primefaces: Ajax update cause fail on form

Apache Tomcat + JSF + Primefaces: Ajax update cause fail on form

My environment is:
PrimeFaces: 3.1.1
Server: Apache Tomcat 7.0.34.0
JSF: Mojarra 2.2.0
JDK: 1.7.0_25
IDE: Netbeans 7.3.1
SO: Linux Ubuntu 13.04 64bits

I am having the following situation:
There is in my xhtml a form with several components. One of this
components is this below:
<h:panelGrid columns="4"
rendered="#{!inputControlador.tipoDocumentoPessoa()}">
<p:autoComplete
value="#{inputControlador.movimentacao.fornecedor}"
completeMethod="#{inputControlador.completaPjs}"
id="fornecedor"
rendered="#{!inputControlador.tipoDocumentoPessoa()}"
size="50"
var="pj"
itemLabel="#{pj}"
itemValue="#{pj.id}"
forceSelection="true"
converter="#{inputControlador.converterPJ}"
onkeydown="cleanCampos(this.id)">
<p:ajax event="itemSelect"
listener="#{inputControlador.primeiraCategoria}"
update="@form"/>
</p:autoComplete>
...
</h:panelGrid>
When I choose a element in the autoComplete component the anothers
autoCompletes in the form start to fail with this error:
Set 11, 2013 7:00:38 PM
com.sun.faces.application.view.FaceletViewHandlingStrategy
handleRenderException
SEVERE: Error Rendering View[/privado/input/input/edita.xhtml]
java.lang.NullPointerException
at
org.primefaces.component.autocomplete.AutoCompleteRenderer.encodeSuggestionsAsList(AutoCompleteRenderer.java:366)
at
org.primefaces.component.autocomplete.AutoCompleteRenderer.encodeSuggestions(AutoCompleteRenderer.java:313)
at
org.primefaces.component.autocomplete.AutoCompleteRenderer.encodeResults(AutoCompleteRenderer.java:92)
at
org.primefaces.component.autocomplete.AutoCompleteRenderer.encodeEnd(AutoCompleteRenderer.java:74)
at
javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:924)
at
javax.faces.component.UIComponent.encodeAll(UIComponent.java:1863)
at
com.sun.faces.context.PartialViewContextImpl$PhaseAwareVisitCallback.visit(PartialViewContextImpl.java:559)
at
com.sun.faces.component.visit.PartialVisitContext.invokeVisitCallback(PartialVisitContext.java:183)
at
javax.faces.component.UIComponent.visitTree(UIComponent.java:1689)
at
javax.faces.component.UIComponent.visitTree(UIComponent.java:1700)
at
javax.faces.component.UIComponent.visitTree(UIComponent.java:1700)
at
javax.faces.component.UIComponent.visitTree(UIComponent.java:1700)
at
javax.faces.component.UIComponent.visitTree(UIComponent.java:1700)
at javax.faces.component.UIForm.visitTree(UIForm.java:371)
at
javax.faces.component.UIComponent.visitTree(UIComponent.java:1700)
at
javax.faces.component.UIComponent.visitTree(UIComponent.java:1700)
at
com.sun.faces.context.PartialViewContextImpl.processComponents(PartialViewContextImpl.java:399)
at
com.sun.faces.context.PartialViewContextImpl.processPartial(PartialViewContextImpl.java:319)
at
javax.faces.context.PartialViewContextWrapper.processPartial(PartialViewContextWrapper.java:219)
at
javax.faces.component.UIViewRoot.encodeChildren(UIViewRoot.java:1004)
at
javax.faces.component.UIComponent.encodeAll(UIComponent.java:1856)
at
com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:417)
at
com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
at
com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at
com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
at
javax.faces.webapp.FacesServlet.service(FacesServlet.java:647)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at
org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:79)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at
br.com.clicksistemas.web.FiltroEntityManager.doFilter(FiltroEntityManager.java:73)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:581)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
java.lang.IllegalStateException: CDATA tags may not nest
at
com.sun.faces.renderkit.html_basic.HtmlResponseWriter.startCDATA(HtmlResponseWriter.java:681)
at
javax.faces.context.ResponseWriterWrapper.startCDATA(ResponseWriterWrapper.java:179)
at
javax.faces.context.PartialResponseWriter.startError(PartialResponseWriter.java:341)
at
org.primefaces.context.PrimePartialResponseWriter.startError(PrimePartialResponseWriter.java:210)
at
com.sun.faces.context.AjaxExceptionHandlerImpl.handlePartialResponseError(AjaxExceptionHandlerImpl.java:200)
at
com.sun.faces.context.AjaxExceptionHandlerImpl.handle(AjaxExceptionHandlerImpl.java:124)
at
javax.faces.context.ExceptionHandlerWrapper.handle(ExceptionHandlerWrapper.java:100)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:119)
at
com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
at
javax.faces.webapp.FacesServlet.service(FacesServlet.java:647)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at
org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:79)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at
br.com.clicksistemas.web.FiltroEntityManager.doFilter(FiltroEntityManager.java:73)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:581)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
java.lang.IllegalStateException: getWriter() has already been
called for this response
at
org.apache.catalina.connector.Response.getOutputStream(Response.java:605)
at
org.apache.catalina.connector.ResponseFacade.getOutputStream(ResponseFacade.java:197)
at
br.com.clicksistemas.web.FiltroEntityManager.sendProcessingError(FiltroEntityManager.java:172)
at
br.com.clicksistemas.web.FiltroEntityManager.doFilter(FiltroEntityManager.java:113)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:581)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
The interesting (or not) about this is that the same code runs fine
deploying at Windows in mostly cases, occuring rarely.
If instead of send a update for entirely form sent only for some
components someones of its don't stay consitently. Don't show or hide, the
values stay wrong.
It is a very weird behavior and only occurs on this page, on this component.

Java literals, really constants?

Java literals, really constants?

I see/hear people talking about literals as constants, but are they really
constants?
I think of final as a constant:
final constantNumber = 10;
E.g. in the literal below, I am able to change the value.
int testNumber = 10;
System.out.println(testNumber);
testNumber = 20;
System.out.println(testNumber);

Options for working with two databases in C#

Options for working with two databases in C#

Ok I`m new to C# and new to Programing. I have taken on a small task(goal)
for writing my own program for work.
Basically this program will take two databases. One data base will be
update weekly (lets call this doctor list) and the other data base will be
updated as needed (lets call this employee).
Basically I want to make my program compare the two databases and look for
any matching employees on this list doctor list.
I can figure out the code for the searching and basic stuff.. But I have
no clue where to begin with databases.
I'm ok with SQL but my problem is that my doctor list comes in a dbf file.
I've looked up converting to access and sql but this program needs to be
easy to use for are hr department.
Is there away to write the conversion? (again new to this)
What kind of options do I have with just working with programing it to
read off an excel sheet?
If I do go the access or sql router do the computers this program run off
of need to have access or sql loaded?
I`m not looking for someone to write me the code.. just point me in a good
directions and answer some questions...

Can not find definition for element 'document'

Can not find definition for element 'document'

I try to make a SOAP call and one of the parameters is a xml itself. My
call looks like this:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:ns1="vasws.GPAuftrag" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<ns1:insertOrder>
<xmlAuftrag>
<![CDATA[<?xml version="1.0" ?>
<document>
<header><client>029</client></header>
<body><test>1</test></body>
</document>]]>
</xmlAuftrag>
<ziel xsi:type="xsd:string">PISTEST</ziel>
</ns1:insertOrder>
</SOAP-ENV:Body></SOAP-ENV:Envelope>
In return I get an pharsing error:
Can not find definition for element 'document'
I guess I have to somehow define what document but I don't know how. I do
have an order.xsd for validating the inner xml. Maybe I have to use this
somehow?
The SOAP call goes to an axis2 system if that's any help. In the API
definitions I was given only <header> and <body> was defined as well as
the function call insertOrder(xmlAuftrag, ziel) but not how to connect
them.

Is a given graph a k-plex? (similiar to clique)

Is a given graph a k-plex? (similiar to clique)

My problem is the following:
I need to find an algorithm or at least an idea, how to find out in
efficient time if a given graph is a k-plex.
(Quote: "A k-plex is a maximal subgraph with the following property: each
vertex of the induced subgraph is connected to at least n-k other
vertices, where n is the number of vertices in the induced
subgraph."[http://www.analytictech.com/ucinet/help/1pdb_fw.htm])
Is there anything better than just checking if each node is connected to
n-k other nodes?
I would appreciate any help. Thanks in advance.

Delete task is not working under Context Menu?

Delete task is not working under Context Menu?

I was developing Windows Phone App using this sample: Local Database Sample
In that sample, Delete Task has been implemented using an icon. I have
modified Delete Task by Context Menu. But, it does not works for me.
If I pressed Delete, nothing happens.
I dunno what mistake I have done.
My modified Code:
XAML Code:
<TextBlock
Text="{Binding ItemName}"
FontWeight="Thin" FontSize="28"
Grid.Column="0" Grid.Row="0"
VerticalAlignment="Top">
<toolkit:ContextMenuService.ContextMenu>
<toolkit:ContextMenu Name="ContextMenu">
<toolkit:MenuItem Name="Delete" Header="Delete"
Click="deleteTaskButton_Click"/>
</toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>
</TextBlock>
C# Code:
private void deleteTaskButton_Click(object sender, RoutedEventArgs e)
{
// Cast the parameter as a button.
var button = sender as TextBlock;
if (button != null)
{
// Get a handle for the to-do item bound to the button.
ToDoItem toDoForDelete = button.DataContext as ToDoItem;
App.ViewModel.DeleteToDoItem(toDoForDelete);
MessageBox.Show("Deleted Successfully");
}
// Put the focus back to the main page.
this.Focus();
}
Working original Code in that sample:
XAML Code:
<TextBlock
Text="{Binding ItemName}"
FontSize="{StaticResource PhoneFontSizeLarge}"
Grid.Column="1" Grid.ColumnSpan="2"
VerticalAlignment="Top" Margin="-36, 12, 0, 0"/>
<Button
Grid.Column="3"
x:Name="deleteTaskButton"
BorderThickness="0"
Margin="0, -18, 0, 0"
Click="deleteTaskButton_Click">
<Image
Source="/Images/appbar.delete.rest.png"
Height="75"
Width="75"/>
</Button>
C# Code:
private void deleteTaskButton_Click(object sender, RoutedEventArgs e)
{
// Cast the parameter as a button.
var button = sender as Button;
if (button != null)
{
// Get a handle for the to-do item bound to the button.
ToDoItem toDoForDelete = button.DataContext as ToDoItem;
App.ViewModel.DeleteToDoItem(toDoForDelete);
MessageBox.Show("Deleted Successfully");
}
// Put the focus back to the main page.
this.Focus();
}

Tuesday, 10 September 2013

Using Python-requests

Using Python-requests

I was trying to access an API using Python-requests.
When I try this:
url = "http://domain.com"
data = {'field': 'project_id', 'op' : 'eq', 'value' : 'some value'}
r = r.requests(url, params=data)
I could get an API response with the project id specified.
But if I try to pass parameters with the same parameters name with
different value, it cancelled out the first params (project_id):
data = {
'field': 'project_id', 'op' : 'eq', 'value' : 'some value',
'field': 'event_type', 'op' : 'eq', 'value' : 'some event_type'
}
I could get an API response with specified event_type only.
API accepts multi-parameters name, but i just dont know how to do it in
python requests.
I would like to know if I am able to do it using python requests or should
I use different one.

How to modify iOS mail app?

How to modify iOS mail app?

I'd like to add functionality to the existing iOS mail app.
However, I can't find the Apple API to modify the mail app.
How would I go about adding functionality to the existing iOS mail app?

Django 1.4: prefect_related with custom model manager and order_by?

Django 1.4: prefect_related with custom model manager and order_by?

This is a long shot question (doesn't seem like it is possible from the
Django docs, but thought I'd ask just to see if anyone has any ideas).
Note: I'm using Django 1.4.
I want to use a custom model manager on a prefetch_related() query. Then,
on top of that, I want to order the prefetched results in a certain way.
To put it in simplified code, I have the following models (note:
Participant model excluded from code because it is irrelevant):
class GoalParticipant(models.Model):
"""Many-to-many model between Goal and Participant models."""
participant = models.ForeignKey(
'Participant', related_name='goal_participants')
goal = models.ForeignKey('Goal', related_name='goal_participants')
active = models.BooleanField(default=True)
class Goal(models.Model):
name = models.CharField(max_length=50)
progress = models.IntegerField()
active = models.BooleanField(default=True)
class Milestone(models.Model):
name = models.CharField(max_length=50)
progress = models.IntegerField()
goal = models.ForeignKey('Goal', related_name='milestones')
active = models.BooleanField(default=True)
From here, my page controller gets a GoalParticipant Id value (called,
say, pid). I want to display all of the goals and milestones for that ID.
So something like this would work normally:
GoalParticipant.objects.filter(participant=pid).select_related(
).prefetch_related('goal__milestones')
Here are the two wrinkles:
1: Custom Model Manager
All of my classes have custom model managers, like this:
objects = ActiveManager()
all_objects = models.Manager()
The ActiveManager runs .filter(active=True) on the queryset. This is for
convenience, so that I can easily just say .objects by default and have
the active filter thrown in. Occasionally, though, I need to display all
of the objects, not just active ones. So I tried this:
GoalParticipant.all_objects.filter(participant=pid).select_related(
).prefetch_related('goal__milestones')
This gives me all of the goal_participants and all of the goals, but still
restricts to only active milestones. Is there a way to force
prefetch_related to use the all_objects model manager?
2: Custom Ordering for Milestones
Users can actually order the goals / milestones by either name or progress
in the UI, and the ordering should be consistent. For example, if the
goals are ordered by progress, the milestones should also be ordered by
progress. So, say I have a var called ordering with the correct ordering,
I could do this:
GoalParticipant.objects.filter(participant=pid).select_related(
).order_by(ordering).prefetch_related('goal__milestones')
This orders the goals correctly, but there does not seem to be any way to
force the milestones to order in the same way. Is there a way to do this?
Thanks in advance for your help and let me know if I can clarify anything.

Jquery.rating.js validate issue on rails

Jquery.rating.js validate issue on rails

Hi there iam making a form in rails that uses jquery.rating.js , im also
using jquery validation plugin .. I just need to make the stars rating
mandatory (10groups of stars from 1 to 5 stars) .. I search on this cause
i thougth there will be tons of topics, but i just could found 1 with my
issue, and it is not marked as correct answer .. Validation for a required
element, jQuery Star Rating
Also i dont think to "ignore" is the best way to validate a field. Im
using this one http://www.fyneworks.com/jquery/star-rating/
Ok in the application_helper.rb i have this
def rate(player, attribute, disabled=false)
rating = ''
rating = rating + label_tag(:attribute,
t("activerecord.attributes.player.#{attribute}") )
for i in 1..5
rating = rating + radio_button_tag("player[#{attribute}]", i,
player.send(attribute) == i ? true : false, :class => "star",
:disabled => disabled)
end
rating = rating
rating.html_safe
end
My Code wich is validating other stuff (i do not now how to set this to
validate he has rated each one of the questions)
Im using Jquery Validate.
<%= javascript_tag do %>
window.onload = function() {
// validate signup form on keyup and submit
$(".edit_player").validate({ // initialize the plugin
errorElement: 'div'});
$("#player_name").rules("add", { required: true, minlength:2, messages: {
required: "<%= t('generales.camporequerido') %>", minlength: "Mínimo 2
caracteres"}});
$("#player_lastname").rules("add", { required: true, minlength:2,
messages: { required: "<%= t('generales.camporequerido') %>", minlength:
"uh minlength?"}});
$("#player_birthday_1i").rules("add", { required: true, messages: {
required: "<%= t('generales.camporequerido') %>"}});
$("#player_birthday_2i").rules("add", { required: true, messages: {
required: "<%= t('generales.camporequerido') %>"}});
$("#player_birthday_3i").rules("add", { required: true, messages: {
required: "<%= t('generales.camporequerido') %>"}});
$("#player_height").rules("add", { required: true, messages: { required:
"<%= t('generales.camporequerido') %>"}});
$("#player_weight").rules("add", { required: true, messages: { required:
"<%= t('generales.camporequerido') %>"}});
$("#player_city").rules("add", { required: true, messages: { required:
"<%= t('generales.camporequerido') %>"}});
$("#player_birthplace").rules("add", { required: true, messages: {
required: "<%= t('generales.camporequerido') %>"}});
$("#player_citizen").rules("add", { required: true, messages: { required:
"<%= t('generales.camporequerido') %>"}});
$("#player_phone").rules("add", { required: true, messages: { required:
"<%= t('generales.camporequerido') %>"}});
$("#player_cellphone").rules("add", { required: true, messages: {
required: "<%= t('generales.camporequerido') %>"}});
$("#files").rules("add", { required: true, messages: { required: "<%=
t('generales.camporequerido') %>"}});
};
jQuery.extend(jQuery.validator.messages, {
required: "<%= t('generales.camporequerido') %>",
remote: "Please fix this field.",
email: "Ingresa un correo electrónico válido.",
url: "Please enter a valid URL.",
date: "Please enter a valid date.",
dateISO: "Please enter a valid date (ISO).",
number: "Please enter a valid number.",
digits: "Please enter only digits.",
creditcard: "Please enter a valid credit card number.",
equalTo: "Please enter the same value again.",
accept: "Please enter a value with a valid extension.",
maxlength: jQuery.validator.format("Please enter no more than {0}
characters."),
minlength: jQuery.validator.format("Please enter at least {0}
characters."),
rangelength: jQuery.validator.format("Please enter a value between {0}
and {1} characters long."),
range: jQuery.validator.format("Please enter a value between {0} and
{1}."),
max: jQuery.validator.format("Please enter a value less than or equal
to {0}."),
min: jQuery.validator.format("Please enter a value greater than or
equal to {0}.")
});
<% end %>
My html is printed like this
<span class="star-rating-control">
<div class="rating-cancel"><a title="Cancel Rating"></a></div>
<div class="star-rating rater-0 star star-rating-applied
star-rating-live" id="player_short_passes_1">
<a title="1">1</a></div><div class="star-rating rater-0 star
star-rating-applied star-rating-live" id="player_short_passes_2">
<a title="2">2</a></div><div class="star-rating rater-0 star
star-rating-applied star-rating-live" id="player_short_passes_3">
<a title="3">3</a></div><div class="star-rating rater-0 star
star-rating-applied star-rating-live" id="player_short_passes_4">
<a title="4">4</a></div><div class="star-rating rater-0 star
star-rating-applied star-rating-live" id="player_short_passes_5">
<a title="5">5</a></div></span>