Saturday, 31 August 2013

How can I open the running application opened by my previous login?

How can I open the running application opened by my previous login?

Now I am using a remote desktop to connect to a remote linux(ubuntu)
virtual machine.Yesterday ,I opened a applicationiKomodojCand closed my
remote desktop client when I left(the virtual machine was kept
running).Today ,I reconnect to my VM and want to reuse the Komodo I opened
yesterday,What can I do?When I directly click the Komodo tag on my
desktop,I cannot open it because there is already a Komodo process
running.So I have to manually kill the process in the terminal and then
click the Komodo tag on my desktop.I think it's not a very good way
because every time I reconnect to my VM,I have to kill the Komodo process.

2D dynamic allocation in C error when incrementing the pointer

2D dynamic allocation in C error when incrementing the pointer

I wanted to allocate a string array dynamically , the program is supposed
to ask the user for characters and collect them in the first string in the
array till letter 'q' is entered then the program starts adding the
characters to the second line and so on.
When I print the characters memory location it seems like each character
takes two memory cells instead of one though I increment it only once.
Here is the source code to my program
#include <stdio.h>
void main(){
char** txt;
char* baseAddress;
txt = (char **)malloc(5*sizeof(char*));
*txt = (char *)malloc(20*sizeof(char));
baseAddress=*txt;
while(*(*txt)!='q'){
(*txt)++;
scanf("%c",(*txt));
printf("%p\r\n",(*txt));
}
*txt='\0';
printf("%p",baseAddress);
free(baseAddress);
free(txt);
}
the output is like this
>j
>0x9e12021
>0x9e12022
>s
>0x9e12023
>0x9e12024
>
I think there may be something wrong with the pointers. How do I go about
accomplishing this? and sorry for the bad english

How do you run DaoTest

How do you run DaoTest

I really don't know anything about JUnit, and I want a quick answer. I
built and ran DAOtest using eclipse, but where are the entry points. Or
where see the execution.

Tab bar icons pixelated and cut off

Tab bar icons pixelated and cut off

I am trying to set my UITabbar icons via interface builder. Here is what I
am seeing:

Two problems here:
Why is the bottom cut off? The dimensions of these 3 images in order is
64x42, 44x44, 46x46.
Why are they pixelated/blurry?
I am following the guidelines for tab bar icons listed here:
https://developer.apple.com/library/ios/documentation/userexperience/conceptual/mobilehig/IconsImages/IconsImages.html
I am not using the image, image@2x naming scheme. I am just setting these
in IB. This app will be only released to devices with retina displays in
any case. The screenshot is from an iPhone 5.

How to frame two for loops in list comprehension python

How to frame two for loops in list comprehension python

I have two lists as below
tags = [u'man', u'you', u'are', u'awesome']
entries = [[u'man', u'thats'],[ u'right',u'awesome']]
result = []
for tag in tags:
for entry in entries:
if tag in entry:
result.append(entry)
How to do the above logic using list comprehension in a single line, and
that should be ultimate and very fast ?

iOS postpone screen update until next user interaction

iOS postpone screen update until next user interaction

I need to postpone a screen update until next user interaction. Although
the code has changed the display, but I want it to be shown a bit later,
will it be possible?

Vimgolf Top X explaination

Vimgolf Top X explaination

Challenge: http://vimgolf.com/challenges/51cf1fae5e439e0002000001
Best solution:
S]*daw{@.UP@.JZZ
Now the question is how does the solution work? Just picking up Vim and
now just getting into the more advanced commands.

How to add dynamic layout in ViewGroup in android?

How to add dynamic layout in ViewGroup in android?

I created FrameLayout dynamically in my activity. Like this
FrameLayout path_zoom;
path_zoom = new FrameLayout(this);
path_zoom.setLayoutParams(new FrameLayout.LayoutParams(1500,1119));
Now i want to add this dynamic layout in ViewGroup for layout zooming. I
need to add my layout like this.
View v = ((LayoutInflater)
getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.ground_zoom,
null, false);
Instead of null i want to pass ViewGroup object. How can i do this? Can
any body tell me? Thanks in advance.

Friday, 30 August 2013

Keep calling on a function while mouseover

Keep calling on a function while mouseover

how do I keep calling a function on mouseover while the mouse is hovered
over an html element for example:
<script>
function a(){
"special code hear"
}
</script>
<div onmouseover('a()')>&nbsp;</div>
How can I keep calling the function a while the mouse is hovered over the
div instead of having it call the function once.

Thursday, 29 August 2013

Can't run two AnyEvent::timers in the same time?

Can't run two AnyEvent::timers in the same time?

I'm trying to build a Jobs Queue Manager that is Inotyfing a folder for
changes, when a job is inserted to the new folder it is being moved to
progress folder and if the job hasn't been successfully processed, the
program moves it to failed folder. Now, I want to add a feature that after
10 minutes that a job is in failed folder, the program will retry to do
the job again by moving the job to the new folder.
Here's my code:
use strict;
use warnings;
package QueueManager;
use AnyEvent;
use AnyEvent::Filesys::Notify;
use Const::Fast;
use DDP;
use File::Basename;
use File::Copy;
use File::Remove qw(remove);
use File::Slurp;
use File::Stat qw(:stat);
use List::Util qw(first);
use List::MoreUtils qw(natatime);
use Moo;
use MooX::Types::MooseLike::Base qw<Str Num InstanceOf ArrayRef HashRef Int>;
use Regexp::Common qw(net);
use v5.10.1;
with 'MooseX::Role::Loggable';
has notifier_interval => (
is => 'ro',
isa => Num,
default => sub {30.0},
);
has failed_interval => (
is => 'ro',
isa => Num,
default => sub{60*10},
);
has number_of_jobs_to_process => (
is => 'ro',
isa => Int,
default => sub{20},
);
has failed_timer => (
is => 'ro',
writer => 'set_failed_timer',
);
has notifier => (
is => 'ro',
isa => InstanceOf['AnyEvent::Filesys::Notify'],
writer => 'set_notifier',
);
has add_output_file => (
is => 'ro',
isa => Str,
default => sub{'.add_route.output'},
);
has del_output_file => (
is => 'ro',
isa => Str,
default => sub{'.del_route.output'},
);
has jobs_folder_path => (
is => 'ro',
isa => Str,
default => sub{'queue_manager/jobs'},
);
has job_folders => (
is => 'ro',
isa => HashRef,
lazy => 1,
builder => '_build_job_folders',
);
has jobs => (
is => 'rw',
isa => ArrayRef,
lazy => 1,
default => sub{ [] },
clearer => '_clear_jobs',
);
has queue => (
is => 'rw',
isa => ArrayRef,
lazy => 1,
default => sub{ [] },
clearer => '_clear_queue',
);
has added_jobs => (
is => 'rw',
isa => ArrayRef[HashRef],
lazy => 1,
default => sub { [] },
clearer => '_clear_added_jobs',
);
has deleted_jobs => (
is => 'rw',
isa => ArrayRef[HashRef],
lazy => 1,
default => sub { [] },
clearer => '_clear_deleted_jobs',
);
has routing_table => (
is => 'rw',
isa => ArrayRef[HashRef],
lazy => 1,
builder => '_build_routing_table',
);
has email_contact => (
is => 'ro',
isa => Str,
default => sub{'some@user.com'},
);
has '+log_to_file' => ( default => sub{1} );
has '+log_path' => ( default => sub{'queue_manager/logs'} );
has '+log_file' => ( default => sub{'queue_manager.log'} );
has '+log_to_stdout' => ( default => sub{1} );
sub _build_job_folders {
my $self = shift;
my $jobs_folder_path = $self->jobs_folder_path;
my %ret_val = (
new => "$jobs_folder_path/new",
progress => "$jobs_folder_path/progress",
failed => "$jobs_folder_path/failed",
);
return \%ret_val;
}
sub _build_routing_table {
my $self = shift;
my @ret_val;
my @routing_table = `ip route show`;
foreach my $line (@routing_table) {
# 1.1.1.1 via 2.2.2.2 dev eth0 proto baba
my ($ip_address, $next_hop) = $line =~ /^($RE{net}{IPv4}) via
($RE{net}{IPv4}) .*proto zebra\s+$/;
if (defined ($ip_address) and defined ($next_hop)) {
push @ret_val, { ip_address => $ip_address, next_hop =>
$next_hop };
}
}
return \@ret_val;
}
sub run {
my $self = shift;
my %job_folders = %{ $self->job_folders };
$self->log("Queue Manager is running...");
$self->set_failed_timer(
AnyEvent->timer(
interval => $self->failed_interval,
cb => sub {
$self->post_process_failed_jobs();
},
)
);
$self->set_notifier(
AnyEvent::Filesys::Notify->new(
dirs => [ $job_folders{'new'} ],
interval => $self->notifier_interval,
cb => sub {
my (@events) = @_;
for my $event (@events) {
if ($event->is_created and basename($event->path) !~
/^\./) {
push @{ $self->jobs }, $event->path;
}
}
my $queue_timer; $queue_timer = AE::timer
$self->notifier_interval, 0, sub {
$self->process_new_jobs();
undef $queue_timer;
};
},
)
);
}
sub process_new_jobs {
my $self = shift;
my $progress_path;
my %job_folders = %{ $self->job_folders };
my @new_jobs = @{ $self->jobs };
foreach my $new_job (@new_jobs) {
my $file_name = basename($new_job);
$progress_path = "$job_folders{'progress'}/$file_name";
move($new_job, $progress_path);
$self->enter_queue($progress_path);
}
$self->_clear_jobs;
$self->start_new_jobs();
}
sub post_process_failed_jobs {
my $self = shift;
my %job_folders = %{ $self->job_folders };
my @failed_files = read_dir($job_folders{'failed'});
if (@failed_files) {
foreach my $failed_file (@failed_files) {
my $file_stat = stat("$job_folders{'failed'}/$failed_file");
my $result = time - $file_stat->mtime;
$self->log("Modified " . int($result/60) . " mins ago");
}
}
}
sub enter_queue {
my $self = shift;
my ($job_to_process) = shift;
my $file_name = basename($job_to_process);
my $args = read_file($job_to_process);
chomp $args;
for ($job_to_process) {
when (/add/) {
my ($ip_address, $next_hop) = split(/ /, $args);
push @{ $self->added_jobs }, {
ip_address => $ip_address,
next_hop => $next_hop,
file_name => $file_name,
};
push @{ $self->queue }, "add:$ip_address:$next_hop";
}
when (/del/) {
my ($ip_address) = $args;
push @{ $self->deleted_jobs }, {
ip_address => $ip_address,
file_name => $file_name,
};
push @{ $self->queue }, "del:$ip_address";
}
}
}
sub start_new_jobs {
my $self = shift;
my $iterator = natatime $self->number_of_jobs_to_process, @{
$self->queue };
while ( my @values = $iterator->() ) {
my $arguments_line = join(' ', @values);
$self->log("Processing: $arguments_line");
}
$self->_clear_queue;
$self->jobs_post_process();
}
sub jobs_post_process {
my $self = shift;
my %job_folders = %{ $self->job_folders };
p $self->added_jobs;
foreach my $added_job ( @{ $self->added_jobs } ) {
my ($ip_address, $next_hop, $file_name) =
($added_job->{'ip_address'},
$added_job->{'next_hop'},
$added_job->{'file_name'});
my $is_in_routing_table =
$self->check_is_in_routing_table($ip_address);
if (not $is_in_routing_table) {
$self->log("FAILED job: $file_name");
move("$job_folders{'progress'}/$file_name",
"$job_folders{'failed'}/$file_name");
$self->send_email($self->add_output_file, $added_job);
}
else {
$self->log("Finished processing job: $file_name");
remove("$job_folders{'progress'}/$file_name");
}
}
$self->_clear_added_jobs;
foreach my $deleted_job ( @{ $self->deleted_jobs } ) {
my ($ip_address, $file_name) =
($deleted_job->{'ip_address'},
$deleted_job->{'file_name'});
my $is_in_routing_table =
$self->check_is_in_routing_table($ip_address);
if ($is_in_routing_table) {
$self->log("FAILED job: $file_name");
move("$job_folders{'progress'}/$file_name",
"$job_folders{'failed'}/$file_name");
$self->send_email($self->del_output_file, $deleted_job);
}
else {
$self->log("Finished processing job: $file_name");
remove("$job_folders{'progress'}/$file_name");
}
}
$self->_clear_deleted_jobs;
}
sub check_is_in_routing_table {
my $self = shift;
my ($ip_address) = shift;
$self->routing_table($self->get_routing_table);
my @addresses = @{ $self->routing_table };
my ($comparable_ip) = $ip_address =~ /($RE{net}{IPv4})\/32$/;
my $ret_val = first { $_->{'ip_address'} eq $comparable_ip } @addresses;
return $ret_val;
}
sub get_routing_table {
my $self = shift;
my @routing_table = `ip route show`;
my @ret_val;
foreach my $line (@routing_table) {
# 1.1.1.1 via 2.2.2.2 dev eth0 proto baba
my ($ip_address, $next_hop) = $line =~ /^($RE{net}{IPv4}) via
($RE{net}{IPv4}) .*proto zebra\s+$/;
if (defined ($ip_address) and defined ($next_hop)) {
push @ret_val, { ip_address => $ip_address, next_hop =>
$next_hop };
}
}
return @ret_val;
}
1;
Now, my problem is that failed_timer runs only once, when the program
starts, and that's it... What have I done wrong?

Is it possible to get the values of the method parameters from the Context() in Play! 2?

Is it possible to get the values of the method parameters from the
Context() in Play! 2?

Using Play!Framework 2.1.3, is there a way to get the value used in the
URL from the matched routes ?
An exemple beeing more precise :
routes :
GET /users/:name/:page controllers.Users.list
and this url :
/users/ben/1
Is it possible, from the Context().current(), to get the value ben and 1
without having to parse the Context().current().path() ?
Thanks for your help :)

