Thursday, 3 October 2013

How to place filters or conditions on navigation properties in Entity Framework

How to place filters or conditions on navigation properties in Entity
Framework

I have a table in my sql database called 'Clients' and in that table is a
field called status. It can contain 2 values, 'A' for active or 'I' for
inactive. Meanwhile in my mvc web application using Entity Framework I
have implemented the repository pattern with a specific ClientRepository.
Whenever I make a call to the ClientRepository there is a predefined
filter that ensures all queries are filtered and that only status 'A'
records are returned.. and all is well.
The problem that I am facing now is when I use LINQ to query a table that
is linked to Clients, eg - ClientOrders and then access the navigation
property called Clients. When I do so it retrieves all clients with any
'status' including 'I'.
Does anyone know if there is a way to configure E.F. in the designer or
context to set conditions on navigation properties to satisfy my
requirements such that only status 'A' will be returned?
Note that this is one example of many cases in my application that use
'status' as a record indicator and there are multiple navigation
properties I will need to apply a fix to.
Thanks.

Wednesday, 2 October 2013

Adding Responsive Framework

Adding Responsive Framework

I'm creating a site which I plan to utilize parallax scrolling and
responsive framework. By theory, is it ok to do the responsive framework
last as I'd like to finish the layout of the site before adding my
settings for the responsive framework?

How to fix the issue git commit diverged?

How to fix the issue git commit diverged?

I am little bit familiar with git and and have successfully done the git
clone, commit etc on my project. But now there is a complex situation
comes in my project because of git. When i check the git status there is a
message like
Your branch and 'origin/develop' have diverged. and have 5 and 3
different commits each, respectively.
Also i am attaching here my git network diagrom
Any body can help to fix this issue?

Upgrading from MySQL 4.7 to 5.5, problematic date fields

Upgrading from MySQL 4.7 to 5.5, problematic date fields

I get this error in a legacy application running SQL from JSP pages (not
my app):
java.sql.SQLException: Value '7Some text from a field123133
2001-09-2012001-10-01 08:37:1910000-00-00 00:00:00' can not be represented
as java.sql.Timestamp/p /blockquote pIt looks like the fields are
concatenated and that is what the timestamp (and date, and datetime) is
trying to decipher. Everything works fine if I run the query in mysql
client and if I remove all date, datetime and timestamp fields. This
happens when executeQuery(query) is run./p pWhat I've done:/p ul
limysqldump the old database/li liimported to the new/li lichanged the old
mysql driver to mysql-connector-java-5.1.26-bin.jar/li liremoved any old
jdbc libraries/li litomcat is running on java 1.7/li /ul pI'm guessing
it's a problem with libraries./p ul liapache-tomcat-7.0.42/li
li5.5.32-0ubuntu0.12.04.1 (Ubuntu)/li lijdk1.7.0_15/li /ul pHere's the
tomcat/lib:/p pactivation.jar catalina-tribes.jar el-api.jar jmxtools.jar
naming-factory.jar poolman.xml tomcat-i18n-es.jar annotations-api.jar
commons-codec-1.4.jar hssf-serializer.jar jsp-api.jar NetComponents.jar
servlet-api.jar tomcat-i18n-fr.jar catalina-ant.jar cos.jar jasper-el.jar
log4j.jar pg73jdbc3.jar tomcat-api.jar tomcat-i18n-ja.jar catalina-ha.jar
dnsjava.jar jasper.jar mail.jar poi-hssf.jar tomcat-coyote.jar
tomcat-jdbc.jar catalina.jar ecj-4.2.2.jar jmxri.jar
mysql-connector-java-5.1.26-bin.jar poolman.jar tomcat-dbcp.jar
tomcat-util.jar/p pAnd a few in the WEB-INF/lib:/p pfop.jar jce1_2_1.jar
jsse.jar NetaxeptClientVirtual.jar soap.jar w3c.jar xerces.jar/p pThanks
for any help!/p

Tuesday, 1 October 2013

How to build a Wordpress form searching posts in a specific category only or sitewide?

How to build a Wordpress form searching posts in a specific category only
or sitewide?

I want to build a Wordpress search from that if somebody selects "Game",
it searches posts in the "Game" category. Or if he/she chooses "The rest
of the site", it searches posts/pages in the site except posts in the
"Game" category. I think radio button is a good option for the selection.
How do I do it? Cheers.

UIPicker no longer working iOS7

UIPicker no longer working iOS7

Hi My UI Picker no longer works on iOS7, it pops up but it is blank. Only
happened on iOS7.
//picker
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row
inComponent:(NSInteger)component{
animationsLabel.text = [optionsArray objectAtIndex:[picker
selectedRowInComponent:0]];
if (pickerView==animationsPicker) {
animationsLabel.text = [optionsArray objectAtIndex:[animationsPicker
selectedRowInComponent:0]];
}
}
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
return 1;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView
numberOfRowsInComponent:(NSInteger)component{
return [optionsArray count];
}
-(NSString *)pickerView:(UIPickerView *)pickerView
titleForRow:(NSInteger)row forComponent:(NSInteger)component{
return [optionsArray objectAtIndex:row];
NSLog(@"title options array %lu",(unsigned long)optionsArray.count);
}
and the action:
-(IBAction)animationActionSheet:(id)sender {
UIActionSheet *selectPopup = [[UIActionSheet alloc]
initWithTitle:@"\n\n\n\n\n\n\n\n"
delegate:nil
cancelButtonTitle:nil
destructiveButtonTitle:nil
otherButtonTitles:nil];
[selectPopup showInView:self.view];
optionsArray = [[NSMutableArray alloc]
initWithObjects:@"1",@"2",@"3",@"4",@"6",@"5",@"7",@"8",@"9", nil];
// Create picker
animationsPicker = [[UIPickerView alloc] initWithFrame:CGRectMake(10, 160,
320, 100)];
animationsPicker.showsSelectionIndicator = YES;
[self.view addSubview:animationsPicker];
animationsPicker.delegate = self;
animationsPicker.dataSource = self;
[selectPopup addSubview:animationsPicker];
// Animate picker opening
[UIView beginAnimations:nil context:nil];
[selectPopup setBounds:CGRectMake(0, 0, 320, 485)];
[UIView commitAnimations];
}
This is what I have tried so far. There was never a problem displaying the
picker in the an Action sheet before, but now it is blank. Im wondering
did anyone else come across this problem, or can you see any errors? I
printed everything to do with the picker.

What does this notation denote?

What does this notation denote?

What does the following notation denote: $$\bigcup_{i=1}^\infty
\bigcap_{j\ge i}^\infty A_i$$
A. All elements that are in finitely many $A_i$;
B. All elements that are in infinitely many $A_i$;
C. All elements that are in all but infinite numbers of $A_i$;
Please help me, thank you.

Dual monitor wont play media centre on primary screen

Dual monitor wont play media centre on primary screen

I am running ubuntu 13.04 on a laptop that is connected to my TV.
Everything seems to work fine but when I open my media centre (XBMC) it
will only run in full screen on the laptop. I have changed the display
settings to a dual screen set up with the TV as the launcher screen but
the only way i can get XBMC on the TV is to run it in a window and drag it
over to the TV. Can anyone help me? Should I have version 12.04 instead?

Monday, 30 September 2013

Extracting a zip file in my machne givs me CRC error?

Extracting a zip file in my machne givs me CRC error?

I have a large zip that contain hundreds of file. I've unzip'ed it in more
than one machine and didn't have any problem before. However, for this
particular machine (Ubuntu Server 12.04) I keep getting CRC error for some
of the files inside my zip. I've unzip'ed the same file it on anther
machine just to and its fine.
Any clue?

Crontab issue with specific days execution

Crontab issue with specific days execution

We have a cron job under a specific user's crontab which should be running
only on working week days. Job was running all days before we changed it.
After we changed in the following line the days statement from '*' to
'1-5', testscript.sh is still running all days and the weekend that is not
supposed to.
00 21 * * 1-5 /usr/local/bin/test_script.sh >>
/var/log/userdirectory/test_script.log 2>&1
Any ideas why?

uwsgi processes * threads = maximum simultanous connections?

uwsgi processes * threads = maximum simultanous connections?

We are using uwsgi to serve the python app behind nginx.
Can I hope that the theoretical maximum of simultaneously served client
connections is equal to uwsgi processes * threads?
We are using server-sent events, so, the connections are held for a long
time.

Android, SOAP Request geting errors

Android, SOAP Request geting errors

