Thursday, 3 October 2013

Cakephp get data from another model

Cakephp get data from another model

I'm developing an e-commerce website. I have 2 tables - Customers & Shipping
Field in Customers - id, name, address, city, postal & country Field in
Shipping - id, address, city, postal & country
The process flow, after the customer click checkout button, they need to
fill up shipping form (shipping - add.ctp).
But in add.ctp, i also want to show address from table customer. So, I can
put check button - Use this address as shipping address.
Anyone can help how the controller & add.ctp looks like? Thank You.

Wednesday, 2 October 2013

Windows Phone 8 push notification push channel always creates new channel uri

Windows Phone 8 push notification push channel always creates new channel uri

I wanted to check that my push notification implementation is correct.
Each time I open my app (in actual fact I register the push channel only
on a specific page so it's each time I go back and forth from that page) a
new push channel uri is created which I store in my mobile services
database to send push notifications to. This doesn't seem correct to me as
each time the app/page is open a new push channel uri is generated and so
the list of channel uri's just grows and grows for each device that uses
my app. I'd assume that you create a push channel, store the channel uri
and push to it as needed. I will make note here that I am using raw push
notifications.
I understand that push channels will expire every so often but for me it's
occuring each time I back out of the app/page and therefore when
onNavigateTo is called I find the push channel which does exist and a new
channel uri is always created. Is this correct?
My code is as follows:
protected override void OnNavigatedTo(NavigationEventArgs e) {
registerPushChannel(); }
private void registerPushChannel()
{
// The name of our push channel.
string channelName = "RawSampleChannel";
// Try to find the push channel.
pushChannel = HttpNotificationChannel.Find(channelName);
// If the channel was not found, then create a new connection to
the push service.
if (pushChannel == null)
{
pushChannel = new HttpNotificationChannel(channelName);
// Register for all the events before attempting to open the
channel.
pushChannel.ChannelUriUpdated += new
EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
pushChannel.ErrorOccurred += new
EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
pushChannel.HttpNotificationReceived += new
EventHandler<HttpNotificationEventArgs>(PushChannel_HttpNotificationReceived);
pushChannel.Open();
}
else
{
// The channel was already open, so just register for all the
events.
pushChannel.ChannelUriUpdated += new
EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
pushChannel.ErrorOccurred += new
EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
pushChannel.HttpNotificationReceived += new
EventHandler<HttpNotificationEventArgs>(PushChannel_HttpNotificationReceived);
// code which passes the new channel URI back to my web service
}
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
pushChannel.Close();
}
So to clarify, the app is opened and the push channel is registered and
the channel uri is saved in my web service. The web service then sends
notifications to the channel uri. When I exit the app or page and return
to it, the push channel is found but there a new channel uri is create
which is saved to my web service. My channels table in effect just keeps
growing and growing.
So is this the way it should work with new channel uri's continually
generated? It kind of doesn't make sense to me. I'm not sure how toast and
tile notifications work but I'd assume the channel uri needs to be static
when the app closes to keep receiving notifications while the app is
closed, but perhaps that could be a functionality of bindtotoast and
bindtotile and what I'm doing is correct because it's to do with raw
notifications.

Moving robot in Java on specified length

Moving robot in Java on specified length

A robot starts at location (0,0) facing east, carrying 7 beepers: Need to
write a method called that accepts an integer parameter and a boolean
parameter. The method should move the robot along the row for the number
of squares specified by the integer parameter, putting down one beeper in
each square (excluding the robot's starting square). Can be assumed that
the integer parameter will be a value that allows the robot to do this
safely. The robot should finish in the square where it put down the last
beeper. If the boolean parameter is true then the program should print out
how many beepers were spread over the row. The message should be one of
the following:
If 0 beepers were spread over the row, the message should be Spread no
beepers
If 1 beeper was spread over the row,the message should be Spread 1 beeper
Otherwise the message should be Spread n beepers,where n is the number of
beepers put down.
My code:
void spreadBeepersOverRow(int x, boolean y) {
while(x>0) {
moveRobotForwards();
dropItemFromRobot();
--x;
}
if(y==true&&x==6||x<6&&x>0)
println("Spread "+ x +" beepers");
else
if(y == true&&x==7)
println("Spread no beepers");
}
}
I am confusing with the conditions of the task... My version gives some
mistakes when compiling

Target elements with different ids Jquery

Target elements with different ids Jquery

How do I target a particular element used with different ids.For instance
that have the ids row and col. I have tried doing this with jquery.
var $drag = $( "#col" );
var $drag2 = $( "#row" );
$("td", $drag, $drag2).droppable({ accept: ".special" });
But the second id "row" stored in drag2 is not selected. What is the
proper way of doing this in jquery.

Signaling in OpenMP

Signaling in OpenMP

I am writing computational code that more-less has the following schematic:
#pragma omp parallel
{
#pragma omp for nowait
// Compute elements of some array A[i] in parallel
#pragma omp single
for (i = 0; i < N; ++i) {
// Do some operation with A[i].
// This time it is important that operations are sequential. e.g.:
result = compute_new_result(result, A[i]);
}
}
Both computing A[i] and compute_new_result are rather expensive. So my
idea is to compute the array elements in parallel and if any of the
threads gets free, it starts doing sequential operations. There is a good
chance that the starting array elements are already computed and the
others will be provided by the other threads doing still the first loop.
However, to make the concept work I have to achieve two things:
To make OpenMP split the loops in alternative way, i.e. for two threads:
thread 1 computing A[0], A[2], A[4] and thread 2: A[1], A[3], A[5], etc.
To provide some signaling system. I am thinking about an array of flags
indicating that A[i] has already been computed. Then compute_new_result
should wait for the flag for respective A[i] to be released before
proceeding.
I would be glad for any hints how to achieve both goals. I need the
solution to be portable across Linux, Windows and Mac. I am writing the
whole code in C++11.

Tuesday, 1 October 2013

Windows API `GetPixel()' always return `CLR_INVALID`, but `SetPixel()` is worked well?

Windows API `GetPixel()' always return `CLR_INVALID`, but `SetPixel()` is
worked well?

My OS is windows 7 64-bits with 2 monitors display.
I use GetPixel(), but it always return CLR_INVALID as result like that:
COLORREF result = GetPixel(dc,x,y);
My GetDeviceCaps(RASTERCAPS) returns result that RC_BITBLT is enabled.
GetDeviceCaps(COLORMGMTCAPS) returns result is CM_GAMMA_RAMP.
Most importantly, if I SetPixel(dc,x,y,RGB(250,250,250)) in advance, and
GetPixel(dc,x,y) later, I can retreive correct result at all. So I think
my coordination should be alright.
Well. I have no idea about why GetPixel() always return CLR_INVALID, but
SetPixel() is always worked well? Any question?

minimum value not in an array of intervals

minimum value not in an array of intervals

You have a list of N integer intervals, and the possible integer values
range from 1 to N^3.
For example, you can have N=5 and intervals
([1,5],[2,9],[18,25],[10,15],[20,22]). I'm trying to figure out an
algorithm to return the smallest integer not in those intervals, i.e. 16,
with a runtime of O(N).
Please help!

Configure FTP on Ubuntu to default to a certain directory

Configure FTP on Ubuntu to default to a certain directory

I am trying to configure an FTP server on my 12.04.3 LTS machine. I am
hosting a website from /home/webuser/public/mywebsite.com/public. Now, I
want to configure the FTP server in such a way where, when an FTP user
logs in, they arrive in the /home/webuser/public/mywebsite.com/public
directory (and that's the ONLY directory that they should be able to
access).
I've tried vsftpd and pure-ftp, and I haven't had much luck. It seems that
most processes involve creating a new, FTP specific user account, and the
home directory is used to publish files to. I can do that, but I need the
uploaded files to go into the webuser's public folder.
Does anyone know how I can accomplish this?

Question about mapping onto the unit circle.

Question about mapping onto the unit circle.

Let $K$ be a positive integer and let $x$ be an angle in $(0,2ð)$.
Consider the map $g: {0,1,..K-1,K}$ onto the unit circle, given by
$g(n)=n*x (mod 2ð)$. Prove the image of $g$ divides the circle into arcs
of one, two, or three different lengths.
I can see that the arc lengths are equal whenever $x$ is of the form
$\dfrac{ð}{b}$, where $b$ is an integer, but I'm confused on how to go
about the rest. Any hints would be greatly appreciated.

Monday, 30 September 2013

Connecting a Linux client to an IPSec VPN (Vyatta)

Connecting a Linux client to an IPSec VPN (Vyatta)

I have just setup an IPSec on a Vyatta server and now I am trying to
connect a Linux client to this router. What I basically am trying to do is
to be able to make that Vyatta machine a physically connected router on
that Linux machine(the connection should also be persistent). I would like
to be able have a virtual interface which will have the Vyatta router as
it's gateway and packets originating from this Linux client will be going
to other end of IPSec VPN which again is another Vyatta machine. How this
can be done? What is the best approach?

Polite alternative word to the term "bitch" when referring to a female dog, and similar for a male dog – english.stackexchange.com

Polite alternative word to the term "bitch" when referring to a female
dog, and similar for a male dog – english.stackexchange.com

I'm not sure if this is the right site, but it seems appropriate. I'm
writing an example of constructing logic, and I need to differentiate
between an adult female dog, an adult male dog and a puppy …

Passing a variable from one php document to another

Passing a variable from one php document to another

I have this PHP code:
poster.php:
<?php
$field_password = 1;
if (empty($_POST['password'])) {
$field_password = 0;
}
?>
I want the "$field_password" variable passed to another page that is
called register.php without using code like this:
include 'poster.php';
required_once 'poster.php';
And so on, I only need the $field_password variable passed. Any ideas how
to do that? oh and btw, the more secure it is, the better.

Suggestions to improve JavaScript code to performance?

Suggestions to improve JavaScript code to performance?

I took a JavaScript challenge to finish a task related to logo of
"Breaking Bad" where letters in your first name and last name are spotted
with elements of periodic table and its respective atomic number. I wrote
the below code, any suggestions to improve performance or any best coding
practices
function Process() {
var ellist = {
"h": "1",
"he": "2",
"li": "3",
"be": "4",
"b": "5",
"c": "6",
.
.
.
"Lv":"116",
"Uus":"117",
"Uuo":"118"
};
var fname = document.getElementById("firstname");
var lname = document.getElementById("lastname");
var splits = fname.split("");
var value;
for (var i = 0; i < splits.length; i++) {
var onevalue = fname.indexOf(splits[i]);
var singlev = fname.substring(onevalue, onevalue + 1);
var doublev = fname.substring(onevalue, onevalue + 2);
var triplev = fname.substring(onevalue, onevalue + 3);
if (ellist[splits[i]] || ellist[doublev] || ellist[triplev]) {
value = splits[i];
if (ellist[doublev] || ellist[triplev]) {
value = ellist[doublev];
if (ellist[triplev]) {
value = ellist[triplev];
// some code here
}
// some code here
}
// some code here
}
}
Using the Process() function which contains the logic. The object ellist
contains the list of elements of periodic table with its atomic number.
First name is taken from textbox on webpage and stored in fname and
similarly the last name in lname and in the for loop it contains the code
which checks whether the firstname contains the string which matches the
elemetns of periodic table. Any suggestions?

Sunday, 29 September 2013

How to make WPF input control show virtual Keyboard when it got focus in touch screen

How to make WPF input control show virtual Keyboard when it got focus in
touch screen

For our WPF application, when it runs on touch screen(Surface Pro .etc),
the TextBox/Password control cannot show virtual keyboard when they get
focused.
Any good way to implement this feature in WPF?

How to convert Illustrator files to EPS via the command line (*nix)

How to convert Illustrator files to EPS via the command line (*nix)

I'm trying to do batch conversion of AI files to EPS files via the command
line on Linux. I'm familiar with using Ghostscript for various EPS and
Postscript related tasks. I have been semi successful using the
Ghostscript epswrite device, but my understanding is this device is
deprecated.
What is the best way to convert Adobe Illustrator files to EPS files via
the command line in a *nix environment?

i want this to loop so that i can print until if(loop==3) sop(exit);

i want this to loop so that i can print until if(loop==3) sop(exit);

String[] item ={"[1]hotdog", "[2]eggpie","[3]menudo","[4]pizza","[5]lumpia"};
int[] cost = {5, 10, 15, 20, 25};
int[] selling = {10,15,20,25,30,};
int[] qty = {2,4,6,8,10};
for (int i = 0; i < item.length; i++)
{
System.out.println(" "
+item[i]+"\t"+cost[i]+"\t\t"+selling[i]+"\t\t"+qty[i]);
}
System.out.print("Item you want to add to list: ");
int item2 = sc.nextInt();
System.out.println("list: "+item2);
System.out.print("how many do you want: ");
int qty2 = sc.nextInt();
System.out.println("list:"+item2 + "["+qty2+"]");
System.out.println("[1]add more");
System.out.println("[2]show list");
System.out.println("[3]exit");
System.out.print("choose number:");
int loop = sc.nextInt();
if(loop==1){
System.out.print(return to choices);
if(loop==2){
System.out.print(shows item(not array.list));
if(loop==3){
System.out.print(exit);
anyone help for looping and i dont know if on my scanner part it is fault
or not. im just using basic im at my first year in programming please i
need basic

writing to a txt file in c#

writing to a txt file in c#

I'm new to c# and have tried out some console based application. I have
earlier experience off programming in Java, and Thus I prefer to use a
manual compiler to make it easier to move around the files and
subdirectories (I didn't like the Java IDE's) in the project folder with a
bit off overview.
I'm using a compiler called mono. Why you might ask? Well, people simply
said it was good. In accordance to what I heard c# has a good capacity, so
it shouldn't be a problem doing such a simple task as creating a save-file
and writing data to it (there are even standards in JDK).
Maybe is it the compilers wrong, maybe am I doing somthing wrong, but the
compiler simply doesn't have wbf acces or somthing like that (whatever
that means) what I have seen it also gives me a message that says I'm
missing Assembly reference. So googling around I have to get somthing
called moonlight for the mono compiler it seems. But I can't find any
instructions or tutorials of how to use nor to install moonlight so I can
get any usage for it in the compiler. Furthermore, it says moonlight is
made for making Unix application, but I wanted to make a console-based
application for windows that does such a simple task as writing a message
to a save-file. Sure I'm not using the compiler that they recomended me to
because I don't want to pay for a fancy IDE, but is this really what they
call time-saving as I heard c# is? Anyways, that's an irrelevant question
so I hope I don't get any haters just because of that. I just wanted to
know a few things:
1.What is an Assembly reference at the first place?
2.What Directories/namespaces do I need to use in order to make such an
application?
3.Why doesn't mono have the same directories as visual studios?
4.(it's not a must) be kind and give some sample code

Saturday, 28 September 2013

\hangindent in tabular environment?

\hangindent in tabular environment?

How do I indent wrapped words in a tabular environment?
I would like my table to look like this:
+-----------+-----------+
| heading 1 | heading 2 |
+-----------+-----------+
| cell 1 | cell 2 |
+-----------+-----------+
| cell 3 | Wrapped |
| | words |
| | with |
| | indent. |
+-----------+-----------+
| cell 4 | cell 5 |
+-----------+-----------+Thanks

JavaScript animation with multiple setTimeout

JavaScript animation with multiple setTimeout

i am trying to animate 3 different shapes with setTimeout it seems like
only 2 second shape has some sort of animation, my question is how can i
use multiple setTimeout to animate 3 different shapes also is there a
better way to do this
window.onload = draw;
var x = 5;
var y = 5;
radius = 50;
var x2 = 50;
var y2 = 120;
var x3 = 53;
var y3 = 230;
function draw(){
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
context.save();
context.clearRect(0,0,720,550);
//drawing a rectangle
context.fillStyle = "rgba(93,119,188,237)";
context.rect(x, y, 50, 50);
context.fill();
context.lineWidth = 7;
context.strokeStyle = 'yellow';
context.stroke();
x2 += 1;
//darwong a circle
context.beginPath();
context.fillStyle = "#0000ff";
//Draw a circle of radius 20 at the current coordinates on the canvas.
context.arc(x2, y2, radius, 0, Math.PI*2, true);
context.closePath();
context.fill();
x2 += 1;
//drawing a second circle
context.beginPath();
context.fillStyle = 'green';
context.arc(x3, y3, radius, 0, Math.PI*2, true);
context.closePath();
context.fill();
context.lineWidth = 5;//border around the circle
context.strokeStyle = 'red';
context.stroke();
x3 += 1;
var loopTimer = setTimeout('draw('+x+','+y+')',20);
var loopTimer2 = setTimeout('draw('+x2+','+y2+')',20);
var loopTimer3 = setTimeout('draw('+x3+','+y3+')',20);
}

What's the difference between constructors and passing parameters?

What's the difference between constructors and passing parameters?

I believe I understand what constructors are now, but to me it seems they
are just used for passing info to methods in another class. So why not
just call a method and supply a parameter instead? Have I got this wrong?

QTableView: how to edit non-editable cells in the program?

QTableView: how to edit non-editable cells in the program?

How should this be done by using the model->setData() method call?
I have derived a class called "MyStandardItemModel" from
QStandardItemModel. I have made my third and fourth columns non-editable
by overriding the protected virtual flags method. This is how it goes:
#define TX_PACKET_COLUMN (4u)
#define RX_PACKET_COLUMN (5u)
Qt::ItemFlags MyStandardItemModel::flags(const QModelIndex& index) const
{
if (index.column() == TX_PACKET_COLUMN || index.column() ==
RX_PACKET_COLUMN)
{
return (QStandardItemModel::flags(index) & ~Qt::ItemIsEditable);
}
else
{
return QStandardItemModel::flags(index);
}
}
...
//Set model
ui->testCaseTableView->setModel(model);
Having this done, I am not able to edit the cells in the third and fourth
column.
Now, I want that when I double click on these cells, a pop-up dialog comes
up. I will modify some data in the editable field of that dialog, and then
copy it back to the non editable cells inside the code.
I tried to just write a doubleclick() handler for the QTreeView and just
copy some data to the cells just to see if it is possible to copy data to
the non-editable cells.
This operation is failing, and the data is not written into the
non-editable cells.
Here you can find the double click handler:
void MainWindow::on_testCaseTableView_doubleClicked(const QModelIndex &index)
{
QVariant variant;
variant.toString() = "AA";
if((index.column() == TX_PACKET_COLUMN)||(index.column() ==
RX_PACKET_COLUMN))
{
model->setData(index, variant); // set new value
}
}
The setData(..) operation is clearing the already written data in the
cells, but string "AA" is not getting written. Please suggest how to copy
some data to non-editable cells inside the code.

Friday, 27 September 2013

How to create a running list using new inputs (php)

How to create a running list using new inputs (php)

Basically I have a simple form and instead of refreshing the page each
time and replacing the echo just to add an echo for each time the form is
submitted. For reference I'm trying to create a to-do list, but this code
just refreshes the page and replaces the current echo.
<form action="#" method="post">
<input type="input" name="task">
<input type="submit" value="Add Task">
</form>
<?php
echo $_POST["task"];
?>

Visualizing Sound (complete noob seeking guidance)

Visualizing Sound (complete noob seeking guidance)

My greatest apologies if this question has been previously asked! I am in
my final year of university studying graphic design and my project is
based on the idea of synesthesia, or visualizing sound. Unfortunately I
know nothing about code or programming at all, so am unable to figure this
out myself! Essentially I want to trans-code the audio signal to video
signal to achieve an outcome like this;
http://www.blakecarrington.com/014.php
but with the inclusion of colour :) Is anyone able to help me? I am happy
to repay the favor also.
Thank you so much for your time!

Send User Copy to his Email #Contact Form #PHP Script

Send User Copy to his Email #Contact Form #PHP Script

this is related to contact form. i am trying to send a copy of email to
user also.
so i thought to replace the same function so i repeated
if(!isset($hasError)) second time and changing $emailTo = $email
and this is not working. i thing the problem might with the headers... can
i write 2 different header tags ?
// to me
if(!isset($hasError)) {
$emailTo = 'myemail@website.com';
$subject = 'Submitted message from '.$name;
$sendCopy = trim($_POST['sendCopy']);
$body = "Name: $name \n\nEmail: $email \n\nComments: $comments";
$headers = 'From: ' .' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' .
$email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
//User Copy
if(!isset($hasError)) {
$EmailTo = '$email';
$Subject = 'Thank you for Contacting';
$Body = "Here is your copy of email which you have sent us. \n\nName:
$name \n\nEmail: $email \n\nComments: $comments \n\n Thank you for
your email. we will get back to your soon";
$headers = 'From: ' .' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$UserEmailSent = true;
}
UPDATE: how to change the sender email id ? i want to change the sender
email id to noreply@example.com. now it showing i got message from myself
:O

How Can I create a "ServerTime" Mysql

How Can I create a "ServerTime" Mysql

Hey Guys so I need to make a "ServerTime" or something like that, What I'm
trying to do is a timer to my game, so all the players will play in that
time.
And also If possible is there any way to make this time run more fast than
normal? like one minute is one second? - thx guys

const parameter vs rvalue parameter pass, when saved internally to the class private variables

const parameter vs rvalue parameter pass, when saved internally to the
class private variables

class A has an object that can be shared, but only internally modified
class A
{
public:
validityClass ** getValidityShared() // I want to make this const
return, not sure how to protect a double pointer const signeture
{
return &validityShared;
}
private:
validityClass * validityShared;
}
class B need an access, read for validations, or B class population
through its constructor
class B
{
B(A & ainst)
{
aValidityShared = ainst.getValidityShared();
}
private:
validityClass ** aValidityShared;/// tried to save it as validityClass
** & aValidityShared but I guess its wrong, even though everything
worked out
}
after B constructor is over, I am no longer need to know anything about A
class!
int main(int argc, char* argv[])
{
A instA;
B(&instA);
return EXIT_SUCCESS;
}
I want B intance to have the A shared variable, but without any extra
resources, so I tried to save it as an rValue.
what do you recommend? (save internally as an rvalue or const (double const))
how is the const protection for a double pointer?
or just never keep it internally saved?
by the way the example is slightly different than what I am using, but it
is the same context
and I am asking this question because I am getting some weird warning:
member initializers forconst char ** classB::xVar`

UTF-8 encoding yields weird characters in Android

UTF-8 encoding yields weird characters in Android

I have an Android app where I need to output some characters shich are not
ASCII. My Java file where I set those characters is encoded as UTF-8:
public void onItemCheckedStateChanged(ActionMode mode, int position,
long id, boolean checked) {
mode.setSubtitle(llista.getCheckedItemCount() + " elements
sel·leccionats.");
}
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.setTitle("Sel·lecciona!");
MenuInflater inflater = mode.getMenuInflater();
if (inflater != null) {
inflater.inflate(R.menu.menudetallllista, menu);
}
return true;
}
But the output I get is this:

Is there any way to fix this besides changing the file Encoding to
Windows-1252?

Jquery validare in foreach

Jquery validare in foreach

I have many form create in for
I have this HTML
<form method="post" id="form_commento-[i]" class="form_fancybox_commenti">
<div class="form-section">
<span style="position: relative">
<input type="text" id="commento_form_[i]_commento"
name="commento_form_[i][commento]" required="required"/>
<button type="submit" class="submit-button"
id="submit_form_commenti">Commenta</button>
</span>
</div>
</form>
Where [i] is index
in my document ready I have
$(document).ready(function() {
jQuery.validator.addMethod("alphanumeric", function (value, element) {
return this.optional(element) || /^[a-zA-Z0-9\n\-'àèìòù: <_,.
!?()]*$/.test(value);
}, "error");
$('.form_fancybox_commenti').each(function(index, numero_form) {
var theRules = {};
theRules[
'commento_form_'+index+'[commento]'] = {alphanumeric: true};
$(this).validate({
rules: theRules,
submitHandler: function(form) {
save(form);
}
});
});
but my custom rules doesn't works.
Anyway to resolve this problem?

Thursday, 26 September 2013

MySQL database hostname

MySQL database hostname

I have created a MySQL database and a table via cPanel on a web server of
mine. My question is this: How can I access this Database and Table from a
Visual Basic.net application?
What do I use as the host address? The http address to the web server is
http://www.canninginc.co.nz

Wednesday, 25 September 2013

call a JQuery function from code behind in C#

call a JQuery function from code behind in C#

I want to call this JQuery function from C# code behind but it is not work
Here is the JQuery function
function showDialog(id, title) {
$(id).dialog({
modal: true, minWidth: 600, title: title
});
$(id).parent().appendTo($("form:first"));
}
and here is the code behind which i use
ClientScript.RegisterClientScriptBlock(this.GetType(), "myfunction",
"$(document).ready(function(){showDialog('#editCustomer','äÍÏíË ãÚáæãÇÊ
Úãíá');});", true);
But it is not work

Thursday, 19 September 2013

Dapper parameters not working

Dapper parameters not working

I'm trying to use the Dapper orm with the following simple query:
var sqlString = new StringBuilder();
sqlString.Append("select a.acct AccountNumber,");
sqlString.Append(" b.first_name FirstName,");
sqlString.Append(" b.last_name LastName,");
sqlString.Append(" a.rr RrNumber,");
sqlString.Append(" c.addr1 AddressLine1,");
sqlString.Append(" c.addr2 AddressLine2,");
sqlString.Append(" c.addr3 AddressLine3,");
sqlString.Append(" c.addr4 AddressLine4,");
sqlString.Append(" c.addr5 AddressLine5,");
sqlString.Append(" c.addr6 AddressLine6,");
sqlString.Append(" c.addr7 AddressLine7,");
sqlString.Append(" c.addr8 AddressLine8 ");
sqlString.Append("from (pub.mfclac as a left join pub.mfcl as b on
a.client=b.client) ");
sqlString.Append("left join pub.mfclad as c on a.client=c.client ");
sqlString.Append("where a.acct = '@ZYX'");
var connection = new OdbcConnection(_connectionString);
var result = connection.Query(sqlString.ToString(),
new
{
ZYX = accountNumber
});
However when I execute this with an accountNumber known to exist, dapper
returns nothing. So I tried to remove the quotes to verify that the
parameter is in fact being replaced with the account number, however the
error being returned from the server indicates a syntax error around
"@ZYX". Which means dapper is not replacing the parameter with it's given
value. Any ideas why this is happening? From the limited documentation out
there, this should 'just work'.

How to use mysqli in codeigniter?

How to use mysqli in codeigniter?

I have read some information about the differences between mysql and
mysqli. First of all, I want to ask that why codeigniter uses mysql
dbdriver by default and not mysqli although myslqi is better? Is
codeigniter active record works only with mysql driver?
I have read this topic but there is no good answer for my question
Is it enough to change dbdriver in config.php file as mysqli, to use msqli
in codeigniter without any error?
Thanks.

iOS 7 no longer allowing pages to be non-zoomable with tag?

iOS 7 no longer allowing pages to be non-zoomable with tag?

I've been using the following to keep the mobile version of my website
from being scalable/zoomable:
<META content="width=device-width; initial-scale=1.0; maximum-scale=1.0;
user-scalable=0;" name="viewport" />
After I updated my phone to iOS 7, I noticed that you can now zoom to your
heart's content. (This is true in both Mobile Safari and Chrome for iOS.)
This change has wreaked some havoc on the layout, and I'd rather not have
to have separate stylesheets for each iteration of the OS. Is there an
alternative method to disabling zooming on mobile devices? Thanks.

MVC4 Entity Framework one paticular column not updating

MVC4 Entity Framework one paticular column not updating

I am having an infuriating issue where one paticular column in my entity
will not save/update. I have tried numerous methods of updating the row
such as manally assigning each property I want to update, to where I am
now (see code block below). 2 columns update and save as expected
(absent_type_id, and point_value) however no matter what I do the
"description" column just will not save.
I have checked the debugger to see what the value is before the
db.SaveChanges(); and confirmed it is set to the new value; however,
selecting the row after the save (and checking the database) shows that
the others values are updated, but the description reverts back to what it
was...why could this be?
[HttpPost]
public JsonResult UpdateOccurrence(int occ_id,
string absent_type,
string description,
int point_value)
{
try
{
// Get id for the absent type
int absent_type_id = db.AT_absent_types.Single(a =>
a.absent_type == absent_type).absent_type_id;
var occurrenceToUpdate = new AT_occurrences
{
occ_id = occ_id,
absent_type_id = absent_type_id,
description = description,
point_value = point_value
};
db.AT_occurrences.Attach(occurrenceToUpdate);
db.SaveChanges();
//return call omitted
}
catch (Exception ex)
{
return Json(new {Result = "ERROR", Message = ex.Message});
}
}
As I mentioned - posting the point_value and absent_type save and update
the entity perfectly, the description just will not save! i have no idea
why. Any help or insight would be very much appreciated - this is driving
me crazy! Cheers!

Loop only when between 2 numbers

Loop only when between 2 numbers

I have been putting off asking this questions as it seemed like such a
simple problem I could solve but i have be racking my brains and now cant
think.
I need to make my app only run the loops below when between 2 number. For
example:
Do While SOPickRS.RecordCount >=1 and <=4
I have tried loads of different combinations of code but cant seem to find
the correct one.
This is what I currently have that doesnt work because when the
RecordCount is 1 for example they will all run one after the other. I
understand why it is doing this however I cannot find the solution to it:
Do Until SOPickRS.RecordCount = 4
'Do Stuff
Loop
Do Until SOPickRS.RecordCount = 8
'Do Stuff
Loop
Do Until SOPickRS.RecordCount = 12
'Do Stuff
Loop

TortoiseSVN regex to look for multiple values

TortoiseSVN regex to look for multiple values

I would like to be able to search the TortoiseSVN log for a list of
Revisions or Bug-Ids.
The list could be for any number of individual values or ranges e.g.
search for SVN revisions 1 to 4, or 7, or 12, or 18 to 25 ......
I do not want to look for a range of 1 to 25 which would include revisions
that I am not interested in.
I am hoping to define an 'bugtraq:logregex' parameter search string value
to accomplish this.
Any advice on this please, would be greatly appreciated.
thanks
Nick

Wednesday, 18 September 2013

Use awk/sed scripting to extract function parameters

Use awk/sed scripting to extract function parameters

I have Python code from which I want to extract HTTP parameters.
In the following: how can I leave the def lines alone, but from remaining
lines preserve only what is within params['...'] perhaps with multiple
params['...'] on one line:
Input:
def delete_bazooka (request):
BType.objects.get(id=params['id']).delete()
BType.objects.get(name=params['name']).delete()
def create_bazooka (request):
s = Skill.objects.get(id=params['skill'])
l = Level.objects.get(id=params['level'])
bt = BType.objects.get(name=params['type'])
b = Bazooka(type=qt, bin=b, bin_sequence=b.count, text=params['text'],
explanation=params['chocolate'], passage=p)
def delete_hoop (request):
h = Hoop.objects.get(id=params['id'])
Desired Output:
def delete_bazooka (request):
id
name
def create_bazooka (request):
skill
level
type
text chocolate
def delete_hoop (request):
id

textField stringValue returns null when I make it a default for an attribute of an entity in core data

textField stringValue returns null when I make it a default for an
attribute of an entity in core data

Please help:
I am trying to use text fields as inputs by making them change the default
attribute of an entity before adding that entity to my table view. So if
you typed "item 1" in the text field then the next entity would appear
pre-populated with the "title" column's attribute reading "item 1."
Unfortunately, when I try to use [textField stringValue] to set the string
of the default it just returns null at run time!
What am I missing? Thank you
My Entity .h
// ItemEntity.h
#import <Foundation/Foundation.h>
@interface ItemEntity : NSManagedObject{
}
-(NSString *) titleValue;
@end
.m
// ItemEntity.m
#import "ItemEntity.h"
#import "MyManager.h"
@implementation ItemEntity
-(NSString *)titleValue{
MyManager *sharedManager = [MyManager sharedManager];
NSString *nam = [NSString stringWithFormat:@"%@",
sharedManager.titleText]; //titleText from MyManager;
return nam;
}
@end
My Manager Object .h
// MyManager.h
#import <Foundation/Foundation.h>
@interface MyManager : NSObject {
NSString *titleText;
@public
IBOutlet NSTextField *titleLabel;
}
@property (nonatomic, retain) NSString *titleText;
+ (id)sharedManager;
@end
Here's where the problem is I think .m
// MyManager.m
#import "MyManager.h"
@implementation MyManager
@synthesize titleText;
+ (id)sharedManager {
static MyManager *sharedMyManager = nil;
@synchronized(self) {
if (sharedMyManager == nil)
sharedMyManager = [[self alloc] init];
}
return sharedMyManager;
}
- (id)init {
if (self = [super init]) {
titleText = [NSString stringWithFormat:@"default"];
}
return self;
}
- (NSString *)titleText;{ //this is being called - but still returns (null)
NSString *y = [[NSString alloc] initWithFormat:@"why is this returning
(null)?, %@", [titleLabel stringValue]];
return y;
}
@end

No line numbers in VS 2010 despite checked

No line numbers in VS 2010 despite checked

I am having a problem with visual studio not displaying line numbers
despite having checked "Line numbers" in Tools -> Options. I have included
a pic with proof, and all the solutions I have found don't answer this.
How can I enable line number, despite already having enabled it?
http://imgur.com/7cmfqcZ

XML to PostgreSQL with Python

XML to PostgreSQL with Python

My code looks like :
#!/usr/bin/python
import codecs
import re
import psycopg2
import sys
import os
import time
import shutil
import csv
# Code for converting from iso-8859-2 to utf-8
BLOCKSIZE = 1048576
with codecs.open('DVBSNOOP/epg_dvb_snoop.txt', "r", "iso-8859-2") as
sourceFile:
with codecs.open('DVBSNOOP/epg_slo_sort.txt', "w", "utf-8") as
targetFile:
while True:
contents = sourceFile.read(BLOCKSIZE)
if not contents:
break
targetFile.write(contents)
break
# Code for regex remove specific string from text
input_file = open('epg_slo_sort.txt', "r") # read
output_file = open('epg_slo_xml.txt', "w") # write
for line in input_file:
line = re.sub(r"\d{8}:|\d{7}:|\d{6}:|\d{5}:|\d{4}:","", line) # remove
before nubers
line = re.sub(r"^//","",line) # remove //
line = re.sub(r"\([^)]*\)","",line) # remove ()
line = re.sub(r"= --> refers to PMT program_number","",line) # remove
= --> refers to PMT program_number
line = re.sub(r"-- Charset: ISO/IEC 8859 special table","",line) #
remove -- Charset: ISO/IEC 8859 special table
line = re.sub(r"[\[]\]","",line) # remove []
line = re.sub(r"Duration: \d{1}[^0-9]\d{7}","Duration",line) #remove
Duration: 0x0021000
line = re.sub(r"Start_time: \d{1}\w+","Start ",line) #remove
Start_time: 0xdce9115000
line = line.replace('"..',"").replace('"',"").replace(" . .
.","").replace("-","") # remove ".. , "" ....
line = line.replace ("Service_ID:","Program") # replace Service_ID to
Program
line = line.replace("event_name:","Title") # Replace event_name to Title
line = line.replace("[=","").replace("]","") # replace [= to blank
output_file.write(line) # write to file
# Code for output orginal file with time-stamp copy of epg_slo_xml.txt
current_time = time.strftime("_%d.%m.%y_%H:%M", time.localtime()) #
Get local time
shutil.copy('SORT/epg_slo_xml.txt','SORT/BACKUP/epg_slo_xml%s.txt' %
current_time) # Copy file to SORT/BACKUP/ file+date+time
Create XML file code:
# Code for creating XML document
output = open('epg.xml','w')
print >> output, '<?xml version="1.0" encoding="utf-8" ?>'
print >> output, '<epg>'
with open('SORT/epg_slo_xml.txt','r') as txt:
for line in txt:
if 'Program' in line:
output.write('<item>'+'<program>'+line+'</program>')
if 'Start' in line:
output.write('<start>'+line+'</start>')
if 'Duration' in line:
output.write('<duration>'+line+'</duration>')
if 'Title' in line :
output.write('<title>'+line+'</title>'+'</item>')
print >> output , '</epg>'
And the question part:
# Connection to Database
def main():
#Define our connection string
conn_string = ("host=localhost dbname=epg user=car password=pass")
# get a connection, if a connect cannot be made an exception will be
raised here
conn = psycopg2.connect(conn_string)
# conn.cursor will return a cursor object
cursor = conn.cursor()
print "Connected!\n"
if __name__ == "__main__":
main()
The question is how can I process my XML file, I mean open it process
every line with tags and upload into PostgrSQL table with all informations
from XML.
And my XML file looks like :
<?xml version="1.0" encoding="utf-8" ?>
<epg>
<item>
<program> Program 10 </program>
<start> Start 20130918 11:50:00 </start>
<duration> Duration 02:10:00 </duration>
<title> Title Obvestila </title>
</item>
</epg>
Thx, for reading this article, if you can give me any solution or code,
for processing xml file to postgresql.

Delete table row with JQuery animation in Firefox

Delete table row with JQuery animation in Firefox

I have an HTML table which uses jQuery DataTables
(https://datatables.net/). The rows are rendered with html links to delete
a row. I have used the following code to handle the click event of link,
delete the row on the server and then animate deletion of the row on the
front end.
$(document).on("click", ".delete-operation", function (e) {
e.preventDefault();
var oTable = $('#alloperations').dataTable();
var operationId = $(this).data('id');
// Get the parent table row and mark it as having been selected
// due to the fact rowindex does not work in order in datatables
var tableRow = $(e.toElement).parents('tr').addClass('row_selected');
bootbox.confirm("Are you sure?", function (answer) {
if (answer) {
// send request to delete operation with given id.
$.ajax({
type: 'delete',
url: "/operations/" + operationId,
success: function () {
var anSelected = fnGetSelected(oTable);
//Get all the row cells and animate a deletion
tableRow.children().animate({ backgroundColor:
"red", color: "black" }, 300, function() {
tableRow.fadeOut(2000, function() {
oTable.fnDeleteRow(anSelected[0]);
});
});
},
error: function(result) {
$("#messageContainer").html(result.responseJSON.ResponseView);
}
});
return true;
}
else {
// User clicked cancel
return true;
}
});
});
QUESTION: This works perfectly in Chrome but does not work at all in
Firefox, does anyone know how I would get it to work in Firefox as well?

How to get table cell values any where in the table using jquery

How to get table cell values any where in the table using jquery

I have the following table that returns the each cell value when clicked
using javascript?
How can i do the same using jquery?
<script language="javascript">
var tbl = document.getElementById("tblMain");
if (tbl != null) {
for (var i = 0; i < tbl.rows.length; i++) {
for (var j = 0; j < tbl.rows[i].cells.length; j++)
tbl.rows[i].cells[j].onclick = function () {
getval(this); };
}
}
function getval(cel) {
alert(cel.innerHTML);
}
</script>
<table align="center" id="tblMain" border="1" style="cursor: pointer;">
<tr>
<td>
R1C1
</td>
<td>
R1C2
</td>
<td>
R1C3
</td>
<td>
R1C4
</td>
</tr>
<tr>
<td>
R2C1
</td>
<td>
R2C2
</td>
<td>
R2C3
</td>
<td>
R2C4
</td>
</tr>
<tr>
<td>
R3C1
</td>
<td>
R3C2
</td>
<td>
R3C3
</td>
<td>
R3C4
</td>
</tr>
<tr>
<td>
R4C1
</td>
<td>
R4C2
</td>
<td>
R4C3
</td>
<td>
R4C4
</td>
</tr>
</table>

Some problems to understand CSS paged media style

Some problems to understand CSS paged media style

I have some doubt about the paged media in CSS.
If I have something like this code:
@page rotated {size: landscape}
TABLE {page: rotated; page-break-before: right}
what exactly happen? can you explain to me this code? I am reading the
documentation but I am finding some problems...
Tnx Andrea

Methods UITextField of UISearchBar return nil

Methods UITextField of UISearchBar return nil

I've got a searchBar wich sometimes has text filled in. I would like to
set the cursor of the underlying UITextField to a certain position. I
Already have a pointer that is not nil to the UITextField:
UITextField *searchField = [self.searchBar valueForKey:@"_searchField"];
And I fill in the text:
self.searchBar.text = addressToComplete.description;
And checked if the UITextField text is filled in and it is. Still, all the
methods regarding UITextPosition and UITextRange return nil:
UITextRange *selectedRange = [searchField selectedTextRange];
//selectedRange = nil
UITextPosition *newPosition = [searchField
positionFromPosition:selectedRange.start
offset:addressToComplete.street.length]; //newPosition = nil
UITextRange *newRange = [searchField textRangeFromPosition:newPosition
toPosition:newPosition]; //newRange = nil
I'm wondering what am I doing wrong here?

Tuesday, 17 September 2013

Intellisense Plugin Options in Visual Studio

Intellisense Plugin Options in Visual Studio

I can't find in VS 2012 or 2010 where you specify Resharper vs. using
Visual studio's build in intellisense.
I installed R# as usual and I always use R# Jedi option. But just curious
where I can go back and change this if I ever need to through VS options.

How to prevent DbContext from altering the database?

How to prevent DbContext from altering the database?

I'm learning Entity Framework (currently using EF6 beta) and I'm using the
code first pattern on an existing database. The entities and DbContext
class are created automatically using a T4 template.
I would like to prevent the DbContext from creating / altering anything
into the database at runtime.
How can I do that?

Uwsgi/Nginx Gives Me -- unavailable modifier requested: 0 -- Error

Uwsgi/Nginx Gives Me -- unavailable modifier requested: 0 -- Error

I am trying to get uwsgi to work with nginx on a Gentoo System. Here's how
I have it configured:
nginx:
server {
listen 192.168.1.40;
server_name localhost;
access_log /var/log/nginx/localhost.access_log main;
error_log /var/log/nginx/localhost.error_log info;
location ~*
(web|download|authenticate|db_login|delete|dir_list|upload)\.py$ {
uwsgi_pass 127.0.0.1:3031;
include uwsgi_params;
}
root /var/www/dude;
}
development uwsgi.d # cat web.ini
[uwsgi]
socket = 127.0.0.1:3031
chdir = /home/one/development/copy_files/modules/
module = web
processes = 4
threads = 2
development uwsgi.d #
I have a simple python script to test: development uwsgi.d # cat
/home/one/development/copy_files/modules/web.py
def application(env, start_response):
start_response('200 OK', [('Content-Type','text/html')])
return "Hello World"
development uwsgi.d #
The way I call the script is in javascript with:
xml.open("GET", "python/web.py", true);
But when I click on the button of my web page that runs xml.open("GET",
"python/web.py", true); I get a "-- unavailable modifier requested: 0 --"
uwsgi error:
development uwsgi.d # uwsgi web.ini
[uWSGI] getting INI configuration from web.ini
*** Starting uWSGI 1.4.10 (64bit) on [Tue Sep 17 19:59:07 2013] ***
compiled with version: 4.6.3 on 17 September 2013 19:12:48
os: Linux-3.10.7-gentoo #1 SMP Wed Sep 11 20:17:44 CDT 2013
nodename: development
machine: x86_64
clock source: unix
pcre jit disabled
detected number of CPU cores: 1
current working directory: /etc/uwsgi.d
detected binary path: /usr/bin/uwsgi
uWSGI running as root, you can use --uid/--gid/--chroot options
*** WARNING: you are running uWSGI as root !!! (use the --uid flag) ***
*** WARNING: you are running uWSGI without its master process manager ***
your processes number limit is 16003
your memory page size is 4096 bytes
detected max file descriptor number: 1024
lock engine: pthread robust mutexes
uwsgi socket 0 bound to TCP address 127.0.0.1:3031 fd 3
your server socket listen backlog is limited to 100 connections
mapped 329536 bytes (321 KB) for 8 cores
*** Operational MODE: preforking+threaded ***
*** no app loaded. going in full dynamic mode ***
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI worker 1 (pid: 27975, cores: 2)
spawned uWSGI worker 2 (pid: 27976, cores: 2)
spawned uWSGI worker 3 (pid: 27977, cores: 2)
spawned uWSGI worker 4 (pid: 27978, cores: 2)
-- unavailable modifier requested: 0 --
-- unavailable modifier requested: 0 --
-- unavailable modifier requested: 0 --
Can anyone please help? Been stuck on this for a good while.

Show tooltip on keypress for anchor tag using Jquery

Show tooltip on keypress for anchor tag using Jquery

can i know how to show a tooltip during keypress on an anchor tag using
Jquery ?
<a id="resultToolTip" href="#" data-tooltip="" class="has-tip"
title="User: Test Passed">Test Results</a>
<script>
$(document).ready(function() {
$('#resultToolTip').keypress(function(){
});
</script>

Borders and shadows, how to implement card style for a UIView in iOS?

Borders and shadows, how to implement card style for a UIView in iOS?

I have a collection view, it does its job but it's ugly... what I have now
is:

I want to decorate the cell like this:

What's the best way? Draw a custom layer or use resizable png assets? What
are the exact steps for reproduce the borders and shadows as the 2nd
image? Thanks

MySQL for excel and editing table data

MySQL for excel and editing table data

I am trying to update data in a column of a mysql table using mysql for
excel.
the data is acessed via a formula. When I put that formula in and Commit
Changes, I think MySQL for Excel is uploading the actual formula and not
the value. Is there any way around this?
ty

Sunday, 15 September 2013

getting error on run time when i give space between words

getting error on run time when i give space between words

I am storing words on run time in array but when i give space between
words the program don't ask for second input it give me an output directly
without taking second input here is my coding .
#include<iostream>
#include<conio.h>
using namespace std;
int main(){
char a[50];
char b[50];
cout<<"please tell us what is your language\t";
cin>>a;
cout<<"please tell us what is your language\t";
cin>>b;
cout<<a<<b;
getch();
}

using callback function in objective-C

using callback function in objective-C

I see have 2 type use callback function in objective C Ios is : function
a(& b) and function a(b)- b is callback function . What differnt between
them?

Slide up activity

Slide up activity

I have an activity and another activity. I want my first activity to end
when I slide up the screen. The animation should be like the activity is
sliding up too. Like the notification screen. Is that possible? I have
done many Google searches before posting this question, but could not get
anything.
P.S - I don't want this to be seen as a casual question since there is no
code shown. I just need some point to start and I am completely baffled.

Android music player inside service and seek bar in acivity how to sync both?

Android music player inside service and seek bar in acivity how to sync both?

Android music player inside service and seekbar in activity how to sync
both, I tried with a broad cast receiver inside activity to update seek
bar and send broadcast from service in every 2 seconds. but that is not
updating seekbar, I'm using a handler inside activity and passing that
while creating Broadcast receiver object and I use
handler.post(runnable... to update seekbar inside receiver. How can I
solve this I need to sync the seekbar and mediaplayer?

PHP Upload form, PDF, Doc & Docx

PHP Upload form, PDF, Doc & Docx

I'm struggling to make this upload code work for a docx file, it works
okay for doc and pdf..
$allowedExts = array("pdf", "doc", "docx");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "application/pdf")
|| ($_FILES["file"]["type"] == "application/msword"))
&& ($_FILES["file"]["size"] < 20000000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
this is part of a project from a while ago and i honestly can't remember
how to do it..
I know it's not the most secure upload method, but if someone could help
it would be appreciated!
I'm thinking i need to add another line here:
if ((($_FILES["file"]["type"] == "application/pdf")
|| ($_FILES["file"]["type"] == "application/msword"))
&& ($_FILES["file"]["size"] < 20000000)
Just not sure what.. Help is appreciated!

Is #import part of the C++11 standard?

Is #import part of the C++11 standard?

I'm trying to find out whether it's safe to use #import (instead of
#include with include guards) in a cross-platform C++11 library?
The articles I found on SO and elsewhere seem to indicate that #import was
proposed to be included in the C++11 standard, yet judging by answers from
around ~2012 it still seemed to be Microsoft and GCC specific extensions
with import not being an accepted standard.

Reloading/changing displayed person with ABPersonViewController on iOS7

Reloading/changing displayed person with ABPersonViewController on iOS7

I have a class which contains an ABPersonViewController child view
controller. Until iOS7, I was able to pass the setDisplayedPerson: message
several times, updating or replacing the displayed information. However,
with iOS7, once the viewDidLoad fires for the ABPersonViewController child
view controller, any subsequent calls to setDisplayedPerson: are seemingly
ignored.
I could replace the child view controller with another, and even animate
the transition between them, but this is very inelegant.
Anyone seen this?

Saturday, 14 September 2013

Javascript: How to dynamicly add a number to a variable name?

Javascript: How to dynamicly add a number to a variable name?

Say I have to following code: var numb = $(selector).length;
And now I want to dynamicly make variables based on this: var temp+numb = ...
How would I be able to do this?

What is different between Winform and Webform TreeView

What is different between Winform and Webform TreeView

I'm a new to webform C#. I use TreeView in Webform, it seems AfterSelect
Event, Tag, Name properties don't exist? I cannot get data from TreeView
without that properties. Is there any equivalent properties???
And what is different between two TreeView???

Can I write mapper and reducer program in different language

Can I write mapper and reducer program in different language

I felt doing my Mapper operation in Perl script but then I realized it
would be easier to write Reducer in Python. Can Mapper and Reducer can
work in different programming language?

setting the right mysql innodb_log_file_size

setting the right mysql innodb_log_file_size

We ran an alter table today today that took down the DB. We failed over to
the salve, and in the post-mortem, we discovered this in the mysql
error.log
InnoDB: ERROR: the age of the last checkpoint is 90608129,
InnoDB: which exceeds the log group capacity 90593280.
InnoDB: If you are using big BLOB or TEXT rows, you must set the
InnoDB: combined size of log files at least 10 times bigger than the
InnoDB: largest such row.
This error rings true because we were working on a very large table that
contains BLOB data types.
The best answer we found online said
To solve it, you need to stop MySQL cleanly (very important), delete the
existing InnoDB log files (probably lb_logfile* in your MySQL data
directory, unless you've moved them), then adjust the innodb_log_file_size
to suit your needs, and then start MySQL again. This article from the
MySQL performance blog might be instructive.
and in the comments
Yes, the database server will effectively hang for any updates to InnoDB
tables when the log fills up. It can cripple a site.
which is I guess what happened, based on our current (default)
innodb_log_file_size?
SHOW GLOBAL VARIABLES LIKE '%innodb_log%';
+-----------------------------+----------+
| Variable_name | Value |
+-----------------------------+----------+
| innodb_log_buffer_size | 8388608 |
| innodb_log_compressed_pages | ON |
| innodb_log_file_size | 50331648 |
| innodb_log_files_in_group | 2 |
| innodb_log_group_home_dir | ./ |
+-----------------------------+----------+
So, this leads me to two pointed questions and one open-ended one:
how do we determine the largest row so we can set our
cinnodb_log_file_size to be bigger than that?
what is the consequence of the action in step 1? I'd read about long
recovery times with bigger logs.
is there anything else I should worry about regarding migrations,
considering that we have a large table (650k rows, 6169.8GB) with
unrestrained, variable length BLOB fields.
We're running mysql 5.6 and here's our my.cnf.
[mysqld]
#defaults
basedir = /opt/mysql/server-5.6
datadir = /var/lib/mysql
port = 3306
socket = /var/run/mysqld/mysqld.sock
tmpdir = /tmp
bind-address = 0.0.0.0
#logs
log_error = /var/log/mysql/error.log
expire_logs_days = 4
slow_query_log = on
long_query_time = 1
innodb_buffer_pool_size = 11G
#http://stackoverflow.com/a/10866836/182484
collation-server
= utf8_bin
init-connect ='SET NAMES utf8'
init_connect ='SET collation_connection = utf8_bin'
character-set-server = utf8
max_allowed_packet = 64M
skip-character-set-client-handshake
#cache
query_cache_size = 268435456
query_cache_type = 1
query_cache_limit = 1048576
```

GNU-C-preprocessing FORTRAN source to change array indices causes recursion whilst expanding macro

GNU-C-preprocessing FORTRAN source to change array indices causes
recursion whilst expanding macro

I am parallelizing an existing FORTRAN application. I don't want to
directly change parts of its code so I am using preprocessor directives to
accomplish my goal. This way I am able to maintain the readability of the
code and I won't induce errors in parts of the code that have already been
tested. However, when I try to preprocess my source with the GNU C
preprocessor I get the following error message (gcc version 4.7.2 (Debian
4.7.2-5)):
test.f:9:0: error: detected recursion whilst expanding macro "ARR""
This simple test program demonstrates my problem:
PROGRAM TEST
IMPLICIT NONE
INTEGER I,OFFSET,ARR(10)
#define ARR(I) ARR(OFFSET+I)
DO I=1,10
ARR(I)=I
END DO
#undef ARR(I)
END PROGRAM TEST
This is the commandline output:
testing$ gfortran -cpp -E test.f
# 1 "test.f"
# 1 "<command-line>"
# 1 "test.f"
PROGRAM TEST
[...]
test.f:9:0: error: detected recursion whilst expanding macro "ARR"
DO I=1,10
ARR(OFFSET+OFFSET+OFFSET+OFFSET+OFFSET+OFFSET+OFFSET+OFFSET+OFFSET+OFFSET+OFFSET+OFFSET+OFFSET+OFFSET+OFFSET+OFFSET+OFFSET+OFFSET+OFFSET+OFFSET+OFFSET+I)=I
END DO
[...]
END PROGRAM TEST
This site provides some information on the preprocessor I am using:
http://tigcc.ticalc.org/doc/cpp.html#SEC10
As it seems I am using a function-like macro with macro arguments.
Why is the preprocessor detecting a recursion?
Why isn't the preprocessor capable of interpreting upper case directives
(#DEFINE instead of #define)? - I am asking, because I haven't had this
problem with the ifort preprocessor.
BTW: I am able to preprocess the code either using the ifort preprocessor
-fpp, or by changing the source in the following way:
PROGRAM TEST
IMPLICIT NONE
INTEGER I,OFFSET,ARR(10)
#define ARR_T(I) ARR(OFFSET+I)
DO I=1,10
ARR_T(I)=I
END DO
#undef ARR_T(I)
END PROGRAM TEST

Check if the data in datagridview is empty or null

Check if the data in datagridview is empty or null

I have a problem, probably you guys in this forum could help me.
Here is my problem:
I want to show the MessageBox that say there is no data in datagridview,
you cannot delete it. I already can delete the data in the datagridview,
but when the datagridview contains 0 data, and i click delete "button", it
is error. The error is: Object reference not set to an instance of an
object. NullReferenceException
Here is the code that pointed by the error: int rowNum =
dataGridView1.CurrentRow.Index;
Here is the code:
private void Delete(object sender, EventArgs e)
{
DataTable dt = (DataTable)dataGridView1.DataSource;
int rowNum = dataGridView1.CurrentRow.Index;
int id = Convert.ToInt32(dt.DefaultView[rowNum]["ID"]);
dt.DefaultView[rowNum].Delete();
using (OleDbConnection conn = new
OleDbConnection(connectionString))
{
string query = "DELETE FROM [Table] WHERE [ID] = @ID";
conn.Open();
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.AddWithValue("@ID", id);
cmd.ExecuteNonQuery();
}
if (choice.comboBox1.Text == "English")
{
System.Media.SoundPlayer sound = new
System.Media.SoundPlayer(@"C:\Windows\Media\Windows
Exclamation.wav");
sound.Play();
MessageBox.Show("Deleted Successfully!", "Deleted");
if (rowNum == 0)
{
bool rowIsEmpty = true;
foreach (DataGridViewCell cell in
dataGridView1.CurrentRow.Cells)
{
if (cell.Value != null)
{
rowIsEmpty = false;
break;
}
}
if (rowIsEmpty)
{
System.Media.SoundPlayer sounds = new
System.Media.SoundPlayer(@"C:\Windows\Media\Windows
Exclamation.wav");
sounds.Play();
MessageBox.Show("Tidak ada Data di Baris
ini!", "Error");
}
else
{
Delete(sender, e);
}
}
}
}
Does anyone knows how to fix it?

Python Hosting - Flask - Gevent - Socketio - mySQL

Python Hosting - Flask - Gevent - Socketio - mySQL

Which Python Hosting provider supports application build with
Flask,Gevent,Socketio,mySQL?

write to file from stack

write to file from stack

folks. I'm trying to write to a file from a stack. The stack was created
by reading from another file. I'm using the stack so that I can reverse
the file I read in. The file names to read and write to are from the
command line. This is how I have my stack implemented:
while(read.hasNext()) {
stack.push(read.next());}
The code for my other file that the stack is supposed to write to:
FileWriter w = null;
try {
w = new FileWriter(new File(args[1]));
} catch (IOException e) {
e.printStackTrace();
}
if (!stack.isEmpty()) { //this was a while statement
try {
w.write(stack.pop());
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("Didn't make it.");
}
The problem that I'm having is when I run my program, the file I want to
write to is created, but nothing gets written to the file. I originally
thought that my stack didn't have anything in it (that's why I changed my
while statement to an if; it's temporary). The "Didn't make it." didn't
print so I now know it's not that. What am I doing wrong here? Any help is
appreciated.

Friday, 13 September 2013

What is the simplest code to auto update content in the web browser without reloading?

What is the simplest code to auto update content in the web browser
without reloading?

I'm looking for the simplest code I can add to any text field or other
content on a web page that will update its value in accordance with the
response of a web service such as REST. Either JavaScript, jQuery or
WebSockets. Flash, native, etc... are cool too.

Jquery finish on mouseout multiple events

Jquery finish on mouseout multiple events

Okay so I am trying to make multiple animations happen, onmouseenter i
have a bounce effect that uses finish(); on mouseout and onclick moves
position problem is, if you click and and then move your mouse out of the
div it finishes the click animation, i have tried using variables, .data
and other various methods but have failed miserably and am looking for a
quick solution.
Here is the jsfiddle: http://jsfiddle.net/fMxfp/13/
Here is the code
$.fx.speeds._default = 1000;
$.fn.StartBounce = function() {
var self = this;
(function runEffect() {
self.effect('bounce', {distance:20}, 5000, runEffect);
}) ();
return this;
};
$('.iconeffect').mouseenter(function() {
$(this).stop().StartBounce();
});
$('.iconeffect').mouseout(function() {
$(this).finish();
})
$('#effect1').click(function() {
if( $("#desc1").is(":hidden") ) {
bounced = false;
$(this).finish();
$(this).stop(true, true).animate({ left: -50});
$('#effect2, #effect3').stop(true, true).animate({ left: 1000});
$('#desc1').show( "blind", 1000);
} else {
$(this).finish();
$(this).stop(true, true).animate({ left: 0});
$('#effect2, #effect3').stop(true, true).animate({ left: 0});
$('#desc1').hide( "blind", 1000);
}
});

Allow php script access only from Android client

Allow php script access only from Android client

I am trying to call a php script from my android app to pass some data and
store it in the database. Is there a way to allow access to php script
from my android client only?
Thanks.

Google App Engine ancestor query in JPA

Google App Engine ancestor query in JPA

What is the way to implement ancestor query for the app engine in JPA?
I know about @Extension annotation but how is it used in the query?
@Entity
public class Event {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Extension(vendorName="datanucleus", key="gae.parent-pk", value =
"true")
private Key id;
}

Fill matrix from data frame

Fill matrix from data frame

I have a data frame which contains some data (Claims) and two additional
columns, containing row and column information, for example:
Claim row Column
5000 2 10
etc.
I have a matrix that contains some data as well as NAs. I'd like to
replace the NAs with the data from the data frame, using the row/column
information. So 5000 would replace the NA in the matrix that is currently
in row 2, column 10.
Is there an easy way to accomplish this with R?

Thursday, 12 September 2013

assign color to mouse cursor in HTML

assign color to mouse cursor in HTML

How can I assign color to the mouse cursor in a web-page?
Can anyone suggest me a way to do it using any of the technologies e.g.
HTML, CSS, JavaScript?

ExtJS: consolidating records in store

ExtJS: consolidating records in store

Considering a simple example, consider the following store of records:
{ item: 'A', group: 'red', quantity: 1 },
{ item: 'A', group: 'green', quantity: 1 },
{ item: 'B', group: 'red', quantity: 1 },
{ item: 'B', group: 'blue', quantity: 1 },
{ item: 'C', group: 'green', quantity: 1 }
My goal is to have a grid with each distinct group field as a filter,
where all active filters consolidate. Examples:
// show: red, green // show: green // show: red, blue
item | quantity item | quantity item | quantity
--------------- --------------- ---------------
A | 2 A | 1 A | 1
B | 1 C | 1 B | 2
C | 1
Is there a built-in way to handle this? My thoughts were to first apply a
filter on group, then use a collector, then a special renderer.
Thoughts?

Parsing empty XML elements in PHP

Parsing empty XML elements in PHP

PHP newbie here. I'm parsing a long XML file, setting each tag to a
variable. If the element's tag is empty, I want to assign it the value
"N/A"
I'm wondering if there's a more concise way to do this than my current
approach:
$elements = array()
$propertyOwner = $report->PropertyProfile->PrimaryOwnerName[0];
array[] = $propertyOwner;
$propertyAddress = $report->PropertyProfile->SiteAddress[0];
array[] = $propertyAddress;
...
for($i=0; $i<count($elements); $i++) {
if (array[i] === '') {
array[i] = 'N/A');
}
}

Object storing a non-owning reference that must be informed before the reference is destructed

Object storing a non-owning reference that must be informed before the
reference is destructed

I have a class following this pattern:
class Foo
{
public:
// Create a Foo whose value is absolute
Foo(int x) : other_(0), a_(x) {}
// Create a Foo whose value is relative to another Foo
Foo(Foo * other, int dx) : other_(other), a_(dx) {}
// Get the value
double x() const
{
if(other_)
return other_->x() + a_;
else
return a_;
}
private:
Foo * other_;
int a_;
};
The Foo objects are all owned by a Bar:
class Bar
{
public:
~Bar() { for(int i=0; i<foos_.size(); i++) delete foos_[i]; }
private:
vector<Foo*> foos_;
};
Of course, this is a simplified example to get the idea. I have a
guarantee that there are no loop of Foos, and that linked Foos all belong
to the same instance of Bar. So far, so good. To do things the C++11 way,
I would use vector< unique_ptr<Foo> > foos_; in Bar, and pass
foos_[i].get() as potential argument of a Foo constructor.
There is the deal:
This a GUI application, and the user can interactively delete some Foo at
will. The expected behaviour is that if foo1 is deleted, and foo2 is
relative to foo1, then foo2 becomes now "absolute":
void Foo::convertToAbsolute() { a_ += other_->x(); other_ = 0; }
void usageScenario()
{
Foo * foo1 = new Foo(42);
Foo * foo2 = new Foo(foo1, 42);
// Here, foo1->x() = 42 and foo2->x() = 84
foo1->setX(10);
// Here, foo1->x() = 10 and foo2->x() = 52
delete foo1;
// Here, foo2->x() = 52
}
How would you handle this situation? The simplest raw pointer approach I
can think of is to have a two-way link instead of a one-way, so the Foo
are aware of who is relative to them:
class Foo { /* ... */ vector<Foo*> areRelativeToMe_; };
Foo::~Foo()
{
for(int i=0; i<areRelativeToMe_.size(); i++)
areRelativeToMe_[i]->convertToAbsolute();
}
Is there a way using standard C++11 smart pointers to avoid having this
two-way dependency (well, the dependency is hidden instead), and then
avoid explicitely calling areRelativeToMe_[i]->convertToAbsolute(); in the
destructor of Foo? I was thinking about weak_ptr, something in the spirit
of:
class Foo { /* ... */ weak_ptr<Foo> other_; };
double Foo::x() const
{
if(other_.isExpired())
convertToAbsolute();
// ...
}
But the issue is that convertToAbsolute() needs the relative Foo to still
exist. So I need a non-owning smart-pointer that can tell "this reference
is logically expired", but actually extends the lifetime of the referenced
object, until it is not needed.
It could be seen either like a weak_ptr extending the lifetime until it is
not shared with any other weak_ptr:
class Foo { /* ... */ extended_weak_ptr<Foo> other_; };
double Foo::x() const
{
if(other_.isExpired())
{
convertToAbsolute();
other_.reset(); // now the object is destructed, unless other
// foos still have to release it
}
// ...
}
Or like a shared_ptr with different level of ownership:
class Bar { /* ... */ vector< multilevel_shared_ptr<Foo> foos_; };
class Foo { /* ... */ multilevel_shared_ptr<Foo> other_; };
void Bar::createFoos()
{
// Bar owns the Foo* with the highest level of ownership "Level1"
// Creating an absolute Foo
foos_.push_back( multilevel_unique_ptr<Foo>(new Foo(42), Level1) );
// Creating a relative Foo
foos_.push_back( multilevel_unique_ptr<Foo>(new Foo(foos_[0],7),
Level1) );
}
Foo::Foo(const multilevel_unique_ptr<Foo> & other, int dx) :
other_( other, Level2 ),
// Foo owns the Foo* with the lowest level of ownership "Level2"
a_(dx)
{
}
double Foo::x() const
{
if(other_.noLevel1Owner()) // returns true if not shared
// with any Level1 owner
{
convertToAbsolute();
other_.reset(); // now the object is destructed, unless
// shared with other Level2 owners
}
// ...
}
Any thoughts?

How do I use getClass() to tell if an Object is numeric?

How do I use getClass() to tell if an Object is numeric?

I want to dynamically tell if an Object in Java is numeric or not. My code
is as the following:
if(obj.getClass().equals(Number.class)) {
attributeTypeStr = "Numeric";
} else {
attributeTypeStr = "Non-Numeric";
}
The Object obj can be any numeric types like Integer, Float, Double, etc.
But when I tested it with Integer/Float/Double, the attributeTypeStr
always returns "Non-Numeric". I guess that's because Integer/Float/Double
are subclasses of Number but Number.class does not equal Double.class. I
could use something like
if(obj.getClass().equals(Integer.class) ||
obj.getClass().equals(Float.class) || obj.getClass().equals(Double.class))
But it looks too verbose. So is there a simple way to do that?

PHP Category Reverse Traversal Algorithm

PHP Category Reverse Traversal Algorithm

pI'm trying to optimize an e-commerce category system with unlimited
category depth (barring system memory limitations). I retrieve all the
categories at once and order them as a multi-dimensional array that
emroughly/em looks like:/p precode[array] ( [0] ( 'CategoryId' =gt; 1,
'ParentCategoryId' =gt; 0, 'Title' =gt; 'Category A', 'SubCategories' =gt;
[array] ( [0] ( 'CategoryId' =gt; 2, 'ParentCategoryId' =gt; 1, 'Title'
=gt; 'Category B', 'SubCategories' =gt; [array] ( [0] ( 'CategoryId' =gt;
3, 'ParentCategoryId' =gt; 2, 'Title' =gt; 'Category C' ) ) ) ) ) )
/code/pre pEach item in the array is actually an object, but for
simplicity I wrote it out kind of like an array format./p pI'm able to
traverse my tree downwards using this function:/p precode/** * Find Branch
using Recursive search by Object Key * @param String Needle * @param Array
Haystack * @return Array */ public static function findBranchByKey($key,
$needle, $haystack) { foreach ($haystack as $item) { if ( $item-gt;$key ==
$needle || ( is_object($item) amp;amp; $item = self::findBranchByKey($key,
$needle, $item-gt;SubCategories)) ) { return $item; } } return false; }
/code/pre pThis finds the object with a matching key and returns it (which
may contain more subcategories). /p pMy issue is figuring out how to
traverse the other direction. For example, using the data above, let's say
I am displaying Category C and want to create bread crumbs of it's
parents. I can't think of a good way to take my strongtree/strong array,
jump to a specific subcategory, then iterate upwards to get each parent. A
resulting array from something like this could be like this so it's easy
to spit them out as bread crumbs:/p precode array( 'Category A', 'Category
B', 'Category C' ) /code/pre pI could probably do this using SQL in my
database but I'd like to retrieve the tree once, cache it, and perform
traversal on that object whenever I need to rather than making tons of
queries./p pTL;DR; How can I traverse upwards in a multidimensional array
of categories?/p

Realtime audio processing without having to output

Realtime audio processing without having to output

Thanks for always being there, i am new to iOS programming and I've been
having having a challenge of not wanting to output my audio samples to
speaker but doing DSP on them. Does anyone have any working code or link
on how to go about it. I know this question has been asked by @Simpleman
and replied by @Mar0ux but I doubt if a solution has been found yet.
Thanks in advance.

C# RegEx Not returning what it should

C# RegEx Not returning what it should

I got this Regex problem where I need to select the last part of a string
however no matter what I do it will only select on till it hit's a "\n"
(newline) Here's what I have tried so far
sms = Regex.Match(datalog, "\"\\r\\n.*").ToString();
Or
sms = Regex.Match(datalog, @"\""\r\n.*").ToString();
Here is what datalog contains
"\r\n+CMT: \"+4528835769\",,\"13/09/11,15:09:32+08\"\r\nLinje
1\nLinje2\nLinje 3\r\n
And what i need the Rexex to return
"\r\nLinje 1\nLinje2\nLinje 3\r\n
but this is what it returns (and what the string sms ends up containing)
"\"\r\nLinje 1"
What am I doing wrong?? since it stops selecting after Linje 1\n I assume
the problem is with the newline.
I have also tried using .+ instead of .* but the result is the same

Wednesday, 11 September 2013

DNN: Using multiple web user controls in one module and showing different controls in different pages

DNN: Using multiple web user controls in one module and showing different
controls in different pages

I'm a DotNetNuke newbie. Please be gentle. I'm using the "DotNetNuke 6
Compiled Module" template to build my module. I already have View.ascx
control in the project and have added another control called test.ascx.
My question is: how do I show different different views in different pages
I add the module to. (if that is possible at all) e.g Show View.ascx on
say the default.aspx page and then on the default2.aspx page show the
test.ascx user control?
If this is not possible does it mean I need different visual studio
projects for each ascx control. Surely not.

Using self-referential arrays, polygons are invisible

Using self-referential arrays, polygons are invisible

I used an array that refers to previous elements in the same array to
determine what the next value will be. This is so that I can get relative
values for position when drawing polygons. There are no reported syntax
errors, but the triangles I use here in the example are either invisible
or don't exist.
For this example, I would like to make small black triangles randomly
scattered in the top half of the window without regard for the window's
edges and the other triangles. The following is the code which includes an
example of what I'm trying to achieve, but without using a
self-referential array (I wrote this in BlueJ and have never written
anything outside of BlueJ. I don't know how to write continuous code so
please bear with me. I wrote where each of the two classes begin after
each // :
//first class
import javax.swing.*;
public class patterns {
public static void main(String[] args) {
JFrame f = new JFrame("Example");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
example p = new example();
f.add(p);
f.setSize(400,400);
f.setVisible(true);
}
}
//next class
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.Color;
public class example extends JPanel{
public void paintComponent (Graphics g){
super.paintComponent(g);
this.setBackground(Color.WHITE);
int[] xC = new int[3];
xC[0]= (int)Math.random()*400;
xC[1]= xC[0]+(int)Math.random()*20;
xC[2]= xC[1]+(int)Math.random()*4;
int[] yC = new int[3];
yC[0]= (int)Math.random()*200;
yC[1]= yC[0]-(int)Math.random()*10;
yC[2]= yC[0]-(int)Math.random()*3;
g.setColor(Color.BLACK);
int x=0;
while(x<14){
g.drawPolygon(xC,yC,3);
x++;
}
int[] xCe = new int[3];
xCe[0]= 200;
xCe[1]= 210;
xCe[2]= 213;
int[] yCe = new int[3];
yCe[0]= 300;
yCe[1]= 295;
yCe[2]= 299;
g.fillPolygon(xCe,yCe,3);
g.drawString("There should be a whole bunch of little triangles
that look",20,320);
g.drawString("sort of like this one, but on the top half of this
window.", 40,340);
g.drawLine(170,270,200,290);
g.drawLine(194,289,200,290);
g.drawLine(197,285,200,290);
g.drawString("this one",140,260);
}

PHPMailer AddStringAttachment with PDF

PHPMailer AddStringAttachment with PDF

I am new to phpmailer and I am able to send emails, emails with
attachments, and stringattachments that are .txt files however I cannot
send stringattachments with PDF's. The email is sent, but the PDF is
corrupted/unable to open. Can anyone help to send the AddStringAttachment
with the attachment being a PDF rather than a .txt? Thanks
<?php
require_once('class.phpmailer.php');
$mail = new PHPMailer();
$body2 = "You are receiving this email because the Transfer Application
submitted for $Name transferring to $Receiving is missing required
documentation.
Please see the note below for details. The transfer application will not
be reviewed until all of the necessary materials are received by the
UHSAA.
<p> Details:
$Notes ";
$mail->IsSMTP();
$mail->AddAddress($emailp);
$mail->AddCC('transfers@uhsaa.org');
$mail->AddStringAttachment($body2, 'Filename.pdf', 'base64',
'application/octet-stream');
$mail->Subject = "Test";
$body = ("See attachment");
$mail->MsgHTML($body);
$mail->AddAddress($address);
$mail->AddCC($address);
if(!$mail->Send())
;
?>
Again, if I just change Filename.pdf to Filename.txt everything works so
I'm assuming the problem is with the encoding but I can't figure it out.
Please help so I can send stringattachment PDF's. Thanks.

The value is invalid according to its datatype

The value is invalid according to its datatype

This has been eluding me all day. First, here is the config section:
<system.serviceModel>
<services>
<service name="Namespace.FooService"
behaviorConfiguration="Namespace.FooBehavior">
<endpoint address="" binding="basicHttpBinding"
contract="Namespace.IFooService" />
<endpoint address="mex" binding="mexHttpBinding"
contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:80/FooServices" />
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="Namespace.FooBehavior">
<serviceMetadata httpsGetEnabled="true" httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
The contract:
[ServiceContract(Namespace="https://Example.com/Foo")]
public interface IPrintDriverService
...
public class FooService: IFooService
which is giving me the warnings:
WCF configuration validation warning: The 'contract' attribute is invalid
- The value 'Namespace.IFooService' is invalid according to its datatype
'serviceContractType'.
WCF configuration validation warning: The 'name' attribute is invalid -
The value 'Namespace.FooService' is invalid according to its datatype
'serviceNameType'.
Which I can't seem to get rid of. When I go to debug it in
WcfServiceHost.exe, the service runs fine. But, when I go to publish it
fails silently.
Is there a way to see why the publish failed?
Does anyone know how to get rid of those warnings?

PHPMyAdmin 4.0.5 - Grid edit, checkbox, Edit, Copy and Delete features are not available

PHPMyAdmin 4.0.5 - Grid edit, checkbox, Edit, Copy and Delete features are
not available

I see this warning in PHPMyAdmin 4.0.5 "does not contain a unique column.
Grid edit, checkbox, Edit, Copy and Delete features are not available." In
PHPMyAdmin 3.5.1 these options appear correctly using the same database.
Can fix this? How? thanks in advance Fabián.

Render GSP view as compact html file

Render GSP view as compact html file

I have gsp view files wherein tags are formatted for readability with
whitespaces. I am expected to remove those so that the rendered html file
is compact. So, is there a way in grails using plugin or any other means
that I can tell grails to remove the whitespaces/newlines between tags and
generate a compact view? I dont want to remove them from gsp file itself
but only from the html file rendered by grails.

Tuesday, 10 September 2013

CSS background color width reduces when browser window is minimized

CSS background color width reduces when browser window is minimized

I have a page but when i minimize the browser window the background color
gets cut down. I want the color to expand to the full browser width. What
is the fix for this?
The page can be seen here: http://www.domainandseo.com/classmarker/index.html
The CSS is below:
@charset "utf-8";
/* ==========================================================================
RESET STYLES
==========================================================================
*/
* {
margin: 0; padding: 0;
}
html,
button,
input,
select,
textarea {
color: #222;
}
body {
font-size: 1em;
line-height: 1.4;
}
img {
border: 0 none;
}
/* ==========================================================================
BASE STYLES
==========================================================================
*/
html {
height: 100%;
}
body {
font-family: Arial, Helvetica Sans-serif;
width: 100%;
height: 100%;
color: #595959;
}
.col-full {
width: 1014px;
margin: 0 auto;
}
h1, h2, h3, h4, h5, h6 {
font-family: Helvetica, Arial, Sans-serif;
}
/* ==========================================================================
HEADER STYLES
==========================================================================
*/
#header h1 {
margin-top: 26px;
float: left;
}
h1 a span {
display: none;
}
#login-form {
float: right;
margin: 25px 92px 12px 0;
}
#login-form input {
width: 150px;
height: 29px;
line-height: 29px;
border: 1px solid #a5a5a5;
color: #797979;
font-size: 14px;
padding-left: 8px;
margin-left: 3px;
}
#login-form #login-button {
width: 72px;
height: 30px;
background: url(../img/login-bg.png) top repeat-x;
border: 1px solid #494949;
cursor: pointer;
margin-left: 0;
font-weight: bold;
color: #FFF;
font-size: 13px;
padding-left: 0;
text-shadow: 1px 1px 1px #3f3f3f;
filter: dropshadow(color=#3f3f3f, offx=1, offy=1);
}
.form-buttons {
margin-left: 3px;
}
.form-buttons a {
text-decoration: none;
font-size: 12px;
color: #ef4926;
margin-right: 116px;
}
.nav {
clear: both;
width: 100%;
height: 47px;
background: #000;
}
.nav ul {
margin-top: 10px;
float: left;
}
.nav ul li {
float: left;
list-style: none;
margin-right: 53px;
}
.nav ul li a {
text-decoration: none;
font-family: Helvetica;
font-weight: bold;
color: #FFF;
/*font-size: 16px;*/
font-size: 15px;
}
.top-heading {
background: #363737;
height: 57px;
border-top: 1px solid #727272;
border-bottom: 1px solid #727272;
}
.top-heading h2 {
/*font-size: 28px;*/
font-size: 27px;
color: #FFF;
text-shadow: 1px 1px 2px #282929;
filter: dropshadow(color=#282929, offx=1, offy=1);
padding-top:8px;
}
#featured {
background: url(../img/featured-gd.png) repeat-x;
}
#featured .col-full {
background: url(../img/featured-bg.jpg) no-repeat;
}
.featured-content {
width: 454px;
float: left;
margin-right: 40px;
}
.featured-content h2 {
color: #FFF;
/*font-size: 38px;*/
font-size: 37px;
line-height: 1.15;
margin-top: 45px;
margin-bottom: 12px;
text-shadow: 1px 1px 2px #282929;
filter: dropshadow(color=#282929, offx=1, offy=1);
}
.featured-content p {
font-size: 15px;
color: #FFF;
line-height: 1.46;
}
.register-btn {
display: block;
width: 164px;
height: 39px;
text-decoration: none;
background: url(../img/register-btn.png) repeat-x;
text-align: center;
font-family: Helvetica;
font-weight: bold;
margin-top: 27px;
font-size: 22px;
color: #FFF;
padding-top: 4px;
-webkit-box-shadow: 0px 0px 1px 1px #2e2e2e;
box-shadow: 0px 0px 2px 2px #2e2e2e;
}
#featured img {
margin-top: 6px;
margin-bottom: 2px;
}
/* ==========================================================================
MAIN STYLES
==========================================================================
*/
#features {
background: #ff5423;
overflow: hidden;
}
#features h3 {
line-height: 1.15;
color: #FFF;
font-family: Helvetica;
padding-top: 24px;
margin-bottom: 13px;
/*font-size: 26px;*/
font-size: 25px;
}
.features-left {
width: 447px;
float: left;
margin-right: 62px;
}
.features-right {
width: 472px;
float: left;
}
.features-right ul {
margin-left: 15px;
}
.features-right ul li {
line-height: 1.76;
color: #ffc3b2;
font-size: 14px;
padding-left: 2px;
}
.features-right ul li span {
font-size: 17px;
color: #fefefe;
position: relative;
top: 2px;
}
.more-features {
display: block;
width: 144px;
height: 28px;
color: #fb3800;
font-family: Helvetica;
/*font-size: 17px;*/
font-size: 16px;
font-weight: bold;
text-align: center;
padding-top: 4px;
text-decoration: none;
background: url(../img/more-features.png) repeat-x;
margin-top: 38px;
margin-bottom: 23px;
}
#client-list {
border-top: 4px solid #a6a6a6;
border-bottom: 4px solid #c6c6c6;
padding-bottom: 7px;
}
#client-list .col-full {
width: 1080px;
}
#client-list h4 {
color: #4d4d4d;
/*font-size: 18px;*/
font-size: 17px;
margin-top: 39px;
}
#client-list .more-clients {
float: left;
text-decoration: none;
font-size: 15px;
color: #ff5423;
}
#client-list img {
margin-left: 90px;
margin-top: -44px;
}
#main {
clear: both;
background: url(../img/main-gd.png) repeat;
}
.col-446 {
width: 446px;
float: left;
margin-right: 55px;
}
.col-476 {
width: 476px;
float: left;
}
.col-476 p {
margin-right: 25px;
}
#main h3 {
font-family: Helvetica;
/*font-size: 28px;*/
font-size: 27px;
color: #535353;
line-height: 1.07;
margin-top: 30px;
margin-bottom: 14px;
}
#main p {
font-size: 14px;
line-height: 1.64;
margin-bottom: 21px;
}
.site-features {
margin-top: 32px;
float: left;
}
.site-features li {
list-style: none;
float: left;
margin-right: 35px;
}
li.sf-last {margin-right: 0;}
.site-features li a {
}
.join-box {
}
.join-btn {
}
.join-box p {
}
/* ==========================================================================
FOOTER STYLES
==========================================================================
*/
h4 a span {
display: none;
}
#footer {
clear: both;
}