No installed components were detected on snaping the app

No installed components were detected on snaping the app

I am getting the error message when I snap windows 8 metro application I
mean moving the application at left side.

Wednesday, 28 August 2013

Monad to catch multiple exceptions (not just fail on single)

Monad to catch multiple exceptions (not just fail on single)

I have a similar question to what is asked here (Multiple or Single Try
Catch), however in my case I need to follow this pattern for functional
(and not performance reasons)
Essentially I am handling parameter errors in Scalatra, and I need an easy
way to catch if any conversions fail without the first failure skipping
the rest of the try calls
In other words, I need something that follows a pattern like this
def checkMultiple(a:Seq[Try]):Either[Map[_,Throwable],Map[_,Success]] = {
???
}
I put in a Sequence of try clauses. Should any of them fail, it will
return back a map of all of the failed try's , not just the first one
(which will have a map of the try that failed, along with its exception),
else it will return a map of all of the try's mapped with their success
values
Does anyone know if there is a monadic pattern that already does this in
essence, or if there is some util library which does this? Else how would
you define the above function?

How do you reference a html tag in php?

How do you reference a html tag in php?

I'm new at html and php. I want to put in a conditional in the below code
and prevent the php post from running if there is no selection of the
"branches" radio buttons. I can't find the syntax to do this correctly.
I'm not sure how to refer to a html tag in a conditional statement. Any
help would be greatly appreciated.
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
alert("Data has been submitted!");
}
</script>
</head>
<body>
<h1>Reference Stats Input</h1>
<form method="post">
<h2>Select Branch</h2>
<label><input type="radio" name="branches" value="AR">AR</label><br>
<label><input type="radio" name="branches" value="BK">BK</label><br>
<label><input type="radio" name="branches" value="BR">BR</label><br>
<label><input type="radio" name="branches" value="EM">EM</label><br>
<label><input type="radio" name="branches" value="MD">MD</label><br>
<label><input type="radio" name="branches" value="PT">PT</label><br>
<label><input type="radio" name="branches" value="UR">UR</label><br>
<label><input type="radio" name="branches" value="WA">WA</label><br>
<br>
<br>
<br>
Type of Reference question:<select name="refquestion" <br><br>
<option value="ADULT">ADULT</option>
<option value="CHILD">CHILD</option>
<option value="JUVENILE">JUVENILE</option>
</select><br><br>
<input name="Submit" type="submit" onclick="myFunction()" value="INPUT">
<?php
if(!empty("branches"){
$con = mysql_connect("localhost","root","dyno!mutt");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("refstats", $con);
$sql="INSERT INTO reftable (branch, statcat)
VALUES
('$_POST[branches]','$_POST[refquestion]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
mysql_close($con)
}
?>
</form>
</body>
</html>

how to POST list of objects in django?

how to POST list of objects in django?

Sorry I'm new to django, I need to transfer a list by POST in django, The
problem is that the list elements need to be complex objects, dictionaries
every list entry should have first name and last name parameters. I only
know how to make list of simple values like this :
<input type="hidden" name="alist" value="1" />
<input type="hidden" name="alist" value="2" />
<input type="hidden" name="alist" value="3" />
and then :
alist = request.POST.getlist('alist')
What is the best practice of doing this? Thanks

What happens if i don't free/delete dynamically allocated arrays?

What happens if i don't free/delete dynamically allocated arrays?

This code is not written bt me! In the class WebServer we overload
+=operator. The class uses dynamically allocated array of objects of type
WebPage(another class, composition) defined as WebPage *wp;
WebServer & operator +=( WebPage webPage ) {
WebPage * tmp = new WebPage [ count + 1];
for (int i = 0; i < count ; i ++)
tmp [i] = wp[i];
tmp [ count ++] = webPage ;
delete [] wp;
wp = tmp;
return * this ;
}
So we create a new array of dynamically allocated WebPages with extra
space for one object, then we assign them the values that wp held, and
then the object that we wanted to add to the array. So if i remove
delete[] wp; the program still works ok. So what happens if i remove that
line of code? And also wp=tmp, what does that mean, is wp only a new name
for that dynamically so it would suit the name in the class, but the
location in memory is still the same? Or?

ModX register -> request new password sends 3 emails

ModX register -> request new password sends 3 emails

Hoi community,
i use a ModX Revolution with the Register Package. All fine so far. Now,
if i request a new password, i get three Emails with different passwords.
i think only one email is enough.
The snippet call looks like this:
[[!ForgotPassword? &resetResourceId=`15` &emailTpl=`lgnForgotPassEmail`
&emailSubject = `password request` &sentTpl = `lgnForgotPassSentTpl` ]]
anyone knows, the package is buggy maybe ?
Has anyone the same problem ? help needed pls.
Thanks.

Tuesday, 27 August 2013

Stmixing string with array variable to assign an id for an element in javascript

Stmixing string with array variable to assign an id for an element in
javascript

I´m trying to mix a string to assign variable(array) I don´t know what´s
wrong I can not get it work.
in php I will send array of id to javascript via json_encode(); I will get
like :arr= 100, 101, 102 etc.
Then in javascript with a conditon like this:
function xx (key, arr)
for (var v in arr){ //LOOP
var k = arr[v];
if (document.getElementById("swas"+k) != key) {
document.getElementById("swas"+k).className =" colorme";
}
}
What have I done wrong ?

Can I have an iOS OpenGL CGI scene with multiple interactive items?

Can I have an iOS OpenGL CGI scene with multiple interactive items?

If I have a 3D scene (say a room) in OpenGL and want to export it for iOS.
Can I have multiple items in the same 'scene' that users can touch.
I know (roughly) how to export to OpenGL ES for iOS, but how do I include
multiple models that users can interact with. E.g. if in a room, users can
look around it and see a cup or plate and pick it up or touch it so text
shows over it. (is it better to learn Unity and use that?)
Is this possible in OpenGL-ES? If so, how? Would it be importing multiple
separate items or them all in one OpenGL export and the iOS system
recognising them for me to add things like text when touched.
I realise this is broad, but what I am really after is a yes or no, to if
this can be done and perhaps an example if anyone knows of one. Thanks.

Android Multi-Select Checkbox Issue [URGENT]

Android Multi-Select Checkbox Issue [URGENT]

I will be honest I am pretty much getting very stressed over this Android
Issue
Please see the code below, I would be very very grateful for someone to
help me...
Basically it works, but does not show the Tick box when the user tabs on
the checkbox.... But when you scroll down and back up to the top on the
scroll the checkbox appears, but does not appear and disappear when user
tries to check it on the first time...
Please someone help!
Many thanks.
.........................................................................................
listener = new OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int position,
long id) {
// TODO Auto-generated method stub
// recent_pos=position;
if(currentdir.equals(root)){
index_back = getListView().getFirstVisiblePosition(); // set
//
last_visited_pos
// in
mStarStates[position] = !mStarStates[position]; // invert
// selection //
list
// view
index_grid = position; // set last_visited_pos in grid view
}
if (searchflag == true && searchlength > 0) {
String filepath = founditems[position];
File file = new File(filepath);
if (file.isDirectory()) {
OnclickOperation(filepath);
}
else {
OnclickOperation(filepath);
}
}
else {
if (multiselectflag) {
multiSelectData.clear();
int last_pos = position;
myGrid.setAdapter(new IconicGrid());
myGrid.setSelection(last_pos);
for (int i = 0; i < multiItems; i++) {
if (mStarStates[i]) {
multiSelectData.add(paths[i]);
} else {
multiSelectData.remove(paths[i]);
}
}
if (mStarStates[position]) {
multiSelectData.add(paths[position]); // add to
// multiselectdata
// if item
// is
// selected
} else if (!mStarStates[position]) {
multiSelectData.remove(paths[position]);
}
// fileInfo.setText(multiSelectData.size() +
// " items selected");
// find this
}
else {
String filepath = paths[position];
OnclickOperation(filepath);
}
}
}
};