I Try to start SAOP request via android an i got some code:
WSRequests wsr = new WSRequests();
try {
WSRequests.getList(Constants.STUDY_WSDL,
Constants.OC_USERNAME, Constants.OC_PASSWORD);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
There i start a method in WSRequests, the Code from WSRequest:
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPException;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.imirwthaachen.camtests.constants.Constants;
import com.imirwthaachen.ws.study.StudyType;
import com.imirwthaachen.ws.study.WsService;
public class WSRequests {
public static List<StudyType> getList(String OpenclinicaWSurl, String
username, String hashedPassword) throws IOException {
HeaderHandler.username = username;
HeaderHandler.password = hashedPassword;
HeaderHandler.doc = null;
URL wsdlLocation = new URL (Constants.STUDY_WSDL);
WsService ws = new WsService(wsdlLocation, new
QName("http://openclinica.org/ws/study/v1", "wsService"));
ws.setHandlerResolver(new ClientHandlerResolver());
ws.getWsSoap11().listAll("");
List<StudyType> r = new ArrayList<StudyType>();
try{
NodeList nodes =
HeaderHandler.responseMessage.getSOAPBody().getElementsByTagName("study");
for(int index = 0; index < nodes.getLength(); index++){
Node node = nodes.item(index);
if(node.getNodeType() != Node.ELEMENT_NODE)
continue;
Element element = (Element)node;
StudyType study = new StudyType();
study.setIdentifier(element.getElementsByTagName("identifier").item(0).getTextContent());
study.setName(element.getElementsByTagName("name").item(0).getTextContent());
study.setOid(element.getElementsByTagName("oid").item(0).getTextContent());
r.add(study);
}
}
catch(SOAPException ex){
ex.printStackTrace();
}
return r;
}
and the Code from HeaderHandler is like :
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class HeaderHandler implements SOAPHandler<SOAPMessageContext> {
public static String username = "XXXXX";
public static String password = "XXXXXXXXX";
/** The soap response message */
public static SOAPMessage responseMessage;
public static Document doc;
public boolean handleMessage(SOAPMessageContext smc) {
Boolean outboundProperty = (Boolean) smc
.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (outboundProperty.booleanValue()) {
try {
SOAPEnvelope envelope = smc.getMessage().getSOAPPart()
.getEnvelope();
SOAPHeader header = envelope.addHeader();
SOAPElement security = header
.addChildElement(
"Security",
"wsse",
"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
SOAPElement usernameToken = security.addChildElement(
"UsernameToken", "wsse");
usernameToken
.addAttribute(
new QName("xmlns:wsu"),
"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
SOAPElement username = usernameToken.addChildElement(
"Username", "wsse");
username.addTextNode(HeaderHandler.username);
SOAPElement password = usernameToken.addChildElement(
"Password", "wsse");
password.setAttribute(
"Type",
"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText");
password.addTextNode(HeaderHandler.password);
if (doc != null) {
Node odmNode = smc.getMessage().getSOAPBody()
.getOwnerDocument()
.importNode(doc.getDocumentElement(), true);
NodeList nodes = smc.getMessage().getSOAPBody()
.getChildNodes();
for (int index = 0; index < nodes.getLength(); index++) {
Node node = nodes.item(index);
if (node.getNodeType() == Node.ELEMENT_NODE) {
node.appendChild(odmNode);
break;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
try {
// This handler does nothing with the response from the Web
// Service so
// we just print out the SOAP message.
responseMessage = smc.getMessage();
// message.writeTo(System.out);
System.out.println("");
} catch (Exception ex) {
ex.printStackTrace();
}
}
return outboundProperty;
}
now to my problem, i know its a tone of code but i think these
Informations are nessesary after i run my app i will get an exeption. On
first :I/dalvikvm(632): Failed resolving
Lcom/imirwthaachen/ocws/HeaderHandler; interface 1883
'Ljavax/xml/ws/handler/soap/SOAPHandler;'
and at least : FATAL EXCEPTION: main 09-30 08:51:28.897:
E/AndroidRuntime(632): java.lang.NoClassDefFoundError:
com.imirwthaachen.ocws.HeaderHandler
i´m searching the internet for 2 days and tryed out many solutions but
nothing helps. please can someone explain me whats wrongwith my code /
Projekt setup?
PS.: I Treied to setup up the Play Store, movine gen on top, moveing
andorid on top, deleeting som references from build path... nothing works
Thanks a lot Christian

Sunday, 29 September 2013

Question about Royden's proof that Lebesgue measure is countably additive.

Question about Royden's proof that Lebesgue measure is countably additive.

In Royden's book, he gives the following book for the proof that Lebesgue
measure is countable additive. I will just give a sketch of the proof.
Let $\{E_k \}_{k=1}^{\infty}$ be a collection of disjoint measurable sets.
We only need to show that $$ m(\cup_{k=1}^{\infty} E_k) \geq
\sum_{k=1}^{\infty} m(E_k) $$ since it follows by countable subadditivtiy
that $$ m(\cup_{k=1}^{\infty} E_k) \leq \sum_{k=1}^{\infty} m(E_k) $$ For
any finite subcollection of $\{E_k \}_{k=1}^{\infty}$, it follows by
monotonicty that $$ m(\cup_{k=1}^{\infty} E_k) \geq \sum_{k=1}^{n} m(E_k)
$$ for each n. What confuses me is the next statement: "Since the left
hand side of the inequality is independent of n it follows that"
$$ m(\cup_{k=1}^{\infty} E_k) \geq \sum_{k=1}^{\infty} m(E_k) $$ as
desired. Why is it true that the left hand side of this inequality is
independent of n?

Java. How to get constant read times from text file?

Java. How to get constant read times from text file?

I have text file which contains over 1kk integer numbers. I want to read
the n-th number in constant time. I'm not allowed to put all integers in
the array. I heard that there is a technique which operates with bytes, so
I could just write method "getNthInteger(int nth, int
elementLengthInBytes)" or something like that. Please give me reference to
this technique, any help is appreciated!

What is the number of all set permutations in a power set?

What is the number of all set permutations in a power set?

For a set of size n, the size of its power set is 2^n. Generate all
permutations for each element of the power set. The power set for set {a,
b} is {{}, {a}, {b}, {a,b}}. Generate all permutations on each set, we can
get {(),(a),(b),(a,b),(b,a)}. So the number of all subset permutation for
a power set generated from a 2-element set is 5. And such a number for a
3-item set is 16. Is there a formula for this number defined in terms of
n?

Abstract class error? (MinGW)

Abstract class error? (MinGW)

I'm getting a error that's I don't know why. First, here is my codes:
//IProgram.h
class IProgram
{
public:
virtual void Log(const char* msg) = 0;
};
//Program.h
#include "IProgram.h"
class Program
{
private:
IProgram &m_IProgram;
public:
Program(IProgram &iprg) : m_IProgram(iprg)
{
m_IProgram.Log("Program initialized!");
}
};
//MyClass
#include "IProgram.h"
class MyClass : public IProgram
{
private:
Program m_Program;
void Log(const char* msg)
{
printf("%s\n", msg);
}
public:
MyClass() : m_Program(*this) { }
};
The problem is, if I include another header like pthread.h to 'Program.h'
compiler (MinGW) says: "expected ',' or '...' before 'struct'" and
"expected primary-expression before 'struct'". Error is casting from
'Program(IProgram &iprg)' constructor. What's wrong?
(IProgram is not a struct, it is a abstract class. And compiler called it
with "struct"?)
EDIT: If I don't include anything (only Interface.h), there is no error.

Saturday, 28 September 2013

Problem about indexing files between partitions

Problem about indexing files between partitions

I'm here for talking to you about a problem. First of all sorry for being
noobish but I just installed Ubuntu this night. Anyhow, here's the
problem: I have my PC with a double boot Ubuntu+Windows 8 and I installed
Ubuntu in a secondary partition in my 500gb hard drive. In the other
partition there are my files such as music, downloads etc for my windows
hard drive ( I have an SSD where is stored 8 and an hard drive where I
have my files and Ubuntu). So now I'm trying to use my music with
banshee's library system and at the first time that I used that library I
got no problems. Now that I reboot Ubuntu when I try to play the music the
software just says that he can't find the file ( I suppose that Ubuntu
gets some time before loading files from other partitions but dunno... ).
And the same thing happens with my Dropbox folder withc is in the same
partition of the music one. So, Is there a way to fix this annoying
problem or it's just something that I should ignore ? Anyhow, Ubuntu 13.04
is installed on ext4 and my file partition on ntfs. For better
understanding here a little graphic explanation about my partitions:
C: -> Windows 8 D: -> Ubuntu partition (E:) My files Basically the file
hard drive has two partitions Sorry for my English mistackes but I'm
Italian
Thank you for the attention given to me and have a nice day

RewriteRule without absolute path

RewriteRule without absolute path

I want to make this url point to another url in the same directory but I
can't get it to work without giving the absolute url.
I want this url http://www.mysite.com/path/file/
To point to: http://www.mysite.com/path/file.php
I have this: RewriteRule ^(\w+)/?$ /path/$1.php
I want this: RewriteRule ^(\w+)/?$ $1.php
So it should automatically infer that the url should point to a file with
the same name in the same directory. Is it possible?

How to use javascript using PHP?

How to use javascript using PHP?

Scenario:
I created a filtering using IF ELSE where when the user click BOX A AND
BOX B... Then assuming the BOX A is already full, after the user hit the
"SAVE BUTTON", a confirmation message will display saying that... "The Box
you chosen is already full. Do you want to save the other items?"
Here's my Code:
else if($box== "BOX A" && $row[item] == "100")
{
<?php
echo "<script type='text/javascript'>";
echo "var r=confirm('The Box you chosen is already full. Do you want
to save the other items?')";
echo "if (r==true){";
echo "alert('You pressed OK!')}";
echo "else{";
echo "alert('You pressed Cancel!')}";
echo "</script>";
?>
}
I have a problem with the code and when I try to trace it using echo
"enter here"; its always stop after the program read this code
echo "<script type='text/javascript'>";
Then it will jump it in here:
echo "</script>";
RESULT:
its not displaying the pop up message ... So all I need is to display the
pop up message and I dont know why, why its not displaying... There is no
button involve for the displaying of confirmation message...It will just
pass by in if else and then it will prompt up if the user wants to
continue the saving if one of the box is already full if not he/she will
press the cancel...
NOTE: I'm only a beginner for PHP and Javascript..
Thank you in advance.

underscore find method issue on array of objects

underscore find method issue on array of objects

I have following array of objects
var ppl = [
{
name: "John",
content: "<p>description</p>"
},
{
name: "Mike",
content: "<p>Desc</p>"
},
{
name: "Steve",
content: "html"
},
{
name: "Michael",
content: "<p>description</p>"
}
];
What I am doing is to display above array. Then when user clicks on name
return his content. Like following
$('a.ppl').on('click', function (e) {
e.preventDefault();
var text = $(this).text();
var content = _.find(ppl, function (desc) { if (desc.name ===
text) return desc.content; });
console.log(content);
});
What above code does is it finds the content of the person clicked however
it returns the entire object of that person e.g. when John is clicked the
his entire object { name: "John", content: "<p>description</p>" } is
returned by the _.find() function. I just need the content. How can I
return content only?

Friday, 27 September 2013

A few problems with code

A few problems with code

So far I have the code below:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Fiddler;
using Newtonsoft.Json;
namespace KAWAlliesBot
{
public partial class main_Form : Form
{
delegate void UpdateUI();
string[] Allies = new string[26];
public main_Form()
{
InitializeComponent();
}
private void main_Form_Load(object sender, EventArgs e)
{
Fiddler.FiddlerApplication.AfterSessionComplete +=
FiddlerApplication_AfterSessionComplete;
Fiddler.FiddlerApplication.FiddlerDetach +=
FiddlerApplication_OnDetach;
Fiddler.FiddlerApplication.Startup(0,
Fiddler.FiddlerCoreStartupFlags.Default);
}
void FiddlerApplication_AfterSessionComplete(Fiddler.Session oSession)
{
if (oSession.url ==
"api.kingdomsatwar.com/game/user/search_clan_members_by_cost/")
{
main_Listbox.Invoke(new UpdateUI(() =>
{
oSession.utilDecodeResponse();
var allies_Array =
JsonConvert.DeserializeObject<RootObject>(oSession.GetResponseBodyAsString());
var totalBonusUsers = (from user in allies_Array.users
let tot = user.bonus.GetTotalBonus()
select new TotalUserBonus {
username = user.username,
totalBonus = tot
}).ToList().OrderByDescending(u =>
u.totalBonus).ToList();
foreach(var values in totalBonusUsers) {
main_Listbox.Items.Add(values.totalBonus + " --- " +
values.username);
main_Listbox.Sorted = true;
}
}));
}
}
private void main_Form_FormClosing(object sender, FormClosingEventArgs e)
{
Fiddler.FiddlerApplication.Shutdown();
}
static void FiddlerApplication_OnDetach() {
MessageBox.Show("Program is reseting proxies please exit again!");
System.Diagnostics.Process.Start("proxycfg.exe", "-u");
}
private void button1_Click(object sender, EventArgs e)
{
main_Listbox.Items.Clear();
}
}
public class Bonus
{
public int spy_defense { get; set; }
public int plunder { get; set; }
public int attack { get; set; }
public int defense { get; set; }
public int spy_attack { get; set; }
public int GetTotalBonus()
{
return spy_defense + attack + defense + spy_attack;
}
}
public class User
{
public string username { get; set; }
public int user_id { get; set; }
public List<object> recent_gifts { get; set; }
public int class_id { get; set; }
public Bonus bonus { get; set; }
public object superpower_expire_date { get; set; }
public int avatar_id { get; set; }
public int avatar_type { get; set; }
public object cost { get; set; }
}
public class RootObject
{
public List<User> users { get; set; }
}
public class TotalUserBonus
{
public string username { get; set; }
public int totalBonus { get; set; }
}
}
Now the site this works for only loads 26 values at a time. So it sorts
26, but when you goto the next page it starts over again where the new
values are being added to the list box. How would I fix this/ sort them by
the bonus value?

Hunchentoot dispatch by HTTP method

Hunchentoot dispatch by HTTP method

I couldn't find any documentation on how to dispatch based on HTTP method
(on the same uri). The closest I got was :default-request-type on the
define-easy-handler -- but it seems to dispatch to the latter, even though
I use GET method:
(define-easy-handler (index :uri "/" :default-request-type :get) ()
(log-message* :info "GET on index ------ ")
(format nil "Hello World"))
(define-easy-handler (echo :uri "/" :default-request-type :post) ()
(log-message* :info "POST on index ------ ")
(format nil "~S" (raw-post-data :force-text t)))

Duplicate all strings in Xcode?

Duplicate all strings in Xcode?

I remember reading somewhere about one of Xcode's features which will
cause all strings in your application to appear as double in length,
simply by repeating their contents. For example, if a UILabel contains the
text Username:, it will now contain the text Username:Username:. I can't
find any reference to this on Google. How can I access this feature in
Xcode?
The idea is that it can help you debug localization issues, since some
languages have very long strings compared to English.

match portions of an optional section

match portions of an optional section

I have a regex set up to match a US-formatted date and time. It looks like
this:
/(\d{1,2})\/(\d{1,2})\/(\d{2,4}) (\d{1,2}):(\d{1,2})(am|pm|AM|PM|Am|Pm)/
However, I need it to also match dates that do not contain the time
component.
How do I modify this, so that if it's a date, I get 3 matches, and if it's
a date-time, I get six?

Why are these asp values not passed to code behind? (ASP & Visual Studio)

Why are these asp values not passed to code behind? (ASP & Visual Studio)

This web form should feed into an access database. However it keeps saying
stuff like " Field 'Exhibits.FirsNtame' cannot be a zero-length string." I
know the code works because it will write to the database if I hard code
in values. How do I get values to the variables in the code behind the
page?
Here is the web page:
<%@ Page Language="VB" MasterPageFile="~/Site.master"
AutoEventWireup="false" CodeFile="ScienceFair.aspx.vb"
Inherits="_Default" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent"
Runat="Server">
<style type="text/css">
.auto-style1 {
text-align: center;
}
</style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent"
Runat="Server">
<div id="RuleBreaker">
<h2 class="auto-style1">Science Fair Registration</h2>
<p class="auto-style1" >
First Name:
<br />
<asp:TextBox ID="FirsNtame" runat="server"
AutoCompleteType="FirstName"></asp:TextBox>
<br />
<asp:RequiredFieldValidator id="FirsNtameValidator1" runat="server"
ControlToValidate="FirsNtame"
ErrorMessage="A first name is required."
ForeColor="Red">
</asp:RequiredFieldValidator>
<br />
Last Name:
<br />
<asp:TextBox ID="LasNtame" runat="server"
AutoCompleteType="LastName"></asp:TextBox>
<br />
<asp:RequiredFieldValidator id="LasNtameValidator2" runat="server"
ControlToValidate="LasNtame"
ErrorMessage="A last name is required."
ForeColor="Red">
</asp:RequiredFieldValidator>
<br />
Student Email Address:
<br />
<asp:TextBox ID="StudentEmail" runat="server"
AutoCompleteType="Email"></asp:TextBox>
<br />
<asp:RequiredFieldValidator id="StudentEmailValidator3" runat="server"
ControlToValidate="StudentEmail"
ErrorMessage="A Student Email is required."
ForeColor="Red">
</asp:RequiredFieldValidator>
<br />
<br />
School:
<br />
<asp:TextBox ID="School" runat="server"></asp:TextBox>
<br />
<asp:RequiredFieldValidator id="SchoolValidator4" runat="server"
ControlToValidate="School"
ErrorMessage="Your school name is required."
ForeColor="Red">
</asp:RequiredFieldValidator>
<br />
Grade:
<br />
<asp:DropDownList id="Grade" runat="server" Width="86px">
<asp:ListItem>7</asp:ListItem>
<asp:ListItem>8</asp:ListItem>
<asp:ListItem>9</asp:ListItem>
<asp:ListItem>10</asp:ListItem>
<asp:ListItem>11</asp:ListItem>
<asp:ListItem>12</asp:ListItem>
</asp:DropDownList>
<br />
<asp:RequiredFieldValidator id="GradeValidator5" runat="server"
ControlToValidate="Grade"
ErrorMessage="A grade is required."
ForeColor="Red">
</asp:RequiredFieldValidator>
<br />
Teacher's Last Name (only):<br />
<asp:TextBox id="Teacher" runat="server"
Width="500px"></asp:TextBox>
<br />
<asp:RequiredFieldValidator id="TeacherValidator6" runat="server"
ControlToValidate="Teacher"
ErrorMessage="A teacher last name is required."
ForeColor="Red">
</asp:RequiredFieldValidator>
<br />
Teacher E-mail:<br />&nbsp;<asp:TextBox ID="TeacherEmail"
runat="server"
Width="500px"></asp:TextBox>
<br />
<asp:RequiredFieldValidator id="TeacherEmailValidator7" runat="server"
ControlToValidate="TeacherEmail"
ErrorMessage="A teacher email is required field."
ForeColor="Red">
</asp:RequiredFieldValidator>
<br />
<%-- Teacher Phone Number:<br />&nbsp;<asp:TextBox
id="TPhone" runat="server" Width="500px"></asp:TextBox>
--%>
<%-- Might put the above in later --%>
Catagory :<br />&nbsp;<asp:DropDownList id="Catagory"
runat="server" Width="212px">
<asp:ListItem>Behavorial &amp; Social
Sciences</asp:ListItem>
<asp:ListItem>Biochemistry &amp;
Microbiology</asp:ListItem>
<asp:ListItem>Botany</asp:ListItem>
<asp:ListItem>Environmental Sciences</asp:ListItem>
<asp:ListItem>Medicine &amp; Health</asp:ListItem>
<asp:ListItem>Zoology</asp:ListItem>
<asp:ListItem>Chemistry</asp:ListItem>
<asp:ListItem>Computer Science</asp:ListItem>
<asp:ListItem>Earth &amp; Space Sciences</asp:ListItem>
<asp:ListItem>Engineering</asp:ListItem>
<asp:ListItem>Mathematics</asp:ListItem>
<asp:ListItem>Physics</asp:ListItem>
</asp:DropDownList>
<br />
<asp:RequiredFieldValidator id="CatagoryValidator8" runat="server"
ControlToValidate="Catagory"
ErrorMessage="A catagory is required."
ForeColor="Red">
</asp:RequiredFieldValidator>
<br />
Exibit Title :<br />&nbsp;<asp:TextBox id="ExibitTite"
runat="server" Width="500px"></asp:TextBox>
<br />
<asp:RequiredFieldValidator id="ExibitTiteValidator9" runat="server"
ControlToValidate="ExibitTite"
ErrorMessage="A title is required."
ForeColor="Red">
</asp:RequiredFieldValidator>
<br />
Does your exhibit use electricity?<br />
<%-- Possible issues here, may need to use 1 & 0 instead--%>
<asp:DropDownList id="Electricity" runat="server">
<asp:ListItem Value="Yes">Yes</asp:ListItem>
<asp:ListItem Value="No">No</asp:ListItem>
</asp:DropDownList>
<br />
<asp:RequiredFieldValidator id="ElectricityValidator10" runat="server"
ControlToValidate="Electricity"
ErrorMessage="Does your computer use electricity?"
ForeColor="Red">
</asp:RequiredFieldValidator>
<br />
</p>
<p class="auto-style1" >
<asp:Button ID="SciFairSubmit" runat="server"
Text="Submit" />
<br />
<br />
</p>
</div>
</asp:Content>
Here is the aspx code behind the page:
Imports System.Data.OleDb
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub SciFairSubmit_Click(sender As Object, e As
EventArgs) Handles SciFairSubmit.Click
'form data
requests----------------------------------------------------------------------------C:\Users\NCG-PC\Webmastering\TamugSciFair13\WebSite1\Default1.aspx.vb
Dim strName As String = If(Request.Form("FirsNtame"), "")
Dim strLasNtame As String = If(Request.Form("LasNtame"), "")
Dim strStudentEmail As String =
If(Request.Form("strStudentEmail"), "")
Dim strSchool As String = If(Request.Form("strSchool"), "")
Dim numGrade As String = If(Request.Form("numGrade"), "")
Dim strTeacher As String = If(Request.Form("strTeacher"), "")
Dim strTeacherEmail As String =
If(Request.Form("strTeacherEmail"), "")
Dim strCatagory As String = If(Request.Form("strCatagory"), "")
Dim strExibitTite As String =
If(Request.Form("strExibitTite"), "")
Dim strElectricity As String =
If(Request.Form("strElectricity"), "")
'Open Db
Connection---------------------------------------------------------------------------------------------------------
Dim strSQL As String
Dim dbconn As OleDbConnection = Nothing
dbconn = New
OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;data
source=" &
Server.MapPath("\GalvestonScienceFair\App_Data\sf13.mdb"))
dbconn.Open()
'SQL actions
----------------------------------------------------------------------------------------------------------
strSQL = "INSERT INTO Exhibits (FirsNtame, LasNtame,
StudentEmail, School, Grade, Teacher, TeacherEmail, Category,
ExibitTite, Electricity) values (@FirsNtame, @LasNtame,
@StudentEmail, @School, @Grade, @Teacher, @TeacherEmail,
@Category, @ExibitTite, @Electricity)"
Dim objcmd = New OleDbCommand(strSQL, dbconn)
objcmd.Parameters.Add(New
System.Data.OleDb.OleDbParameter("@FirsNtame", strName))
objcmd.Parameters.Add(New
System.Data.OleDb.OleDbParameter("@LasNtame", strLasNtame))
objcmd.Parameters.Add(New
System.Data.OleDb.OleDbParameter("@StudentEmail",
strStudentEmail))
objcmd.Parameters.Add(New
System.Data.OleDb.OleDbParameter("@School", strSchool))
objcmd.Parameters.Add(New
System.Data.OleDb.OleDbParameter("@Grade", numGrade))
objcmd.Parameters.Add(New
System.Data.OleDb.OleDbParameter("@Teacher", strTeacher))
objcmd.Parameters.Add(New
System.Data.OleDb.OleDbParameter("@TeacherEmail",
strTeacherEmail))
objcmd.Parameters.Add(New
System.Data.OleDb.OleDbParameter("@Category", strCatagory))
objcmd.Parameters.Add(New
System.Data.OleDb.OleDbParameter("@ExibitTite",
strExibitTite))
objcmd.Parameters.Add(New
System.Data.OleDb.OleDbParameter("@Electricity",
strElectricity))
'Sets each parameter to "DBNULL" or "blank" if they are
null/blank
'objcmd.Parameters.Add(New
System.Data.OleDb.OleDbParameter("@FirsNtame", If(strName,
DBNull.Value)))
For Each param As System.Data.OleDb.OleDbParameter In
objcmd.Parameters
If param.Value Is Nothing Then
param.Value = DBNull.Value
End If
Next
objcmd.ExecuteNonQuery()
'Close DB Connection
dbconn.Close()
Response.Write("Thank you for registering!")
End Sub
End Class

NSTimer Milliseconds countdown

NSTimer Milliseconds countdown

I would like to make a simple countdown with seconds and millisecond:
SS:MM. However, i would like to stop the timer or do something when the
timer reach 0:00. Currently the timer works, but it doesnt stop at 0:00. I
can make the seconds stop, but not the milliseconds. What is wrong?
-(void) setTimer {
MySingletonCenter *tmp = [MySingletonCenter sharedSingleton];
tmp.milisecondsCount = 100;
tmp.secondsCount = 2;
tmp.countdownTimerGame = [NSTimer
scheduledTimerWithTimeInterval:.01 target:self
selector:@selector(timerRun) userInfo:nil repeats:YES];
}
-(void) timerRun {
MySingletonCenter *tmp = [MySingletonCenter sharedSingleton];
tmp.milisecondsCount = tmp.milisecondsCount - 1;
if(tmp.milisecondsCount == 0){
tmp.milisecondsCount = 100;
tmp.secondsCount -= 1;
}
NSString *timerOutput = [NSString stringWithFormat:@"%2d:%2d",
tmp.secondsCount, tmp.milisecondsCount];
timeLabel.text = timerOutput;
if ((tmp.secondsCount == 0) && tmp.milisecondsCount == 0) {
NSLog(@"Test");
tmp.lives = tmp.lives - 1;
NSString *newLivesOutput = [NSString stringWithFormat:@"%d",
tmp.lives];
livesLabel.text = newLivesOutput;
[tmp.countdownTimerGame invalidate];
tmp.countdownTimerGame = nil;
[self setTimer];
if (tmp.lives == 0) {
[self performSelector:@selector(stopped) withObject:nil];
}

Creating Class instances in Unity at runtime

Creating Class instances in Unity at runtime

I want to create X objects in a loop, access and set properties of newly
created objects. I've used the Instantiate method with a passed RigidBody,
like shown in the tutorial, but I need to access the properties of the
script connected to the object, not just it's rigid body.
Here's the method I'm trying to make work:
public void makeGrid(int w = 10, int h = 10)
{
gridWidth = w;
gridHeight = h;
int tileArrayLength = gridWidth * gridHeight;
tileArray = new Tile[tileArrayLength];
for (int i = 0; i < gridWidth; i++)
{
for (int j = 0; j < gridHeight; j++)
{
// add tiles
Tile t = new Tile(); // !!! doesn't work >_<
t.posX = i;
t.posY = j;
t.id = j + 10 * i;
tileArray[t.id] = t;
}
}
}

Thursday, 26 September 2013

Google App Engine Deploy Fails: "Can't get the System Java Compiler"

Google App Engine Deploy Fails: "Can't get the System Java Compiler"

I have been deploying my app no trouble, then all of a sudden it fails. I
am not sure what I have done to cause this. The error messages when
deploying with the eclipse plugin were not very helpful. This info when
deploying from the commandline seems a little more informative:
Reading application configuration data...
Sep 27, 2013 5:48:50 PM
com.google.apphosting.utils.config.AppEngineWebXmlReader
readAppEngineWebXml
INFO: Successfully processed ./war\WEB-INF/appengine-web.xml
Sep 27, 2013 5:48:50 PM
com.google.apphosting.utils.config.AbstractConfigXmlRead
er readConfigXml
INFO: Successfully processed ./war\WEB-INF/web.xml
Sep 27, 2013 5:48:50 PM
com.google.apphosting.utils.config.AbstractConfigXmlRead
er readConfigXml
INFO: Successfully processed ./war\WEB-INF/queue.xml
Sep 27, 2013 5:48:50 PM
com.google.apphosting.utils.config.IndexesXmlReader read
ConfigXml
INFO: Successfully processed
.\war\WEB-INF\appengine-generated\datastore-indexes
-auto.xml
Beginning interaction for module default...
0% Created staging directory at:
'C:\Users\XXXXXX\AppData\Local\Temp\appcfg690
1219943971905638.tmp'
5% Scanning for jsp files.
8% Compiling jsp files.
Error Details:
Sep 27, 2013 5:50:39 PM org.apache.jasper.JspC processFile
INFO: Built File: \about.jsp
Sep 27, 2013 5:50:40 PM org.apache.jasper.JspC processFile
INFO: Built File: \admin.jsp
Then it spits out a whole bunch of lines for all the jsp files in the
project. After that it says:
java.lang.RuntimeException: Cannot get the System Java Compiler. Please
use a JD
K, not a JRE.
Unable to update app: Cannot get the System Java Compiler. Please use a
JDK, not
a JRE.
Please see the logs
[C:\Users\XXXXXXX\AppData\Local\Temp\appcfg6782250184385148
38.log] for further information.
This is what the error logs says:
Unable to update:
java.lang.RuntimeException: Cannot get the System Java Compiler. Please
use a JDK, not a JRE.
at
com.google.appengine.tools.admin.Application.compileJavaFiles(Application.java:814)
at
com.google.appengine.tools.admin.Application.compileJsps(Application.java:801)
at
com.google.appengine.tools.admin.Application.createStagingDirectory(Application.java:615)
at
com.google.appengine.tools.admin.AppAdminImpl.doUpdate(AppAdminImpl.java:418)
at
com.google.appengine.tools.admin.AppAdminImpl.update(AppAdminImpl.java:55)
at
com.google.appengine.tools.admin.AppCfg$UpdateAction.execute(AppCfg.java:1326)
at com.google.appengine.tools.admin.AppCfg.executeAction(AppCfg.java:327)
at com.google.appengine.tools.admin.AppCfg.<init>(AppCfg.java:210)
at com.google.appengine.tools.admin.AppCfg.<init>(AppCfg.java:121)
at com.google.appengine.tools.admin.AppCfg.main(AppCfg.java:117)
com.google.appengine.tools.admin.AdminException: Unable to update app:
Cannot get the System Java Compiler. Please use a JDK, not a JRE.
at
com.google.appengine.tools.admin.AppAdminImpl.doUpdate(AppAdminImpl.java:425)
at
com.google.appengine.tools.admin.AppAdminImpl.update(AppAdminImpl.java:55)
at
com.google.appengine.tools.admin.AppCfg$UpdateAction.execute(AppCfg.java:1326)
at com.google.appengine.tools.admin.AppCfg.executeAction(AppCfg.java:327)
at com.google.appengine.tools.admin.AppCfg.<init>(AppCfg.java:210)
at com.google.appengine.tools.admin.AppCfg.<init>(AppCfg.java:121)
at com.google.appengine.tools.admin.AppCfg.main(AppCfg.java:117)
Caused by: java.lang.RuntimeException: Cannot get the System Java
Compiler. Please use a JDK, not a JRE.
at
com.google.appengine.tools.admin.Application.compileJavaFiles(Application.java:814)
at
com.google.appengine.tools.admin.Application.compileJsps(Application.java:801)
at
com.google.appengine.tools.admin.Application.createStagingDirectory(Application.java:615)
at
com.google.appengine.tools.admin.AppAdminImpl.doUpdate(AppAdminImpl.java:418)
... 6 more

Wednesday, 25 September 2013

Adding Web Reference to eclipse in java

Adding Web Reference to eclipse in java

I am badly in need of help to add web reference in eclipse for java
project. I followed the following link for the same:
http://wsdl2javawizard.sourceforge.net/ But I am getting error as follows:
The selected wizard could not be started. Plug-in
"org.apache.axis.wsdl2java.eclipse" was unable to instantiate class
"org.apache.axis.wsdl2java.eclipse.wizards.WebReferenceImportWizard".
org/eclipse/core/internal/utils/Assert Can any of you please help me to
resolve the issue? Since from 3 days I am hitting head but no use. Or
provide some other solution to add web reference in eclipse.
Thanks in advance, Geeta V P

Thursday, 19 September 2013

How can i know if a variable is a number or a letter with Pascal?

How can i know if a variable is a number or a letter with Pascal?

I'm trying to make a (very) little code to determine whether a given
variable x is a number or a letter. It has to be done by hand without
things like type(x) -assuming there is such thing Pascal-.
My plan was to verify x is not a number one by one, then i wrote this:
(*let ischar be a boolean and let x be a letter or a number.*)
for i:=0 to 9 do
begin
if (x=i) then
ischar = false;
end;
if ischar then
write('x is a number!');
else
write('x is a letter');
I was hoping that the test "x=i" would return false if x is a letter, but
here i don't even get to compile because of the following error: "Got
char, expected long int". It seems that i can't compare x and i, i knew
that but i tought that under that circumstances if would return false. Is
there another way to do this 'by hand'?

Basic questions on C++ operators?

Basic questions on C++ operators?

I'm currently in a c++ class but I can't understand my professor very well
at all. English is his second language and many of us are having problems
with his explanations.
I currently have this code:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int a;
cout << "Enter a number for a: "; //Prompts the user for a and b inputs
cin >> a;
int b;
cout << "Enter a number for b: ";
cin >> b;
cout << "A is " << a << "\tB is " << b << end1;
cout <<"Sum of a and b is equal to " << a << "+" << b << "and the result
is " << (a + b) << end1;
cout <<"Product of a and b is equal to " << a << "*" << b << "and the
result is " << (a * b) << end1;
cout <<"a > b is " << a << ">" << b << "and the result is " << (a > b) <<
end1;
cout <<"a < b is " << a << ">" << b << "and the result is " << (a < b) <<
end1;
cout <<"a == b is " << a << "==" << b << "and the result is " << (a == b)
<< end1;
cout <<"a >= b is " << a << ">=" << b << "and the result is " << (a >= b)
<< end1;
cout <<"a <= b is " << a << "<=" << b << "and the result is " << (a <= b)
<< end1;
cout <<"a != b is " << a << "!=" << b << "and the result is " << (a != b)
<< end1;
return 0;
}`
and I'm receiving these errors
main.cpp: In function 'int main()':
main.cpp:10:44: error: 'end1' was not declared in this scope
I'm not really sure what I'm doing wrong. Any help would be greatly
appreciated.

Error when returning xml document from cfc

Error when returning xml document from cfc

I am creating a dynamic xml document in a cfc and returning it back to the
calling page. I am getting the following error:
An error occured while Parsing an XML document. The processing instruction
target matching "[xX][mM][lL]" is not allowed. <br>The error occurred on
line 65.
I'm not trying to process the xml document. All I'm doing is creating the
document, before sending it to a web service.
Calling the method:
<cfset tcuvXML = tcuvObj.getTCUVXml(inventory[i].oem_key,temp1Array,i)>
The method:
<cffunction name="getTCUVXml" access="public" returntype="xml"
returnformat="plain">
<cfargument name="dealer_code" required="true" type="string" />
<cfargument name="vinsArray" required="true" type="array" />
<cfargument name="counter" required="true" type="numeric" />
<cfset var tzInfo = #getTimeZoneInfo().utcHourOffset#>
<cfset var gmtDate = #dateFormat(now(), "yyyy-mm-dd")#>
<cfset var gmtTime = "T" & #timeFormat(now(), "HH:MM:SS")# & "-0" &
#tzinfo# & ":00">
<cfset var gmt = #gmtDate# & #gmtTime#>
<cfset var uuidLibObj = createObject("java", "java.util.UUID")>
<cfset var guidStr = uuidLibObj.randomUUID().tostring()>
<cfoutput>
<cfsavecontent variable="tcuvXML">
EXCLUDING THE ACTUAL DOCUMENT FOR SPACE
</cfsavecontent>
</cfoutput>
<cfreturn tcuvxml>
</cffunction>
If the actual xml document is needed, I'll post it. I excluded it because
of the length.

tornado use longpolling and how to know client alive

tornado use longpolling and how to know client alive

here is a global var queue={}
class Handler(object):
@tornado.web.asynchronous
def get(self):
queue['1']=self.response
def response(self):
self.finish('over')
def on_connection_close(self)
#if the stream is closed
return
if the client's network down or power off , the server still has the
stream and I how to know the stream is dead?

Python 2.7.5: Change type 'function' to type 'int'

Python 2.7.5: Change type 'function' to type 'int'

I have a function that returns a number. I added this number to an integer
type but it threw me an error, saying the number returned by the function
was a 'function' type.
How do I convert the 'function' type to 'int' type so i can perform math
functions on them? Is there a way to make the function return an 'int'? I
tried the following in the function but it still won't return an 'int'
type:
return int(blah blah blah)
but the function still returns:
type 'function'

Regex to remove a php function call

Regex to remove a php function call

i would like to remove some functions call from my php files. for example,
how i can remove myslq_escape_value calls? It's possible to have this
situations:
<?php
mysql_escape_value ( "some" ); //-> "some";
mysql_escape_value(some) //-> some
.mysql_escape_value ($some ). //-> .$some.
. mysql_escape_value ($some ) . //-> . $some . or .$some.
(mysql_escape_value ($some )) //-> ($some)
?>
regards

iOS 7 Lock Screen's background audio progress bar no longer working

iOS 7 Lock Screen's background audio progress bar no longer working

So I'm updating my app to iOS 7 and the progress bar on the lock screen no
longer updates, it remains at 0:00 throughout the length of the audio
being played.
I'm scouring every corner I can find for anyone else that experienced this
problem, dealt with it, but am coming up absolutely empty. I'd give more
details if I could, but I'm stumped as to where to begin with this one.
Anyone else seen this, any idea where to start digging?

dealing with garbage value in merge sort

dealing with garbage value in merge sort

we have two sorted arrays and have to merge those arrays into a third one,
yeah that's easy,
int[] answer = new int[a.length + b.length];
int i = 0, j = 0, k = 0;
while (i < a.length && j < b.length)
{
if (a[i] < b[j])
{
answer[k] = a[i];
i++;
}
else
{
answer[k] = b[j];
j++;
}
k++;
}
while (i < a.length)
{
answer[k] = a[i];
i++;
k++;
}
while (j < b.length)
{
answer[k] = b[j];
j++;
k++;
}
return answer;
}
but if a[] finds a garbage value at a[a.length+1] and b[] finds garbage at
b[b.length] and let both garbage values are not in sorted order, so, how
can we avoid those?

Wednesday, 18 September 2013

Regular expression replace text contents

Regular expression replace text contents

I have this paragraph:
"This person name #Question1#, #Question2#, has #Question3# been drinking
in the past two days."
I use regex to find an array of matching entries for #Question[0-9]+#, my
question is, how can utilise the regex feature to replace these
#Question[0-9]+# with actual answers from my database.
I can provide a dictionary of replacing string from database. Any ideas?

C++ :: Notation with OpenGL

C++ :: Notation with OpenGL

I have this line of code:
model = ArticulatedModel::create(spec);
And I would like to grab the AABox from it using AABox
G3D::ArticulatedModel::Part::boxBounds but I'm having trouble getting the
C++ syntax to work.
How do I reference the boxBounds?

JSF 2 display List values in 2 columns

JSF 2 display List values in 2 columns

I am a newbie in JSF. I am using JSF 2 and there is a list being populated
by my bean file. In my .xhtml file, I want to display this information as
2 columns.
In bean class List modules;(Contains module.enable module.name)
The list has say 30 modules. I want to display all these modules
information in 2 columns. For eg: I want to display first module
information(module.enable module.name) in one column and the second in
second column. Or it can be first 15 modules in first column and the
remaining 15 in second column. Tried with both h:dataTable and h:panelGrid
but couldn't get it working.
Any help would be highly appreciated.
Thanks Shyju

Crashing C Program

Crashing C Program

I am trying to write an algorithm that searches a document for a
particular chunk. If the chunk is found, a 1 will be returned, if not, a
0. Basically if the chunk is "abcd" and a particular length is 2, the
chunk would be split into "ab" and "cd." Then search the document to see
if either "ab" or "cd" is there. I think my algorithm is pretty much fine,
but the program keeps crashing. I think it has to do with the strncmp, but
I can't figure out how to fix it.
Here's my code:
int main( )
{
char s1[] = "abcdef";
char s3[] = "cd";
size_t s1Size = strlen(s1);
int k = 2;
if(simple_substr_match(s3,k,s1,s1Size))
printf("Match Found\n");
else
printf("No Match Found\n");
return 0;
}
int simple_substr_match(const unsigned char *ps, int k, const unsigned
char *ts, int n)
{
int isMatch;
int i;
int j;
for(i=0;i<n;i++)
{
for(j=0;j<k;j++)
{
if( (strncmp(ts[i],ps[j], k)) == 0)
{
isMatch = 1;
break;
}
}
ps+=k;
}
return isMatch;
}

I forgot what this is called?

I forgot what this is called?

Ok so I have this code and I KNOW it's not good programming practice. I
just forgot what it's called.
int main()
{
int variable;
{
int variable;
}
}
Is that a local namespace or something? I just can't remember the correct
term for doing something such as that.

How to pass data between wpf page and a window

How to pass data between wpf page and a window

I'm developing a WPF and C# application and i have problems to pass data
between a page and a window.
How is the best way to do it?
Thanks!

How can a .NET 4.0 project reference an assembly that uses the v2.0.50727 runtime?

How can a .NET 4.0 project reference an assembly that uses the v2.0.50727
runtime?

I have a c# project I am converting from .net 3.5 to .net 4.0 in VS2010.
It has references to other 3rd party dll's that have a runtime version of
v2.0.50727.
How can this be? I kind of expected a warning or breakage when building or
running, but I haven't. If my compiled .net 4 project is running with the
.net v4.0.30319 runtime, is it running the referenced dll with the .net
2.0.50727 runtime? And therefore, I still need old versions of .net
installed?
Or is the referenced dll running in the v4.0.30319 runtime?

Can you run hibernate without a database set up?

Can you run hibernate without a database set up?

I am currently working on an application that uses hibernate as its ORM;
however, there is currently no database set up on my machine and I was
wanting to start running some tests without one. I figure since hibernate
is object/code based that there must be a way to simulate the DB
functionality.
If there isn't a way to do it through hibernate, how can this be achieved
in the general case (simulation of database)? Obviously, it wont need to
handle large amounts of data, just testing functionality.

how to represent a text command template

how to represent a text command template

I'm working on an application in which a user creates a file consisted of
multiple commands, each command on a separate line. Commands have a
particular format that user must follow. for example:
String(a command such as "open"),String(a subject such as
"door1")|Double(a time such as 100ms)
I'd like to know what is the best way to inform the user of the commands
template. Should I just use a text file for instruction or there is a
graphical representation for such things?

Tuesday, 17 September 2013

accurate display of size of an 1D array

accurate display of size of an 1D array

I have a problem in displaying the size of the array correctly. I know
array size is 256000 but it is displaying as 8 when I enter the loop. size
will be displayed accurately if dynamic allocation is not used. How do I
rectify the bug using dynamic allocation?

Add listview within scrollview

Add listview within scrollview

I want to have a scrollable list which also includes list view. I did
research everywhere and no solution yet :( As per the code below, when I
add ScrollView, the listview height becomes smaller (single row). I want
the ListView height to be dynamic (based on the content) and also make the
complete page scrollable. How do I achieve this? Or is there a way to
create dynamic linear / relative list UI? Please suggest.
XML code:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingTop="@dimen/activity_horizontal_margin"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin">
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/kollege_name"
android:width="170dp" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:gravity="right"
android:text="@string/grade_value"
android:width="120dp" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/textView2"
android:layout_below="@+id/textView2"
android:text="@string/code_value" />
</RelativeLayout>
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:background="@android:color/darker_gray" />
<TextView
android:id="@+id/textView4"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/your_fit"
android:textSize="12sp" />
<ListView
android:id="@+id/listview"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:background="@android:color/darker_gray" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin" >
<TextView
android:id="@+id/textView10"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/tuition"
android:textSize="12sp" />
<TextView
android:id="@+id/textView11"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="@string/tuition_value" />
</RelativeLayout>
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:background="@android:color/darker_gray" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin" >
<TextView
android:id="@+id/textView12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/placements"
android:textSize="12sp" />
<TextView
android:id="@+id/textView13"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView12"
android:text="@string/EXTC"
android:layout_marginTop="3dp" />
<TextView
android:id="@+id/textView14"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView13"
android:text="@string/IT"
android:layout_marginTop="3dp" />
<TextView
android:id="@+id/textView15"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView14"
android:text="@string/COMP"
android:layout_marginTop="3dp" />
<TextView
android:id="@+id/textView16"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView15"
android:text="@string/MECH"
android:layout_marginTop="3dp" />
<TextView
android:id="@+id/textView17"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView16"
android:text="@string/INST"
android:layout_marginTop="3dp" />
</RelativeLayout>
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:background="@android:color/darker_gray" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin" >
<TextView
android:id="@+id/textView18"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/placements"
android:textSize="12sp" />
<TextView
android:id="@+id/textView19"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView18"
android:text="@string/EXTC"
android:layout_marginTop="3dp" />
<TextView
android:id="@+id/textView20"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView19"
android:text="@string/IT"
android:layout_marginTop="3dp" />
</RelativeLayout>
</LinearLayout>
</ScrollView>
</LinearLayout>

Can I define an array type of different types?

Can I define an array type of different types?

I'd like to define an array type which consists of different types, such
as String, Integer, Boolean, Double, etc. but no objects, structures, or
anything of that nature. Then I'd like to use this type as a function
argument, for example...
type
TMyArray = array of ...?...;
function GetSomething(const Input: TMyArray): String;
var
X: Integer;
begin
for X:= 0 to Length(Input) - 1 do begin
//Identify type and handle accordingly...
//Serialize data for the result...
end;
end;
and use it like...
Variable:= GetSomething(['some string', 123, 'something else', 12.3, false]);
Then, how do I identify what type each element is when iterating through
such an array?
I'm pretty sure this is possible, but have no idea even what terminology
to search for. How do I do this?
Would I have to define this as an array of Variants? Or is there a way to
define exactly which types the array accepts?

Deleting a file from BroadcastReceiver

Deleting a file from BroadcastReceiver

I have a class that calls a BroadcastReceiver. I am struggling to delete a
file when it's called.
If I use deleteFile("file.txt") within the class it works and deletes the
file.
However if I try deleteFile("file.txt") within the BroadcastReceiver class
it won't work.
Any ideas on how I can delete a file within a BroadcastReceiver class? I
have tried many different ways and I an guessing there is something
fundamental I'm missing.
Thanks in advance for any help.

twitter bootstrap carousel bug in chrome when sliding/transition on top of each other

twitter bootstrap carousel bug in chrome when sliding/transition on top of
each other

I am having issues with Bootstrap 3 carousel in Chrome where the next item
to slide across the screen appears on top of the current slide before it
moves.
This only happens in latest Chrome(windows 7) works fine in Firefox and
IE9 show switches the image which is fine.
The bootstrap carousel is the yellow bar click the arrows -
http://tinyurl.com/p7tqcxl
But I have been testing it in chrome and this works fine:
http://bootply.com/81554
I just can't find whats causing this.

Android Ant build causes runtime ClassNotFoundException when Eclipse build does not

Android Ant build causes runtime ClassNotFoundException when Eclipse build
does not

I've been trying to get a command line build working for my Android
project so it can be automated in Jenkins, however, the Ant build causes a
runtime ClassNotFoundException error despite my Eclipse build not having
any issues.
I'm wondering what is causing the discrepancy. I noticed the path doesn't
appear to be correct, so that might be where to start.
LogCat
W/dalvikvm( 1243): threadid=1: thread exiting with uncaught exception
(group=0x40a70930)
E/AndroidRuntime( 1243): FATAL EXCEPTION: main
E/AndroidRuntime( 1243): java.lang.RuntimeException: Unable to instantiate
activity
ComponentInfo{gov.va.fbb.android/gov.va.fbb.android.activities.StartupActivity}:
java.lang.ClassNotFoundException: Didn't find class
"gov.va.fbb.android.activities.StartupActivity" on path:
/system/framework/com.google.android.maps.jar:/data/app/gov.va.fbb.android-1.apk
E/AndroidRuntime( 1243): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)
E/AndroidRuntime( 1243): at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
E/AndroidRuntime( 1243): at
android.app.ActivityThread.access$600(ActivityThread.java:141)
E/AndroidRuntime( 1243): at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
E/AndroidRuntime( 1243): at
android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime( 1243): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime( 1243): at
android.app.ActivityThread.main(ActivityThread.java:5039)
E/AndroidRuntime( 1243): at java.lang.reflect.Method.invokeNative(Native
Method)
E/AndroidRuntime( 1243): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime( 1243): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
E/AndroidRuntime( 1243): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
E/AndroidRuntime( 1243): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime( 1243): Caused by: java.lang.ClassNotFoundException:
Didn't find class "gov.va.fbb.android.activities.StartupActivity" on path:
/system/framework/com.google.android.maps.jar:/data/app/gov.va.fbb.android-1.apk
E/AndroidRuntime( 1243): at
dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:65)
E/AndroidRuntime( 1243): at
java.lang.ClassLoader.loadClass(ClassLoader.java:501)
E/AndroidRuntime( 1243): at
java.lang.ClassLoader.loadClass(ClassLoader.java:461)
E/AndroidRuntime( 1243): at
android.app.Instrumentation.newActivity(Instrumentation.java:1054)
E/AndroidRuntime( 1243): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
E/AndroidRuntime( 1243): ... 11 more
W/ActivityManager( 297): Force finishing activity
gov.va.fbb.android/.activities.StartupActivity
W/WindowManager( 297): Failure taking screenshot for (123x205) to layer 21010

Problems in creating config files in iPCU for MDM server

Problems in creating config files in iPCU for MDM server

I'm in early stage building an MDM server and I have encountered some
issues in using iPCU to create a mdm certificate. Appreciate your help.
The most important problems are I don't know where to find the Topic and
Identity, I have looked for a lot of solutions, it seems that I should
first create an APNS certificate and load this to Credentials (payload) in
iPCU, so I just used a previous p12 file to test (it's for a different
app, but since the apns certificate should link to an app, this is should
be fine, right?).
For topic, I know it should be like com.apple.mgmt.*, but where can I find
this?
From the doc I found, it seems the server end should be listening for a
PUT request, and when right after the installation of configuration file,
the server should get a PUT request containing the initial information
like PushMagic and DeviceToken. Since I got stuck on the config installing
part, I can't test this, so if I'm wrong on this, please give some advice.
PS: These are the documents I'm using:
http://media.blackhat.com/bh-us-11/Schuetz/BH_US_11_Schuetz_InsideAppleMDM_WP.pdf
---------------> on Page 7 setting up APNS, it says I should locate the
APNS certificate like "ASPS: uuid" in Keychain, none of my previous
certificate are like this.
http://adcdownload.apple.com//Documents/mobile_device_management_protocol/mobiledevicemanagement_121211.pdf
--------> apple's official doc, i'm wondering why I couldn't find any
updated one

Sunday, 15 September 2013

JqGrid does not load data in mvc

JqGrid does not load data in mvc

My .cshtml is as follows:
<script type="text/javascript">
$(function () {
$("#list").jqGrid({
url: '/LogInManagement/DisplayItems/',//this is action in
controller which returns the json as result.
datatype: 'json',
mtype: 'GET',
colNames: ['ID', 'Product Name', 'Description',
'IsInStock', 'Attachment'],//column name
colModel: [
{ name: 'ID', index: 'Id', width: 40, align: 'left' },
{ name: 'ProductName', index: 'ProductName', width: 240, align:
'left' },
{ name: 'Description', index: 'Description', width: 200, align:
'left' },
{ name: 'IsInStock', index: 'IsInStock', width: 40, align:
'left' },
{ name: 'Attachment', index: 'Attachment', width: 240, align:
'left' }],
pager: jQuery('#pager'),
rowNum: 10,
rowList: [5, 10, 20, 50],
sortname: 'Id',
sortorder: "desc",
viewrecords: true,
caption: 'Items'
});
});
</script>
@{
ViewBag.Title = ViewBag.DisplayName;
}
<h2>Welome : @ViewBag.DisplayName</h2>
<table id="list" class="scroll" cellpadding="0" cellspacing="0"></table>
<div id="pager" class="scroll" style="text-align:center;"></div>
I am calling the method "DisplayItems" as follows:
public ActionResult DisplayItems()
{
Item item = new Item();
int pages = 0;
var resultItems = Assignment.Models.Item.GetItems().ToArray();
var jsonData = new
{
total = 1,
page = pages,
records = resultItems.Count(),
rows = resultItems
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
And it is returning data properly. But the grid in cshtml shows
"Loading...", but no data. Data is coming in following format:

Pls help, Regards

Constructors and Objects in java`

Constructors and Objects in java`

double x;
x =
69.2*(c1.(this.longitude)-c2.(this.longitude))*Math.cos((c1.(this.latitude)+c2.(this.latitude))/2);
what is wrong in this expression?
errors displa's as <identifier expected>
Here c1,c2 are the object of class City. This expression is in the
method(calculateDistance(City)) of a class City.. Plz Reply me

Load an "Indexed8" image on Windows Phone

Load an "Indexed8" image on Windows Phone

I have a byte array that represents an image that is stored in the Index8
format. I need to load this into a BitmapImage on windows phone. Is this
possible? And if so how?

Cube design sql server 2008

Cube design sql server 2008

i have a database that is related with direct marketing campaigns of a
Portuguese banking institution. The marketing campaigns were based on
phone calls. Often, more than one contact to the same client was required,
in order to access if the product (bank term deposit) would be (or not)
subscribed.
The columns provided are the following (column name,description):
age (numeric)
job : type of job (categorical:
"admin.","unknown","unemployed","management","housemaid","entrepreneur","student",
"blue-collar","self-employed","retired","technician","services")
marital : marital status (categorical: "married","divorced","single";
note: "divorced" means divorced or widowed)
education (categorical: "unknown","secondary","primary","tertiary")
default: has credit in default? (binary: "yes","no")
balance: average yearly balance, in euros (numeric)
housing: has housing loan? (binary: "yes","no")
loan: has personal loan? (binary: "yes","no") # related with the last
contact of the current campaign:
contact: contact communication type (categorical:
"unknown","telephone","cellular")
day: last contact day of the month (numeric)
month: last contact month of year (categorical: "jan", "feb", "mar", ...,
"nov", "dec")
duration: last contact duration, in seconds (numeric) # other attributes:
campaign: number of contacts performed during this campaign and for this
client (numeric, includes last contact)
pdays: number of days that passed by after the client was last contacted
from a previous campaign (numeric, -1 means client was not previously
contacted)
previous: number of contacts performed before this campaign and for this
client (numeric)
poutcome: outcome of the previous marketing campaign (categorical:
"unknown","other","failure","success") #Output variable (desired target):
y - has the client subscribed a term deposit? (binary: "yes","no")
My problem is that i can't decide which columns to use to make a cube .
Any help ?

XPath query foreach

XPath query foreach

$table = $PageXpath->query('//table[10]');
$data['tr'] = $table->item(0)->nodeValue;
print_r($data);
Above works. It gives the the text of everything in that table.
However, it does not give me the tr and td html mark up. I need all of the
TR elements, marked up. That way I can start dissecting them and passing
them each in to a variable.
I need to target that specific table, then do a for each TR, do X with the
first then Y with the second then Z with the third .
Please assist me!

pivot not working while using stored procedure in sql server

pivot not working while using stored procedure in sql server

I have store procedure like this:
ALTER procedure [dbo].[performance] @startdate nvarchar(100),
@enddate nvarchar(100) as
begin
declare @date1 nvarchar(100)=convert(varchar,
@startdate+'00:00:00.000',120)
declare @date2 nvarchar(100)= convert(varchar,
@enddate+'23:59:59.000',120)
set NOCOUNT on;
select l.LocName,v.Vtype,
SUM(convert(numeric(18, 2),
DATEDIFF(MI,t.DelDate,t.Paydate))) as TotalDiff,
[dbo].[testfunctionstacknew]
(CONVERT(decimal(10,1),
AVG( CONVERT(NUMERIC(18,2),
DATEDIFF(SS,t.Paydate,t.DelDate) ) ))
) as Average
from Transaction_tbl t
left join VType_tbl v on t.vtid=v.vtid
left join Location_tbl l on t.Locid=l.Locid
where t.Locid in (select t1.Locid from Transaction_tbl t1) and
dtime between @date1 and @date2 and
Status =5
group by v.Vtype,l.LocName,l.Locid
order by l.Locid
end
I am getting out put like this:
LocName Vtype TotalDiff Average
Address Normal 15 00:10:01
Adress vip 18 00:08:01
Address VVIP 9 00:04:00
Address Pass 20 00:15:00
Goldsouk normal 45 00:18:08
Goldsouk vip 17 00:11:36
Fashion vip 78 00:35:25
Fashion VVip 2 00:01:00
but i need output in different model as
LocName Normal Vip VVip Pass Staff
Address 00:10:01 00:08:01 00:04:00 0 0
GoldSouck 00:18:08 00:11:36 0 0 0
Fashion 0 00:35:25 00:01:00 0 0
I don't want to use pivot manually.. because some time my vtype name will
change so I try to write the same stored procedure by using pivot ALTER
procedure [dbo].[ParkingSummary1] @startdate nvarchar(100), @enddate
nvarchar(100) as begin declare @date1 nvarchar(100) = convert(varchar,
@startdate+' 00:00:00.000', 120) declare @date2 nvarchar(100) =
convert(varchar, @enddate+' 23:59:59.000', 120) DECLARE @cols AS
NVARCHAR(MAX),@query AS NVARCHAR(MAX) select @cols = STUFF((SELECT
distinct ',' + QUOTENAME(Vtype) from VType_tbl FOR XML PATH(''),
TYPE).value('.', 'NVARCHAR(MAX)') ,1,1,'') set @query = 'SELECT LocName, '
+ @cols + ' from (select l.LocName,Vtype from Transaction_tbl t join
VType_tbl v on t.vtid = v.vtid join dbo.Location_tbl l on t.locid=l.Locid
where dtime between '''+ @date1 +''' and '''+ @date2 +'''
and Status = 5) d pivot ( count(Vtype) for Vtype in (' + @cols + ')) p '
print @query end after executing this am not getting any value..what is
wrong with my pivot stored procedure

Setting a TimePicker's current time if it is within a fragment

Setting a TimePicker's current time if it is within a fragment

I have a TimePicker within a Fragment. Upon creation, I want the fragment
to set the TimePicker's current time selection to 0:00, but it always
seems to want to set it to the current time by default.
How do I set it via setCurrentHour/Minute and make sure it sticks? (I
should not have to do this from the host activity!)
Here is my fragment:
public class CreateProfileFragment extends Fragment implements
OnClickListener {
private OnClickListener listener;
private EditText name;
private CheckBox sun, mon, tue, wed, thur, fri, sat;
private TimePicker reportTimePicker;
private Button createNewProfileButton;
/**
* Required interface the host activity must implement to handle click
* events.
*
* @author Tony Tran
*
*/
public interface OnClickListener {
public void createNewProfile(UserProfile profile);
}
/**
* Checks to see if the host activity has implemented the required
interface.
*/
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof OnClickListener) {
listener = (OnClickListener) activity;
} else {
throw new ClassCastException(activity.toString()
+ " must implement CreateProfileFragment.OnClickListener");
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View toReturn = inflater.inflate(
R.layout.fragment_create_new_profile_layout, container, false);
name = (EditText) toReturn.findViewById(R.id.new_profile_name);
sun = (CheckBox) toReturn
.findViewById(R.id.checkbox_create_new_profile_recording_day_sunday);
mon = (CheckBox) toReturn
.findViewById(R.id.checkbox_create_new_profile_recording_day_monday);
tue = (CheckBox) toReturn
.findViewById(R.id.checkbox_create_new_profile_recording_day_tuesday);
wed = (CheckBox) toReturn
.findViewById(R.id.checkbox_create_new_profile_recording_day_wednesday);
thur = (CheckBox) toReturn
.findViewById(R.id.checkbox_create_new_profile_recording_day_thursday);
fri = (CheckBox) toReturn
.findViewById(R.id.checkbox_create_new_profile_recording_day_friday);
sat = (CheckBox) toReturn
.findViewById(R.id.checkbox_create_new_profile_recording_day_saturday);
reportTimePicker = (TimePicker) toReturn
.findViewById(R.id.report_time_picker);
reportTimePicker.setCurrentHour(0);
reportTimePicker.setCurrentHour(0);
createNewProfileButton = (Button) toReturn
.findViewById(R.id.create_new_profile_btn);
createNewProfileButton.setOnClickListener(this);
return toReturn;
}
/**
* OnClick handler for this fragment.
*/
@Override
public void onClick(View v) {
switch (v.getId()) {
case (R.id.create_new_profile_btn):
generateProfileToReturn();
}
}
/**
* Retrieves entered information and sends back to host's
createNewProfile()
* method.
*/
private void generateProfileToReturn() {
String profileName = name.getText().toString();
boolean[] loggingDays = { sun.isChecked(), mon.isChecked(),
tue.isChecked(), wed.isChecked(), thur.isChecked(),
fri.isChecked(), sat.isChecked() };
int reportHour = reportTimePicker.getCurrentHour();
int reportMinute = reportTimePicker.getCurrentMinute();
UserProfile createdProfile = new UserProfile(profileName, loggingDays,
reportHour, reportMinute);
listener.createNewProfile(createdProfile);
}
}

Saturday, 14 September 2013

rails cancan i18n exception message

rails cancan i18n exception message

I have followed this to write exception handling for cancan. First, I have
a Product model in the "new" action Here is the english locale file:
# in config/locales/en.yml
en:
unauthorized:
manage:
all: "Not authorized to %{action} %{subject}."
The expected result is fine:
Not authorized to new Product.
But my question is now I have another locale ex: .de
# in config/locales/en.yml
de:
unauthorized:
manage:
all: "Non autorisé à %{action} %{subject}."
Then I'll get
Non autorisé à% new Product
What I want is
Non autorisé à nouveau produit.
Temporarily I have to options to achieve this, One is I guess I could just
modify the source code in cancan. The second is append some translated
text to it. But is there something native way?
Thanks

adding random characters to $_GET variable

adding random characters to $_GET variable

I was just wondering if it was possible to add random characters to the
variable I am passing to the second page. I want this because if the user
changes the value in the url, then the system is gonna mess up because I
am inserting data to database based on the message id. I can't use session
because the first session is overriding the others.
If I have something like view_inbox.php?messageid=2 then the user can
change it to something view_inbox.php?message=4.
So is it possible to have some random characters like
view_inbox.php?messageid=GXLSsd2sdcds? The id is coming from database.
echo"<a
href='view_inbox.php?messageid=".$row['id']."'>".$row['from_user']."</a>";
view_inbox.php
$id = $_GET['messageid'];

SQLLite Insert with all default values

SQLLite Insert with all default values

My SQL Structure has 3 elements, all with default values.
"create table " + TB_NAME +
" (" +
INDEX + " integer DEFAULT 0," +
SWATCH + " text DEFAULT ''," +
COLOR_INDEX + " integer DEFAULT 0" +
");"
Needless to say, what is the INSERT call when there aren't any parameters?

Detecting CloudFlare Errors

Detecting CloudFlare Errors

I'm trying to create a custom service to monitor uptime. I did research on
if CloudFlare does anything different specifically when a error is
displayed but I didn't find much. I saw CF-RAY in the headers of every
CloudFlare network request and learned it might be useful but I can not
find any documentation on it or if it's even usable to the public. Does
anyone have any ideas on how I can do this?