How to check whether the iterator hit the end without container?
For example, how to implement the following function without any other
information?
bool isEnd(set<int> :: iterator itr);
Saturday, 31 August 2013
Too much function call when painting using Direct2D, not efficient?
Too much function call when painting using Direct2D, not efficient?
The following code is from a example in Microsoft SDK, compared to GDI,
much more extra calls when painting. Because the function may be called
very frequently, it is not efficient, isn't it? And hr =
CreateDeviceResources(hWnd); uses something implicit, I don't think it is
a good design, because it is not clear, I can find the render target here.
BTW, if I want to past some code, do I have to indent every line with
spaces?
LRESULT DemoApp::OnPaint(HWND hWnd)
{
HRESULT hr = S_OK;
PAINTSTRUCT ps;
if (BeginPaint(hWnd, &ps))
{
// Create render target if not yet created
hr = CreateDeviceResources(hWnd);
if (SUCCEEDED(hr) && !(m_pRT->CheckWindowState() &
D2D1_WINDOW_STATE_OCCLUDED))
{
m_pRT->BeginDraw();
m_pRT->SetTransform(D2D1::Matrix3x2F::Identity());
// Clear the background
m_pRT->Clear(D2D1::ColorF(D2D1::ColorF::White));
D2D1_SIZE_F rtSize = m_pRT->GetSize();
// Create a rectangle same size of current window
D2D1_RECT_F rectangle = D2D1::RectF(0.0f, 0.0f, rtSize.width,
rtSize.height);
// D2DBitmap may have been released due to device loss.
// If so, re-create it from the source bitmap
if (m_pConvertedSourceBitmap && !m_pD2DBitmap)
{
m_pRT->CreateBitmapFromWicBitmap(m_pConvertedSourceBitmap,
NULL, &m_pD2DBitmap);
}
// Draws an image and scales it to the current window size
if (m_pD2DBitmap)
{
m_pRT->DrawBitmap(m_pD2DBitmap, rectangle);
}
hr = m_pRT->EndDraw();
// In case of device loss, discard D2D render target and
D2DBitmap
// They will be re-create in the next rendering pass
if (hr == D2DERR_RECREATE_TARGET)
{
SafeRelease(m_pD2DBitmap);
SafeRelease(m_pRT);
// Force a re-render
hr = InvalidateRect(hWnd, NULL, TRUE)? S_OK : E_FAIL;
}
}
EndPaint(hWnd, &ps);
}
return SUCCEEDED(hr) ? 0 : 1;
}
The following code is from a example in Microsoft SDK, compared to GDI,
much more extra calls when painting. Because the function may be called
very frequently, it is not efficient, isn't it? And hr =
CreateDeviceResources(hWnd); uses something implicit, I don't think it is
a good design, because it is not clear, I can find the render target here.
BTW, if I want to past some code, do I have to indent every line with
spaces?
LRESULT DemoApp::OnPaint(HWND hWnd)
{
HRESULT hr = S_OK;
PAINTSTRUCT ps;
if (BeginPaint(hWnd, &ps))
{
// Create render target if not yet created
hr = CreateDeviceResources(hWnd);
if (SUCCEEDED(hr) && !(m_pRT->CheckWindowState() &
D2D1_WINDOW_STATE_OCCLUDED))
{
m_pRT->BeginDraw();
m_pRT->SetTransform(D2D1::Matrix3x2F::Identity());
// Clear the background
m_pRT->Clear(D2D1::ColorF(D2D1::ColorF::White));
D2D1_SIZE_F rtSize = m_pRT->GetSize();
// Create a rectangle same size of current window
D2D1_RECT_F rectangle = D2D1::RectF(0.0f, 0.0f, rtSize.width,
rtSize.height);
// D2DBitmap may have been released due to device loss.
// If so, re-create it from the source bitmap
if (m_pConvertedSourceBitmap && !m_pD2DBitmap)
{
m_pRT->CreateBitmapFromWicBitmap(m_pConvertedSourceBitmap,
NULL, &m_pD2DBitmap);
}
// Draws an image and scales it to the current window size
if (m_pD2DBitmap)
{
m_pRT->DrawBitmap(m_pD2DBitmap, rectangle);
}
hr = m_pRT->EndDraw();
// In case of device loss, discard D2D render target and
D2DBitmap
// They will be re-create in the next rendering pass
if (hr == D2DERR_RECREATE_TARGET)
{
SafeRelease(m_pD2DBitmap);
SafeRelease(m_pRT);
// Force a re-render
hr = InvalidateRect(hWnd, NULL, TRUE)? S_OK : E_FAIL;
}
}
EndPaint(hWnd, &ps);
}
return SUCCEEDED(hr) ? 0 : 1;
}
Open map location from Apple maps in my mapping app
Open map location from Apple maps in my mapping app
I'm developing an iOS mapping app. I would like to open a location from
the built-in maps app into my app. Ideally, my app would show up in the
Maps location sharing sheet along with Mail, Twitter, and Facebook. Is
this possible?
The best I've come up with is configuring my app as a routing app so that
Maps can send a routing request to my app, and using the destination as
the point being shared. There are a few problems with that, though. First,
my app doesn't do routing, so that's misleading to the user. Second, in my
opinion, there are too many steps for the user to get to the routing
options screen. Lastly, Apple might not approve an app that advertises
itself to the system as being a routing provider but doesn't actually do
any routing.
I've searched around quite a bit, but I haven't seen this question asked,
and I haven't found anything in Apple's documentation. Any suggestions?
I'm developing an iOS mapping app. I would like to open a location from
the built-in maps app into my app. Ideally, my app would show up in the
Maps location sharing sheet along with Mail, Twitter, and Facebook. Is
this possible?
The best I've come up with is configuring my app as a routing app so that
Maps can send a routing request to my app, and using the destination as
the point being shared. There are a few problems with that, though. First,
my app doesn't do routing, so that's misleading to the user. Second, in my
opinion, there are too many steps for the user to get to the routing
options screen. Lastly, Apple might not approve an app that advertises
itself to the system as being a routing provider but doesn't actually do
any routing.
I've searched around quite a bit, but I haven't seen this question asked,
and I haven't found anything in Apple's documentation. Any suggestions?
input onfocus not changing div style
input onfocus not changing div style
I have two input forms. I want the second input form to appear when the
user focuses on the first input form. I used a simple javascript "onfocus"
within the input tags. This worked fine when it was changing the style of
another input form. This however left an unwanted gap. I tried making it
so the entire div group appeard onfocus but it had no effect.
I want to make the entire "form-group" div to appear when the user focuses
on the first input form but for some reason, this is not working at all.
HTML
<div class="form-group<?php if(form_error('con_password') != ''){ echo "
has-error"; } ?>">
<div class="col-md-10">
<input type="password" name="con_password" class="form-control
input-lg" placeholder="Password Confirmation"
onfocus="occupation.style.display='block'">
<span class="help-block"><?php echo form_error('con_password');
?></span>
</div>
</div>
<div class="form-group<?php if(form_error('occupation') != ''){ echo "
has-error"; } ?>" id="occupation">
<div class="col-md-10">
<input type="text" name="occupation" class="form-control input-lg"
value="<?php echo set_value('occupation'); ?>"
placeholder="Occupation" onfocus="hearus.style.display='block'">
<span class="help-block"><?php echo form_error('occupation');
?></span>
</div>
</div>
CSS
#occupation{
display: none;
}
I have two input forms. I want the second input form to appear when the
user focuses on the first input form. I used a simple javascript "onfocus"
within the input tags. This worked fine when it was changing the style of
another input form. This however left an unwanted gap. I tried making it
so the entire div group appeard onfocus but it had no effect.
I want to make the entire "form-group" div to appear when the user focuses
on the first input form but for some reason, this is not working at all.
HTML
<div class="form-group<?php if(form_error('con_password') != ''){ echo "
has-error"; } ?>">
<div class="col-md-10">
<input type="password" name="con_password" class="form-control
input-lg" placeholder="Password Confirmation"
onfocus="occupation.style.display='block'">
<span class="help-block"><?php echo form_error('con_password');
?></span>
</div>
</div>
<div class="form-group<?php if(form_error('occupation') != ''){ echo "
has-error"; } ?>" id="occupation">
<div class="col-md-10">
<input type="text" name="occupation" class="form-control input-lg"
value="<?php echo set_value('occupation'); ?>"
placeholder="Occupation" onfocus="hearus.style.display='block'">
<span class="help-block"><?php echo form_error('occupation');
?></span>
</div>
</div>
CSS
#occupation{
display: none;
}
401 - "You are not authorized to view this page error for rdlc files
401 - "You are not authorized to view this page error for rdlc files
I am using .rdlc file in my application to show the reports. When i
deployed my application on staging, the rdlc file rendered without any
issue. But when i deploy the same code on my production server i am
getting 401 - "You are not authorized to view this page" error. Is there
any special previleges required for .rdlc files? My reports are in folder
called 'Reports', which has full privileges for Everyone. Also the
anonymous access is enable for application. Other aspx pages are rendered
and display without any issue.
Thanks in advance. Brijen Patel
I am using .rdlc file in my application to show the reports. When i
deployed my application on staging, the rdlc file rendered without any
issue. But when i deploy the same code on my production server i am
getting 401 - "You are not authorized to view this page" error. Is there
any special previleges required for .rdlc files? My reports are in folder
called 'Reports', which has full privileges for Everyone. Also the
anonymous access is enable for application. Other aspx pages are rendered
and display without any issue.
Thanks in advance. Brijen Patel
How to keep ProgressBar Indeterminate animating
How to keep ProgressBar Indeterminate animating
I've been learning about how this issue is confronted via Threads
(BackgroundWorker and others) and how to keep the UI responsive. I've
managed to do so but then I realized that is not what I want. What I need
actually is just to display an animating ProgressBar while a long
operation is performed. (I don't need/want to update the UI because in
that operation I'm exporting all graphical representation and the plotter
is updated constantly).
I have thought about a Dialog popping-up with the progress bar while the
operation is being performed. The problem is that I get this exception:
The calling thread cannot access this object because a different thread
owns it
There are plenty of questions about this and the answer is to use Dispatcher:
Dispatcher.CurrentDispatcher.Invoke(() => myOperation(),
DispatcherPriority.Normal);
Here is what've done:
I'm using Modern UI, there is a Dialog called ModernDialog, it's just a
fancy dialog:
class DialogProgress
{
public ModernDialog progressDlg = new ModernDialog();
public DialogProgress()
{
ProgressBar bar = new ProgressBar();
bar.IsIndeterminate = true;
bar.Width = 150;
StackPanel content = new StackPanel();
content.Children.Add(bar);
progresoDlg.Content = content ;
//Thread paralel = new Thread(() => myOperation());
//paralel.SetApartmentState(ApartmentState.STA);
//paralel.Start();
Dispatcher.CurrentDispatcher.Invoke(() => myOperation(),
DispatcherPriority.Normal);
}
void myOperation()
{
progresoDlg.ShowDialog();
}
}
I know I'm mixing stuff there, there are Threads and Dispatcher, but I
can't figure out how to use them.
Here is how I call this dialog:
public void MyLongMethod()
{
DialogProgress progress = new DialogProgress();
}
If I use only Dispatcher, the dialog shows up and the bar is being
animated but MyLongMethod is not working (it starts after closing the
dialog).
If I use Threads I get the mentioned exception.
How can I solve this problem?
(P.D. using a dialog Is only a suggestion, I would be happy too if the
progress bar is in the UI and I switch the visibility when the long method
starts/ends)
I've been learning about how this issue is confronted via Threads
(BackgroundWorker and others) and how to keep the UI responsive. I've
managed to do so but then I realized that is not what I want. What I need
actually is just to display an animating ProgressBar while a long
operation is performed. (I don't need/want to update the UI because in
that operation I'm exporting all graphical representation and the plotter
is updated constantly).
I have thought about a Dialog popping-up with the progress bar while the
operation is being performed. The problem is that I get this exception:
The calling thread cannot access this object because a different thread
owns it
There are plenty of questions about this and the answer is to use Dispatcher:
Dispatcher.CurrentDispatcher.Invoke(() => myOperation(),
DispatcherPriority.Normal);
Here is what've done:
I'm using Modern UI, there is a Dialog called ModernDialog, it's just a
fancy dialog:
class DialogProgress
{
public ModernDialog progressDlg = new ModernDialog();
public DialogProgress()
{
ProgressBar bar = new ProgressBar();
bar.IsIndeterminate = true;
bar.Width = 150;
StackPanel content = new StackPanel();
content.Children.Add(bar);
progresoDlg.Content = content ;
//Thread paralel = new Thread(() => myOperation());
//paralel.SetApartmentState(ApartmentState.STA);
//paralel.Start();
Dispatcher.CurrentDispatcher.Invoke(() => myOperation(),
DispatcherPriority.Normal);
}
void myOperation()
{
progresoDlg.ShowDialog();
}
}
I know I'm mixing stuff there, there are Threads and Dispatcher, but I
can't figure out how to use them.
Here is how I call this dialog:
public void MyLongMethod()
{
DialogProgress progress = new DialogProgress();
}
If I use only Dispatcher, the dialog shows up and the bar is being
animated but MyLongMethod is not working (it starts after closing the
dialog).
If I use Threads I get the mentioned exception.
How can I solve this problem?
(P.D. using a dialog Is only a suggestion, I would be happy too if the
progress bar is in the UI and I switch the visibility when the long method
starts/ends)
get variable to jQuery from php
get variable to jQuery from php
this is my variable in setings.php
$error = output_errors($errors);
i want to echo out in my jQuery file 'settings.js'
$('#save_settings').click(function(){
var first_name = $('#first_name').val();
var last_name = $('#last_name').val();
var email = $('#email').val();
$.post('settings.php', { first_name: first_name, last_name: last_name,
email: email});
alert(error);
$('#show').html('settings
saved').fadeIn(500).delay(2000).fadeOut(500);
});
this is my variable in setings.php
$error = output_errors($errors);
i want to echo out in my jQuery file 'settings.js'
$('#save_settings').click(function(){
var first_name = $('#first_name').val();
var last_name = $('#last_name').val();
var email = $('#email').val();
$.post('settings.php', { first_name: first_name, last_name: last_name,
email: email});
alert(error);
$('#show').html('settings
saved').fadeIn(500).delay(2000).fadeOut(500);
});
PHP Download file, limit max speed and calculate downloading speed
PHP Download file, limit max speed and calculate downloading speed
I have written a script that gives you ability to download the file with
my maximum file speed that I allow, however when I allow 'unlimited' speed
like 10000kB/s then the ftell works strange, it behaves like it downloads
with 10000kBps speed, which is not true and I can not make calculations in
database like time remaining, current download speed and so on... So
browser downloads file after some time, but in database it is already like
'downloaded', how could I make some precision calculations even I set the
unlimited speed so user can download a file at the speed of the network
and the database values are also counted by his network speed not by the
ftell()...?
Thanks in advance!
<?php
while(!feof($fopen)) {
//echo fread($fopen, 4096);
$this->get_allowed_speed_limit($download_rate);
//$download_rate = 350;
print fread($fopen, round($download_rate * 1024));
sleep(1); //needed for download speed limit
if(connection_status() != 0 || connection_aborted()) {
$bytes_transferred = ftell($fopen);
if($bytes_transferred < $bytes) {
//CANCELLED
$this->download_unsuccessfull($file_name);
} else {
//CANCELLED (but gets executed only on strange networks like
eduroam in CZE)
$this->download_unsuccessfull($file_name);}
flush();
die;
} else {
$progress = ftell($fopen) / $bytes * 100;
if($progress >= 100) {
//DONE
$this->download_successfull($file_name);
flush();
} else {
//DOWNLOADING
if(ftell($fopen) != 0) {
$bytes_transferred = ftell($fopen);
$time_end = microtime(true);
$time = $time_end - $time_start;
$dl_speed = floor(($bytes_transferred / $time) / 1000);
mysqli_query($con, "UPDATE `download_meter` SET
`current_speed` = '".mysqli_real_escape_string($con,
$bytes_transferred)."'");
$this->update_active_downloads($file_name,
$bytes_transferred, $dl_speed);
}
flush();
}
}
//Activate this for delay download.
//flush();
//sleep(1);
}
?>
I have written a script that gives you ability to download the file with
my maximum file speed that I allow, however when I allow 'unlimited' speed
like 10000kB/s then the ftell works strange, it behaves like it downloads
with 10000kBps speed, which is not true and I can not make calculations in
database like time remaining, current download speed and so on... So
browser downloads file after some time, but in database it is already like
'downloaded', how could I make some precision calculations even I set the
unlimited speed so user can download a file at the speed of the network
and the database values are also counted by his network speed not by the
ftell()...?
Thanks in advance!
<?php
while(!feof($fopen)) {
//echo fread($fopen, 4096);
$this->get_allowed_speed_limit($download_rate);
//$download_rate = 350;
print fread($fopen, round($download_rate * 1024));
sleep(1); //needed for download speed limit
if(connection_status() != 0 || connection_aborted()) {
$bytes_transferred = ftell($fopen);
if($bytes_transferred < $bytes) {
//CANCELLED
$this->download_unsuccessfull($file_name);
} else {
//CANCELLED (but gets executed only on strange networks like
eduroam in CZE)
$this->download_unsuccessfull($file_name);}
flush();
die;
} else {
$progress = ftell($fopen) / $bytes * 100;
if($progress >= 100) {
//DONE
$this->download_successfull($file_name);
flush();
} else {
//DOWNLOADING
if(ftell($fopen) != 0) {
$bytes_transferred = ftell($fopen);
$time_end = microtime(true);
$time = $time_end - $time_start;
$dl_speed = floor(($bytes_transferred / $time) / 1000);
mysqli_query($con, "UPDATE `download_meter` SET
`current_speed` = '".mysqli_real_escape_string($con,
$bytes_transferred)."'");
$this->update_active_downloads($file_name,
$bytes_transferred, $dl_speed);
}
flush();
}
}
//Activate this for delay download.
//flush();
//sleep(1);
}
?>
Friday, 30 August 2013
Add vertical spacing between UITextView and UIButton?
Add vertical spacing between UITextView and UIButton?
I have a view with UITextViewat the top UIButton at the bottom. (I really
wanted a multiline UITextField, but that's not available according to How
to create a multiline UITextfield?).
When the program runs, the UITextView takes the entire view so the
UIButton is not visible.
Hoe does one add a vertical spacer between the UITextView and the
UIButton? The spacers are greyed out in Interface Builder.
I have a view with UITextViewat the top UIButton at the bottom. (I really
wanted a multiline UITextField, but that's not available according to How
to create a multiline UITextfield?).
When the program runs, the UITextView takes the entire view so the
UIButton is not visible.
Hoe does one add a vertical spacer between the UITextView and the
UIButton? The spacers are greyed out in Interface Builder.
Thursday, 29 August 2013
How can I get which 'IF' condition makes loop true with OR & AND?
How can I get which 'IF' condition makes loop true with OR & AND?
assume if i have code like:
if(condition1 || condition2 || condition 3 || condition4)
{
// this inner part will executed if one of the condition true. Now I want
to know by which condition this part is executed.
}
else
{
}
assume if i have code like:
if(condition1 || condition2 || condition 3 || condition4)
{
// this inner part will executed if one of the condition true. Now I want
to know by which condition this part is executed.
}
else
{
}
Wednesday, 28 August 2013
Sanitize cell values with SuperCSV
Sanitize cell values with SuperCSV
What is the best way to sanitize fields from a csv in supercsv? For
example the First_Name column: trim the field, capitalize the first
letter, remove various characters (quotes, commas, asterisks etc). Is it
to write a custom CellProcessor like FmtName()? Maybe another one for
FmtEmail() that lowercases everything, removes certain invalid characters?
What is the best way to sanitize fields from a csv in supercsv? For
example the First_Name column: trim the field, capitalize the first
letter, remove various characters (quotes, commas, asterisks etc). Is it
to write a custom CellProcessor like FmtName()? Maybe another one for
FmtEmail() that lowercases everything, removes certain invalid characters?
How properly set background opacity in one line in style of body?
How properly set background opacity in one line in style of body?
How properly set background opacity with next:
<body style="background-image: url(images/background.jpg);
background-color: white;
background-position: center center; background-size: 100%;
background-repeat: no-repeat">
I try with:
background-opacity: 0.5;
But fail.
It should be something like:
background-image: url(images/background.jpg) opacity: 0.5;
Even,
opacity: .4;
Doesn't affect on image, but affect on the text and whole of body.
Solutions with div doesn't accepted.
My web page: http://shell.bshellz.net/~panzerdivision/
Browsers: firefox & chrome
How properly set background opacity with next:
<body style="background-image: url(images/background.jpg);
background-color: white;
background-position: center center; background-size: 100%;
background-repeat: no-repeat">
I try with:
background-opacity: 0.5;
But fail.
It should be something like:
background-image: url(images/background.jpg) opacity: 0.5;
Even,
opacity: .4;
Doesn't affect on image, but affect on the text and whole of body.
Solutions with div doesn't accepted.
My web page: http://shell.bshellz.net/~panzerdivision/
Browsers: firefox & chrome
Tuesday, 27 August 2013
Capistrano authentication to server fails but ssh for deploy user works
Capistrano authentication to server fails but ssh for deploy user works
I've been working with capistrano for about a year deploying an app and
everything went fine, until a couple of days ago when I got this
** [server_name :: out] fatal: Authentication failed
after typing deploy user's password. Trying to ssh using the same
credentials works perfectly.
Do you have any idea about what could have caused this? I'm using
capistrano (2.15.5) and ruby 1.9.3, and this is my Capfile:
load 'deploy' if respond_to?(:namespace) # cap2 differentiator
# Uncomment if you are using Rails' asset pipeline
# load 'deploy/assets'
Dir['vendor/gems/*/recipes/*.rb','vendor/plugins/*/recipes/*.rb'].each {
|plugin| load(plugin) }
load 'config/deploy' # remove this line to skip loading any of the default
tasks
default_run_options[:pty] = true
Thanks a lot!
I've been working with capistrano for about a year deploying an app and
everything went fine, until a couple of days ago when I got this
** [server_name :: out] fatal: Authentication failed
after typing deploy user's password. Trying to ssh using the same
credentials works perfectly.
Do you have any idea about what could have caused this? I'm using
capistrano (2.15.5) and ruby 1.9.3, and this is my Capfile:
load 'deploy' if respond_to?(:namespace) # cap2 differentiator
# Uncomment if you are using Rails' asset pipeline
# load 'deploy/assets'
Dir['vendor/gems/*/recipes/*.rb','vendor/plugins/*/recipes/*.rb'].each {
|plugin| load(plugin) }
load 'config/deploy' # remove this line to skip loading any of the default
tasks
default_run_options[:pty] = true
Thanks a lot!
Are SSD's really better then hard drives?
Are SSD's really better then hard drives?
I have learned that there is a lot of talk about storage moving to SSDs
instead of hard drives because they are better. It is true that they are
faster and use storage more efficiently but other factors might bring this
down, like strength, and cost. So I want to know it once and for all.
Are SSDs Better than Hard Drives?
I have learned that there is a lot of talk about storage moving to SSDs
instead of hard drives because they are better. It is true that they are
faster and use storage more efficiently but other factors might bring this
down, like strength, and cost. So I want to know it once and for all.
Are SSDs Better than Hard Drives?
display = 'none' does not work in javascript
display = 'none' does not work in javascript
I want to hide divA and show divB. If I click a button I want to hide divB
and show divA. I don't want to use JQuery.
I have troubles hiding divA when the page loads. When I click the button,
the divB is hidden correctly.
I added this in the beginning of the document
<script>
var doNotShow= document.getElementById('divA');
doNotShow.style.display = 'none';
</script>
The thing is, it does not work. The weird thing is that when later, I try
to hide divB via a button click then divB hides as it should. The divA is
after the javascript part in the file.
I want to hide divA and show divB. If I click a button I want to hide divB
and show divA. I don't want to use JQuery.
I have troubles hiding divA when the page loads. When I click the button,
the divB is hidden correctly.
I added this in the beginning of the document
<script>
var doNotShow= document.getElementById('divA');
doNotShow.style.display = 'none';
</script>
The thing is, it does not work. The weird thing is that when later, I try
to hide divB via a button click then divB hides as it should. The divA is
after the javascript part in the file.
Interpolation technique inpainting Opencv
Interpolation technique inpainting Opencv
i'd like to know which interpolation method is used in inpainting function
in OPENCV and how it works.
Thank you very much for every reply.
i'd like to know which interpolation method is used in inpainting function
in OPENCV and how it works.
Thank you very much for every reply.
Problem importing img with xml feed using wpallimport
Problem importing img with xml feed using wpallimport
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?
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?
learning AWS components and tutorials
learning AWS components and tutorials
My questions says it all, Looking forward to learn about AWS components
,creating instances and may be with screenshots of the website to give
more better look,some videos, Any website that could help me? I am a quick
learner but honestly Amazon website is just full of content with nothing
catchy and understandable.
My questions says it all, Looking forward to learn about AWS components
,creating instances and may be with screenshots of the website to give
more better look,some videos, Any website that could help me? I am a quick
learner but honestly Amazon website is just full of content with nothing
catchy and understandable.
Monday, 26 August 2013
Not able to get all the links properly
Not able to get all the links properly
I am new to python, and have little confusion over the code.
In the below code i am trying to get all the links of one table, this is
giving me all the links, the code is this:
>>> import mechanize
>>> from BeautifulSoup import BeautifulSoup
>>> i=0
url = "http://www.miamidade.gov/water/bill_app/bill_expired.asp"
br = mechanize.Browser()
br.open(url)
br.select_form(name="frm")
br["AcctId"] = '8428995632'
br.submit()
for link in br.links(url_regex="ID="):
billurl = "http://www.miamidade.gov/water/bill_app/"+link.url
billdata = br.open(billurl)
html = billdata.read()
soup1 = BeautifulSoup(html)
print link
now when i am adding one more parameter to get print of the same page, i
am not getting all the links which were printed previously and data which
i want to print for all the links page, below is the code, his is the
extra line i have added
print soup1('font')[0].text[11:]
I am new to python, and have little confusion over the code.
In the below code i am trying to get all the links of one table, this is
giving me all the links, the code is this:
>>> import mechanize
>>> from BeautifulSoup import BeautifulSoup
>>> i=0
url = "http://www.miamidade.gov/water/bill_app/bill_expired.asp"
br = mechanize.Browser()
br.open(url)
br.select_form(name="frm")
br["AcctId"] = '8428995632'
br.submit()
for link in br.links(url_regex="ID="):
billurl = "http://www.miamidade.gov/water/bill_app/"+link.url
billdata = br.open(billurl)
html = billdata.read()
soup1 = BeautifulSoup(html)
print link
now when i am adding one more parameter to get print of the same page, i
am not getting all the links which were printed previously and data which
i want to print for all the links page, below is the code, his is the
extra line i have added
print soup1('font')[0].text[11:]
iscsiadm "no portals found"
iscsiadm "no portals found"
I installed a iscsi targets on a Centos6 server and configure one target
that can be found on one client machine (Ubuntu 1304 in network
192.168.95.x). However, when I add one more target and try to connect from
another machine (Centos5 in same subnet) but it show "no portals found".
Below is the printout of the settings:
iscsi target in 192.168.180.88
[root@iscsi01 ~]# tgt-admin --show
Target 1: iqn.2013-08.com.xxx:vm.01<br>
System information:
Driver: iscsi
State: ready
I_T nexus information:
LUN information:
LUN: 0
Type: controller
SCSI ID: IET 00010000
SCSI SN: beaf10
Size: 0 MB, Block size: 1
Online: Yes
Removable media: No
Prevent removal: No
Readonly: No
Backing store type: null
Backing store path: None
Backing store flags:
LUN: 1
Type: disk
SCSI ID: IET 00010001
SCSI SN: beaf11
Size: 1989308 MB, Block size: 512
Online: Yes
Removable media: No
Prevent removal: No
Readonly: No
Backing store type: rdwr
Backing store path: /data/iqn.2013-08.com.xxx.vm.img
Backing store flags:
Account information:
wilson
ACL information:
192.168.180.0/24
192.168.163.0/24
192.168.95.0/24
Target 2: iqn.2013-08.com.xxx:wy
System information:
Driver: iscsi
State: ready
I_T nexus information:
LUN information:
LUN: 0
Type: controller
SCSI ID: IET 00020000
SCSI SN: beaf20
Size: 0 MB, Block size: 1
Online: Yes
Removable media: No
Prevent removal: No
Readonly: No
Backing store type: null
Backing store path: None
Backing store flags:
LUN: 1
Type: disk
SCSI ID: IET 00020001
SCSI SN: beaf21
Size: 107374 MB, Block size: 512
Online: Yes
Removable media: No
Prevent removal: No
Readonly: No
Backing store type: rdwr
Backing store path: /data/iqn.2013-08.com.xxx.wy.img
Backing store flags:
Account information:
wilson
ACL information:
192.168.95.0/24
192.168.180.0/24
iscsi initiator in same subnet (192.168.180.x - Centos5)
[root@syslong ~]# iscsiadm -m discovery -t st -p 192.168.180.88
iscsiadm: No portals found
/etc/iscsi/iscsid.conf
node.startup = automatic
node.leading_login = Yes
node.session.auth.authmethod = CHAP
node.session.auth.username = wilson
node.session.auth.password = xxxx
discovery.sendtargets.auth.authmethod = CHAP
discovery.sendtargets.auth.username = wilson
discovery.sendtargets.auth.password = xxxx
iscsi initiator in different subnet (192.168.95.x - Ubuntu 1304)
wilson@guntank:~$ sudo iscsiadm -m discovery -t st -p 192.168.180.88
[sudo] password for wilson:
192.168.180.88:3260,1 iqn.2013-08.com.xxx:wy
In the ubuntu machine, it only found one of the target in iscsi target
server but in the iscsi target server both target can be shown by using
tgt-admin command. Is there anything I configured incorrect?
Thanks a lot!
Wilson
I installed a iscsi targets on a Centos6 server and configure one target
that can be found on one client machine (Ubuntu 1304 in network
192.168.95.x). However, when I add one more target and try to connect from
another machine (Centos5 in same subnet) but it show "no portals found".
Below is the printout of the settings:
iscsi target in 192.168.180.88
[root@iscsi01 ~]# tgt-admin --show
Target 1: iqn.2013-08.com.xxx:vm.01<br>
System information:
Driver: iscsi
State: ready
I_T nexus information:
LUN information:
LUN: 0
Type: controller
SCSI ID: IET 00010000
SCSI SN: beaf10
Size: 0 MB, Block size: 1
Online: Yes
Removable media: No
Prevent removal: No
Readonly: No
Backing store type: null
Backing store path: None
Backing store flags:
LUN: 1
Type: disk
SCSI ID: IET 00010001
SCSI SN: beaf11
Size: 1989308 MB, Block size: 512
Online: Yes
Removable media: No
Prevent removal: No
Readonly: No
Backing store type: rdwr
Backing store path: /data/iqn.2013-08.com.xxx.vm.img
Backing store flags:
Account information:
wilson
ACL information:
192.168.180.0/24
192.168.163.0/24
192.168.95.0/24
Target 2: iqn.2013-08.com.xxx:wy
System information:
Driver: iscsi
State: ready
I_T nexus information:
LUN information:
LUN: 0
Type: controller
SCSI ID: IET 00020000
SCSI SN: beaf20
Size: 0 MB, Block size: 1
Online: Yes
Removable media: No
Prevent removal: No
Readonly: No
Backing store type: null
Backing store path: None
Backing store flags:
LUN: 1
Type: disk
SCSI ID: IET 00020001
SCSI SN: beaf21
Size: 107374 MB, Block size: 512
Online: Yes
Removable media: No
Prevent removal: No
Readonly: No
Backing store type: rdwr
Backing store path: /data/iqn.2013-08.com.xxx.wy.img
Backing store flags:
Account information:
wilson
ACL information:
192.168.95.0/24
192.168.180.0/24
iscsi initiator in same subnet (192.168.180.x - Centos5)
[root@syslong ~]# iscsiadm -m discovery -t st -p 192.168.180.88
iscsiadm: No portals found
/etc/iscsi/iscsid.conf
node.startup = automatic
node.leading_login = Yes
node.session.auth.authmethod = CHAP
node.session.auth.username = wilson
node.session.auth.password = xxxx
discovery.sendtargets.auth.authmethod = CHAP
discovery.sendtargets.auth.username = wilson
discovery.sendtargets.auth.password = xxxx
iscsi initiator in different subnet (192.168.95.x - Ubuntu 1304)
wilson@guntank:~$ sudo iscsiadm -m discovery -t st -p 192.168.180.88
[sudo] password for wilson:
192.168.180.88:3260,1 iqn.2013-08.com.xxx:wy
In the ubuntu machine, it only found one of the target in iscsi target
server but in the iscsi target server both target can be shown by using
tgt-admin command. Is there anything I configured incorrect?
Thanks a lot!
Wilson
django dajaxice javascript callback with additional parameters
django dajaxice javascript callback with additional parameters
How do I go about adding extra parameters on the call back function?
eg.
function callback(data){
alert(data.message);
}
And you would call it by Dajaxice.examples.args_example(callback,
{'text':$('#text').val()}
what if I want to add an extra parameter in the callback function
function callback(data, flag){
alert(data.message);
if (flag){ /* do something */}
}
How do I initiate the call?
How do I go about adding extra parameters on the call back function?
eg.
function callback(data){
alert(data.message);
}
And you would call it by Dajaxice.examples.args_example(callback,
{'text':$('#text').val()}
what if I want to add an extra parameter in the callback function
function callback(data, flag){
alert(data.message);
if (flag){ /* do something */}
}
How do I initiate the call?
The Fastest OpenSource WebServer? [on hold]
The Fastest OpenSource WebServer? [on hold]
How can I improve performance of these servers?
cherokee-project.com
nginx.org
open.litespeedtech.com
Server Configuration
VirtualBox CentOS 6.4 64bit
Xeon W3540 @3.2Ghz allocated 4 cpu threads
1500MB memory
20GB disk on 1TB Western Digital Black Caviar
PHP info and locations
hxxp header comparisons
curl -I hxxp://FastTest.com/phpinfo.php
Server: nginx centminmod
Date: Sat, 24 Aug 2013 03:33:05 GMT
Content-Type: text/html; charset=utf-8
Connection: keep-alive
Vary: Accept-Encoding
curl -I hxxp://FastTest.com:8088/phpinfo.php
hxxp/1.1 200 OK
Content-type: text/html
Date: Sat, 24 Aug 2013 03:33:05 GMT
Accept-Ranges: bytes
Server: LiteSpeed
curl -I hxxp://FastTest.com:81/phpinfo.php
hxxp/1.1 200 OK
Connection: close
Date: Sat, 24 Aug 2013 03:33:06 GMT
Server: Cherokee
Content-type: text/html
Setup Configuration
Nginx 1.4.2 phpinfo.php (php-fpm 5.4.18 + APC Cache 3.1.13) =
hxxp://FastTest.com/phpinfo.php
OpenLiteSpeed 1.2.4 phpinfo.php (php-fpm 5.4.18 + APC Cache 3.1.13) =
hxxp://FastTest.com:8088/phpinfo.php
Cherokee 1.2.103 phpinfo.php (php-fpm 5.4.18 + APC Cache 3.1.13) =
hxxp://FastTest.com:81/phpinfo.php
Siege benchmark v3.0.2 Results
Run Siege benchmark v3.0.2 with following parameters:
siege -q -b -c25 -r50 hxxp://FastTest.com/phpinfo.php
siege -q -b -c25 -r50 hxxp://FastTest.com:8088/phpinfo.php
siege -q -b -c25 -r50 hxxp://FastTest.com:81/phpinfo.php
Results
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
SIEGE BENCHMARK V3.0.2 | ELAPSED TIME | DATA TRANSFERED |
RESPONSE TIME | TRANSACTION RATE | THROUGHPUT | LONGEST TRANSCATION |
SHORTEST TRANSACTION
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
Nginx 1 worker_process | 2.92 | 14.65 | 0.06
| 428.08 | 5.02 | 0.11 | 0.01
Nginx 4 worker_process | 2.05 | 14.65 | 0.04
| 609.76 | 7.15 | 0.11 | 0.01
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
OpenLiteSpeed with 1 worker | 2.89 | 12.67 | 0.06
| 432.53 | 4.38 | 0.10 | 0.01
OpenLiteSpeed with 1 worker | 1.41 | 12.67 | 0.03
| 886.52 | 8.98 | 0.10 | 0.00
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
Cherokee allow PHP caching | 2.29 | 14.50 | 0.05
| 545.85 | 6.33 | 0.13 | 0.02
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
Cherokee forbid PHP caching | 5.00 | 14.50 | 0.06
| 249.80 | 2.91 | 4.72 | 0.01
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
| | |
| | |
|
Conclusions
Here are my findings:
Nginx also can be configured to cache its PHP requests using
fastcgi_cache. Example setup for Centmin Mod and Wordpress with
fastcgi_cache. So for proper comparison with default Cherokee PHP cache
enabled setup, you would need to compare with Nginx and php-fpm configured
with fastcgi_cache.
Litespeed Enterprise server can do the same via LiteSpeed Cache.
Unfortuantely, OpenLiteSpeed free open source version of LiteSpeed
Enterprise has it's LiteSpeed Cache support removed. But it looks like it
performs fairly well with non-cached PHP requests already from above
benchmarks. You would need Litespeed Enterprise if you want to use
LiteSpeed Cache and cache PHP requests.
Cherokee seems to be default have PHP caching enabled although they do
have a note that mentions it's experimental in nature and to use with
caution. They also mention that by default front line cache doesn't cache
results with cookies. So not sure if phpinfo.php PHP file is the best
choice to benchmark against versus PHP files and PHP apps which utilise
cookies extensively ? No idea why even with PHP cache disabled, that Siege
benchmarks would fluctuate between non-cached and cached like results ? If
any Cherokee users know, please let me know via comments
How can I improve performance of these servers?
cherokee-project.com
nginx.org
open.litespeedtech.com
Server Configuration
VirtualBox CentOS 6.4 64bit
Xeon W3540 @3.2Ghz allocated 4 cpu threads
1500MB memory
20GB disk on 1TB Western Digital Black Caviar
PHP info and locations
hxxp header comparisons
curl -I hxxp://FastTest.com/phpinfo.php
Server: nginx centminmod
Date: Sat, 24 Aug 2013 03:33:05 GMT
Content-Type: text/html; charset=utf-8
Connection: keep-alive
Vary: Accept-Encoding
curl -I hxxp://FastTest.com:8088/phpinfo.php
hxxp/1.1 200 OK
Content-type: text/html
Date: Sat, 24 Aug 2013 03:33:05 GMT
Accept-Ranges: bytes
Server: LiteSpeed
curl -I hxxp://FastTest.com:81/phpinfo.php
hxxp/1.1 200 OK
Connection: close
Date: Sat, 24 Aug 2013 03:33:06 GMT
Server: Cherokee
Content-type: text/html
Setup Configuration
Nginx 1.4.2 phpinfo.php (php-fpm 5.4.18 + APC Cache 3.1.13) =
hxxp://FastTest.com/phpinfo.php
OpenLiteSpeed 1.2.4 phpinfo.php (php-fpm 5.4.18 + APC Cache 3.1.13) =
hxxp://FastTest.com:8088/phpinfo.php
Cherokee 1.2.103 phpinfo.php (php-fpm 5.4.18 + APC Cache 3.1.13) =
hxxp://FastTest.com:81/phpinfo.php
Siege benchmark v3.0.2 Results
Run Siege benchmark v3.0.2 with following parameters:
siege -q -b -c25 -r50 hxxp://FastTest.com/phpinfo.php
siege -q -b -c25 -r50 hxxp://FastTest.com:8088/phpinfo.php
siege -q -b -c25 -r50 hxxp://FastTest.com:81/phpinfo.php
Results
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
SIEGE BENCHMARK V3.0.2 | ELAPSED TIME | DATA TRANSFERED |
RESPONSE TIME | TRANSACTION RATE | THROUGHPUT | LONGEST TRANSCATION |
SHORTEST TRANSACTION
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
Nginx 1 worker_process | 2.92 | 14.65 | 0.06
| 428.08 | 5.02 | 0.11 | 0.01
Nginx 4 worker_process | 2.05 | 14.65 | 0.04
| 609.76 | 7.15 | 0.11 | 0.01
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
OpenLiteSpeed with 1 worker | 2.89 | 12.67 | 0.06
| 432.53 | 4.38 | 0.10 | 0.01
OpenLiteSpeed with 1 worker | 1.41 | 12.67 | 0.03
| 886.52 | 8.98 | 0.10 | 0.00
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
Cherokee allow PHP caching | 2.29 | 14.50 | 0.05
| 545.85 | 6.33 | 0.13 | 0.02
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
Cherokee forbid PHP caching | 5.00 | 14.50 | 0.06
| 249.80 | 2.91 | 4.72 | 0.01
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
| | |
| | |
|
Conclusions
Here are my findings:
Nginx also can be configured to cache its PHP requests using
fastcgi_cache. Example setup for Centmin Mod and Wordpress with
fastcgi_cache. So for proper comparison with default Cherokee PHP cache
enabled setup, you would need to compare with Nginx and php-fpm configured
with fastcgi_cache.
Litespeed Enterprise server can do the same via LiteSpeed Cache.
Unfortuantely, OpenLiteSpeed free open source version of LiteSpeed
Enterprise has it's LiteSpeed Cache support removed. But it looks like it
performs fairly well with non-cached PHP requests already from above
benchmarks. You would need Litespeed Enterprise if you want to use
LiteSpeed Cache and cache PHP requests.
Cherokee seems to be default have PHP caching enabled although they do
have a note that mentions it's experimental in nature and to use with
caution. They also mention that by default front line cache doesn't cache
results with cookies. So not sure if phpinfo.php PHP file is the best
choice to benchmark against versus PHP files and PHP apps which utilise
cookies extensively ? No idea why even with PHP cache disabled, that Siege
benchmarks would fluctuate between non-cached and cached like results ? If
any Cherokee users know, please let me know via comments
Imagick convert SVG to PNG - colors replaced by black and white
Imagick convert SVG to PNG - colors replaced by black and white
I'am trying to convert an SVG Image which is created by the SVGGraph
library ( http://www.goat1000.com/svggraph.php).
The SVG is colored (red, green, yellow, gray, ...) in the browser and
everything is fine. But when I convert it, its just black and white.
With this code I convert it:
//new instance of imagick
$im = new Imagick();
//read the svg file/data (its not saved on the filesystem)
$im->readImageBlob($svgFile);
$im->setImageFormat("png24");
$im->writeImage('cylinder.png');
$im->clear();
$im->destroy();
I've tried it with jpeg and png as output format but the result is the
same, all colors will be replaced with black
does anyone have an idea how to fix that ?
I'am trying to convert an SVG Image which is created by the SVGGraph
library ( http://www.goat1000.com/svggraph.php).
The SVG is colored (red, green, yellow, gray, ...) in the browser and
everything is fine. But when I convert it, its just black and white.
With this code I convert it:
//new instance of imagick
$im = new Imagick();
//read the svg file/data (its not saved on the filesystem)
$im->readImageBlob($svgFile);
$im->setImageFormat("png24");
$im->writeImage('cylinder.png');
$im->clear();
$im->destroy();
I've tried it with jpeg and png as output format but the result is the
same, all colors will be replaced with black
does anyone have an idea how to fix that ?
Windows 8: multiple monitors not found on restart
Windows 8: multiple monitors not found on restart
I have a laptop with Windows 8 and a 22" monitor that I use
simultaneously. If I start up, then connect the monitor via HDMI (using
Intel HD3000 graphics) I can set up an extened desktop no problem. However
when I next turn on the computer, leaving the cable plugged in, my laptop
display stays blank. The Intel control panel and Windows control panel
both agree that it's there, and I can drag windows there, but it stoically
refuses to turn on.
Has anyone else had this, and/or know what to do about it?
Thanks.
I have a laptop with Windows 8 and a 22" monitor that I use
simultaneously. If I start up, then connect the monitor via HDMI (using
Intel HD3000 graphics) I can set up an extened desktop no problem. However
when I next turn on the computer, leaving the cable plugged in, my laptop
display stays blank. The Intel control panel and Windows control panel
both agree that it's there, and I can drag windows there, but it stoically
refuses to turn on.
Has anyone else had this, and/or know what to do about it?
Thanks.
Why is there a need of the 2 following methods in NumberFormat?
Why is there a need of the 2 following methods in NumberFormat?
I see that NumberFormat has two methods very similar:
1)
abstract Number parse(String source, ParsePosition parsePosition)
Returns a Long if possible (e.g., within the range [Long.MIN_VALUE,
Long.MAX_VALUE] and with no decimals), otherwise a Double.
2)
Object parseObject(String source, ParsePosition pos)
Parses text from a string to produce a Number.
In presence of parse(s,ParseIndex) what would be the need of
parseObject(..) which needs to be cast to the desired output? I am aware
that the first method throws ParseException and the latter does not. Just
wondering why the need of these 2 very similar methods. Thanks in advance.
I see that NumberFormat has two methods very similar:
1)
abstract Number parse(String source, ParsePosition parsePosition)
Returns a Long if possible (e.g., within the range [Long.MIN_VALUE,
Long.MAX_VALUE] and with no decimals), otherwise a Double.
2)
Object parseObject(String source, ParsePosition pos)
Parses text from a string to produce a Number.
In presence of parse(s,ParseIndex) what would be the need of
parseObject(..) which needs to be cast to the desired output? I am aware
that the first method throws ParseException and the latter does not. Just
wondering why the need of these 2 very similar methods. Thanks in advance.
receive pending notification in android gcm
receive pending notification in android gcm
Admin side have to enter some text means the message have to receive the
notification on our device when logged in that customer.otherwise its not
receive. its working well.
But here i have facing following problem.
The problem is.,
if my customer is logout long times.that time the admin side gave me more
offers.
the customer have to logged in the app after 2 days means have to receive
that messages now.how can i get the message pending messages ??? please
give me solution ???
Admin side have to enter some text means the message have to receive the
notification on our device when logged in that customer.otherwise its not
receive. its working well.
But here i have facing following problem.
The problem is.,
if my customer is logout long times.that time the admin side gave me more
offers.
the customer have to logged in the app after 2 days means have to receive
that messages now.how can i get the message pending messages ??? please
give me solution ???
Sunday, 25 August 2013
Get last modification date on banch of SVN repos
Get last modification date on banch of SVN repos
I'm hosting svn server for my developers. From server I see all configured
dirs with svn repos. I want to get last modification date on all of
them(obout 30 different projects). I don't want to connect to all of them
make checkout and then with svn command on each check last modification. I
want use only bash to extract that info but have no idea how and even is
it possible in that way.
I'm hosting svn server for my developers. From server I see all configured
dirs with svn repos. I want to get last modification date on all of
them(obout 30 different projects). I don't want to connect to all of them
make checkout and then with svn command on each check last modification. I
want use only bash to extract that info but have no idea how and even is
it possible in that way.
Denying access via .htaccess according to referrer
Denying access via .htaccess according to referrer
I'm trying to block access to my website depending on whether a visitor
had visited the site through another website. The latter has been using up
my traffic by using an iframe to display content through his site, masking
my site's identity.
I have modenvif activated in apache2.
ErrorDocument 403 /error403.html
SetEnv noaccess=0
SetEnvIf Referer "^http://sitetoblock.tk/" noaccess=1
SetEnvIf Referer "^http://www.sitetoblock.tk/" noaccess=1
<FilesMatch "\.(gif|png|jpe?g|php|html)$">
Order Allow,Deny
Deny from env=noaccess
</FilesMatch>
The problem is that this directive is blocking all traffic including
direct visitors to the site. What am I doing wrong?
I'm trying to block access to my website depending on whether a visitor
had visited the site through another website. The latter has been using up
my traffic by using an iframe to display content through his site, masking
my site's identity.
I have modenvif activated in apache2.
ErrorDocument 403 /error403.html
SetEnv noaccess=0
SetEnvIf Referer "^http://sitetoblock.tk/" noaccess=1
SetEnvIf Referer "^http://www.sitetoblock.tk/" noaccess=1
<FilesMatch "\.(gif|png|jpe?g|php|html)$">
Order Allow,Deny
Deny from env=noaccess
</FilesMatch>
The problem is that this directive is blocking all traffic including
direct visitors to the site. What am I doing wrong?
What is the purpose of having 2 endian representations?
What is the purpose of having 2 endian representations?
I was wondering what the purpose of having 2 different endian
representations is. I get the difference between the 2, how to store
values, by why have 2 of them?
I was wondering what the purpose of having 2 different endian
representations is. I get the difference between the 2, how to store
values, by why have 2 of them?
How to drag a drop elements into input fields
How to drag a drop elements into input fields
I'm trying to develop a page that has the following functionality:
Page will have two columns: one being #origin(left column), containing a
lot of rectangles(which represent variables), and the second one will be
#drop(right column),containing inputs where the rectangles can be dropped
on.
In order to get the result I want , I'd thought of using two plugins:
jquery ui draggable and jQuery Tokeninput
The question is , how can I make that once I drop a rectangle( <li> ) into
an input field , it is displayed as a tag. It'd also be OK to use the same
<li> element , so long I can enter more text into the input(to complete a
formula) ,and if later the user changes its mind and decides that the
variable (tag) was not the one he or she wanted, the page should allow
them to delete the tag(by clicking the "X" in the top-right corner or
returning the tag to its original location on the left column)
Has someone done something similar already and can give me some guidance??
Or has someone another idea for this?
Any help is greatly appreciated.
I'm trying to develop a page that has the following functionality:
Page will have two columns: one being #origin(left column), containing a
lot of rectangles(which represent variables), and the second one will be
#drop(right column),containing inputs where the rectangles can be dropped
on.
In order to get the result I want , I'd thought of using two plugins:
jquery ui draggable and jQuery Tokeninput
The question is , how can I make that once I drop a rectangle( <li> ) into
an input field , it is displayed as a tag. It'd also be OK to use the same
<li> element , so long I can enter more text into the input(to complete a
formula) ,and if later the user changes its mind and decides that the
variable (tag) was not the one he or she wanted, the page should allow
them to delete the tag(by clicking the "X" in the top-right corner or
returning the tag to its original location on the left column)
Has someone done something similar already and can give me some guidance??
Or has someone another idea for this?
Any help is greatly appreciated.
HTML5 Audio element
HTML5 Audio element
I want to play from dynamic link for MP3
I am using this code to send mp3 instead of direct link :
PHP Side :
$filename = "jadi.mp3";
$mime_type = "audio/mpeg, audio/x-mpeg, audio/x-mpeg-3, audio/mpeg3";
if (is_file($filename)) {
header("Content-Type: {$mime_type}");
header('Content-length: ' . filesize($filename));
header("Content-Disposition: attachment;filename = jadi.mp3");
header('X-Pad: avoid browser bug');
header('Cache-Control: no-cache');
header("Content-Transfer-Encoding: binary");
$fd = fopen($filename, "r");
while (!feof($fd)) {
echo fread($fd, 1024 * 200);
}
fclose($fd);
exit();
}
HMLL side :
<audio controls>
<source src="http://localhost/music.php" type="audio/mpeg"
preload="auto">
Your browser does not support the audio element.
</audio>
But the Browser can not play that , I have no problem with WAV file , but
for mp3 , it does not work
there is no problem if I use direct link instead of php script , so my
browser can support MP3
thanks
I want to play from dynamic link for MP3
I am using this code to send mp3 instead of direct link :
PHP Side :
$filename = "jadi.mp3";
$mime_type = "audio/mpeg, audio/x-mpeg, audio/x-mpeg-3, audio/mpeg3";
if (is_file($filename)) {
header("Content-Type: {$mime_type}");
header('Content-length: ' . filesize($filename));
header("Content-Disposition: attachment;filename = jadi.mp3");
header('X-Pad: avoid browser bug');
header('Cache-Control: no-cache');
header("Content-Transfer-Encoding: binary");
$fd = fopen($filename, "r");
while (!feof($fd)) {
echo fread($fd, 1024 * 200);
}
fclose($fd);
exit();
}
HMLL side :
<audio controls>
<source src="http://localhost/music.php" type="audio/mpeg"
preload="auto">
Your browser does not support the audio element.
</audio>
But the Browser can not play that , I have no problem with WAV file , but
for mp3 , it does not work
there is no problem if I use direct link instead of php script , so my
browser can support MP3
thanks
Saturday, 24 August 2013
Addition inequalities with lim sup and lim inf
Addition inequalities with lim sup and lim inf
$\lim\inf a_n+\lim\sup b_n\le\lim\sup(a_n+b_n)\le\lim\sup a_n+\lim\sup b_n$
For the right inequality, I assume $A=\lim\sup a_n, B = \lim\sup B_n$.
Hence for any $\varepsilon$, there exists $n_0$ such that
$a_{n}<A+\varepsilon$ for all $n\ge n_0$. Similarly for $b_n$. Hence for
any $\varepsilon$, there exists $n_0$ such that $a_n+b_n<A+B+\varepsilon$
for all $n\ge n_0$. Therefore $\lim\sup(a_n+b_n)\leq A+B$.
Now for the left inequality, assume $A=\lim\inf a_n, B = \lim\sup B_n$.
How can this be compared to $\lim\sup(a_n+b_n)$?
$\lim\inf a_n+\lim\sup b_n\le\lim\sup(a_n+b_n)\le\lim\sup a_n+\lim\sup b_n$
For the right inequality, I assume $A=\lim\sup a_n, B = \lim\sup B_n$.
Hence for any $\varepsilon$, there exists $n_0$ such that
$a_{n}<A+\varepsilon$ for all $n\ge n_0$. Similarly for $b_n$. Hence for
any $\varepsilon$, there exists $n_0$ such that $a_n+b_n<A+B+\varepsilon$
for all $n\ge n_0$. Therefore $\lim\sup(a_n+b_n)\leq A+B$.
Now for the left inequality, assume $A=\lim\inf a_n, B = \lim\sup B_n$.
How can this be compared to $\lim\sup(a_n+b_n)$?
Internationalization support for command descriptions?
Internationalization support for command descriptions?
I'm introducing internationalization to my extension. I just tried the
following:
"commands": {
"nextVideo": {
"suggested_key": { "default": "Ctrl+Shift+Right" },
"description": "__MSG_nextVideoCommandDescription__"
},
"previousVideo": {
"suggested_key": { "default": "Ctrl+Shift+Left" },
"description": "__MSG_previousVideoCommandDescription__"
},
"toggleVideo": {
"suggested_key": { "default": "Ctrl+Shift+Up" },
"description": "__MSG_toggleVideoCommandDescription__"
},
"_execute_browser_action": {
"suggested_key": { "default": "Ctrl+Shift+Down" }
}
}
but the description values are interpreted literally. All other instances
of referencing messages.json in _locales work as expected.
Is this a bug?
I'm introducing internationalization to my extension. I just tried the
following:
"commands": {
"nextVideo": {
"suggested_key": { "default": "Ctrl+Shift+Right" },
"description": "__MSG_nextVideoCommandDescription__"
},
"previousVideo": {
"suggested_key": { "default": "Ctrl+Shift+Left" },
"description": "__MSG_previousVideoCommandDescription__"
},
"toggleVideo": {
"suggested_key": { "default": "Ctrl+Shift+Up" },
"description": "__MSG_toggleVideoCommandDescription__"
},
"_execute_browser_action": {
"suggested_key": { "default": "Ctrl+Shift+Down" }
}
}
but the description values are interpreted literally. All other instances
of referencing messages.json in _locales work as expected.
Is this a bug?
Add the whole user object to session on login in geddy app
Add the whole user object to session on login in geddy app
I have a geddy app set up with auth support. Currently, it only adds the
userId to the session on login. This is a problem because I want to
display usernames on the website and querying the mongo database every
time wouldn't be too good for performance.
Is there a way for me to add the whole user object to the session on
login. If that's too much, at least the userId and the username. I'm not
sure where the best place to put that code would be.
I have a geddy app set up with auth support. Currently, it only adds the
userId to the session on login. This is a problem because I want to
display usernames on the website and querying the mongo database every
time wouldn't be too good for performance.
Is there a way for me to add the whole user object to the session on
login. If that's too much, at least the userId and the username. I'm not
sure where the best place to put that code would be.
Computer connects to the wrong router
Computer connects to the wrong router
I have 2 routers connected together and multiple computers connected to
each router. (see image)
The problem is that when I connect a computer to Router 1 and let it get
the IP automatically, it connects to the Router 2 (default gateway, DHCP
and DNS are set to 192.168.1.117).
So for every computer that uses my network I need to set IP, default
gateway and DNS server addresses manually. I would like to get IPs and all
setting set automatically. If I disconnect Router 2 everything works ok.
Router 1 is Linksys WRT54G and Router 2 is TP-LINK TL-WR741N.
I have 2 routers connected together and multiple computers connected to
each router. (see image)
The problem is that when I connect a computer to Router 1 and let it get
the IP automatically, it connects to the Router 2 (default gateway, DHCP
and DNS are set to 192.168.1.117).
So for every computer that uses my network I need to set IP, default
gateway and DNS server addresses manually. I would like to get IPs and all
setting set automatically. If I disconnect Router 2 everything works ok.
Router 1 is Linksys WRT54G and Router 2 is TP-LINK TL-WR741N.
Google Map not displayed in Ajax process
Google Map not displayed in Ajax process
With this code Im displaying google map in my index.php page:
<!--[if IE]>
<script
src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Include Google Maps JS -->
<script
src="http://maps.googleapis.com/maps/api/js?v=3&libraries=geometry&sensor=true"
type="text/javascript"></script>
$indirizzo = "corso Buones Aires";
$comune = "Milano";
$map = new simpleGMapAPI();
$geo = new simpleGMapGeocoder();
$map->setWidth(332);
$map->setHeight(250);
$map->setBackgroundColor('#d0d0d0');
$map->setMapDraggable(true);
$map->setDoubleclickZoom(true);
$map->setScrollwheelZoom(true);
$map->showDefaultUI(true);
$map->showMapTypeControl(true, 'DEFAULT');
$map->showNavigationControl(true, 'DEFAULT');
$map->showScaleControl(true);
$map->showStreetViewControl(false);
$map->setZoomLevel(9);
$map->setInfoWindowBehaviour('SINGLE_CLOSE_ON_MAPCLICK');
$map->setInfoWindowTrigger('CLICK');
$map->addMarkerByAddress($indirizzo . " " . $comune, $indirizzo,
$indirizzo, "http://google-maps-icons.googlecode.com/files/villa.png");
echo $map->showMap(false);
this code works great, but if I try to get google map in ajax process, I
cant displayed it.
In others words, if I place above code in map.php page
<?php
require("../inc/config.php");
echo " <!--[if IE]>\n";
echo " <script
src=\"http://html5shim.googlecode.com/svn/trunk/html5.js\"></script>\n";
echo " <![endif]-->\n";
echo " <!-- Include Google Maps JS -->\n";
echo " <script
src=\"http://maps.googleapis.com/maps/api/js?v=3&libraries=geometry&sensor=true\"
type=\"text/javascript\"></script>";
if($_POST["comune"])
{
$indirizzo = "corso Buones Aires";
$comune = $_POST["comune"];
$map = new simpleGMapAPI();
$geo = new simpleGMapGeocoder();
$map->setWidth(332);
$map->setHeight(250);
$map->setBackgroundColor('#d0d0d0');
$map->setMapDraggable(true);
$map->setDoubleclickZoom(true);
$map->setScrollwheelZoom(true);
$map->showDefaultUI(true);
$map->showMapTypeControl(true, 'DEFAULT');
$map->showNavigationControl(true, 'DEFAULT');
$map->showScaleControl(true);
$map->showStreetViewControl(false);
$map->setZoomLevel(9);
$map->setInfoWindowBehaviour('SINGLE_CLOSE_ON_MAPCLICK');
$map->setInfoWindowTrigger('CLICK');
$map->addMarkerByAddress($indirizzo . " " . $comune, $indirizzo,
$indirizzo,
"http://google-maps-icons.googlecode.com/files/villa.png");
echo $map->showMap(false);
}
?>
and call this page using jquery:
$(document).ready(function(){
$("#spanComune").change(function(){
var $body = $("body"),
comune=$("#spanComune option:selected").text();
$body.addClass("loading");
$.ajax({
type:"POST",
url:"ajax/map.php",
data: "comune="+comune,
success:function(data){
$("#spanMappa").empty().html(data);
$body.removeClass("loading");
}
});
});
});
In index.php:
<div id="spanMappa"></div>
Google Map is not displayed. Very strange issue! How Can I solve this?
With this code Im displaying google map in my index.php page:
<!--[if IE]>
<script
src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Include Google Maps JS -->
<script
src="http://maps.googleapis.com/maps/api/js?v=3&libraries=geometry&sensor=true"
type="text/javascript"></script>
$indirizzo = "corso Buones Aires";
$comune = "Milano";
$map = new simpleGMapAPI();
$geo = new simpleGMapGeocoder();
$map->setWidth(332);
$map->setHeight(250);
$map->setBackgroundColor('#d0d0d0');
$map->setMapDraggable(true);
$map->setDoubleclickZoom(true);
$map->setScrollwheelZoom(true);
$map->showDefaultUI(true);
$map->showMapTypeControl(true, 'DEFAULT');
$map->showNavigationControl(true, 'DEFAULT');
$map->showScaleControl(true);
$map->showStreetViewControl(false);
$map->setZoomLevel(9);
$map->setInfoWindowBehaviour('SINGLE_CLOSE_ON_MAPCLICK');
$map->setInfoWindowTrigger('CLICK');
$map->addMarkerByAddress($indirizzo . " " . $comune, $indirizzo,
$indirizzo, "http://google-maps-icons.googlecode.com/files/villa.png");
echo $map->showMap(false);
this code works great, but if I try to get google map in ajax process, I
cant displayed it.
In others words, if I place above code in map.php page
<?php
require("../inc/config.php");
echo " <!--[if IE]>\n";
echo " <script
src=\"http://html5shim.googlecode.com/svn/trunk/html5.js\"></script>\n";
echo " <![endif]-->\n";
echo " <!-- Include Google Maps JS -->\n";
echo " <script
src=\"http://maps.googleapis.com/maps/api/js?v=3&libraries=geometry&sensor=true\"
type=\"text/javascript\"></script>";
if($_POST["comune"])
{
$indirizzo = "corso Buones Aires";
$comune = $_POST["comune"];
$map = new simpleGMapAPI();
$geo = new simpleGMapGeocoder();
$map->setWidth(332);
$map->setHeight(250);
$map->setBackgroundColor('#d0d0d0');
$map->setMapDraggable(true);
$map->setDoubleclickZoom(true);
$map->setScrollwheelZoom(true);
$map->showDefaultUI(true);
$map->showMapTypeControl(true, 'DEFAULT');
$map->showNavigationControl(true, 'DEFAULT');
$map->showScaleControl(true);
$map->showStreetViewControl(false);
$map->setZoomLevel(9);
$map->setInfoWindowBehaviour('SINGLE_CLOSE_ON_MAPCLICK');
$map->setInfoWindowTrigger('CLICK');
$map->addMarkerByAddress($indirizzo . " " . $comune, $indirizzo,
$indirizzo,
"http://google-maps-icons.googlecode.com/files/villa.png");
echo $map->showMap(false);
}
?>
and call this page using jquery:
$(document).ready(function(){
$("#spanComune").change(function(){
var $body = $("body"),
comune=$("#spanComune option:selected").text();
$body.addClass("loading");
$.ajax({
type:"POST",
url:"ajax/map.php",
data: "comune="+comune,
success:function(data){
$("#spanMappa").empty().html(data);
$body.removeClass("loading");
}
});
});
});
In index.php:
<div id="spanMappa"></div>
Google Map is not displayed. Very strange issue! How Can I solve this?
Getting NullPointerException when running simple JMS
Getting NullPointerException when running simple JMS
Am trying to run a simple JMS app, sadly got NullPointException .
following are the links to the files of the app :
1. Producer.java
2. SynchConsumer.java
following is the exception
Exception in thread "main" java.lang.NullPointerException
at coreservlets.Producer.main(Producer.java:96)
Any flash put into this shall be appreciated .
Am trying to run a simple JMS app, sadly got NullPointException .
following are the links to the files of the app :
1. Producer.java
2. SynchConsumer.java
following is the exception
Exception in thread "main" java.lang.NullPointerException
at coreservlets.Producer.main(Producer.java:96)
Any flash put into this shall be appreciated .
Friday, 23 August 2013
iis error when removing server header
iis error when removing server header
I have written these lines to remove server headers in Global.asax:
protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
{
var app = sender as HttpApplication;
if (app == null || !app.Request.IsLocal || app.Context == null)
return;
var headers = app.Context.Response.Headers;
headers.Remove("Server");
}
But when I set a break point there I see this error:
This operation requires IIS integrated pipeline mode.
I am using asp.net mvc 4 and my iis version is 7.5
By the way I have set both Classic.Net AppPool and Default AppPool
pipeline modes to Integrated but the error exist yet.
What should I try?
Thanks.
I have written these lines to remove server headers in Global.asax:
protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
{
var app = sender as HttpApplication;
if (app == null || !app.Request.IsLocal || app.Context == null)
return;
var headers = app.Context.Response.Headers;
headers.Remove("Server");
}
But when I set a break point there I see this error:
This operation requires IIS integrated pipeline mode.
I am using asp.net mvc 4 and my iis version is 7.5
By the way I have set both Classic.Net AppPool and Default AppPool
pipeline modes to Integrated but the error exist yet.
What should I try?
Thanks.
Allow scrolling and clicking to go through an overlapping Div
Allow scrolling and clicking to go through an overlapping Div
A client's website design is dark teal and he didn't like the scroll bar
since it ruins the rest of the style. He also wishes I do it without third
party libraries and a way he can hopefully understand. So the only way I
can think of doing that was creating a div, setting it to position:
absolute;, same background-color as the rest of the theme and then setting
opacity: 0.8; so that it looks 'blended' in better.
He is happy with the result, since it works for all browsers, he thought I
even created my own scroll-bar when he first saw it. The problem however
is, if a person would like to actually click on the scroll bar, they can't
because there's a div above it. Is there any way I can allow a div to be
visible, but all the clicks and hovers and everything go through it to the
next div? Scrolling also does not work when above the scroll bar because
i'm in the div that's overlapping the real div that actually has the
scroll bar.
Any help is greatly appreciated.
A client's website design is dark teal and he didn't like the scroll bar
since it ruins the rest of the style. He also wishes I do it without third
party libraries and a way he can hopefully understand. So the only way I
can think of doing that was creating a div, setting it to position:
absolute;, same background-color as the rest of the theme and then setting
opacity: 0.8; so that it looks 'blended' in better.
He is happy with the result, since it works for all browsers, he thought I
even created my own scroll-bar when he first saw it. The problem however
is, if a person would like to actually click on the scroll bar, they can't
because there's a div above it. Is there any way I can allow a div to be
visible, but all the clicks and hovers and everything go through it to the
next div? Scrolling also does not work when above the scroll bar because
i'm in the div that's overlapping the real div that actually has the
scroll bar.
Any help is greatly appreciated.
Does iTunes in the Cloud apply to Movie Rentals?
Does iTunes in the Cloud apply to Movie Rentals?
I rented a movie from iTunes on my Mac running OS X 10.8. I was under the
assumption that it would be available on my iPhone (iOS 6) and iPad (iOS
6) to stream or download but it isn't. It doesn't appear in the Videos app
and I can't find it under Purchased in the iTunes Store on my devices. All
of my devices are logged in under the same account.
Are iTunes movie rentals not available in the cloud? I know movie
purchases are.
Every support document I found on Apple's website didn't mention rentals,
only purchases.
I rented a movie from iTunes on my Mac running OS X 10.8. I was under the
assumption that it would be available on my iPhone (iOS 6) and iPad (iOS
6) to stream or download but it isn't. It doesn't appear in the Videos app
and I can't find it under Purchased in the iTunes Store on my devices. All
of my devices are logged in under the same account.
Are iTunes movie rentals not available in the cloud? I know movie
purchases are.
Every support document I found on Apple's website didn't mention rentals,
only purchases.
PL/SQL Error With Nested IF statements
PL/SQL Error With Nested IF statements
Apex 4.2
I have the following pl/sql code block below but whenever I run it in
APex, I keep getting the error:
ORA-06550: line 35, column 4: PLS-00103: Encountered the symbol ";" when
expecting one of the following: if
DECLARE
show_changes BOOLEAN;
l_exists INTEGER;
BEGIN
Select count(*) into l_exists
From dba_role_privs
where grantee = upper(:APP_USER) and
(granted_role = 'SURVEY_JOB_SUID' or granted_role = 'SURVEY_SUID');
IF l_exists = 0 THEN /* unauthorized */
IF :P32_SURVEY_JOB_REQUEST_ID IS NOT NULL AND (:P32_SUBMISSION_DATE IS
NULL AND :P32_LOCK_DATE IS NULL) THEN
show_changes := TRUE;
IF :P32_SURVEY_JOB_REQUEST_ID IS NOT NULL AND (:P32_SUBMISSION_DATE IS
NOT NULL AND :P32_LOCK_DATE IS NULL) THEN
show_changes := TRUE;
IF :P32_SURVEY_JOB_REQUEST_ID IS NOT NULL AND (:P32_SUBMISSION_DATE IS
NOT NULL AND :P32_LOCK_DATE IS NOT NULL) THEN
show_changes := FALSE;
END IF;
ELSE /* authorized */
IF :P32_SURVEY_JOB_REQUEST_ID IS NOT NULL AND (:P32_SUBMISSION_DATE IS
NULL AND :P32_LOCK_DATE IS NULL) THEN
show_changes := TRUE;
IF :P32_SURVEY_JOB_REQUEST_ID IS NOT NULL AND (:P32_SUBMISSION_DATE IS
NOT NULL AND :P32_LOCK_DATE IS NULL) THEN
show_changes := TRUE;
IF :P32_SURVEY_JOB_REQUEST_ID IS NOT NULL AND (:P32_SUBMISSION_DATE IS
NOT NULL AND :P32_LOCK_DATE IS NOT NULL) THEN
show_changes := TRUE;
END IF;
Return show_changes;
END;
I'm not sure what the problem is. Any help would be greatly appreciated.
Thanks in advance.
Apex 4.2
I have the following pl/sql code block below but whenever I run it in
APex, I keep getting the error:
ORA-06550: line 35, column 4: PLS-00103: Encountered the symbol ";" when
expecting one of the following: if
DECLARE
show_changes BOOLEAN;
l_exists INTEGER;
BEGIN
Select count(*) into l_exists
From dba_role_privs
where grantee = upper(:APP_USER) and
(granted_role = 'SURVEY_JOB_SUID' or granted_role = 'SURVEY_SUID');
IF l_exists = 0 THEN /* unauthorized */
IF :P32_SURVEY_JOB_REQUEST_ID IS NOT NULL AND (:P32_SUBMISSION_DATE IS
NULL AND :P32_LOCK_DATE IS NULL) THEN
show_changes := TRUE;
IF :P32_SURVEY_JOB_REQUEST_ID IS NOT NULL AND (:P32_SUBMISSION_DATE IS
NOT NULL AND :P32_LOCK_DATE IS NULL) THEN
show_changes := TRUE;
IF :P32_SURVEY_JOB_REQUEST_ID IS NOT NULL AND (:P32_SUBMISSION_DATE IS
NOT NULL AND :P32_LOCK_DATE IS NOT NULL) THEN
show_changes := FALSE;
END IF;
ELSE /* authorized */
IF :P32_SURVEY_JOB_REQUEST_ID IS NOT NULL AND (:P32_SUBMISSION_DATE IS
NULL AND :P32_LOCK_DATE IS NULL) THEN
show_changes := TRUE;
IF :P32_SURVEY_JOB_REQUEST_ID IS NOT NULL AND (:P32_SUBMISSION_DATE IS
NOT NULL AND :P32_LOCK_DATE IS NULL) THEN
show_changes := TRUE;
IF :P32_SURVEY_JOB_REQUEST_ID IS NOT NULL AND (:P32_SUBMISSION_DATE IS
NOT NULL AND :P32_LOCK_DATE IS NOT NULL) THEN
show_changes := TRUE;
END IF;
Return show_changes;
END;
I'm not sure what the problem is. Any help would be greatly appreciated.
Thanks in advance.
Java - Index a String (Substring)
Java - Index a String (Substring)
I have this string:
201057&channelTitle=null_JS
I want to be able to cut out the '201057' and make it a new variable. But
I don't always know how long the digits will be, so can I somehow use the
'&' as a reference?\
myDigits substring(0, position of &)?
Thanks
I have this string:
201057&channelTitle=null_JS
I want to be able to cut out the '201057' and make it a new variable. But
I don't always know how long the digits will be, so can I somehow use the
'&' as a reference?\
myDigits substring(0, position of &)?
Thanks
How to activate subpage programmatically?
How to activate subpage programmatically?
I would like to activate subPage of myPage programmatically everytimes
when the author activates the parent page (in my case myPage). I use
eventhandler to detect an activation action and try to activate the subPae
with a replicatior as follows:
@Property(name = "event.topics", value = { ReplicationAction.EVENT_TOPIC })
public class mySubPageActivator extends AbstractRepositoryService
implements EventHandler {
public void handleEvent(final Event event) {
ReplicationAction action = ReplicationAction.fromEvent(event);
if (action.getType().equals(ReplicationActionType.ACTIVATE)) {
Replicator repl = getResourceResolver().adaptTo(Replicator.class);
repl.replicate(getAdminSession(), ReplicationActionType.ACTIVATE,
subPagePath);
}
}
}
the compiler prints java.lang.NullPointerException.
I would like to activate subPage of myPage programmatically everytimes
when the author activates the parent page (in my case myPage). I use
eventhandler to detect an activation action and try to activate the subPae
with a replicatior as follows:
@Property(name = "event.topics", value = { ReplicationAction.EVENT_TOPIC })
public class mySubPageActivator extends AbstractRepositoryService
implements EventHandler {
public void handleEvent(final Event event) {
ReplicationAction action = ReplicationAction.fromEvent(event);
if (action.getType().equals(ReplicationActionType.ACTIVATE)) {
Replicator repl = getResourceResolver().adaptTo(Replicator.class);
repl.replicate(getAdminSession(), ReplicationActionType.ACTIVATE,
subPagePath);
}
}
}
the compiler prints java.lang.NullPointerException.
Thursday, 22 August 2013
inst is undefined error in jquery datepicker in a lightview
inst is undefined error in jquery datepicker in a lightview
I basically have a jquery datepicker in a lightview. The datepicker shows
up but it doesnt seem functional as it does nothing when a day is
selected. It doesn't work and previous and next are selected as well.
I get the "inst is undefined" error
-- the script
jQuery(function() {
jQuery("#datepicker1").datepicker();
});
-- the element
<input type="text" id="datepicker1" name="datepicker1"/>
I basically have a jquery datepicker in a lightview. The datepicker shows
up but it doesnt seem functional as it does nothing when a day is
selected. It doesn't work and previous and next are selected as well.
I get the "inst is undefined" error
-- the script
jQuery(function() {
jQuery("#datepicker1").datepicker();
});
-- the element
<input type="text" id="datepicker1" name="datepicker1"/>
Horizontal Thumbnails in Bootstrap 3
Horizontal Thumbnails in Bootstrap 3
I'm trying to have 3 thumbnails horizontally beside one another and
centred. The issue with these is that they are not centred. I'm also
wondering whether I could simplify the code since for example <div
class="column"> is repetitive in all 3 parts. However, when I try to do
that, the pictures stack vertically instead of horizontally and I'm not
sure why. So my questions are:
How do I centre the 3 pictures on the page?
How do I simplify the code without the images becoming vertically stacked?
Current code
<div class="column">
<div class="col-sm-6 col-md-3">
<div class="thumbnail">
<img
src="http://www.microsoft.com/global/en-us/news/PublishingImages/bod/billg/gates_print.jpg"
alt="My Image" />
<div class="caption">
<h3>Thumbnail label</h3>
<p>Lalalala</p>
</div>
</div>
</div>
</div>
<div class="column">
<div class="col-sm-6 col-md-3">
<div class="thumbnail">
<img
src="http://www.microsoft.com/global/en-us/news/PublishingImages/bod/billg/gates_print.jpg"
alt="My Image" />
<div class="caption">
<h3>Thumbnail label</h3>
<p>Lalalala</p>
</div>
</div>
</div>
</div>
<div class="column">
<div class="col-sm-6 col-md-3">
<div class="thumbnail">
<img
src="http://www.microsoft.com/global/en-us/news/PublishingImages/bod/billg/gates_print.jpg"
alt="My Image" />
<div class="caption">
<h3>Thumbnail label</h3>
<p>Lalalala</p>
</div>
</div>
</div>
</div>
I'm trying to have 3 thumbnails horizontally beside one another and
centred. The issue with these is that they are not centred. I'm also
wondering whether I could simplify the code since for example <div
class="column"> is repetitive in all 3 parts. However, when I try to do
that, the pictures stack vertically instead of horizontally and I'm not
sure why. So my questions are:
How do I centre the 3 pictures on the page?
How do I simplify the code without the images becoming vertically stacked?
Current code
<div class="column">
<div class="col-sm-6 col-md-3">
<div class="thumbnail">
<img
src="http://www.microsoft.com/global/en-us/news/PublishingImages/bod/billg/gates_print.jpg"
alt="My Image" />
<div class="caption">
<h3>Thumbnail label</h3>
<p>Lalalala</p>
</div>
</div>
</div>
</div>
<div class="column">
<div class="col-sm-6 col-md-3">
<div class="thumbnail">
<img
src="http://www.microsoft.com/global/en-us/news/PublishingImages/bod/billg/gates_print.jpg"
alt="My Image" />
<div class="caption">
<h3>Thumbnail label</h3>
<p>Lalalala</p>
</div>
</div>
</div>
</div>
<div class="column">
<div class="col-sm-6 col-md-3">
<div class="thumbnail">
<img
src="http://www.microsoft.com/global/en-us/news/PublishingImages/bod/billg/gates_print.jpg"
alt="My Image" />
<div class="caption">
<h3>Thumbnail label</h3>
<p>Lalalala</p>
</div>
</div>
</div>
</div>
Qt widgets 4.7 vs. 5.1
Qt widgets 4.7 vs. 5.1
I recently started on a new project where we will be using Qt to create
the GUI. Without getting into details, it has been mandated by management
that we use Qt 4.7. There are no valid reasons for this decision. We are
not porting any existing code to Qt 5, this is all new implementation. I
am the UI lead for the project and I need to make a case for using Qt 5.1.
I am going to explain why the concerns held by some of the engineers about
moving to 5.1 are not legitimate, but I would also like to strengthen my
case by giving specific reasons that we should use Qt 5.1 over 4.7. My
main reason behind wanting to use 5.1 is just that it's the latest version
with many improvements over 4.7. While this reason is valid, I would
appreciate it if anybody who is familiar with the differences between Qt
4.7+ compared to 5.0+ would help me come up with some specific reasons. I
have not used Qt 5 yet myself. We will be using widgets either way, not
QtQuick/QML, so please only consider differences pertaining to Qt widgets.
I recently started on a new project where we will be using Qt to create
the GUI. Without getting into details, it has been mandated by management
that we use Qt 4.7. There are no valid reasons for this decision. We are
not porting any existing code to Qt 5, this is all new implementation. I
am the UI lead for the project and I need to make a case for using Qt 5.1.
I am going to explain why the concerns held by some of the engineers about
moving to 5.1 are not legitimate, but I would also like to strengthen my
case by giving specific reasons that we should use Qt 5.1 over 4.7. My
main reason behind wanting to use 5.1 is just that it's the latest version
with many improvements over 4.7. While this reason is valid, I would
appreciate it if anybody who is familiar with the differences between Qt
4.7+ compared to 5.0+ would help me come up with some specific reasons. I
have not used Qt 5 yet myself. We will be using widgets either way, not
QtQuick/QML, so please only consider differences pertaining to Qt widgets.
file-name is transparently redirecting to file-name.php
file-name is transparently redirecting to file-name.php
If I request /file-name I get /file-name.php's content back. I want to
know how this is happening but can't seem to figure it out.
I emptied the .htaccess and it's still doing it. I verified that the
.htaccess I emptied was the correct one by placing "zzz" in it and that
resulted in an internal server error, as I'd expect.
I can't find anything in the httpd.conf file in /etc/apache2/sites-enabled
either.
Any ideas?
If I request /file-name I get /file-name.php's content back. I want to
know how this is happening but can't seem to figure it out.
I emptied the .htaccess and it's still doing it. I verified that the
.htaccess I emptied was the correct one by placing "zzz" in it and that
resulted in an internal server error, as I'd expect.
I can't find anything in the httpd.conf file in /etc/apache2/sites-enabled
either.
Any ideas?
Ajax File Upload not work with multiple form
Ajax File Upload not work with multiple form
Multiple form with multiple progress bar not work, When I click on the
first form all the progress bar are activated, , but when you click on the
first form, only the first progress bar must be activated!!
HTML
<form id="myForm" action="upload.php" method="post"
enctype="multipart/form-data">
<input type="file" size="60" name="myfile" id="inputItemId">
<input type="submit" value="Ajax File Upload">
<input type="text" size="60" name="file-input" id="hiddenDivId" value="">
</form>
<div id="myForm">
<div class="progress" >
<div class="bar" ></div>
<div class="percent" >0%</div>
</div>
<br/>
<div class="message" ></div>
</div>
<form id="myForm1" action="upload.php" method="post"
enctype="multipart/form-data">
<input type="file" size="60" name="file1" id="inputItemId">
<input type="hidden" id="upload" value="upload-2">
<input type="submit" value="Ajax File Upload">
<input type="text" size="60" name="file-input" id="hiddenDivId" value="">
</form>
<div id="myForm1">
<div class="progress" >
<div class="bar" ></div>
<div class="percent" >0%</div>
</div>
<br/>
<div class="message" ></div>
</div>
AJAX
$(document).ready(function()
{
var bar = $('div.bar');
var percent = $('div.percent');
var progress = $('div.progress');
var message = $('div.message');
var options = {
beforeSend: function()
{
var value = $('#upload').val();
var inputName = $('#inputItemId').val();
progress.show();
//clear everything
bar.width('0%');
message.html("");
percent.html("0%");
},
uploadProgress: function(event, position, total, percentComplete)
{
bar.width(percentComplete+'%');
percent.html(percentComplete+'%');
},
success: function()
{
bar.width('100%');
percent.html('100%');
},
complete: function(response)
{
message.html("<font color='green'>"+response.responseText+"</font>");
$('#hiddenDivId').val(response.responseText);
},
error: function()
{
message.html("<font color='red'> ERROR: unable to upload files</font>");
}
};
$("#myForm").ajaxForm(options);
$("#myForm1").ajaxForm(options);
$("#myForm2").ajaxForm(options);
});
Multiple form with multiple progress bar not work, When I click on the
first form all the progress bar are activated, , but when you click on the
first form, only the first progress bar must be activated!!
HTML
<form id="myForm" action="upload.php" method="post"
enctype="multipart/form-data">
<input type="file" size="60" name="myfile" id="inputItemId">
<input type="submit" value="Ajax File Upload">
<input type="text" size="60" name="file-input" id="hiddenDivId" value="">
</form>
<div id="myForm">
<div class="progress" >
<div class="bar" ></div>
<div class="percent" >0%</div>
</div>
<br/>
<div class="message" ></div>
</div>
<form id="myForm1" action="upload.php" method="post"
enctype="multipart/form-data">
<input type="file" size="60" name="file1" id="inputItemId">
<input type="hidden" id="upload" value="upload-2">
<input type="submit" value="Ajax File Upload">
<input type="text" size="60" name="file-input" id="hiddenDivId" value="">
</form>
<div id="myForm1">
<div class="progress" >
<div class="bar" ></div>
<div class="percent" >0%</div>
</div>
<br/>
<div class="message" ></div>
</div>
AJAX
$(document).ready(function()
{
var bar = $('div.bar');
var percent = $('div.percent');
var progress = $('div.progress');
var message = $('div.message');
var options = {
beforeSend: function()
{
var value = $('#upload').val();
var inputName = $('#inputItemId').val();
progress.show();
//clear everything
bar.width('0%');
message.html("");
percent.html("0%");
},
uploadProgress: function(event, position, total, percentComplete)
{
bar.width(percentComplete+'%');
percent.html(percentComplete+'%');
},
success: function()
{
bar.width('100%');
percent.html('100%');
},
complete: function(response)
{
message.html("<font color='green'>"+response.responseText+"</font>");
$('#hiddenDivId').val(response.responseText);
},
error: function()
{
message.html("<font color='red'> ERROR: unable to upload files</font>");
}
};
$("#myForm").ajaxForm(options);
$("#myForm1").ajaxForm(options);
$("#myForm2").ajaxForm(options);
});
Tools for a bug hunt
Tools for a bug hunt
I'd like to find following potential bugs in code, for many different
functions A and B:
find places where the result of function A is not immediately checked
find functions (maybe using some heuristic) where some resource is
allocated with function A, then we possibly return because of an error,
but the resource is not deallocated with function B
I am currently using Coccinelle for these tasks, are there any other choices?
I'd like to find following potential bugs in code, for many different
functions A and B:
find places where the result of function A is not immediately checked
find functions (maybe using some heuristic) where some resource is
allocated with function A, then we possibly return because of an error,
but the resource is not deallocated with function B
I am currently using Coccinelle for these tasks, are there any other choices?
Extract SRC's from selected images, comma seperated
Extract SRC's from selected images, comma seperated
I'm using a Wordpress plugin where I can only type attachment urls (comma
seperated) in an input box. I need to alter the code so I can click an
image and it will extract the src to put it in the input box.
I made it possible with only one image.
First, I echo'd all the images from my media library. And then I did this:
<img class="media-image" src="<?php echo $images[$i]; ?>"/>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('.media-image').click(function(){
var thisValue = jQuery(this).attr('src');
var thisTarget = jQuery('#target');
thisTarget.val(thisValue);
return false;
});
});
</script>
<input id="target" type="text"></input>
What this does: Whenever I click an image, the src will be put in the
input text box. When I click another image, the value will be changed
accordingly.
But how can I achieve this with multiple images? So, if I click 3 images,
I want all the src's to be comma seperated in the input field. Whenever I
click a selected image again, I want it to be deselected (i.e. I want the
src to be removed from the input).
Any ideas?
I'm using a Wordpress plugin where I can only type attachment urls (comma
seperated) in an input box. I need to alter the code so I can click an
image and it will extract the src to put it in the input box.
I made it possible with only one image.
First, I echo'd all the images from my media library. And then I did this:
<img class="media-image" src="<?php echo $images[$i]; ?>"/>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('.media-image').click(function(){
var thisValue = jQuery(this).attr('src');
var thisTarget = jQuery('#target');
thisTarget.val(thisValue);
return false;
});
});
</script>
<input id="target" type="text"></input>
What this does: Whenever I click an image, the src will be put in the
input text box. When I click another image, the value will be changed
accordingly.
But how can I achieve this with multiple images? So, if I click 3 images,
I want all the src's to be comma seperated in the input field. Whenever I
click a selected image again, I want it to be deselected (i.e. I want the
src to be removed from the input).
Any ideas?
Wednesday, 21 August 2013
Save only the contents of php array to file
Save only the contents of php array to file
I have an array $urls_array, how do I only save the contents and not
anything else into a file?
INPUT:
Array (
[0] => "http://google.com"
[1] => "http://facebook.com"
[2] => "http://yahoo.com"
)
OUTPUT:
http://google.com
http://facebook.com
http://yahoo.com
I tried using json_encode($urls_array) and serialize() and print_r(), but
nothing gave me the clean result I wanted. Any help?
I have an array $urls_array, how do I only save the contents and not
anything else into a file?
INPUT:
Array (
[0] => "http://google.com"
[1] => "http://facebook.com"
[2] => "http://yahoo.com"
)
OUTPUT:
http://google.com
http://facebook.com
http://yahoo.com
I tried using json_encode($urls_array) and serialize() and print_r(), but
nothing gave me the clean result I wanted. Any help?
Python : why import modules on top of everything if that is like importing stuff from china w/o knowing if there will be a demand for it?
Python : why import modules on top of everything if that is like importing
stuff from china w/o knowing if there will be a demand for it?
You are about to be provided with information to
start your own Google.
Some people posted comments and said this can not
be done because google has 1 million servers and we do not.
The truth is, google has those many servers for trolling
purposes (e.g. google +, google finance, youtube the bandwidth consuming
no-profit making web site, etc ).
all for trolling purposes.
if you wanted to start your own search engine...
you need to know few things.
1 : you need to know how beautiful mysql is.
2: you need to not listen to people that tell you to use a framework
with python, and simply use mod-wsgi.
3: you need to cache popular searches when your search engine is running.
3: you need to connect numbers to words. maybe even something like..
numbers to numbers to words.
in other words let's say in the past 24 hours people searched for
some phrases over and over again.. you cache those and assign numbers
to them, this way you are matching numbers with numbers in mysql.
not words with words.
in other words let's say google uses 1/2 their servers for trolling
and 1/2 for search engine.
we need technology and ideas so that you can run a search engine
on 1 or 2 dedicated servers that cost no more than $100/month each.
once you make money, you can begin buying more and more servers.
after you make lots of money.. you probably gonna turn into a troll
too like google inc.
because god is brutal.
god is void-state
it keeps singing you songs when you are sleeping and says
"nothing matters, there is simply no meaning"
but of course to start this search engine, you need a jump start.
if you notice google constantly links to other web sites with a
trackable way when people click on search results.
this means google knows which web sites are becoming popular
are popular, etc. they can see what is rising before it rises.
it's like being able to see the future.
the computer tells them " you better get in touch with this guy
before he becomes rich and becomes un-stopable "
sometimes they send cops onto people. etc.
AMAZON INC however..
will provide you with the top 1 million web sites in the world.
updated daily in a cvs file.
downloadable at alexa.com
simply click on 'top sites' and then you will see the downloadable
file on the right side.
everyday they update it. and it is being given away for free.
google would never do this.
amazon does this.
this list you can use to ensure you show the top sites first in your
search engine .
this makes your search engine look 'credible'
in other words as you start making money, you first display things
in a "Generic" way but at the same time not in a "questionable" way
by displaying them based on "rank"
of course amazon only gives you URLS of the web sites.
you need to grab the title and etc from the web sites.
the truth is, to get started you do not need everything from web sites.
a title and some tags is all you need.
simple.
basic.
functional
will get peoples attention.
i always ask questions on SO but most questions get deleted. here's
something that did not get deleted..
How do I ensure that re.findall() stops at the right place?
use python, skrew php, php is no good.
do not use python frameworks, it's all lies and b.s. use mod-wsgi
use memcache to cache the templates and thus no need for a template engine.
always look at russian dedicated servers, and so on.
do not put your trust in america.
it has all turned into a mafia.
google can file a report, fbi can send cops onto you, and next thing you know
they frame you as a criminal, thug, mentally ill, bipolar, peadophile, and
so on.
all you can do is bleed to death behind bars.
do not give into the lies of AMERICA.
find russian dedicated servers.
i tried signing up with pw-service.com but i couldn't do it due to
restrictions with their russian payment systems and so on..
again, amazon's web site alexa.com provides you with downloadable
top 1 mil web sites in the form of a cvs file.
use it.
again, do not give into python programmers suggesting frameworks for python.
it's all b.s. use mod_wsgi with memcache.
again, american corporations can ruin you with lies and all you can do is
bleed to death behind bars
again, a basic search engine needs : url, title, tags, and popular searches
can be "cached" and words can be connected to "numbers" within the mysql.
mysql has capabilities to cache things as well.
cache once, cache twice, and you will not need 1 million servers in order
to troll.
if you need some xdotool commands to deal with people calling you a troll
here it is;
xdotool key ctrl+c
xdotool key Tab Tab Tab Return
xdotool type '@'
xdotool key ctrl+v
xdotool type --clearmodifiers ', there can not be such thing as a `troll`
unless compared to a stationary point, if you are complaining, you are not
stationary. which means you are the one that is trolling.'
xdotool key Tab Return
create an application launcher on your gnome-panel, and then select the
username in the comments section that called you a 'troll' and click the
shortcut on the gnome-panel.
it will copy the selected username to the clipboard and then hit TAB TAB
TAB RETURN
which opens the comment typing box. and then it will type @ + username +
comma, and then the rest.
..............................................................
stuff from china w/o knowing if there will be a demand for it?
You are about to be provided with information to
start your own Google.
Some people posted comments and said this can not
be done because google has 1 million servers and we do not.
The truth is, google has those many servers for trolling
purposes (e.g. google +, google finance, youtube the bandwidth consuming
no-profit making web site, etc ).
all for trolling purposes.
if you wanted to start your own search engine...
you need to know few things.
1 : you need to know how beautiful mysql is.
2: you need to not listen to people that tell you to use a framework
with python, and simply use mod-wsgi.
3: you need to cache popular searches when your search engine is running.
3: you need to connect numbers to words. maybe even something like..
numbers to numbers to words.
in other words let's say in the past 24 hours people searched for
some phrases over and over again.. you cache those and assign numbers
to them, this way you are matching numbers with numbers in mysql.
not words with words.
in other words let's say google uses 1/2 their servers for trolling
and 1/2 for search engine.
we need technology and ideas so that you can run a search engine
on 1 or 2 dedicated servers that cost no more than $100/month each.
once you make money, you can begin buying more and more servers.
after you make lots of money.. you probably gonna turn into a troll
too like google inc.
because god is brutal.
god is void-state
it keeps singing you songs when you are sleeping and says
"nothing matters, there is simply no meaning"
but of course to start this search engine, you need a jump start.
if you notice google constantly links to other web sites with a
trackable way when people click on search results.
this means google knows which web sites are becoming popular
are popular, etc. they can see what is rising before it rises.
it's like being able to see the future.
the computer tells them " you better get in touch with this guy
before he becomes rich and becomes un-stopable "
sometimes they send cops onto people. etc.
AMAZON INC however..
will provide you with the top 1 million web sites in the world.
updated daily in a cvs file.
downloadable at alexa.com
simply click on 'top sites' and then you will see the downloadable
file on the right side.
everyday they update it. and it is being given away for free.
google would never do this.
amazon does this.
this list you can use to ensure you show the top sites first in your
search engine .
this makes your search engine look 'credible'
in other words as you start making money, you first display things
in a "Generic" way but at the same time not in a "questionable" way
by displaying them based on "rank"
of course amazon only gives you URLS of the web sites.
you need to grab the title and etc from the web sites.
the truth is, to get started you do not need everything from web sites.
a title and some tags is all you need.
simple.
basic.
functional
will get peoples attention.
i always ask questions on SO but most questions get deleted. here's
something that did not get deleted..
How do I ensure that re.findall() stops at the right place?
use python, skrew php, php is no good.
do not use python frameworks, it's all lies and b.s. use mod-wsgi
use memcache to cache the templates and thus no need for a template engine.
always look at russian dedicated servers, and so on.
do not put your trust in america.
it has all turned into a mafia.
google can file a report, fbi can send cops onto you, and next thing you know
they frame you as a criminal, thug, mentally ill, bipolar, peadophile, and
so on.
all you can do is bleed to death behind bars.
do not give into the lies of AMERICA.
find russian dedicated servers.
i tried signing up with pw-service.com but i couldn't do it due to
restrictions with their russian payment systems and so on..
again, amazon's web site alexa.com provides you with downloadable
top 1 mil web sites in the form of a cvs file.
use it.
again, do not give into python programmers suggesting frameworks for python.
it's all b.s. use mod_wsgi with memcache.
again, american corporations can ruin you with lies and all you can do is
bleed to death behind bars
again, a basic search engine needs : url, title, tags, and popular searches
can be "cached" and words can be connected to "numbers" within the mysql.
mysql has capabilities to cache things as well.
cache once, cache twice, and you will not need 1 million servers in order
to troll.
if you need some xdotool commands to deal with people calling you a troll
here it is;
xdotool key ctrl+c
xdotool key Tab Tab Tab Return
xdotool type '@'
xdotool key ctrl+v
xdotool type --clearmodifiers ', there can not be such thing as a `troll`
unless compared to a stationary point, if you are complaining, you are not
stationary. which means you are the one that is trolling.'
xdotool key Tab Return
create an application launcher on your gnome-panel, and then select the
username in the comments section that called you a 'troll' and click the
shortcut on the gnome-panel.
it will copy the selected username to the clipboard and then hit TAB TAB
TAB RETURN
which opens the comment typing box. and then it will type @ + username +
comma, and then the rest.
..............................................................
Expect/Exp_Send Only works with two expects in a row
Expect/Exp_Send Only works with two expects in a row
I have an tcl script that is supposed to send a grep command to a server,
but will only execute the command if I put another expect with exp_send
immediately after.
set spawn_id [::SshLibrary::connect **.***.**.*** username password]
;#just ssh, essentially
set cmd "grep \"$str\" /var/log/syslog/$smtsIp"
expect -re $::LinuxLIbrary::prompt { exp_send "$cmd\r"}
expect -re $::LinuxLibrary::prompt { exp_send "echo \" \"\r }
...
So, through experimentation, I've found out that the first expect will
only exp_send its command if the second expect statement is present
(Similarly for the second expect command, regarding the presence of the
first) even though they expect the same thing and the second statement is
entirely useless. I'm unsure of what the problem is, it seems totally
illogical. Any suggestions?
I have an tcl script that is supposed to send a grep command to a server,
but will only execute the command if I put another expect with exp_send
immediately after.
set spawn_id [::SshLibrary::connect **.***.**.*** username password]
;#just ssh, essentially
set cmd "grep \"$str\" /var/log/syslog/$smtsIp"
expect -re $::LinuxLIbrary::prompt { exp_send "$cmd\r"}
expect -re $::LinuxLibrary::prompt { exp_send "echo \" \"\r }
...
So, through experimentation, I've found out that the first expect will
only exp_send its command if the second expect statement is present
(Similarly for the second expect command, regarding the presence of the
first) even though they expect the same thing and the second statement is
entirely useless. I'm unsure of what the problem is, it seems totally
illogical. Any suggestions?
Why does the cost of C++ virtual call depends on the number of derived classes?
Why does the cost of C++ virtual call depends on the number of derived
classes?
I've written a short example program that I was using to study the
overhead of virtual calls.
File virtual.h:
#pragma once
static const int NUM_DERIVED = 10;
struct Base {
int val;
#ifdef NO_VIRTUAL
#define virtual
classes?
I've written a short example program that I was using to study the
overhead of virtual calls.
File virtual.h:
#pragma once
static const int NUM_DERIVED = 10;
struct Base {
int val;
#ifdef NO_VIRTUAL
#define virtual
Function call takes longer in composite class
Function call takes longer in composite class
Trying to understand run time performance with class composition, I wrote
the following test code. In it, I compare the time taken to call a
function directly as a member function of a class, versus to call it
through a composite class that has the original class as a member.
It seems like the methods should take comparable time, but they don't:
calling through the composite class takes almost twice as long.
Here's the code:
const int REPS(1e8);
const double INPUT(5.29);
class Base {
public:
inline double BaseFunc(double x) const;
};
double Base::BaseFunc(double x) const {
return 2.718*x + 3.14;
};
class Super {
public:
inline double BaseFunc(double x) const;
private:
Base b_;
};
double Super::BaseFunc(double x) const {
b_.BaseFunc(x);
};
int main() {
auto t0 = std::chrono::high_resolution_clock::now();
// Call to base directly.
Base b;
for (int i = 0; i < REPS; ++i)
b.BaseFunc(INPUT);
auto t1 = std::chrono::high_resolution_clock::now();
// Call to base through composited class.
Super s;
for (int i = 0; i < REPS; ++i)
s.BaseFunc(INPUT);
auto t2 = std::chrono::high_resolution_clock::now();
// Find average durations.
auto diff1 =
std::chrono::duration_cast<std::chrono::nanoseconds>(t1-t0).count();
diff1 /= REPS;
auto diff2 =
std::chrono::duration_cast<std::chrono::nanoseconds>(t2-t1).count();
diff2 /= REPS;
std::cout << "Calling directly to base took " << diff1 << "nsec.\n";
std::cout << "Calling to base through a composited class took " << diff2
<< "nsec.\n";
}
Compiling with g++ Version 4.7.2, with -std=c++11 -O0 -Winline, I get:
Calling directly to base took 13nsec.
Calling to base through a composited class took 24nsec.
Why is there such a disparity between these two ways of calling
essentially the same function? I figure that since everything is inlined
(gcc doesn't tell me otherwise) these should be the same thing.
Am I thinking about this totally incorrectly? Any help is appreciated!
Thanks!
Trying to understand run time performance with class composition, I wrote
the following test code. In it, I compare the time taken to call a
function directly as a member function of a class, versus to call it
through a composite class that has the original class as a member.
It seems like the methods should take comparable time, but they don't:
calling through the composite class takes almost twice as long.
Here's the code:
const int REPS(1e8);
const double INPUT(5.29);
class Base {
public:
inline double BaseFunc(double x) const;
};
double Base::BaseFunc(double x) const {
return 2.718*x + 3.14;
};
class Super {
public:
inline double BaseFunc(double x) const;
private:
Base b_;
};
double Super::BaseFunc(double x) const {
b_.BaseFunc(x);
};
int main() {
auto t0 = std::chrono::high_resolution_clock::now();
// Call to base directly.
Base b;
for (int i = 0; i < REPS; ++i)
b.BaseFunc(INPUT);
auto t1 = std::chrono::high_resolution_clock::now();
// Call to base through composited class.
Super s;
for (int i = 0; i < REPS; ++i)
s.BaseFunc(INPUT);
auto t2 = std::chrono::high_resolution_clock::now();
// Find average durations.
auto diff1 =
std::chrono::duration_cast<std::chrono::nanoseconds>(t1-t0).count();
diff1 /= REPS;
auto diff2 =
std::chrono::duration_cast<std::chrono::nanoseconds>(t2-t1).count();
diff2 /= REPS;
std::cout << "Calling directly to base took " << diff1 << "nsec.\n";
std::cout << "Calling to base through a composited class took " << diff2
<< "nsec.\n";
}
Compiling with g++ Version 4.7.2, with -std=c++11 -O0 -Winline, I get:
Calling directly to base took 13nsec.
Calling to base through a composited class took 24nsec.
Why is there such a disparity between these two ways of calling
essentially the same function? I figure that since everything is inlined
(gcc doesn't tell me otherwise) these should be the same thing.
Am I thinking about this totally incorrectly? Any help is appreciated!
Thanks!
How to connect to Wired and DSL connection simultaneously?
How to connect to Wired and DSL connection simultaneously?
I'm using a Linksys wireless router/modem. In order to share my internet
connection on the network, I need to be connected to both the wired and
the DSL connections. But if I connect to the DSL connection, the wired one
is dropped and vice versa. Please help.
I'm using a Linksys wireless router/modem. In order to share my internet
connection on the network, I need to be connected to both the wired and
the DSL connections. But if I connect to the DSL connection, the wired one
is dropped and vice versa. Please help.
Measure rendering progress
Measure rendering progress
I have some large reports that are automatically generated and compiled
using xelatex. Just wondering if anyone knows of a way to track the
rendering progress as these reports can take over a minute to render (many
tikz figures and 2-300 pages). I'm using xelatex on ubuntu.
I have some large reports that are automatically generated and compiled
using xelatex. Just wondering if anyone knows of a way to track the
rendering progress as these reports can take over a minute to render (many
tikz figures and 2-300 pages). I'm using xelatex on ubuntu.
Tuesday, 20 August 2013
Error occured while communication 32 bit TWAIN.DLL with 64 bit Machine
Error occured while communication 32 bit TWAIN.DLL with 64 bit Machine
I am using this code for scanning ,
this code is working perfectly on 32 bit Machine but I am switching my
application to 64 Bit machine where I am getting an error .I searched a
lot and found many solutions ,
common Solution I found that compile the application on 32 bit machine but
it does not improve my application performance so i do not want to use
this solution on 64-bit machine.
Error is :
An attempt was made to load a program with an incorrect format. (Exception
fromHRESULT: 0x8007000B)
Code is :
namespace TwainLib
{
public enum TwainCommand
{
Not = -1,
Null = 0,
TransferReady = 1,
CloseRequest = 2,
CloseOk = 3,
DeviceEvent = 4
}
public class Twain
{
private const short CountryUSA = 1;
private const short LanguageUSA = 13;
public Twain()
{
appid = new TwIdentity();
appid.Id = IntPtr.Zero;
appid.Version.MajorNum = 1;
appid.Version.MinorNum = 1;
appid.Version.Language = LanguageUSA;
appid.Version.Country = CountryUSA;
appid.Version.Info = "Hack 1";
appid.ProtocolMajor = TwProtocol.Major;
appid.ProtocolMinor = TwProtocol.Minor;
appid.SupportedGroups = (int)(TwDG.Image | TwDG.Control);
appid.Manufacturer = "NETMaster";
appid.ProductFamily = "Freeware";
appid.ProductName = "Hack";
srcds = new TwIdentity();
srcds.Id = IntPtr.Zero;
evtmsg.EventPtr = Marshal.AllocHGlobal(Marshal.SizeOf(winmsg));
}
~Twain()
{
Marshal.FreeHGlobal(evtmsg.EventPtr);
}
public void Init(IntPtr hwndp)
{
Finish();
TwRC rc = DSMparent(appid, IntPtr.Zero, TwDG.Control,
TwDAT.Parent, TwMSG.OpenDSM, ref hwndp);
if (rc == TwRC.Success)
{
rc = DSMident(appid, IntPtr.Zero, TwDG.Control,
TwDAT.Identity, TwMSG.GetDefault, srcds);
if (rc == TwRC.Success)
hwnd = hwndp;
else
rc = DSMparent(appid, IntPtr.Zero, TwDG.Control,
TwDAT.Parent, TwMSG.CloseDSM, ref hwndp);
}
}
public void Select()
{
TwRC rc;
CloseSrc();
if (appid.Id == IntPtr.Zero)
{
Init(hwnd);
if (appid.Id == IntPtr.Zero)
return;
}
rc = DSMident(appid, IntPtr.Zero, TwDG.Control, TwDAT.Identity,
TwMSG.UserSelect, srcds);
}
/// <summary>
/// Returns a list of twain sources
/// </summary>
/// <returns></returns>
public IEnumerable<TwIdentity> GetSources()
{
TwRC rc;
CloseSrc();
if (appid.Id == IntPtr.Zero)
{
Init(hwnd);
if (appid.Id == IntPtr.Zero)
return null;
}
List<TwIdentity> sources = new List<TwIdentity>();
TwIdentity identity = new TwIdentity();
rc = DSMident(appid, IntPtr.Zero, TwDG.Control, TwDAT.Identity,
TwMSG.GetFirst, identity);
while (rc == TwRC.Success)
{
sources.Add(identity);
identity = new TwIdentity();
rc = DSMident(appid, IntPtr.Zero, TwDG.Control,
TwDAT.Identity, TwMSG.GetNext, identity);
}
return sources;
}
/// <summary>
/// Sets the source from which images will be acquired
/// </summary>
/// <param name="Source_p"></param>
public void SetSource(TwIdentity Source_p)
{
srcds = Source_p;
}
public void Acquire()
{
TwRC rc;
CloseSrc();
if (appid.Id == IntPtr.Zero)
{
Init(hwnd);
if (appid.Id == IntPtr.Zero)
return;
}
rc = DSMident(appid, IntPtr.Zero, TwDG.Control, TwDAT.Identity,
TwMSG.OpenDS, srcds);
if (rc != TwRC.Success)
return;
TwCapability cap = new TwCapability(TwCap.XferCount, 1);
rc = DScap(appid, srcds, TwDG.Control, TwDAT.Capability,
TwMSG.Set, cap);
if (rc != TwRC.Success)
{
CloseSrc();
return;
}
TwUserInterface guif = new TwUserInterface();
guif.ShowUI = 1;
guif.ModalUI = 1;
guif.ParentHand = hwnd;
rc = DSuserif(appid, srcds, TwDG.Control, TwDAT.UserInterface,
TwMSG.EnableDS, guif);
if (rc != TwRC.Success)
{
CloseSrc();
return;
}
}
public List<IntPtr> TransferPictures()
{
List<IntPtr> pics = new List<IntPtr>();
if (srcds.Id == IntPtr.Zero)
return pics;
TwRC rc;
IntPtr hbitmap = IntPtr.Zero;
TwPendingXfers pxfr = new TwPendingXfers();
do
{
pxfr.Count = 0;
hbitmap = IntPtr.Zero;
TwImageInfo iinf = new TwImageInfo();
rc = DSiinf(appid, srcds, TwDG.Image, TwDAT.ImageInfo,
TwMSG.Get, iinf);
if (rc != TwRC.Success)
{
CloseSrc();
return pics;
}
rc = DSixfer(appid, srcds, TwDG.Image, TwDAT.ImageNativeXfer,
TwMSG.Get, ref hbitmap);
if (rc != TwRC.XferDone)
{
CloseSrc();
return pics;
}
rc = DSpxfer(appid, srcds, TwDG.Control, TwDAT.PendingXfers,
TwMSG.EndXfer, pxfr);
if (rc != TwRC.Success)
{
CloseSrc();
return pics;
}
pics.Add(hbitmap);
}
while (pxfr.Count != 0);
rc = DSpxfer(appid, srcds, TwDG.Control, TwDAT.PendingXfers,
TwMSG.Reset, pxfr);
return pics;
}
public TwainCommand PassMessage(ref Message m)
{
if (srcds.Id == IntPtr.Zero)
return TwainCommand.Not;
int pos = GetMessagePos();
winmsg.hwnd = m.HWnd;
winmsg.message = m.Msg;
winmsg.wParam = m.WParam;
winmsg.lParam = m.LParam;
winmsg.time = GetMessageTime();
winmsg.x = (short)pos;
winmsg.y = (short)(pos >> 16);
Marshal.StructureToPtr(winmsg, evtmsg.EventPtr, false);
evtmsg.Message = 0;
TwRC rc = DSevent(appid, srcds, TwDG.Control, TwDAT.Event,
TwMSG.ProcessEvent, ref evtmsg);
if (rc == TwRC.NotDSEvent)
return TwainCommand.Not;
if (evtmsg.Message == (short)TwMSG.XFerReady)
return TwainCommand.TransferReady;
if (evtmsg.Message == (short)TwMSG.CloseDSReq)
return TwainCommand.CloseRequest;
if (evtmsg.Message == (short)TwMSG.CloseDSOK)
return TwainCommand.CloseOk;
if (evtmsg.Message == (short)TwMSG.DeviceEvent)
return TwainCommand.DeviceEvent;
return TwainCommand.Null;
}
public void CloseSrc()
{
TwRC rc;
if (srcds.Id != IntPtr.Zero)
{
TwUserInterface guif = new TwUserInterface();
rc = DSuserif(appid, srcds, TwDG.Control, TwDAT.UserInterface,
TwMSG.DisableDS, guif);
rc = DSMident(appid, IntPtr.Zero, TwDG.Control,
TwDAT.Identity, TwMSG.CloseDS, srcds);
}
}
public void Finish()
{
TwRC rc;
CloseSrc();
if (appid.Id != IntPtr.Zero)
rc = DSMparent(appid, IntPtr.Zero, TwDG.Control, TwDAT.Parent,
TwMSG.CloseDSM, ref hwnd);
appid.Id = IntPtr.Zero;
}
private IntPtr hwnd;
private TwIdentity appid;
private TwIdentity srcds;
private TwEvent evtmsg;
private WINMSG winmsg;
// ------ DSM entry point DAT_ variants:
[DllImport("twain_32.dll", EntryPoint = "#1")]
private static extern TwRC DSMparent([In, Out] TwIdentity origin,
IntPtr zeroptr, TwDG dg, TwDAT dat, TwMSG msg, ref IntPtr refptr);
[DllImport("twain_32.dll", EntryPoint = "#1")]
private static extern TwRC DSMident([In, Out] TwIdentity origin,
IntPtr zeroptr, TwDG dg, TwDAT dat, TwMSG msg, [In, Out] TwIdentity
idds);
[DllImport("twain_32.dll", EntryPoint = "#1")]
private static extern TwRC DSMstatus([In, Out] TwIdentity origin,
IntPtr zeroptr, TwDG dg, TwDAT dat, TwMSG msg, [In, Out] TwStatus
dsmstat);
// ------ DSM entry point DAT_ variants to DS:
[DllImport("twain_32.dll", EntryPoint = "#1")]
private static extern TwRC DSuserif([In, Out] TwIdentity origin, [In,
Out] TwIdentity dest, TwDG dg, TwDAT dat, TwMSG msg, TwUserInterface
guif);
[DllImport("twain_32.dll", EntryPoint = "#1")]
private static extern TwRC DSevent([In, Out] TwIdentity origin, [In,
Out] TwIdentity dest, TwDG dg, TwDAT dat, TwMSG msg, ref TwEvent evt);
[DllImport("twain_32.dll", EntryPoint = "#1")]
private static extern TwRC DSstatus([In, Out] TwIdentity origin, [In]
TwIdentity dest, TwDG dg, TwDAT dat, TwMSG msg, [In, Out] TwStatus
dsmstat);
[DllImport("twain_32.dll", EntryPoint = "#1")]
private static extern TwRC DScap([In, Out] TwIdentity origin, [In]
TwIdentity dest, TwDG dg, TwDAT dat, TwMSG msg, [In, Out] TwCapability
capa);
[DllImport("twain_32.dll", EntryPoint = "#1")]
private static extern TwRC DSiinf([In, Out] TwIdentity origin, [In]
TwIdentity dest, TwDG dg, TwDAT dat, TwMSG msg, [In, Out] TwImageInfo
imginf);
[DllImport("twain_32.dll", EntryPoint = "#1")]
private static extern TwRC DSixfer([In, Out] TwIdentity origin, [In]
TwIdentity dest, TwDG dg, TwDAT dat, TwMSG msg, ref IntPtr hbitmap);
[DllImport("twain_32.dll", EntryPoint = "#1")]
private static extern TwRC DSpxfer([In, Out] TwIdentity origin, [In]
TwIdentity dest, TwDG dg, TwDAT dat, TwMSG msg, [In, Out]
TwPendingXfers pxfr);
[DllImport("kernel32.dll", ExactSpelling = true)]
internal static extern IntPtr GlobalAlloc(int flags, int size);
[DllImport("kernel32.dll", ExactSpelling = true)]
internal static extern IntPtr GlobalLock(IntPtr handle);
[DllImport("kernel32.dll", ExactSpelling = true)]
internal static extern bool GlobalUnlock(IntPtr handle);
[DllImport("kernel32.dll", ExactSpelling = true)]
internal static extern IntPtr GlobalFree(IntPtr handle);
[DllImport("user32.dll", ExactSpelling = true)]
private static extern int GetMessagePos();
[DllImport("user32.dll", ExactSpelling = true)]
private static extern int GetMessageTime();
[DllImport("gdi32.dll", ExactSpelling = true)]
private static extern int GetDeviceCaps(IntPtr hDC, int nIndex);
[DllImport("gdi32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr CreateDC(string szdriver, string
szdevice, string szoutput, IntPtr devmode);
[DllImport("gdi32.dll", ExactSpelling = true)]
private static extern bool DeleteDC(IntPtr hdc);
public static int ScreenBitDepth
{
get
{
IntPtr screenDC = CreateDC("DISPLAY", null, null, IntPtr.Zero);
int bitDepth = GetDeviceCaps(screenDC, 12);
bitDepth *= GetDeviceCaps(screenDC, 14);
DeleteDC(screenDC);
return bitDepth;
}
}
[StructLayout(LayoutKind.Sequential, Pack = 4)]
internal struct WINMSG
{
public IntPtr hwnd;
public int message;
public IntPtr wParam;
public IntPtr lParam;
public int time;
public int x;
public int y;
}
} // class Twain
}
As per my analysis this error occurred because of 64 bit machine. Please
suggest another solution for this error.
I am using this code for scanning ,
this code is working perfectly on 32 bit Machine but I am switching my
application to 64 Bit machine where I am getting an error .I searched a
lot and found many solutions ,
common Solution I found that compile the application on 32 bit machine but
it does not improve my application performance so i do not want to use
this solution on 64-bit machine.
Error is :
An attempt was made to load a program with an incorrect format. (Exception
fromHRESULT: 0x8007000B)
Code is :
namespace TwainLib
{
public enum TwainCommand
{
Not = -1,
Null = 0,
TransferReady = 1,
CloseRequest = 2,
CloseOk = 3,
DeviceEvent = 4
}
public class Twain
{
private const short CountryUSA = 1;
private const short LanguageUSA = 13;
public Twain()
{
appid = new TwIdentity();
appid.Id = IntPtr.Zero;
appid.Version.MajorNum = 1;
appid.Version.MinorNum = 1;
appid.Version.Language = LanguageUSA;
appid.Version.Country = CountryUSA;
appid.Version.Info = "Hack 1";
appid.ProtocolMajor = TwProtocol.Major;
appid.ProtocolMinor = TwProtocol.Minor;
appid.SupportedGroups = (int)(TwDG.Image | TwDG.Control);
appid.Manufacturer = "NETMaster";
appid.ProductFamily = "Freeware";
appid.ProductName = "Hack";
srcds = new TwIdentity();
srcds.Id = IntPtr.Zero;
evtmsg.EventPtr = Marshal.AllocHGlobal(Marshal.SizeOf(winmsg));
}
~Twain()
{
Marshal.FreeHGlobal(evtmsg.EventPtr);
}
public void Init(IntPtr hwndp)
{
Finish();
TwRC rc = DSMparent(appid, IntPtr.Zero, TwDG.Control,
TwDAT.Parent, TwMSG.OpenDSM, ref hwndp);
if (rc == TwRC.Success)
{
rc = DSMident(appid, IntPtr.Zero, TwDG.Control,
TwDAT.Identity, TwMSG.GetDefault, srcds);
if (rc == TwRC.Success)
hwnd = hwndp;
else
rc = DSMparent(appid, IntPtr.Zero, TwDG.Control,
TwDAT.Parent, TwMSG.CloseDSM, ref hwndp);
}
}
public void Select()
{
TwRC rc;
CloseSrc();
if (appid.Id == IntPtr.Zero)
{
Init(hwnd);
if (appid.Id == IntPtr.Zero)
return;
}
rc = DSMident(appid, IntPtr.Zero, TwDG.Control, TwDAT.Identity,
TwMSG.UserSelect, srcds);
}
/// <summary>
/// Returns a list of twain sources
/// </summary>
/// <returns></returns>
public IEnumerable<TwIdentity> GetSources()
{
TwRC rc;
CloseSrc();
if (appid.Id == IntPtr.Zero)
{
Init(hwnd);
if (appid.Id == IntPtr.Zero)
return null;
}
List<TwIdentity> sources = new List<TwIdentity>();
TwIdentity identity = new TwIdentity();
rc = DSMident(appid, IntPtr.Zero, TwDG.Control, TwDAT.Identity,
TwMSG.GetFirst, identity);
while (rc == TwRC.Success)
{
sources.Add(identity);
identity = new TwIdentity();
rc = DSMident(appid, IntPtr.Zero, TwDG.Control,
TwDAT.Identity, TwMSG.GetNext, identity);
}
return sources;
}
/// <summary>
/// Sets the source from which images will be acquired
/// </summary>
/// <param name="Source_p"></param>
public void SetSource(TwIdentity Source_p)
{
srcds = Source_p;
}
public void Acquire()
{
TwRC rc;
CloseSrc();
if (appid.Id == IntPtr.Zero)
{
Init(hwnd);
if (appid.Id == IntPtr.Zero)
return;
}
rc = DSMident(appid, IntPtr.Zero, TwDG.Control, TwDAT.Identity,
TwMSG.OpenDS, srcds);
if (rc != TwRC.Success)
return;
TwCapability cap = new TwCapability(TwCap.XferCount, 1);
rc = DScap(appid, srcds, TwDG.Control, TwDAT.Capability,
TwMSG.Set, cap);
if (rc != TwRC.Success)
{
CloseSrc();
return;
}
TwUserInterface guif = new TwUserInterface();
guif.ShowUI = 1;
guif.ModalUI = 1;
guif.ParentHand = hwnd;
rc = DSuserif(appid, srcds, TwDG.Control, TwDAT.UserInterface,
TwMSG.EnableDS, guif);
if (rc != TwRC.Success)
{
CloseSrc();
return;
}
}
public List<IntPtr> TransferPictures()
{
List<IntPtr> pics = new List<IntPtr>();
if (srcds.Id == IntPtr.Zero)
return pics;
TwRC rc;
IntPtr hbitmap = IntPtr.Zero;
TwPendingXfers pxfr = new TwPendingXfers();
do
{
pxfr.Count = 0;
hbitmap = IntPtr.Zero;
TwImageInfo iinf = new TwImageInfo();
rc = DSiinf(appid, srcds, TwDG.Image, TwDAT.ImageInfo,
TwMSG.Get, iinf);
if (rc != TwRC.Success)
{
CloseSrc();
return pics;
}
rc = DSixfer(appid, srcds, TwDG.Image, TwDAT.ImageNativeXfer,
TwMSG.Get, ref hbitmap);
if (rc != TwRC.XferDone)
{
CloseSrc();
return pics;
}
rc = DSpxfer(appid, srcds, TwDG.Control, TwDAT.PendingXfers,
TwMSG.EndXfer, pxfr);
if (rc != TwRC.Success)
{
CloseSrc();
return pics;
}
pics.Add(hbitmap);
}
while (pxfr.Count != 0);
rc = DSpxfer(appid, srcds, TwDG.Control, TwDAT.PendingXfers,
TwMSG.Reset, pxfr);
return pics;
}
public TwainCommand PassMessage(ref Message m)
{
if (srcds.Id == IntPtr.Zero)
return TwainCommand.Not;
int pos = GetMessagePos();
winmsg.hwnd = m.HWnd;
winmsg.message = m.Msg;
winmsg.wParam = m.WParam;
winmsg.lParam = m.LParam;
winmsg.time = GetMessageTime();
winmsg.x = (short)pos;
winmsg.y = (short)(pos >> 16);
Marshal.StructureToPtr(winmsg, evtmsg.EventPtr, false);
evtmsg.Message = 0;
TwRC rc = DSevent(appid, srcds, TwDG.Control, TwDAT.Event,
TwMSG.ProcessEvent, ref evtmsg);
if (rc == TwRC.NotDSEvent)
return TwainCommand.Not;
if (evtmsg.Message == (short)TwMSG.XFerReady)
return TwainCommand.TransferReady;
if (evtmsg.Message == (short)TwMSG.CloseDSReq)
return TwainCommand.CloseRequest;
if (evtmsg.Message == (short)TwMSG.CloseDSOK)
return TwainCommand.CloseOk;
if (evtmsg.Message == (short)TwMSG.DeviceEvent)
return TwainCommand.DeviceEvent;
return TwainCommand.Null;
}
public void CloseSrc()
{
TwRC rc;
if (srcds.Id != IntPtr.Zero)
{
TwUserInterface guif = new TwUserInterface();
rc = DSuserif(appid, srcds, TwDG.Control, TwDAT.UserInterface,
TwMSG.DisableDS, guif);
rc = DSMident(appid, IntPtr.Zero, TwDG.Control,
TwDAT.Identity, TwMSG.CloseDS, srcds);
}
}
public void Finish()
{
TwRC rc;
CloseSrc();
if (appid.Id != IntPtr.Zero)
rc = DSMparent(appid, IntPtr.Zero, TwDG.Control, TwDAT.Parent,
TwMSG.CloseDSM, ref hwnd);
appid.Id = IntPtr.Zero;
}
private IntPtr hwnd;
private TwIdentity appid;
private TwIdentity srcds;
private TwEvent evtmsg;
private WINMSG winmsg;
// ------ DSM entry point DAT_ variants:
[DllImport("twain_32.dll", EntryPoint = "#1")]
private static extern TwRC DSMparent([In, Out] TwIdentity origin,
IntPtr zeroptr, TwDG dg, TwDAT dat, TwMSG msg, ref IntPtr refptr);
[DllImport("twain_32.dll", EntryPoint = "#1")]
private static extern TwRC DSMident([In, Out] TwIdentity origin,
IntPtr zeroptr, TwDG dg, TwDAT dat, TwMSG msg, [In, Out] TwIdentity
idds);
[DllImport("twain_32.dll", EntryPoint = "#1")]
private static extern TwRC DSMstatus([In, Out] TwIdentity origin,
IntPtr zeroptr, TwDG dg, TwDAT dat, TwMSG msg, [In, Out] TwStatus
dsmstat);
// ------ DSM entry point DAT_ variants to DS:
[DllImport("twain_32.dll", EntryPoint = "#1")]
private static extern TwRC DSuserif([In, Out] TwIdentity origin, [In,
Out] TwIdentity dest, TwDG dg, TwDAT dat, TwMSG msg, TwUserInterface
guif);
[DllImport("twain_32.dll", EntryPoint = "#1")]
private static extern TwRC DSevent([In, Out] TwIdentity origin, [In,
Out] TwIdentity dest, TwDG dg, TwDAT dat, TwMSG msg, ref TwEvent evt);
[DllImport("twain_32.dll", EntryPoint = "#1")]
private static extern TwRC DSstatus([In, Out] TwIdentity origin, [In]
TwIdentity dest, TwDG dg, TwDAT dat, TwMSG msg, [In, Out] TwStatus
dsmstat);
[DllImport("twain_32.dll", EntryPoint = "#1")]
private static extern TwRC DScap([In, Out] TwIdentity origin, [In]
TwIdentity dest, TwDG dg, TwDAT dat, TwMSG msg, [In, Out] TwCapability
capa);
[DllImport("twain_32.dll", EntryPoint = "#1")]
private static extern TwRC DSiinf([In, Out] TwIdentity origin, [In]
TwIdentity dest, TwDG dg, TwDAT dat, TwMSG msg, [In, Out] TwImageInfo
imginf);
[DllImport("twain_32.dll", EntryPoint = "#1")]
private static extern TwRC DSixfer([In, Out] TwIdentity origin, [In]
TwIdentity dest, TwDG dg, TwDAT dat, TwMSG msg, ref IntPtr hbitmap);
[DllImport("twain_32.dll", EntryPoint = "#1")]
private static extern TwRC DSpxfer([In, Out] TwIdentity origin, [In]
TwIdentity dest, TwDG dg, TwDAT dat, TwMSG msg, [In, Out]
TwPendingXfers pxfr);
[DllImport("kernel32.dll", ExactSpelling = true)]
internal static extern IntPtr GlobalAlloc(int flags, int size);
[DllImport("kernel32.dll", ExactSpelling = true)]
internal static extern IntPtr GlobalLock(IntPtr handle);
[DllImport("kernel32.dll", ExactSpelling = true)]
internal static extern bool GlobalUnlock(IntPtr handle);
[DllImport("kernel32.dll", ExactSpelling = true)]
internal static extern IntPtr GlobalFree(IntPtr handle);
[DllImport("user32.dll", ExactSpelling = true)]
private static extern int GetMessagePos();
[DllImport("user32.dll", ExactSpelling = true)]
private static extern int GetMessageTime();
[DllImport("gdi32.dll", ExactSpelling = true)]
private static extern int GetDeviceCaps(IntPtr hDC, int nIndex);
[DllImport("gdi32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr CreateDC(string szdriver, string
szdevice, string szoutput, IntPtr devmode);
[DllImport("gdi32.dll", ExactSpelling = true)]
private static extern bool DeleteDC(IntPtr hdc);
public static int ScreenBitDepth
{
get
{
IntPtr screenDC = CreateDC("DISPLAY", null, null, IntPtr.Zero);
int bitDepth = GetDeviceCaps(screenDC, 12);
bitDepth *= GetDeviceCaps(screenDC, 14);
DeleteDC(screenDC);
return bitDepth;
}
}
[StructLayout(LayoutKind.Sequential, Pack = 4)]
internal struct WINMSG
{
public IntPtr hwnd;
public int message;
public IntPtr wParam;
public IntPtr lParam;
public int time;
public int x;
public int y;
}
} // class Twain
}
As per my analysis this error occurred because of 64 bit machine. Please
suggest another solution for this error.
Sails.js - Controller is rendering view but the collection is undefined
Sails.js - Controller is rendering view but the collection is undefined
Trying out Sails with a new controller, but the view doesn't render
correctly. My controller looks like this:
/**
* QuestionController
*
* @module :: Controller
* @description :: Contains logic for handling requests.
*/
module.exports = {
/* e.g.
sayHello: function (req, res) {
res.send('hello world!');
}
*/
index: function (req, res) {
return res.view({
questions: [{title: 'Freddy a presidente?', content: 'Últimamente
Freddy se encuentra con más diplomacia.'}]
});
}
};
While my view looks like this:
<h1>Preguntas</h1>
<ul>
<% _.each(questions, function(question) { %>
<li><%= question.title %></li>
<% }) %>
</ul>
But I'm getting the following error:
ReferenceError:
/home/alainus/dev/parlamenta/parlamenta/views/question/index.ejs:3
1| <h1>Preguntas</h1>
2| <ul>
>> 3| <% _.each(questions, function(question) { %>
4| <li><%= question.title %></li>
5| <% }) %>
6| </ul>
questions is not defined
at eval (eval at <anonymous>
(/home/alainus/dev/parlamenta/parlamenta/node_modules/sails/node_modules/ejs/lib/ejs.js:236:14),
<anonymous>:29:68)
at eval (eval at <anonymous>
(/home/alainus/dev/parlamenta/parlamenta/node_modules/sails/node_modules/ejs/lib/ejs.js:236:14),
<anonymous>:29:228)
at
/home/alainus/dev/parlamenta/parlamenta/node_modules/sails/node_modules/ejs/lib/ejs.js:249:15
at Object.exports.render
(/home/alainus/dev/parlamenta/parlamenta/node_modules/sails/node_modules/ejs/lib/ejs.js:287:13)
at Object.exports.renderFile
(/home/alainus/dev/parlamenta/parlamenta/node_modules/sails/node_modules/ejs/lib/ejs.js:317:20)
at View.module.exports [as engine]
(/home/alainus/dev/parlamenta/parlamenta/node_modules/sails/node_modules/ejs-locals/index.js:85:7)
at View.render
(/home/alainus/dev/parlamenta/parlamenta/node_modules/sails/node_modules/express/lib/view.js:76:8)
at Function.app.render
(/home/alainus/dev/parlamenta/parlamenta/node_modules/sails/node_modules/express/lib/application.js:506:10)
at ServerResponse.res.render
(/home/alainus/dev/parlamenta/parlamenta/node_modules/sails/node_modules/express/lib/response.js:756:7)
at renderView
(/home/alainus/dev/parlamenta/parlamenta/node_modules/sails/lib/hooks/views/index.js:298:20)
at
/home/alainus/dev/parlamenta/parlamenta/node_modules/sails/lib/hooks/views/index.js:280:20
at Object.oncomplete (fs.js:107:15)
Any ideas on how to make this work?
Trying out Sails with a new controller, but the view doesn't render
correctly. My controller looks like this:
/**
* QuestionController
*
* @module :: Controller
* @description :: Contains logic for handling requests.
*/
module.exports = {
/* e.g.
sayHello: function (req, res) {
res.send('hello world!');
}
*/
index: function (req, res) {
return res.view({
questions: [{title: 'Freddy a presidente?', content: 'Últimamente
Freddy se encuentra con más diplomacia.'}]
});
}
};
While my view looks like this:
<h1>Preguntas</h1>
<ul>
<% _.each(questions, function(question) { %>
<li><%= question.title %></li>
<% }) %>
</ul>
But I'm getting the following error:
ReferenceError:
/home/alainus/dev/parlamenta/parlamenta/views/question/index.ejs:3
1| <h1>Preguntas</h1>
2| <ul>
>> 3| <% _.each(questions, function(question) { %>
4| <li><%= question.title %></li>
5| <% }) %>
6| </ul>
questions is not defined
at eval (eval at <anonymous>
(/home/alainus/dev/parlamenta/parlamenta/node_modules/sails/node_modules/ejs/lib/ejs.js:236:14),
<anonymous>:29:68)
at eval (eval at <anonymous>
(/home/alainus/dev/parlamenta/parlamenta/node_modules/sails/node_modules/ejs/lib/ejs.js:236:14),
<anonymous>:29:228)
at
/home/alainus/dev/parlamenta/parlamenta/node_modules/sails/node_modules/ejs/lib/ejs.js:249:15
at Object.exports.render
(/home/alainus/dev/parlamenta/parlamenta/node_modules/sails/node_modules/ejs/lib/ejs.js:287:13)
at Object.exports.renderFile
(/home/alainus/dev/parlamenta/parlamenta/node_modules/sails/node_modules/ejs/lib/ejs.js:317:20)
at View.module.exports [as engine]
(/home/alainus/dev/parlamenta/parlamenta/node_modules/sails/node_modules/ejs-locals/index.js:85:7)
at View.render
(/home/alainus/dev/parlamenta/parlamenta/node_modules/sails/node_modules/express/lib/view.js:76:8)
at Function.app.render
(/home/alainus/dev/parlamenta/parlamenta/node_modules/sails/node_modules/express/lib/application.js:506:10)
at ServerResponse.res.render
(/home/alainus/dev/parlamenta/parlamenta/node_modules/sails/node_modules/express/lib/response.js:756:7)
at renderView
(/home/alainus/dev/parlamenta/parlamenta/node_modules/sails/lib/hooks/views/index.js:298:20)
at
/home/alainus/dev/parlamenta/parlamenta/node_modules/sails/lib/hooks/views/index.js:280:20
at Object.oncomplete (fs.js:107:15)
Any ideas on how to make this work?
Listed Platforms in App Details for Facebook Developers
Listed Platforms in App Details for Facebook Developers
I can only see my website as a listed platform in the App Details page but
I need Android and also iOS to be listed. I have not submitted my facebook
app yet, how to I add these as listed platforms before i do
I can only see my website as a listed platform in the App Details page but
I need Android and also iOS to be listed. I have not submitted my facebook
app yet, how to I add these as listed platforms before i do
google drive error processing oauth 2 request 400
google drive error processing oauth 2 request 400
we have several google oauth2 refresh tokens for Google Drive for which we
always get the following error when trying to request a new access token:
POST /o/oauth2/token HTTP/1.1
Connection: close
accept-encoding: gzip, deflate
content-type: application/x-www-form-urlencoded
Content-Length: 208
Host: accounts.google.com
refresh_token=1%2FY5_2XY8uGujYa222rxXnsjR<snipped>&client_id=<clientid>&grant_type=refresh_token&client_secret=<clientsecret>
Response:
HTTP/1.1 400 Error processing OAuth 2 request
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: Fri, 01 Jan 1990 00:00:00 GMT
Date: Tue, 20 Aug 2013 14:55:24 GMT
<HTML>
<HEAD>
<TITLE>Error processing OAuth 2 request</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Error processing OAuth 2 request</H1>
<H2>Error 400</H2>
</BODY>
</HTML>
This only happens for some accounts, others work fine. The broken accounts
fail reproducibly across days and weeks. Is there something wrong with the
data we send? Any hint on what fails the validation?
I could provide you the tokens that are failing if necessary.
we have several google oauth2 refresh tokens for Google Drive for which we
always get the following error when trying to request a new access token:
POST /o/oauth2/token HTTP/1.1
Connection: close
accept-encoding: gzip, deflate
content-type: application/x-www-form-urlencoded
Content-Length: 208
Host: accounts.google.com
refresh_token=1%2FY5_2XY8uGujYa222rxXnsjR<snipped>&client_id=<clientid>&grant_type=refresh_token&client_secret=<clientsecret>
Response:
HTTP/1.1 400 Error processing OAuth 2 request
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: Fri, 01 Jan 1990 00:00:00 GMT
Date: Tue, 20 Aug 2013 14:55:24 GMT
<HTML>
<HEAD>
<TITLE>Error processing OAuth 2 request</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Error processing OAuth 2 request</H1>
<H2>Error 400</H2>
</BODY>
</HTML>
This only happens for some accounts, others work fine. The broken accounts
fail reproducibly across days and weeks. Is there something wrong with the
data we send? Any hint on what fails the validation?
I could provide you the tokens that are failing if necessary.
Adding and removing nodes and links from force diagram in d3 based on filter dropdown
Adding and removing nodes and links from force diagram in d3 based on
filter dropdown
I'm trying to make a force diagram, with a couple of drop down boxes which
filter the data on display. The first one (which is where I'm almost at
now) checks for the type, and only shows nodes & links which have a source
or target matching the type.
What I have now, is the ability to select the filter, and the graph
updates, it removes unnecessary nodes, and reformats the remaining ones to
be correct. But it only works the first time. If I 're-filter' it starts
to go haywire.
Here's my full code, I'm very new to javascript (&d3), and I've been
unashamedly stealing from bl.ocks.org, so please feel free to answer in
'noob'. Thanks in advance.
Also, I've put this on a jsfiddle: http://jsfiddle.net/J85Vu/
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Enterprise Collaboration Map</title>
<script type="text/javascript" src="d3.v3.js"></script>
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
<style type="text/css">
path.link {
fill: none;
stroke: #666;
stroke-width: 1.5px;
}
marker#a {
fill: green;
}
path.link.a {
stroke: green;
}
circle.a {
fill: green;
stroke: #333;
stroke-width: 1.5px;
}
marker#b {
fill: blue;
}
path.link.b {
stroke: blue;
}
circle.b {
fill: blue;
stroke: #333;
stroke-width: 1.5px;
}
marker#c {
fill: orange;
}
path.link.c {
stroke: orange;
}
circle.c {
fill: orange;
stroke: #333;
stroke-width: 1.5px;
}
circle {
fill: #ccc;
stroke: #333;
stroke-width: 1.5px;
}
text {
font: 10px sans-serif;
pointer-events: none;
}
text.shadow {
stroke: #fff;
stroke-width: 3px;
stroke-opacity: .8;
}
</style>
</head>
<body>
<select class="BU">
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
</select>
<script type="text/javascript">
var links = [
{source:"one",target:"two", type:"a", typeKBP:"a"},
{source:"two",target:"three", type:"a", typeKBP:"a"},
{source:"three",target:"four", type:"a", typeKBP:"a"},
{source:"four",target:"five", type:"a", typeKBP:"b"},
{source:"five",target:"six", type:"b", typeKBP:"b"},
{source:"six",target:"seven", type:"b", typeKBP:"b"},
{source:"seven",target:"eight", type:"b", typeKBP:"b"},
{source:"eight",target:"nine", type:"b", typeKBP:"c"},
{source:"nine",target:"ten", type:"c", typeKBP:"c"},
{source:"ten",target:"one", type:"c", typeKBP:"a"},
{source:"one",target:"three", type:"a", typeKBP:"a"},
{source:"two",target:"four", type:"a", typeKBP:"a"},
{source:"three",target:"five", type:"a", typeKBP:"b"},
{source:"four",target:"six", type:"a", typeKBP:"b"},
{source:"five",target:"seven", type:"b", typeKBP:"b"},
{source:"six",target:"eight", type:"b", typeKBP:"b"},
{source:"seven",target:"nine", type:"b", typeKBP:"c"},
{source:"eight",target:"ten", type:"b", typeKBP:"c"},
{source:"nine",target:"one", type:"c", typeKBP:"a"},
{source:"ten",target:"two", type:"c", typeKBP:"a"},
{source:"one",target:"four", type:"a", typeKBP:"a"},
{source:"two",target:"five", type:"a", typeKBP:"b"},
{source:"three",target:"six", type:"a", typeKBP:"b"},
{source:"four",target:"seven", type:"a", typeKBP:"b"},
{source:"five",target:"eight", type:"b", typeKBP:"b"},
{source:"six",target:"nine", type:"b", typeKBP:"c"},
{source:"seven",target:"ten", type:"b", typeKBP:"c"},
{source:"eight",target:"one", type:"b", typeKBP:"a"},
{source:"nine",target:"two", type:"c", typeKBP:"a"},
{source:"ten",target:"three", type:"c", typeKBP:"a"}
];
var inputlinks=[];
var nodes = {};
inputlinks.push(links);
// Compute the distinct nodes from the links.
links.forEach(function(link) {
link.source = nodes[link.source] || (nodes[link.source] = {name:
link.source, type:link.type});
link.target = nodes[link.target] || (nodes[link.target] = {name:
link.target, type:link.typeKBP});
});
var w = 1024,
h = 800;
//setup initial force layout
var force = d3.layout.force()
.gravity(0.4)
.size([w, h])
.nodes(d3.values(nodes))
.links(links)
.linkDistance(100)
.charge(-1000)
.on("tick", tick)
.start();
var svg = d3.select("body").append("svg:svg")
.attr("width", w)
.attr("height", h);
// Per-type markers, as they don't inherit styles.
svg.append("svg:defs").selectAll("marker")
.data(["a","b","c"])
.enter().append("svg:marker")
.attr("id", String)
.attr("viewBox", "0 -5 10 10")
.attr("refX", 15)
.attr("refY", -1.5)
.attr("markerWidth", 6)
.attr("markerHeight", 6)
.attr("orient", "auto")
.append("svg:path")
.attr("d", "M0,-5L10,0L0,5");
var path = svg.append("svg:g").selectAll("path")
.data(force.links())
.enter().append("svg:path")
.attr("class", function(d) { return "link " + d.type; })
.attr("marker-end", function(d) { return "url(#" + d.type +
")"; });
var circle = svg.append("svg:g").selectAll("circle")
.data(force.nodes())
.enter().append("svg:circle")
.attr("r", 6)
.attr("class", function(d) { return d.type; })
.call(force.drag);
var text = svg.append("svg:g").selectAll("g")
.data(force.nodes())
.enter().append("svg:g");
// A copy of the text with a thick white stroke for legibility.
text.append("svg:text")
.attr("x", 8)
.attr("y", ".31em")
.attr("class", "shadow")
.text(function(d) { return d.name; });
text.append("svg:text")
.attr("x", 8)
.attr("y", ".31em")
.attr("class","write")
.text(function(d) { return d.name; });
//jQuery update parts for drop downs.
$(document).ready(function(){
$('.BU').on('change',function(){
curBU=$('.BU').val();
//alert('The selected BU is ' + curBU);
//Filter links and rebuild nodes based on this.
minLinks={};
minLinks=links.filter(function(d){
if ((d.type==curBU) || (d.typeKBP==curBU)) {
return d
}
})
//new nodes
nodes2={};
nodes2=force.nodes().filter(function(d){return
d3.keys(minLinks.filter(function(e){return
e.source.name==d.name ||
e.target.name==d.name;})).length>0});
// minLinks.forEach(function(d) {
// d.source = nodes2[d.source] || (nodes2[d.source] =
{name: d.source, type:d.type});
// d.target = nodes2[d.target] || (nodes2[d.target] =
{name: d.target, type:d.typeKBP});
// });
force
.nodes(nodes2)
.links(minLinks)
.start();
//circle.remove();
newCirc=circle.data(force.nodes());
newCirc.enter().append("svg:circle")
.attr("r", 6)
.attr("class", function(d) { return d.type; })
.call(force.drag);
newCirc.exit().remove();
newPath=path.data(force.links());
newPath
.enter().append("svg:path")
.attr("class", function(d) { return "link " + d.type; })
.attr("marker-end", function(d) { return "url(#" +
d.type + ")"; });
newPath.exit().remove();
newText=text.data(force.nodes());
newText.exit().remove();
newText.select(".shadow").text(function(d){return d.name;});
newText.select(".write").text(function(d){return d.name;});
});
});
// Use elliptical arc path segments to doubly-encode directionality.
function tick() {
path.attr("d", function(d) {
var dx = d.target.x - d.source.x,
dy = d.target.y - d.source.y,
dr = Math.sqrt((dx * dx)/2 + (dy * dy));
return "M" + d.source.x + "," + d.source.y + "A" + dr + "," +
dr + " 0 0,1 " + d.target.x + "," + d.target.y;
});
circle.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
});
text.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
});
}
</script>
</body>
</html>
filter dropdown
I'm trying to make a force diagram, with a couple of drop down boxes which
filter the data on display. The first one (which is where I'm almost at
now) checks for the type, and only shows nodes & links which have a source
or target matching the type.
What I have now, is the ability to select the filter, and the graph
updates, it removes unnecessary nodes, and reformats the remaining ones to
be correct. But it only works the first time. If I 're-filter' it starts
to go haywire.
Here's my full code, I'm very new to javascript (&d3), and I've been
unashamedly stealing from bl.ocks.org, so please feel free to answer in
'noob'. Thanks in advance.
Also, I've put this on a jsfiddle: http://jsfiddle.net/J85Vu/
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Enterprise Collaboration Map</title>
<script type="text/javascript" src="d3.v3.js"></script>
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
<style type="text/css">
path.link {
fill: none;
stroke: #666;
stroke-width: 1.5px;
}
marker#a {
fill: green;
}
path.link.a {
stroke: green;
}
circle.a {
fill: green;
stroke: #333;
stroke-width: 1.5px;
}
marker#b {
fill: blue;
}
path.link.b {
stroke: blue;
}
circle.b {
fill: blue;
stroke: #333;
stroke-width: 1.5px;
}
marker#c {
fill: orange;
}
path.link.c {
stroke: orange;
}
circle.c {
fill: orange;
stroke: #333;
stroke-width: 1.5px;
}
circle {
fill: #ccc;
stroke: #333;
stroke-width: 1.5px;
}
text {
font: 10px sans-serif;
pointer-events: none;
}
text.shadow {
stroke: #fff;
stroke-width: 3px;
stroke-opacity: .8;
}
</style>
</head>
<body>
<select class="BU">
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
</select>
<script type="text/javascript">
var links = [
{source:"one",target:"two", type:"a", typeKBP:"a"},
{source:"two",target:"three", type:"a", typeKBP:"a"},
{source:"three",target:"four", type:"a", typeKBP:"a"},
{source:"four",target:"five", type:"a", typeKBP:"b"},
{source:"five",target:"six", type:"b", typeKBP:"b"},
{source:"six",target:"seven", type:"b", typeKBP:"b"},
{source:"seven",target:"eight", type:"b", typeKBP:"b"},
{source:"eight",target:"nine", type:"b", typeKBP:"c"},
{source:"nine",target:"ten", type:"c", typeKBP:"c"},
{source:"ten",target:"one", type:"c", typeKBP:"a"},
{source:"one",target:"three", type:"a", typeKBP:"a"},
{source:"two",target:"four", type:"a", typeKBP:"a"},
{source:"three",target:"five", type:"a", typeKBP:"b"},
{source:"four",target:"six", type:"a", typeKBP:"b"},
{source:"five",target:"seven", type:"b", typeKBP:"b"},
{source:"six",target:"eight", type:"b", typeKBP:"b"},
{source:"seven",target:"nine", type:"b", typeKBP:"c"},
{source:"eight",target:"ten", type:"b", typeKBP:"c"},
{source:"nine",target:"one", type:"c", typeKBP:"a"},
{source:"ten",target:"two", type:"c", typeKBP:"a"},
{source:"one",target:"four", type:"a", typeKBP:"a"},
{source:"two",target:"five", type:"a", typeKBP:"b"},
{source:"three",target:"six", type:"a", typeKBP:"b"},
{source:"four",target:"seven", type:"a", typeKBP:"b"},
{source:"five",target:"eight", type:"b", typeKBP:"b"},
{source:"six",target:"nine", type:"b", typeKBP:"c"},
{source:"seven",target:"ten", type:"b", typeKBP:"c"},
{source:"eight",target:"one", type:"b", typeKBP:"a"},
{source:"nine",target:"two", type:"c", typeKBP:"a"},
{source:"ten",target:"three", type:"c", typeKBP:"a"}
];
var inputlinks=[];
var nodes = {};
inputlinks.push(links);
// Compute the distinct nodes from the links.
links.forEach(function(link) {
link.source = nodes[link.source] || (nodes[link.source] = {name:
link.source, type:link.type});
link.target = nodes[link.target] || (nodes[link.target] = {name:
link.target, type:link.typeKBP});
});
var w = 1024,
h = 800;
//setup initial force layout
var force = d3.layout.force()
.gravity(0.4)
.size([w, h])
.nodes(d3.values(nodes))
.links(links)
.linkDistance(100)
.charge(-1000)
.on("tick", tick)
.start();
var svg = d3.select("body").append("svg:svg")
.attr("width", w)
.attr("height", h);
// Per-type markers, as they don't inherit styles.
svg.append("svg:defs").selectAll("marker")
.data(["a","b","c"])
.enter().append("svg:marker")
.attr("id", String)
.attr("viewBox", "0 -5 10 10")
.attr("refX", 15)
.attr("refY", -1.5)
.attr("markerWidth", 6)
.attr("markerHeight", 6)
.attr("orient", "auto")
.append("svg:path")
.attr("d", "M0,-5L10,0L0,5");
var path = svg.append("svg:g").selectAll("path")
.data(force.links())
.enter().append("svg:path")
.attr("class", function(d) { return "link " + d.type; })
.attr("marker-end", function(d) { return "url(#" + d.type +
")"; });
var circle = svg.append("svg:g").selectAll("circle")
.data(force.nodes())
.enter().append("svg:circle")
.attr("r", 6)
.attr("class", function(d) { return d.type; })
.call(force.drag);
var text = svg.append("svg:g").selectAll("g")
.data(force.nodes())
.enter().append("svg:g");
// A copy of the text with a thick white stroke for legibility.
text.append("svg:text")
.attr("x", 8)
.attr("y", ".31em")
.attr("class", "shadow")
.text(function(d) { return d.name; });
text.append("svg:text")
.attr("x", 8)
.attr("y", ".31em")
.attr("class","write")
.text(function(d) { return d.name; });
//jQuery update parts for drop downs.
$(document).ready(function(){
$('.BU').on('change',function(){
curBU=$('.BU').val();
//alert('The selected BU is ' + curBU);
//Filter links and rebuild nodes based on this.
minLinks={};
minLinks=links.filter(function(d){
if ((d.type==curBU) || (d.typeKBP==curBU)) {
return d
}
})
//new nodes
nodes2={};
nodes2=force.nodes().filter(function(d){return
d3.keys(minLinks.filter(function(e){return
e.source.name==d.name ||
e.target.name==d.name;})).length>0});
// minLinks.forEach(function(d) {
// d.source = nodes2[d.source] || (nodes2[d.source] =
{name: d.source, type:d.type});
// d.target = nodes2[d.target] || (nodes2[d.target] =
{name: d.target, type:d.typeKBP});
// });
force
.nodes(nodes2)
.links(minLinks)
.start();
//circle.remove();
newCirc=circle.data(force.nodes());
newCirc.enter().append("svg:circle")
.attr("r", 6)
.attr("class", function(d) { return d.type; })
.call(force.drag);
newCirc.exit().remove();
newPath=path.data(force.links());
newPath
.enter().append("svg:path")
.attr("class", function(d) { return "link " + d.type; })
.attr("marker-end", function(d) { return "url(#" +
d.type + ")"; });
newPath.exit().remove();
newText=text.data(force.nodes());
newText.exit().remove();
newText.select(".shadow").text(function(d){return d.name;});
newText.select(".write").text(function(d){return d.name;});
});
});
// Use elliptical arc path segments to doubly-encode directionality.
function tick() {
path.attr("d", function(d) {
var dx = d.target.x - d.source.x,
dy = d.target.y - d.source.y,
dr = Math.sqrt((dx * dx)/2 + (dy * dy));
return "M" + d.source.x + "," + d.source.y + "A" + dr + "," +
dr + " 0 0,1 " + d.target.x + "," + d.target.y;
});
circle.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
});
text.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
});
}
</script>
</body>
</html>
Subscribe to:
Comments (Atom)