jQuery sortable cancel event if not valid

jQuery sortable cancel event if not valid

I have a list which is sortable. Before I start sorting, I want to check
if all the elements of that list are valid. If not, cancel the event and
leave the list intact.
You can find the code here http://jsfiddle.net/DZYW5/4/
When I use this, the event is canceled, but the element is removed.
start: function (event, ui) {
if (!valid()) {
return false;
// it cancel's but the element is removed...
}
}
Maybe I should implement a "beforeStart" event? Suggestions?
Thanks in advanced

How to set a socks proxy server only for one user?

How to set a socks proxy server only for one user?

in Ubuntu 13.04 I tried to insert
export socks_proxy=socks://address:port
into ~/.profile but this is not working.
PS: I need to set it only for a user so not in /etc/enviroment.
Thanks in advance.

How to convert image from XML feed

How to convert image from XML feed

I am using Wordpress with the plugin WP All Import. I am importing 13
feeds, but with one feed I get an error importing the images of items.
This is the feed:
http://xml.ds1.nl/update/?wi=190309&xid=4006&si=5820&type=xml&encoding=ISO-8859-15&general=false&nospecialchars=true
This is an error:
File
http://gstar.cordoba.cdn.lukkien.com/publicpreview?sku=20.0.99124.4378.990&imagetype=front&formatID=productImg&commercial_platform=16005933
is not a valid image and cannot be set as featured one
So the plugin doesn't know how to handle the img url since it doesn't end
with an image extension (.jpg, .png, .gif, etc). All the other feeds have
images with an image extension..
Does anybody know how I could possibly solve this?

Append text to a RichTextBox from another class in VB.NET

Append text to a RichTextBox from another class in VB.NET

I have a form (ClientGUI) that has a RichTextBox. What I want to do is to
append text to this RichTextBox from a Sub located in another class
(MyQuickFixApp). I know that the Sub works, because the debugger go
through, but it doesn't append the text to my RichTextBox.
How do I do that ?
Thanks for you help !



ClientGUI.vb :
Imports QuickFix
Imports QuickFix.Transport
Imports QuickFix.Fields
Public Class ClientGUI
Dim initiator As SocketInitiator
Public Sub ClientGUI_Load(sender As Object, e As EventArgs) Handles
MyBase.Load
Dim filename As String = "Resources/initiator.cfg"
Dim settings As New SessionSettings(filename)
Dim myApp As New MyQuickFixApp()
Dim storeFactory As New FileStoreFactory(settings)
Dim logFactory As New FileLogFactory(settings)
initiator = New SocketInitiator(myApp, storeFactory, settings,
logFactory)
End Sub
Public Sub ConnectToolStripMenuItem_Click(sender As Object, e As
EventArgs) Handles ConnectToolStripMenuItem.Click
ToolStripDropDownButton1.Text = "Establishing connection..."
ToolStripDropDownButton1.Image = My.Resources.Connecting
initiator.Start()
End Sub
Public Sub DisconnectToolStripMenuItem_Click(sender As Object, e As
EventArgs) Handles DisconnectToolStripMenuItem.Click
ToolStripDropDownButton1.Text = "Disconnecting..."
ToolStripDropDownButton1.Image = My.Resources.Disconnecting
initiator.Stop()
End Sub
End Class
MyQuickFixApp.vb :
Imports QuickFix
Imports QuickFix.Transport
Imports QuickFix.Fields
Public Class MyQuickFixApp
Inherits MessageCracker : Implements IApplication
Dim _session As Session = Nothing
Public Sub FromAdmin(message As Message, sessionID As SessionID)
Implements IApplication.FromAdmin
ClientGUI.RichTextBox1.AppendText("")
ClientGUI.RichTextBox1.AppendText("IN (ADMIN): " +
message.ToString())
Try
Crack(message, sessionID)
Catch ex As Exception
ClientGUI.RichTextBox1.AppendText("")
ClientGUI.RichTextBox1.AppendText("==Cracker exception==")
ClientGUI.RichTextBox1.AppendText(ex.ToString())
ClientGUI.RichTextBox1.AppendText(ex.StackTrace)
End Try
End Sub
Public Sub FromApp(message As Message, sessionID As SessionID)
Implements IApplication.FromApp
ClientGUI.RichTextBox1.AppendText("")
ClientGUI.RichTextBox1.AppendText("IN (APP): " + message.ToString())
Try
Crack(message, sessionID)
Catch ex As Exception
ClientGUI.RichTextBox1.AppendText("")
ClientGUI.RichTextBox1.AppendText("==Cracker exception==")
ClientGUI.RichTextBox1.AppendText(ex.ToString())
ClientGUI.RichTextBox1.AppendText(ex.StackTrace)
End Try
End Sub
Public Sub ToApp(message As Message, sessionId As SessionID)
Implements IApplication.ToApp
Try
Dim possDupFlag As Boolean = False
If (message.Header.IsSetField(Tags.PossDupFlag)) Then
possDupFlag =
Converters.BoolConverter.Convert(message.Header.GetField(Tags.PossDupFlag))
End If
If (possDupFlag) Then
Throw New DoNotSend()
End If
Catch ex As FieldNotFoundException
ClientGUI.RichTextBox1.AppendText("OUT (APP): " +
message.ToString())
End Try
End Sub
Public Sub OnCreate(sessionID As SessionID) Implements
IApplication.OnCreate
'_session = Session.LookupSession(sessionID)
ClientGUI.RichTextBox1.AppendText("Session created - " +
sessionID.ToString())
End Sub
Public Sub OnLogon(sessionID As SessionID) Implements
IApplication.OnLogon
ClientGUI.RichTextBox1.AppendText("Logon - " + sessionID.ToString())
ClientGUI.ToolStripDropDownButton1.Text = "Connected"
ClientGUI.ToolStripDropDownButton1.Image = My.Resources.Connected
'MsgBox("onlogon")
End Sub
Public Sub OnLogout(sessionID As SessionID) Implements
IApplication.OnLogout
ClientGUI.RichTextBox1.AppendText("Logout - " + sessionID.ToString())
ClientGUI.ToolStripDropDownButton1.Text = "Disconnected"
ClientGUI.ToolStripDropDownButton1.Image = My.Resources.Disconnected
End Sub
Public Sub ToAdmin(message As Message, sessionID As SessionID)
Implements IApplication.ToAdmin
ClientGUI.RichTextBox1.AppendText("OUT (ADMIN): " +
message.ToString())
End Sub
Public Sub OnMessage(message As FIX42.Heartbeat, sessionID As SessionID)
ClientGUI.RichTextBox1.AppendText("HEARTBEAT")
End Sub
End Class

Monday, 26 August 2013

Creating a CSS-only dropdown menu - one item disappears

Creating a CSS-only dropdown menu - one item disappears

I've created a CSS-only dropdown menu for my menu in Wordpress using a
tutorial on CSSwizardry (don't have enough reputation to post more than 2
links). I've got it working fine on my homepage: http://www.tarawilder.com
(hover over "Portfolio" to see the items "Design" and "Development").
However, when you go into an interior page, only "development" shows up
and not "design". Go here: http://www.tarawilder.com/portfolio/ for an
example.
Why would that be? I want to rip my hair out, I've been trying to figure
this out all night.
Here is the CSS for the menu (which is technically the same on both pages)
#menu1 {
height: 30px;
}
.menu {
position:relative;
z-index:50;
}
.menu li {
position: relative;
}
.menu a {
display:block;
padding:5px;
color:#fff;
text-decoration:none;
}
.menu ul{
background:#fff;
list-style:none;
position:absolute;
left:-9999px;
}
.menu ul li{
padding-top:1px;
float: left;
padding-top: 10px !important;
}
.menu ul a{
white-space:nowrap;
}
.menu li:hover ul{
left:0;
}
.menu li:hover a{
}
.menu li:hover ul a{
text-decoration:none;
}
.menu li:hover ul li a:hover{
}
Thanks in advance!

Delete Sync between searchResultsTableView and mainTableView

Delete Sync between searchResultsTableView and mainTableView

I have a simple question and I am looking for most efficient way to deal
with this.
I have a main table (say mainTableView) and it has search bar controlled
by searchResultsTableView.
My main table has a mutable array say mainItems of say 10 items.
When search is performed, the searchResultsTableView may contain say 3
items in different mutable array say searchedItems
now in that search controller I deleted 2 out of 3 items and I also delete
from searchedItems and searchResultsTableView. These are delete 1 at a
time.
So as I delete from searchedItems I also needs to delete from mainItems to
keep in sync but the index would keep changing for every delete in
mainItems so how do I know the original index to be deleted in mainItems?
Should I look for some dictionary based approach instead of array?

ACE automatic inheritance

ACE automatic inheritance

I want to add an ACE to a registry key but it is not inherited thru
childs. Here is the VBScript code:
Set sdUtil = CreateObject("ADsSecurityUtility")
S = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\XXXX"
Set sd = sdUtil.GetSecurityDescriptor(S, ADS_PATH_REGISTRY,
ADS_SD_FORMAT_IID)
Set oldDacl = sd.DiscretionaryAcl
Set dacl = CreateObject("AccessControlList")
dacl.AclRevision = ADS_REVISION_DS
dacl.AceCount = 0
'remove network service ace if it exists
For Each ace In oldDacl
If UCase(ace.trustee) <> "NT AUTHORITY\NETWORK SERVICE" And
UCase(ace.trustee) <> "S-1-5-20" Then
ace.AceFlags = ace.AceFlags Or OBJECT_INHERIT_ACE Or
CONTAINER_INHERIT_ACE
dacl.AddAce ace
End If
Next
'add the new network service ace
Set ace = CreateObject("AccessControlEntry")
ace.Trustee = "NT AUTHORITY\NETWORK SERVICE"
ace.AccessMask = KEY_ALL_ACCESS
ace.AceFlags = OBJECT_INHERIT_ACE Or CONTAINER_INHERIT_ACE
ace.AceType = ADS_ACETYPE_ACCESS_ALLOWED
dacl.AddAce ace
If (sd.Control And SE_DACL_AUTO_INHERITED) <> 0 Then
sd.Control = sd.Control Or SE_DACL_AUTO_INHERIT_REQ
End If
If (sd.Control And SE_SACL_AUTO_INHERITED) <> 0 Then
sd.Control = sd.Control Or SE_SACL_AUTO_INHERIT_REQ
End If
If (sd.Control And SE_DACL_PROTECTED) <> 0 Then
sd.Control = sd.Control Xor SE_DACL_PROTECTED
End If
ReorderDacl dacl 'This subroutine reorder dacl using w2k rules
sd.DiscretionaryAcl = dacl
ret = sdUtil.SetSecurityDescriptor(S, ADS_PATH_REGISTRY, sd,
ADS_SD_FORMAT_IID)
I also use another routine that scans all children keys and removed all
ACEs except those marked as ADS_ACEFLAG_INHERITED_ACE
After code executes I get that childs of
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\XXXX only inherit SYSTEM,
Administrators, Everyone & Restricted accesses. They are set on the parent
key, but the NETWORK SERVICE access is on
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\XXXX but not propagated to the
childs.

How can I let a user download multiple files when a button is clicked?

How can I let a user download multiple files when a button is clicked?

So I have a httpd server running which has links to a bunch of files. Lets
say the user selects three files from a file list to download and they're
located at:
mysite.com/file1 mysite.com/file2 mysite.com/file3
When they click the download button I want them to download these three
files from the links above.
My download button looks something like:
var downloadButton = new Ext.Button({
text: "Download",
handler: function(){
//download the three files here
}
});

Explorer sort order by date (not by type)

Explorer sort order by date (not by type)

Why Explorer in Windows 7 keeps grouping files by type when I want them by
date?
Each group is sorted by date (modified), but I would like all files sorted
by date (mixed types, like an old'n'good DIR command).

CancellationTokenSource, When to dispose?

CancellationTokenSource, When to dispose?

When am i supposed to Dispose of a CancellationTokenSource? If i for
example make one and put it in Threads everytime i click a button:
private void Button_Click(object sender, EventArgs e)
{
if (clicked == false)
{
clicked = true;
CTSSend = new CancellationTokenSource();
Thread1 = new Thread(() => Method1(CTSSend.Token));
Thread1.Start();
Thread2 = new Thread(() => Method2(CTSSend.Token));
Thread2.Start();
}
else
{
CTSSend.Cancel();
CTSSend.Dispose();
clicked = false;
}
}
Am i supposed to dispose of it like that? Cause if so, it will be a bit
problematic as i need to put it in the Disposer which will dispose when
the application closes, as there isn´t a guarantee that it won´t be
disposed already if i am not carefully waiting for it, and that will cause
an ObjectDisposedException.
I even tried with this to prevent the exception (as i would like to not
use Try Catch, i would like to not even get the error in the first place
in this case).
if (CTSSend != null)
{
CTSSend.Cancel();
CTSSend.Dispose();
}
if (CTSReceive != null)
{
CTSReceive.Cancel();
CTSReceive.Dispose();
}
But well, maybe i should Only dispose of it in the end, and don´t dispose
of it after Cancel everytime? Though i don´t like how that would keep
adding resources to a new object.
How do you people do with these cases?

How to install tcpdump on Cloud Linux

How to install tcpdump on Cloud Linux

I am new on Linux, and I own a server with Cloud Linux installed.
What I like to do is to install the tcpdump but I cannot.
I have try to execute the following command from SSH:
yum install tcpdump
But I am getting the following message:
Loaded plugins: fastestmirror, rhnplugin
Profilename: myserver.host.ext
Not licensed
There was an error communicating with CLN.
CLN support will be disabled.
Error Message:
Service not enabled for system profile: "myserver.host.ext"
Error Class Code: 31
Error Class Info:
This system does not have a valid entitlement for Red Hat Network.
Please visit https://cln.cloudlinux.com/rhn/systems/SystemEntitlements.do
or login at https://cln.cloudlinux.com, and from the "Overview" tab,
select "Subscription Management" to enable RHN service for this system.
Explanation:
Your organization does not have enough Management entitlements to
register this
system to CloudLinux Network. Please notify your organization
administrator of this error.
You should be able to register this system after your organization
frees existing
or purchases additional entitlements. Additional entitlements may be
purchased by your
organization administrator by logging into CloudLinux Network and
visiting
the 'Subscription Management' page in the 'Your RHN' section of RHN.
A common cause of this error code is due to having mistakenly setup an
Activation Key which is set as the universal default. If an
activation key is set
on the account as a universal default, you can disable this key and
retry to avoid
requiring a Management entitlement.
Loading mirror speeds from cached hostfile
cr
| 2.9 kB 00:00
Setting up Install Process
No package tcpdump available.
Error: Nothing to do
So, Is there a way to install tcpdump on cloud linux ? and how ?
Kind regards !

Sunday, 25 August 2013

JQuery Validation Engine with knockout and bootstrap

JQuery Validation Engine with knockout and bootstrap

I am using bootstrap and knockout in my project . Before now i was using
knockout validation , but now i have to use jquery validation engine with
knockout view models and bootstrap html . Suppose this is my html
<fieldset>
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control
placeholder" id="personName" placeholder="Your
name" data-bind="value: name" />
</div>
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control
placeholder" id="personEmail"
placeholder="Your email"
data-original-title="Your activation email
will be sent to this address."
data-bind="value: email, event: { change:
checkDuplicateEmail }" />
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control
placeholder" id="password"
placeholder="Password" data-bind="value:
password" />
</div>
<div class="form-group">
<label for="confirmPassword">Repeat Password</label>
<input type="password" class="form-control
placeholder" id="repeatPassword"
placeholder="Repeat password"
data-bind="value: confirmPassword, event: {
change: matchPassword }" />
</div>
<div class="form-group">
<label for="companyName">Company Name</label>
<input type="text" class="form-control
placeholder" id="companyName"
placeholder="Your company name"
data-bind="value: company" />
</div>
<div class="form-group">
<label for="country">Country</label>
<select class="form-control placeholder"
id="country" data-bind="options:
availableCountries, value: selectedCountry,
optionsCaption: 'Country'">
</select>
</div>
<button id="signupuser" type="button"
data-bind="click: signup" class="btn btn-primary
btn-block">Create Free Account</button>
</fieldset>
now i am confused that how to use Jquery Validation Engine Plugin with my
above code .

Paradoxes without self-reference?

Paradoxes without self-reference?

Most paradoxes involves self-reference, the only exception known to me is
Yablo's paradox, however it is still debated if it is really without
self-reference. So, I was wondering, are there other known paradoxes that
works without self-reference?

Steam exits when opening shutdown or logout dialog

Steam exits when opening shutdown or logout dialog

When I click on the Shut Down... or Log Out... buttons in the system menu
(at the top left of screen), Steam quits regardless of whether I actually
perform the operation (shutdown or logout) or cancel the dialog. Is there
a fix for this?

Saturday, 24 August 2013

Retrieving contents of more than one table in jsp

Retrieving contents of more than one table in jsp

I have two tables in my database named "branch" and "course". I want to
display contents of one column of each table in a select option. I can
retrieve one column successfully but when i try to retrieve data from more
than one table it gives me an Exception which says "result set is closed".
Here's my code:-
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.Connection"%>
<html>
<head>
<title>Type of Test</title>
</head>
<body>
<%
Connection con=null;
Statement s=null;
ResultSet r=null;
ResultSet r1=null;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:online_testing");
s=con.createStatement();
r=s.executeQuery("select * from branch");
r1=s.executeQuery("select * from course");
}
catch(Exception e)
{
response.setContentType("text/html");
out.println(e.toString());
}
%>
<form action="Decidetest" method="post">
<table align="center">
<tr>
<td>Select Branch:-</td>
<td>
<select name="branch">
<%
while(r.next()){
String codeValue = r.getString("code");
%>
<option value="<%=codeValue%>"><%=codeValue%></option>
<%
}
r.close();
%>
</select>
</td>
</tr>
<tr>
<td>Select Course:-</td><td>
<select name="branch">
<%
while(r1.next()){
String courseValue = r1.getString("course");
%>
<option value="<%=courseValue%>"><%=courseValue%></option>
<%
}
r1.close();
s.close();
con.close();
%>
</select>
</td>
</tr>
<tr><td><input type="submit"></td><td><input
type="reset"></td></tr>
</table>
</form>
</div>
</body>
</html>

Error while compling vlc for android ,was it about libtool version?

Error while compling vlc for android ,was it about libtool version?

I have downloaded vlc source code . after running script below
sh compile.sh
I got an error
mkdir -p --
/root/workspace/android/vlc/contrib/arm-linux-androideabi/share/aclocal &&
cd png && autoreconf -fiv
-I/root/workspace/android/vlc/contrib/arm-linux-androideabi/share/aclocal
autoreconf: Entering directory `.'
autoreconf: configure.ac: not using Gettext
autoreconf: running: aclocal -I
/root/workspace/android/vlc/contrib/arm-linux-androideabi/share/aclocal
--force -I scripts
configure.ac:66: error: Libtool version 2.4.2 or higher is required
scripts/libtool.m4:46: LT_PREREQ is expanded from...
configure.ac:66: the top level
autom4te: /usr/bin/m4 failed with exit status: 63
aclocal: /usr/local/bin/autom4te failed with exit status: 63
autoreconf: aclocal failed with exit status: 63
make: *** [.png] Error 63
I thought it was about libtool version ,but the problem remains after i
installed libtool 2.4.2
can somebody kindly tell me what's the problem going on .
Best regards!
Eric Shen

R forecast function not picking up seasonality

R forecast function not picking up seasonality

I am having trouble picking up the seasonality the seems to be implied in
the data. I think (though its just a guess that its using additive and not
multiplicative seasonality). I am using the forecast function and thought
it would automatically pick what I need based on a lecture from Dr.
Hyndman. The following snipet of code plots the chart and I would have
expected the forecast to be higher then it is. Am I missing a model
parameter or something? Any help would be appreciated.
sw<-c(2280, 1754, 1667, 1359, 1285, 1379, 2166, 1053, 1076, 1149, 1277,
1577, 1639, 1719, 1592, 2306, 3075, 2897, 1875, 1966, 2927, 3528, 2948,
2890, 3947, 3913, 3885, 4148, 5293, 5752, 6001, 7719, 5512, 6782, 6320,
6425, 6406, 7237, 8655, 9269, 12447, 13470, 13469, 13949, 17753, 17653,
14531, 14496, 13643, 12652, 12665, 10629, 8962, 8198, 6833, 5027, 4407,
4449, 4399, 5896, 6589, 3786, 4386, 4847, 5597, 5407, 4800, 7803, 9255,
10423, 5523, 8121, 6944, 8434, 9847, 9292, 9794, 10195, 10124, 11310,
12245, 12798, 14611, 15402, 13532, 16154, 15101, 14755, 17139, 16475,
19935, 19980, 25173, 28568, 27839, 28991, 27073, 29615, 25849, 27910,
27067, 21303, 20544, 15188, 13706, 9277, 10815, 7228, 4608, 4409, 9866,
8471, 8223, 6445, 6641, 6833, 11421, 8945, 8127, 10380, 12005, 13272,
9431, 12144, 14934, 14052, 11712, 14888, 15824, 17275, 18067, 19839,
21192, 22763, 22976, 23721, 22681, 20131, 19965, 20539, 19517, 22022,
23076, 30574, 40247, 43111, 39577, 40724, 44982, 44388, 46372, 43153,
36821, 32258, 31256, 27153, 23180, 18252, 16381, 13220, 12500, 10727,
9636, 8892, 8644, 9482, 9170, 10937, 12299, 15781, 11477, 16524, 16752,
18072, 14776, 13388, 18056, 19815, 21263, 22046, 26415, 24247, 25403,
30058, 26331, 32533, 31891, 35973, 27558, 24554, 25692, 25955, 24284,
24930, 28354, 34840, 40055, 42099, 42768, 48279, 50086, 56466, 42244,
51451, 44583, 39091, 33391, 29452, 25533)
swts <- ts(sw, frequency=52, start=c(2006,30))
swfc <- forecast(swts,h=52)
plot(swfc)

How to run example in 'npm phantom'

How to run example in 'npm phantom'

Download and run install.js npm phantom >> PhantomJS is already installed
at /usr/local/bin/phantomjs. Create a file pizza.js with working Phantomjs
example and pizzaTest.js to test it.
var childProcess = require('child_process')
var phantomjs = require('phantomjs')
var binPath = phantomjs.path
var childArgs = [
path.join(__dirname, 'pizza.js'),
]
childProcess.execFile(binPath, childArgs, function(err, stdout, stderr) {
console.log(stdout);
})
an recive an error:
/home/khaljava/coder/phantom/pizzaTest.js:6
path.join(__dirname, 'pizza.js'),
^

.$msg['expire_date_d'].":".$row['expire_date'].

.$msg['expire_date_d'].":".$row['expire_date'].

In PHP webpage. I copy from one page and pase in another this little code
to disply expiry date, it only shows Expire date: but no date.
Can anyone tell me what I do wrong here. This code is working well in the
page I copy from.
".$msg['expire_date_d'].":".$row['expire_date']." </font>
Please help, Thanks a lot,

VS2012 fails to resolve printf,

VS2012 fails to resolve printf,

I've just reinstalled VS2012, when trying to compile a simple "hello
world" it failed to find the most basic functions, I've tried going
through linking options or compiler options for c++ looking for nostd or
some similar option from GCC but failed to do so
can anyone hint me what am I missing ? this is obviously a configuration
problem I can't seem to resolve
1>------ Build started: Project: test, Configuration: Debug Win32 ------
1>Build started 8/24/2013 1:52:58 PM.
1>InitializeBuildStatus:
1> Touching "Debug\test.unsuccessfulbuild".
1>ClCompile:
1> test.cpp
1>LINK : warning LNK4044: unrecognized option '/map(filename)'; ignored
1>test.obj : error LNK2019: unresolved external symbol __imp__printf
referenced in function _main
1>test.obj : error LNK2019: unresolved external symbol __RTC_CheckEsp
referenced in function _main
1>test.obj : error LNK2001: unresolved external symbol __RTC_InitBase
1>test.obj : error LNK2001: unresolved external symbol __RTC_Shutdown
1>LINK : error LNK2001: unresolved external symbol _mainCRTStartup
1>C:\_projects\code\c\test\Debug\test.exe : fatal error LNK1120: 5
unresolved externals
1>
1>Build FAILED.
1>
1>Time Elapsed 00:00:00.47
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

hg: Commit some changes to another branch

hg: Commit some changes to another branch

I was working in branch-a when I found an unrelated bug that should be
fixed in the default branch. So, I'd like commit some of my changes to
default, then merge default into the current branch, and keep working.
As far as I know, Mercurial doesn't allow committing directly into another
branch, so I would have to switch to the default branch first. The problem
is, I can't simply checkout the default branch, because the other changes
would cause conflicts. One workflow I can think of is to shelve, checkout
default, unshelve only the files that relate to the fix, commit, checkout
branch-a, merge default, and finally, unshelve the rest of the files. Is
there an easier way to accomplish this?

Friday, 23 August 2013

taking php and converting it to xml for android app

taking php and converting it to xml for android app

I know this is probably a dumb redundant question. However i found so many
ways to do what i am looking for i just want to know the best way of doing
it.
I am building a simple multiple player game for the android platform. I
have PHP and MYSQL as the server back end. The back end works perfectly.
Now what i need is to send a few simple variables and receive some data.
The app is a basic scorecard. It has the players in the first column
labeled name. The user adds a set of columns with their own custom name
from a script i have made.
I need to send the game id from the server and the row id for the users
name. Also i need to receive the column names the user has chosen, and the
updated score so i can add it to their row/column
//The variable i am using for the the game id is $pw
// Also the variable for the row id is $userid = pid
// and for the column names i am receiving are formatted as follows $loc1
= location A, $loc2 = location B, $loc4 =location C etc.
From the research i have done i need to be using XML with cURL or SOAP.
If you need more information please let me know. The question i am asking
is what would be best to use to get the data from my server to a android
phone and back. Also in the future i plan on making it work with I phone
as well. If you can please provide some helpful links, or code i would
greatly appreciate it. Thanks.

Resize custom textarea not working - jQuery/javascript

Resize custom textarea not working - jQuery/javascript

I am have a button that sets a textarea with a certain width and height.
Those values are changing because I store them in the database.
$("textarea").css({"width":width,"height":height});
The problem is if I do that, the textarea won't be resizable anymore and
it would be always in the same width and height as I set in the jQuery
code.
Is there a fix for this?

How to make PropertyGrid Collection Items semi editable?

How to make PropertyGrid Collection Items semi editable?

I have a class called "BasePath", which contains a drive-, path- and
metaname-property. Furthermore a have created a "BasePathCollection" to
show them in the propertygrid (expandable).
For adding a path you have to click the "three dots button", now you get
another propertygrid where you see all items of the "BasePathCollection"
on the left and the items properties on the right.
First all "BasePath"-properties were [ReadOnly(true)] and I could edit the
path by clicking to another "three dots button". But now I need to make
the the "metaname"-prperty editable and boom, suddenly I can't edit the
path. <-- The "three dots button" not not longer accessible.
What do I need to change for getting the "three dots button" back with the
ability to still edit the "metaname"-property.
Kind Regards
Mario
In a lack of reputation to post images I add a link with a image trying to
demonstrate the problem. Problem images

Solving an equation arising from method of image charges

Solving an equation arising from method of image charges

I'm currently studying electrodynamics where the following equation arose:
$0 = (\frac{q}{\sqrt{R^2 + d^2 - 2Rdcos\theta}} + \frac{q_p}{\sqrt{R^2 +
d_p^2 - 2Rd_p cos\theta}})$
where I need to solve for $q_p$ and $d_p$. The solution given is the
following (factoring out $R^2$ out of the squareroot):
$0 = (\frac{q/R}{\sqrt{1 + (d/R)^2 - 2 (d/R) cos\theta}} +
\frac{q_p/d}{\sqrt{1 + (R/d_p)^2 - 2(R/d_p)cos\theta}}) $ which lets us
read out the solutions: $q/R = - q_p/d_p$ and $d/R = R/d_p$ which can be
easily solved for $d_p$ and $q_p$.
My question is the following: Why can't I solve the equation starting from
the first equation? The first equation is zero if we chose $q_p = -q$ and
$d_p = d$. That solution doesn't make a lot of sense phyisically (it
basically means putting to charges with opposing charges on top of each
other), but why is it wrong mathematically? Or why do I lose solutions
when I do it that way?
I hope someone can help
Cheers

Thursday, 22 August 2013

ipod touch 4th gen doesn't turn on

ipod touch 4th gen doesn't turn on

My ipod touch 4th gen has this CYDIA, I accidentally uninstalled one file
from it. After that, the ipod crashed and never turned on since then.
It turns on (showing apple logo) for 10 seconds, then turns off. After 2
seconds, it turns on again. Whole process repeats. Until battery's
exhausted.
I tried this:
Hold the power button for 2 sec. Without letting go of the power button,
press and hold the home button for 10 sec. Let go of the power button but
not the home button for another 10 sec.
It connects the ipod to itunes, itunes detects the ipod. However, it has
an error message " the ipod software update server could not be
contacted".

Trying to fix double-encoding in htaccess

Trying to fix double-encoding in htaccess

Using .htaccess, is it possible to convert urls to lowercase, but allow
uppercase encoding?
Current file:
RewriteCond %{REQUEST_URI} ^[^A-Z]*[A-Z].* [OR]
RewriteCond %{QUERY_STRING} ^[^A-Z]*[A-Z].*
RewriteRule ^ ${lc:%{REQUEST_URI}}?${lc:%{QUERY_STRING}} [L,NE,R=301]
RewriteRule ^client/(.*) client.php?q=type:$1 [QSA]
Browser: domain.com/client/city?mf[]=liverpool (correct)
Googlebot: domain.com/client/city?mf%5d%5b=liverpool (301, incorrect)
If I remove [NE], the resulting url is double encoded:
Browser: domain.com/client/city?mf%255b%255d=liverpool (200, but incorrect
results)
Googlebot: domain.com/client/city?mf%255b%255d=liverpool (200, but
incorrect results)
Desired output:
Browser: domain.com/client/city?mf[]=liverpool (correct)
Googlebot: domain.com/client/city?mf%5D%5B=liverpool (200, correct)
I'm forcing lowercase using RewriteMap as the previous site was mixed
case, with far too many combinations to manage. Have spent the whole day
reviewing threads, but can't seem to isolate the problem.. or perhaps I'm
looking at this the wrong way.
Thank you.

Django object has no attribute

Django object has no attribute

I have a bulk Update. Each message created I need to call .send(gateway)
This is what I have tried:
objs = [
Message(
recipient_number=e.mobile,
content=content,
sender=e.contact_owner,
billee=user,
sender_name=sender
).send(gateway)
for e in query
]
# Send messages to DB
Message.objects.bulk_create(objs)
I get this error:
Task Request to Process with id 3ab72d3c-5fd8-4b7d-8cc5-e0400455334f
raised exception: 'AttributeError("\'NoneType\' object has no attribute
\'pk\'",)'
why?

Not generating new labels in Winforms

Not generating new labels in Winforms

I've been doing plenty of programming (mainly perl and R) but have
recently gotten into C# for creating some Windows Forms programs.
I have created a program that 1) opens a csv 2)Finds all rows where the
first column value is 0, 3)Outputs another column from those rows to a
message box.
I'm trying to switch this over to instead create a label with the other
column value on the form.
Can I get any help with this?
Below is my code:
string [] readText=File.ReadAllLines(file);
int linenum=0;
foreach (string s in readText)
{
string[] values = s.Split(',');
string analyzed1 = values[0];
//if (analyzed1 is string)
//{
int number = Convert.ToInt32(analyzed1);
//linenum++;
if (number == 0)
{
string sample = values[1];
int y = button1.Bottom + (10 * linenum);
Point mypoint = new Point(100, y);
Label lab = new Label();
lab.Location = mypoint;
lab.Text = sample;
this.Controls.Add(lab);
linenum++;
}
}

Inserting string ›ÄX%ß=dÜgž=ŒT8ï8L]4C®° into sql shows error

Inserting string ›ÄX%ß=dÜgž=ŒT8ï8L]4C®° into sql shows error

here is my code key = KeyGenerator.getInstance(algorithm).generateKey();
byte[] keyBytes = key.getEncoded();
String k=new String(keyBytes);
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
Statement st=con.createStatement();
rs=st.executeQuery("select tid from tid");
while(rs.next())
{
mid=Integer.parseInt(rs.getString(1));
b=Integer.toString(mid);
++mid;
a=Integer.toString(mid);
}
out.println(k);
ps= con.prepareStatement("insert into key values (?,?)");
ps.setString(1,a);
ps.setString(2,k);
ps.executeUpdate();
And the error is javax.servlet.ServletException:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an
error in your SQL syntax; check the manual that corresponds to your MySQL
server version for the right syntax to use near 'key values
('8','›ÄX%ß=dÜgž=ŒT8ï8L]4C®°')' at line 1/p

Javascript to stop working after a certain date

Javascript to stop working after a certain date

I have a JS and I want when the JS expiration date pass, the script to be
disabled.
Without the TOP 3 lines of code the script works properly. I'm not sure
what's wrong with the top 3 lines. Following the entire code:
#include <date.au3>
$ExpirationDate = '9/18/2013'
If _NowDate() = $ExpirationDate Then MsgBox(64, 'Info:', "")
/* TOP 3 lines above - Javascript to stop working after a certain date */
var isloggedin = true;
function bozhoShow() {
jQuery('&quot;div[id^=\&#39;bobito-button-wrapper\&#39;]&quot;').show();
}
function ggtimer() {
if (isloggedin == false) {
disableclicking();
}
jQuery(document).ready(function () {
var testmode = 0;
var dohidex = ' opacity: 0; filter: alpha(opacity = 0); ';
if (testmode == true) {
dohidex = '';
}
jQuery.get('functions.php?type=2', function (data) {
if (data.length > 3) {
//alert(data);
disableclicking();
} else {
//alert(data);
}
});

Wednesday, 21 August 2013

GCC does not allow unused attribute in this position on a function definition

GCC does not allow unused attribute in this position on a function definition

I'm getting that warning from this:
static NSString *NSStringFromRCLAttribute(RCLAttribute attribute)
__attribute__((unused)) {
switch (attribute) {
case RCLAttributeRect: return @"rcl_rect";
case RCLAttributeSize: return @"rcl_size";
case RCLAttributeOrigin: return @"rcl_origin";
}
}
Is this a compiler-specific warning? How is this fixed? Is there an unused
substitute or can unused just be omitted?

Inclusive checkbox list (Automatically checking boxes below selected box)

Inclusive checkbox list (Automatically checking boxes below selected box)

I am making a form where there is a list of permissions available to the
user. Each permission is a checkbox. (Therefore, there is a list of
checkboxes!)
The permissions are inclusive... The top element of the list gives access
to itself as well as the ones below it.
I am trying to model this using the forms UI. I would like the checkboxes
below a checked box to automatically check themselves when a box is
checked above them.

My web driver does not understand xpath

My web driver does not understand xpath

I am working on Selenium . I am new user to selenium implementation . Can
anyone help me out for my following question here : how will webdriver
understand same xpath for different web element in a page?(Lets say
button"A" and "B" has the same Xpath.)

If else insite echo php

If else insite echo php

i want to change this code:
echo"
td class='inhoud_c' width='5%'>".$i."</td>
<td class='inhoud' width='25%'><a
href='profile.php?x=".$naam."'>".$naam."</td>
<td class='inhoud_c' width='50%'>
<table border='0' cellspacing='0' style='margin: 0px;'>
<tr>
<td>
<img src='".$icon."' alt='' border='0'>
</td>
<td>
".$land."
</td>
</tr>
</table>
</td>
<td class='inhoud_c' width='20%'>
".gmdate("H:i:s", $time)."
</td>
</tr> ";
$i++;
To something like this, but i don't know how to do it :(
<td class='inhoud_c' width='20%'>
"if ($tijz >= 0){
gmdate("H:i:s", $tijz);
}
else {
echo "Time's Up!";
}
</td>
So i want a if else statement insite echo, But when i try this the rest of
my code doesn't work,
Can someone help me,
Greetz Kevin

facebook php sdk - Error #200 when trying to use setExtendedAccessToken

facebook php sdk - Error #200 when trying to use setExtendedAccessToken

I have been trying for several days now to successfully post to a client's
Facebook Page wall from their website. I need to be able to do this
without having a user logged in, which I was able to achieve with an
extended access token generated by going to the URL provided in the docs.
What I am trying to do is to fetch an extended token using the PHP SDK as
in this question - Facebook PHP SDK: getting "long-lived" access token now
that "offline_access" is depricated, however I receive the following
error: (#200) The user hasn't authorized the application to perform this
action
The debug of the auth token generated by the Graph API Explorer shows
myself as the User and includes the needed manage_pages and status_update
scopes. However, if I run me/accounts, the perms array does not list these
under the data for the page in question - not sure if this is relevant.
Here is the code that I have attempted to use:
$facebook = new Facebook(array('appId' => 'xxxxxxx', 'secret' => 'xxxxxx'));
$pageID = 'xxxxxxxx';
$facebook->setExtendedAccessToken();
$accessToken = $facebook->getAccessToken();
try {
$page_info = $facebook->api("/$pageID?fields=access_token");
print_r ($page_info);
} catch (FacebookApiException $e) {
echo $e->getMessage();
}
if( !empty($accessToken) ) {
$args = array(
'access_token' => $accessToken,
'message' => "Catch phrase!"
);
$facebook->api("/$pageID/feed","post",$args);
} else {
// Handle error
}

Passing -I to ndk-build

Passing -I to ndk-build

I have some c++ code that fails to compile because it can't find
"cocos2d.h". I figured the cocos2d directory is not in the include path.
Normally adding a directory to your compiler (gcc, msvc, etc.) is done
with -I "directory", but the -I option for ndk-build sets directories
where ndk-build looks for makefiles. How do I do the same with ndk-build?
...
jni/../../foo/bar.h:8:21: fatal error: cocos2d.h: No such file or directory
...

Function return type ambiguity on release and debug versions

Function return type ambiguity on release and debug versions

I have two projects on one solution; say Project1 and Project2. Project1
includes only abstarct classes and their implementations, and it is added
as a referance to Project2. One of the functions, Connect() in Class1 in
Project1 is defined as follows;
public bool Connect() { ...TCP connection code }
On Project2, Connect function of Object1 is called as;
if (carlValentin.Connect() != false) {...}
Visual Studio 2010 is used as IDE. Here comes the oddness. When I choose
Debug as configuration, everything goes fine, compilation is done and
application runs. However, when I swtich the configuration to Release, I
get the following function return type error; Operator != cannot be
applied to the operands of type void and bool. Project1 does not include
any other overloaded methods for Connect function. As mentioned, Project2
is dependent into Project1. I suspect if it is a problem with the changes
I made, since previous definition of Connect had void as return type. But
I'm pretty sure that project build order is configured so that Project1 is
compiled first and then Project2 is built.

Tuesday, 20 August 2013

How to start/open SQL Server Express 2008 in Visual Studio?

How to start/open SQL Server Express 2008 in Visual Studio?

I have Windows 8 and have installed full-pack Microsoft Visual Studio 2010
Ultimate Edition. There was no error while installing Visual Studio 2010
Ultimate Edition.
I exactly don't know which edition and version of SQL Server it installed.
Therefore, please help me to determine, which edition and version of SQL
Server it has installed and also how to start SQL Server Management
Studio.
Regards

The database cannot be opened because it is version 706. This server supports version 655 and earlier. A downgrade path is not supported

The database cannot be opened because it is version 706. This server
supports version 655 and earlier. A downgrade path is not supported

I have database files in my App_Data folder and my web config looks like this
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application,
please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<add name="TicketsConnectionString"
connectionString="Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|Tickets.mdf;Integrated
Security=SSPI;User Instance=True;"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.5"/>
<httpRuntime targetFramework="4.5"/>
</system.web>
</configuration>
I have Default.aspx page
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="LastName" runat="server"></asp:TextBox>
<asp:TextBox ID="FirstName" runat="server"></asp:TextBox>
<asp:TextBox ID="Phone1" runat="server"></asp:TextBox>
<asp:TextBox ID="Phone2" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click"
Text="Button" />
<br />
<br />
<asp:Label ID="DisplayMessage" runat="server" style="color:
#FF0000" Visible="false" />
<br />
<br />
<br />
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:TicketsConnectionString
%>" SelectCommand="SELECT * FROM [Employee]" DeleteCommand="DELETE
FROM [Employee] WHERE [EmpID] = @EmpID" InsertCommand="INSERT INTO
[Employee] ([LastName], [FirstName], [Phone1], [Phone2]) VALUES
(@LastName, @FirstName, @Phone1, @Phone2)" UpdateCommand="UPDATE
[Employee] SET [LastName] = @LastName, [FirstName] = @FirstName,
[Phone1] = @Phone1, [Phone2] = @Phone2 WHERE [EmpID] = @EmpID">
<DeleteParameters>
<asp:Parameter Name="EmpID" Type="Int32" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="LastName" Type="String" />
<asp:Parameter Name="FirstName" Type="String" />
<asp:Parameter Name="Phone1" Type="String" />
<asp:Parameter Name="Phone2" Type="String" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="LastName" Type="String" />
<asp:Parameter Name="FirstName" Type="String" />
<asp:Parameter Name="Phone1" Type="String" />
<asp:Parameter Name="Phone2" Type="String" />
<asp:Parameter Name="EmpID" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False" BackColor="White"
BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px"
CellPadding="3" DataKeyNames="EmpID" DataSourceID="SqlDataSource1"
ForeColor="Black" GridLines="Vertical">
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:CommandField ShowDeleteButton="True"
ShowEditButton="True" />
<asp:BoundField DataField="EmpID" HeaderText="EmpID"
InsertVisible="False" ReadOnly="True"
SortExpression="EmpID" />
<asp:BoundField DataField="LastName" HeaderText="LastName"
SortExpression="LastName" />
<asp:BoundField DataField="FirstName"
HeaderText="FirstName" SortExpression="FirstName" />
<asp:BoundField DataField="Phone1" HeaderText="Phone1"
SortExpression="Phone1" />
<asp:BoundField DataField="Phone2" HeaderText="Phone2"
SortExpression="Phone2" />
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True"
ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black"
HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True"
ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
</asp:GridView>
</div>
</form>
</body>
</html>
and one Default.aspx.cs page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GridView1.DataBind();
}
string connectionString =
ConfigurationManager.ConnectionStrings["TicketsConnectionString"].ConnectionString;
protected void Button1_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("InsertIntoEmployee", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@LastName", SqlDbType.NVarChar).Value =
LastName.Text;
cmd.Parameters.Add("@FirstName", SqlDbType.NVarChar);
cmd.Parameters.Add("@Phone1",
SqlDbType.NVarChar);//SqlDbType.NVarChar allowed to insert Russian
letters
cmd.Parameters.Add("@Phone2", SqlDbType.NVarChar);
cmd.Parameters["@LastName"].Value = LastName.Text;
cmd.Parameters["@FirstName"].Value = FirstName.Text;
cmd.Parameters["@Phone1"].Value = Phone1.Text;
cmd.Parameters["@Phone2"].Value = Phone2.Text;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
DisplayMessage.Text = "Çàïèñü äîáàâëåíà.";
DisplayMessage.Visible = true;
}
}
and it throwing this error
The database 'G:\SITES\WEBSITE6\APP_DATA\TICKETS.MDF' cannot be opened
because it is version 706. This server supports version 655 and earlier. A
downgrade path is not supported.
Could not open new database 'G:\SITES\WEBSITE6\APP_DATA\TICKETS.MDF'.
CREATE DATABASE is aborted.
An attempt to attach an auto-named database for file
G:\sites\WebSite6\App_Data\Tickets.mdf failed. A database with the same
name exists, or specified file cannot be opened, or it is located on UNC
share.
Description: An unhandled exception occurred during the execution of the
current web request. Please review the stack trace for more information
about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: The database
'G:\SITES\WEBSITE6\APP_DATA\TICKETS.MDF' cannot be opened because it is
version 706. This server supports version 655 and earlier. A downgrade
path is not supported.
Could not open new database 'G:\SITES\WEBSITE6\APP_DATA\TICKETS.MDF'.
CREATE DATABASE is aborted.
An attempt to attach an auto-named database for file
G:\sites\WebSite6\App_Data\Tickets.mdf failed. A database with the same
name exists, or specified file cannot be opened, or it is located on UNC
share.
Source Error:
Line 14: protected void Page_Load(object sender, EventArgs e)
Line 15: {
Line 16: GridView1.DataBind();
Line 17: }
Line 18:
I thought there is some problem in connection Strings but for me
everything looks fine, and my question how to fix this problem?

Error trying to execute method after error catch

Error trying to execute method after error catch

I have this jsf code
<h:form>
<h:inputText value="#{agreement.serviceId}"/>
<h:commandButton value="Enter" action="#{agreement.build}" />
<h:form rendered="#{!agreement.valid}">
<h:outputText value="Service id not valid. Please try again"/>
</h:form>
<h:form>
This is the scoped bean's build method.
private String build(){
try{
...//lots of backend logic
valid = true;
return "/agreementDetail.xhtml?faces-redirect=true";
}catch(Exception e){
valid = false;
return null;
}
}
Basically, here's the behavior I need:
The user inputs a serviceId. If this service id is valid, it redirects the
user to the agreementDetail.xhtml page. If false, the user remains in the
main.xhtml page and the "Service id not valid..." message is rendered.
This is what's happening:
If the user inputs a correct service id, everything works fine. If the
user returns to main.xhtml and inputs an incorrect service id, the error
is displayed correctly. But now, if the user inputs a correct service id,
the build() method is not executed. (I've confirmed this with logging).
Basically, once the user inputs a wrong value, the build() method won't be
executed ever again unless the user signs off and signs in again. Clearly,
something's going on when the build() finds an error and catches the
exception.
Any ideas?

How to capture Chef exceptions

How to capture Chef exceptions

I'm working on a Chef recipe right now and I need to update a databag with
some information depending on the result of a code. Basically I need to
update a databag with succeed or failed. The code looks like this:
begin
some code executed
rescue
Update data bag: failed
else
Update data bag: succeed
end
The problem is that even though there is an error like a missing file, the
excecution goes directly to the "else" block and updates the data bag as
"succeed". What I am missing here? Any kind of help with be much
appreciated. Thanks.

how to display an error message over the field in django administration

how to display an error message over the field in django administration

I want to display an error message if the field is blank. At the moment, I
know how to bring ValidationError early in the page, but I need to get the
message right above the blank field. How can this be done?
have not yet been able to find an answer.
class Article(models.Model):
...
title_ru = models.CharField(max_length=255, blank=True)
...
class ArticleAdmin(admin.ModelAdmin):
class form(forms.ModelForm):
class Meta:
model = models.Article
def clean(self):
cleaned_data = super(forms.ModelForm, self).clean()
title_ru = cleaned_data['title_ru']
if not title_ru:
raise forms.ValidationError("Title ru")
return self.cleaned_data
forms.ValidationError("Title ru") displays a message at the top of the
page, but I need this message over the field
how to get the message out over the field Title_ru ?

Same iterator object yields different result in for loop?

Same iterator object yields different result in for loop?

I came across a very strange behaviour in Python. Using a class derived
from UserDict, the iterator a.items() behaves differently in a for loop
than a.data.items(), even though the two are identical:
Python 3.3.1 (default, Apr 17 2013, 22:32:14)
[GCC 4.7.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from datastruct import QueueDict
>>> a=QueueDict(maxsize=1700)
>>> for i in range(1000):
... a[str(i)]=1/(i+1)
...
>>> a.items()
ItemsView(OrderedDict([('991', 0.0010080645161290322), ('992',
0.0010070493454179255), ('993', 0.001006036217303823), ('994',
0.0010050251256281408), ('995', 0.001004016064257028), ('996',
0.0010030090270812437), ('997', 0.001002004008016032), ('998',
0.001001001001001001), ('999', 0.001)]))
>>> a.data.items()
ItemsView(OrderedDict([('991', 0.0010080645161290322), ('992',
0.0010070493454179255), ('993', 0.001006036217303823), ('994',
0.0010050251256281408), ('995', 0.001004016064257028), ('996',
0.0010030090270812437), ('997', 0.001002004008016032), ('998',
0.001001001001001001), ('999', 0.001)]))
>>> a.items()==a.data.items()
True
>>> # nevertheless:
...
>>> for item in a.items(): print(item)
...
('992', 0.0010070493454179255)
>>> for item in a.data.items(): print(item)
...
('993', 0.001006036217303823)
('994', 0.0010050251256281408)
('995', 0.001004016064257028)
('996', 0.0010030090270812437)
('997', 0.001002004008016032)
('998', 0.001001001001001001)
('999', 0.001)
('991', 0.0010080645161290322)
('992', 0.0010070493454179255)
>>>
The class definition is as follows:
import collections, sys
class QueueDict(collections.UserDict):
def __init__(self, maxsize=1*((2**10)**2), *args, **kwargs ):
self._maxsize=maxsize
super().__init__(*args, **kwargs)
self.data=collections.OrderedDict(self.data)
def __getitem__(self, key):
self.data.move_to_end(key)
return super().__getitem__(key)
def __setitem__(self, key, value):
super().__setitem__(key, value)
self._purge()
def _purge(self):
while sys.getsizeof(self.data) > self._maxsize:
self.data.popitem(last=False)
This is quite disturbing. Any ideas how the same object [by "visual"
inspection, and also by (a.items()==a.data.items()) == True] can, and why
it does, behave differently in the for loop?
Thanks for your help and ideas!

Script with sleep() is slowing down server, causing Apache to crash

Script with sleep() is slowing down server, causing Apache to crash

I have a website that has messaging functionality between users. When a
user is logged in, I use jQuery.ajax() to call a PHP script to check for
new messages. To cut down on requests, my PHP script loops a call to the
check_new_messages() function and if there are no new messages, I call
sleep(5) inside the loop, so that it waits 5 seconds and then continues
the loop. I check how long the script has been executing by using
microtime() and if it exceeds 60 seconds, I return 0. The ajax will
receive this value and then call the script again.
function check_message_queue($user) {
$response = 0;
$msgs = 0;
$time_start = microtime(true);
while (!$msgs = check_new_messages($user)) {
sleep(5);
$time_end = microtime(true);
if ($time_end - $time_start >= 60)
return $response;
}
// has new messages
sleep(5);
return $response;
}
My php.ini has max_execution_time set to 120.
At first everything works OK, but when I refresh the page there is about a
10 second delay and sometimes I'll get the PHP error "Max execution time
of 30 seconds has been exceeded" followed by Apache crashing. My PHP
max_execution_time is definitely set to 120 seconds, so I'm not sure
what's going on.
I've never done anything like this before, so hopefully it's just some bad
coding on my part.
Here is my JavaScript:
var request_new_messages = function() {
$.ajax({
url: 'messages/checkqueue',
type: 'post',
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
data: { id: 0 },
complete: function() { request_new_messages(); },
error: function(jqXHR, textStatus, errorThrown) { handle_error(); },
success:
function(data, textStatus, jqXHR) {
if (textStatus == "success") {
if (!isNaN(data)) {
var response = parseInt(data);
if (response > 0)
alert('You have ' + response + ' new messages.');
}
}
}
});
};

Monday, 19 August 2013

Full Page Background Image

Full Page Background Image

I read this article and I understand the issue with printer drivers.
However, I need to use a full page image as a real background so that it
won't print. The full page image is to be used as a guide to complete a
form which will then be printed ONTO the actual form document.
All of the solutions offered in this answer result in "background" images
that print.
Any ideas?

How do i make my twitter bootstrap website work with php?

How do i make my twitter bootstrap website work with php?

i have my new bootstrap website and i dont understand how to let people be
able to register and login because i dont really understand how to connect
php to bootstrap.
If you could send me a link to another website or a video on how to do
this that would also be much appreciated
thanks in advance

.data() binding only first element

.data() binding only first element

I am building an epidemic simulation using D3's force-directed diagram.
When a transmission event occurs, I want to move a circle from the
transmitter to the newly infected individual.
PROBLEM: Only the first element is created and moved according to the
bound data.
First, I gather the coordinates:
xyCoords = getPathogen_xyCoords(newInfections);
Where xyCoords looks like the following:
{receiverX: newInfections[i].x, receiverY: newInfections[i].y,
transmitterX: newInfections[i].infectedBy.x, transmitterY:
newInfections[i].infectedBy.y}
Then I create the circles and bind them to xyCoords:
d3.select(".svg").append("circle")
.attr("class", "pathogen")
d3.selectAll(".pathogen")
.data(xyCoords)
.attr("cx", function(d) { return d.transmitterX})
.attr("cy", function(d) { return d.transmitterY})
.attr("r", 4)
.style("fill", "green")
Finally, the circle is moved with a transition:
d3.selectAll(".pathogen")
.transition()
.duration(500)
.attr("cx", function(d) { return d.receiverX} )
.attr("cy", function(d) { return d.receiverY} );