Ssh X11 forwarding very slow using Xshell
My server is Ubuntu 12.10
And my client is Windows 7 64bit
Now I am using Xshell to connect my server via ssh
But after I forwarding X11, it's take a long time!!
after I enter
$matlab -nodesktop
it's almost take 5~10 mins to ready for use
I have found some speed up issue on the web but it's work on MAC not on
windows(Xshell)!
following is solution for mac and it's worked perfect!
ssh -c arcfour,blowfish-cbc -XC username@host
But when I use Xshell it's always think -c arcfour,blowfish-cbc -XC
usernameis my username!
Is there any other way to make it faster?
Monday, 30 September 2013
What changes in Ubuntu 12.10 as a VM?
What changes in Ubuntu 12.10 as a VM?
I compiled a small "hello world" C program on Ubuntu 10.04 32 bit machine.
Then I put the executable(a.out) on Ubuntu 12.10(64 bit) VMWare virtual
machine and tried to execute it(./a.out). The OS does not identify the
file and says 'No such file or directory'. But when I put the same
executable on a Ubuntu 12.10(64 bit) running on a 64 bit laptop, it runs
fine and I get the desired output. The VM is running on IBM Blade Servers.
I wanted to know why the results for a VM?
I compiled a small "hello world" C program on Ubuntu 10.04 32 bit machine.
Then I put the executable(a.out) on Ubuntu 12.10(64 bit) VMWare virtual
machine and tried to execute it(./a.out). The OS does not identify the
file and says 'No such file or directory'. But when I put the same
executable on a Ubuntu 12.10(64 bit) running on a 64 bit laptop, it runs
fine and I get the desired output. The VM is running on IBM Blade Servers.
I wanted to know why the results for a VM?
Python tkiner grid_forget()
Python tkiner grid_forget()
I have a problem with grid_forget() ,because i want to appear and
disappear a Label, this is part of the code:
def creabackuno():
showinfo( "Wait..","I am creating the backup, please wait...")
vsl=Label(gui,text="Working, please
wait...",font=("arial",16)).grid(row=20,rowspan=1,column=0,columnspan=1,padx=10,sticky=N)
try:
copytree(path,r"backup\dirbackup1\.minecraft")
showinfo( "OK!","Backup (1) created!")
vsl.grid_forget()
except OSError:
showerror( "Nope!","There is already a backup to restore")
vsl.grid_forget()
And this is the error of the console:
AttributeError: 'NoneType' object has no attribute 'grid_forget'
I'm using python 2.7.5 thanks!
I have a problem with grid_forget() ,because i want to appear and
disappear a Label, this is part of the code:
def creabackuno():
showinfo( "Wait..","I am creating the backup, please wait...")
vsl=Label(gui,text="Working, please
wait...",font=("arial",16)).grid(row=20,rowspan=1,column=0,columnspan=1,padx=10,sticky=N)
try:
copytree(path,r"backup\dirbackup1\.minecraft")
showinfo( "OK!","Backup (1) created!")
vsl.grid_forget()
except OSError:
showerror( "Nope!","There is already a backup to restore")
vsl.grid_forget()
And this is the error of the console:
AttributeError: 'NoneType' object has no attribute 'grid_forget'
I'm using python 2.7.5 thanks!
How is the position of an array pointer determined in a preg_replace_callback's callback function with an array of subjects?
How is the position of an array pointer determined in a
preg_replace_callback's callback function with an array of subjects?
e.g.
$array = preg_replace_callback("/pattern/", create_function( '$matches',
'[WHAT IS MY ARRAY POSITION? ($foo = ...)]; return $foo);' ), $array);
preg_replace_callback's callback function with an array of subjects?
e.g.
$array = preg_replace_callback("/pattern/", create_function( '$matches',
'[WHAT IS MY ARRAY POSITION? ($foo = ...)]; return $foo);' ), $array);
Sunday, 29 September 2013
Checking an array list of strings for substring
Checking an array list of strings for substring
I need to write a public method that takes an array of strings and checks
to see if there are any strings in the array that contain the substring or
string "nine". I wrote a method to check for "nine" but I'm stumped for
the substring.
public static boolean doesFive ( String [] input ) {
boolean rez = false;
String n = "nine";
for( int i = 0; i < inputArray.length - 1; i++ ) {
if( inputArray[i].equals(n) ) {
rez = true;
}
}
return rez;
}
I need to write a public method that takes an array of strings and checks
to see if there are any strings in the array that contain the substring or
string "nine". I wrote a method to check for "nine" but I'm stumped for
the substring.
public static boolean doesFive ( String [] input ) {
boolean rez = false;
String n = "nine";
for( int i = 0; i < inputArray.length - 1; i++ ) {
if( inputArray[i].equals(n) ) {
rez = true;
}
}
return rez;
}
Google Analytics: export every visitor
Google Analytics: export every visitor
I'm looking for a method to export every unique visitor from Google
Analytics. So, a visitor could open a website for multiple times, I would
like to export a single row with some information about the visits like
mean time on the website, number of purchases, mean order amount etc.
Thanks in advance.
I'm looking for a method to export every unique visitor from Google
Analytics. So, a visitor could open a website for multiple times, I would
like to export a single row with some information about the visits like
mean time on the website, number of purchases, mean order amount etc.
Thanks in advance.
jquery return only text from filtered results
jquery return only text from filtered results
my html filtered is giving me
$.get(myURL, function(data) {
$(data).find("td.Chats").filter(':gt(5)').appendTo('#regions');
}, 'html')
results:
<td class="Chats">Item 1</td>
<td class="Chats"></td>
<td class="Chats"></td>
<td class="Chats"></td>
<td class="Chats"></td>
<td class="Chats">Item 2</td>
<td class="Chats"></td>
<td class="Chats"></td>
<td class="Chats"></td>
<td class="Chats"></td>
<td class="Chats">Item 3</td>
<td class="Chats"></td>
<td class="Chats"></td>
<td class="Chats"></td>
<td class="Chats"></td>
How would I just get the elements with text? or every 5th ?
my html filtered is giving me
$.get(myURL, function(data) {
$(data).find("td.Chats").filter(':gt(5)').appendTo('#regions');
}, 'html')
results:
<td class="Chats">Item 1</td>
<td class="Chats"></td>
<td class="Chats"></td>
<td class="Chats"></td>
<td class="Chats"></td>
<td class="Chats">Item 2</td>
<td class="Chats"></td>
<td class="Chats"></td>
<td class="Chats"></td>
<td class="Chats"></td>
<td class="Chats">Item 3</td>
<td class="Chats"></td>
<td class="Chats"></td>
<td class="Chats"></td>
<td class="Chats"></td>
How would I just get the elements with text? or every 5th ?
What the difference between SerialPort control and SerialPort class in .Net
What the difference between SerialPort control and SerialPort class in .Net
I am using c# serialPort to communication with inverter that is used in
solar power station.
Now I have a issue: when I use SerialPort control dragged from toolbox,
the DataReceived event will no be fired, but when trun to use SerialPort
class, it is working.
Can anybody please kindly tell me something about it, thank you very much!
I am using c# serialPort to communication with inverter that is used in
solar power station.
Now I have a issue: when I use SerialPort control dragged from toolbox,
the DataReceived event will no be fired, but when trun to use SerialPort
class, it is working.
Can anybody please kindly tell me something about it, thank you very much!
Saturday, 28 September 2013
Cannot use alert() in a jQuery method
Cannot use alert() in a jQuery method
When using jQuery to make an AJAX call, for the time being I want to just
want to have a popup box (using alert()) showing me the response text.
$(document).ready(function() {
$(".jeobutton").mouseup(function() {
var $button = $(this);
$.ajax({ url: 'getdata.php',
data: // <parameters>
type: 'get',
dataType: 'json',
success: function(output) {
// do something
},
error: function(xhr) {
alert("<some error>");
console.error(xhr.responseText);
}
});
});
});
The response text prints out fine. However, the alert() dialog is nowhere
to be found.
Please help this poor noob.
When using jQuery to make an AJAX call, for the time being I want to just
want to have a popup box (using alert()) showing me the response text.
$(document).ready(function() {
$(".jeobutton").mouseup(function() {
var $button = $(this);
$.ajax({ url: 'getdata.php',
data: // <parameters>
type: 'get',
dataType: 'json',
success: function(output) {
// do something
},
error: function(xhr) {
alert("<some error>");
console.error(xhr.responseText);
}
});
});
});
The response text prints out fine. However, the alert() dialog is nowhere
to be found.
Please help this poor noob.
Missing package in Google IO application code
Missing package in Google IO application code
I download the code of iosched(Google I/O App for Android) application and
tried to run it, but i can't find the
com.google.api.services.googledevelopers.model package nor
com.google.api.services.googledevelopers package in the first place,
neither on the website itself nor over the internet. can anyone please
point that out. thank you :)
I download the code of iosched(Google I/O App for Android) application and
tried to run it, but i can't find the
com.google.api.services.googledevelopers.model package nor
com.google.api.services.googledevelopers package in the first place,
neither on the website itself nor over the internet. can anyone please
point that out. thank you :)
Remove empty space from the end of a line in a richtextbox
Remove empty space from the end of a line in a richtextbox
How can I remove empty space from end of line in a richtextbox
Original string
ALTER TABLE "TBLCONCESSIONAIREOFFICES" ADD ("CNCO_IRISAUTOCONFIRMINVOICE"
NUMBER(2,0) DEFAULT 0 --0: No, 1: Yes;
);
Expected result:
ALTER TABLE "TBLCONCESSIONAIREOFFICES" ADD
("CNCO_IRISAUTOCONFIRMINVOICE" NUMBER(2,0) DEFAULT 0 --0: No, 1:
Yes);
My code:
string[] lines2 = comparedResultRTB1.Lines;
lines2.ToString().Replace("; );",");");
How can I remove empty space from end of line in a richtextbox
Original string
ALTER TABLE "TBLCONCESSIONAIREOFFICES" ADD ("CNCO_IRISAUTOCONFIRMINVOICE"
NUMBER(2,0) DEFAULT 0 --0: No, 1: Yes;
);
Expected result:
ALTER TABLE "TBLCONCESSIONAIREOFFICES" ADD
("CNCO_IRISAUTOCONFIRMINVOICE" NUMBER(2,0) DEFAULT 0 --0: No, 1:
Yes);
My code:
string[] lines2 = comparedResultRTB1.Lines;
lines2.ToString().Replace("; );",");");
Cannot compile Mono.Addins
Cannot compile Mono.Addins
I've tried to compile the current version of Mono.Addins, but it failed
with the following error messages:
Building Mono.Addins.Gui.csproj
/usr/lib/mono/4.0/Microsoft.Common.targets: warning : Reference
'glib-sharp, Version=2.12.0.0, Culture=neutral,
PublicKeyToken=35e10195dab3c99f' not resolved
/usr/lib/mono/4.0/Microsoft.Common.targets: warning : Reference
'pango-sharp, Version=2.12.0.0, Culture=neutral,
PublicKeyToken=35e10195dab3c99f' not resolved
/usr/lib/mono/4.0/Microsoft.Common.targets: warning : Reference
'atk-sharp, Version=2.12.0.0, Culture=neutral,
PublicKeyToken=35e10195dab3c99f' not resolved
/usr/lib/mono/4.0/Microsoft.Common.targets: warning : Reference
'gdk-sharp, Version=2.12.0.0, Culture=neutral,
PublicKeyToken=35e10195dab3c99f' not resolved
/usr/lib/mono/4.0/Microsoft.Common.targets: warning : Reference
'gtk-sharp, Version=2.12.0.0, Culture=neutral,
PublicKeyToken=35e10195dab3c99f' not resolved
Mono.Addins.Gui/AddinManagerDialog.cs(30,7): error CS0246: The type or
namespace name Gtk' could not be found. Are you missing an assembly
reference?
Mono.Addins.Gui/AddinTreeWidget.cs(32,7): error CS0246: The type or
namespace nameGtk' could not be found. Are you missing an assembly
reference?
Mono.Addins.Gui/AddinTreeWidget.cs(33,7): error CS0246: The type or
namespace name Gdk' could not be found. Are you missing an assembly
reference?
Mono.Addins.Gui/ManageSitesDialog.cs(31,7): error CS0246: The type or
namespace nameGtk' could not be found. Are you missing an assembly
reference?
I've alread installed the current versions of Mono and Gtk# from sources.
Any idea what's going wrong?
I've tried to compile the current version of Mono.Addins, but it failed
with the following error messages:
Building Mono.Addins.Gui.csproj
/usr/lib/mono/4.0/Microsoft.Common.targets: warning : Reference
'glib-sharp, Version=2.12.0.0, Culture=neutral,
PublicKeyToken=35e10195dab3c99f' not resolved
/usr/lib/mono/4.0/Microsoft.Common.targets: warning : Reference
'pango-sharp, Version=2.12.0.0, Culture=neutral,
PublicKeyToken=35e10195dab3c99f' not resolved
/usr/lib/mono/4.0/Microsoft.Common.targets: warning : Reference
'atk-sharp, Version=2.12.0.0, Culture=neutral,
PublicKeyToken=35e10195dab3c99f' not resolved
/usr/lib/mono/4.0/Microsoft.Common.targets: warning : Reference
'gdk-sharp, Version=2.12.0.0, Culture=neutral,
PublicKeyToken=35e10195dab3c99f' not resolved
/usr/lib/mono/4.0/Microsoft.Common.targets: warning : Reference
'gtk-sharp, Version=2.12.0.0, Culture=neutral,
PublicKeyToken=35e10195dab3c99f' not resolved
Mono.Addins.Gui/AddinManagerDialog.cs(30,7): error CS0246: The type or
namespace name Gtk' could not be found. Are you missing an assembly
reference?
Mono.Addins.Gui/AddinTreeWidget.cs(32,7): error CS0246: The type or
namespace nameGtk' could not be found. Are you missing an assembly
reference?
Mono.Addins.Gui/AddinTreeWidget.cs(33,7): error CS0246: The type or
namespace name Gdk' could not be found. Are you missing an assembly
reference?
Mono.Addins.Gui/ManageSitesDialog.cs(31,7): error CS0246: The type or
namespace nameGtk' could not be found. Are you missing an assembly
reference?
I've alread installed the current versions of Mono and Gtk# from sources.
Any idea what's going wrong?
Friday, 27 September 2013
Dismissing Popover View with Storyboard Segues
Dismissing Popover View with Storyboard Segues
I've been googling and searching all over stack exchange for the right
answer, but I can't seem to find it. What I have is a popover view that is
presented via a popover segue, and when a button is clicked inside the
popover view, I want it to be dismissed and display a UIAlert. Here is the
code I have thus far, with what I have gathered from other answers but
dosn't work:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:@"popOverSegue"]) {
if ([segue isKindOfClass:[UIStoryboardPopoverSegue class]]) {
UIStoryboardPopoverSegue *popoverSegue = (UIStoryboardPopoverSegue
*)segue;
self.myPopoverController = popoverSegue.popoverController;
}
}
}
- (void)methodThatShouldCauseMyPopoverToCloseAnimated:(BOOL)animated
{
[self.myPopoverController dismissPopoverAnimated:animated];
NSLog(@"Dismissed");
}
-(IBAction)presentPopoverView:(id)sender {
if (!popOverViewIsShown){
[self performSegueWithIdentifier:@"popOverSegue" sender:self];
popOverViewIsShown = YES;
}else {
[self methodThatShouldCauseMyPopoverToCloseAnimated:YES];
popOverViewIsShown = NO;
}
}
- (IBAction)logoutMethod:(id)sender {
[self methodThatShouldCauseMyPopoverToCloseAnimated:YES];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Logout"
message:@"Are you sure?"
delegate:self
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"OK", nil];
alert.tag = 0;
[alert show];
}
I'm suspecting that when I call methodThatShouldCauseMyPopoverToClose that
myPopoverController is equal to nil. Any suggestions? Thank you so much!
:)
I've been googling and searching all over stack exchange for the right
answer, but I can't seem to find it. What I have is a popover view that is
presented via a popover segue, and when a button is clicked inside the
popover view, I want it to be dismissed and display a UIAlert. Here is the
code I have thus far, with what I have gathered from other answers but
dosn't work:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:@"popOverSegue"]) {
if ([segue isKindOfClass:[UIStoryboardPopoverSegue class]]) {
UIStoryboardPopoverSegue *popoverSegue = (UIStoryboardPopoverSegue
*)segue;
self.myPopoverController = popoverSegue.popoverController;
}
}
}
- (void)methodThatShouldCauseMyPopoverToCloseAnimated:(BOOL)animated
{
[self.myPopoverController dismissPopoverAnimated:animated];
NSLog(@"Dismissed");
}
-(IBAction)presentPopoverView:(id)sender {
if (!popOverViewIsShown){
[self performSegueWithIdentifier:@"popOverSegue" sender:self];
popOverViewIsShown = YES;
}else {
[self methodThatShouldCauseMyPopoverToCloseAnimated:YES];
popOverViewIsShown = NO;
}
}
- (IBAction)logoutMethod:(id)sender {
[self methodThatShouldCauseMyPopoverToCloseAnimated:YES];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Logout"
message:@"Are you sure?"
delegate:self
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"OK", nil];
alert.tag = 0;
[alert show];
}
I'm suspecting that when I call methodThatShouldCauseMyPopoverToClose that
myPopoverController is equal to nil. Any suggestions? Thank you so much!
:)
Is it possible to set a local notification badge with out the user ever launching the app?
Is it possible to set a local notification badge with out the user ever
launching the app?
I am trying to grab the users attention of the fact my app has updated.
Only now with automatic updates in iOS7 users are less likely to open the
new updated version, let alone know it has updated if they just clear
their notification centres with out giving it a second thought.
My question is.... Is it possible in any way to set a badge on the icon of
my updated app with out the user ever launching the app first. Keeping in
mind I do not have push notifications set up and that wouldn't work unless
they were to open the app up and allow push notifications..making it
redundant in this case.
If it is not possible, do people have any other suggestions to grab
attention? So far I can only think of changing the icon design to a
noticeable enough point.
Thanks.
launching the app?
I am trying to grab the users attention of the fact my app has updated.
Only now with automatic updates in iOS7 users are less likely to open the
new updated version, let alone know it has updated if they just clear
their notification centres with out giving it a second thought.
My question is.... Is it possible in any way to set a badge on the icon of
my updated app with out the user ever launching the app first. Keeping in
mind I do not have push notifications set up and that wouldn't work unless
they were to open the app up and allow push notifications..making it
redundant in this case.
If it is not possible, do people have any other suggestions to grab
attention? So far I can only think of changing the icon design to a
noticeable enough point.
Thanks.
Deployment best practices on production without GIT
Deployment best practices on production without GIT
I have a Production server that I currently deploy my code manually with
sftp. I'd like to improve this deployment process but the Production
server does not have GIT installed and installing is not an option at this
time.
I'm looking for advice on best practices and common tools to make my
deployments simple, mistake proof and partially automated.
I have develop and master branches in my GIT repo. Master branch is always
an exact replica of the Production server. Whenever I'm happy with the
state of develop, I merge changes into master, lookup the list of files
that changed and manually copy them over via sftp.
I would like to improve this process and do following:
Go and create some sort of backup of the live site's main folder.
Have some script that automatically checks what changed in masters last
commit and uploads files via ssh to the Production server.
Allows me to revert back changes is something went wrong (hence step 1)
Are there tools, scripts or procedures you use to do something similar?
Thanks?
I have a Production server that I currently deploy my code manually with
sftp. I'd like to improve this deployment process but the Production
server does not have GIT installed and installing is not an option at this
time.
I'm looking for advice on best practices and common tools to make my
deployments simple, mistake proof and partially automated.
I have develop and master branches in my GIT repo. Master branch is always
an exact replica of the Production server. Whenever I'm happy with the
state of develop, I merge changes into master, lookup the list of files
that changed and manually copy them over via sftp.
I would like to improve this process and do following:
Go and create some sort of backup of the live site's main folder.
Have some script that automatically checks what changed in masters last
commit and uploads files via ssh to the Production server.
Allows me to revert back changes is something went wrong (hence step 1)
Are there tools, scripts or procedures you use to do something similar?
Thanks?
OAuth access token and refresh token generation
OAuth access token and refresh token generation
I'm implementing my own OAuth authentication system (with refresh_token
support) for an app and I have some questions about how to do it:
Client identification: The client is registered in the auth server and
gets a client_id and a client_secret. How do I generate it? is there some
kind of relation between both values?.
User authentication: The client sends the users_credentials
(username+password for example) + client_id and gets a refresh_token and
(temp?)access_token. That access_token is the one I should use in further
request or I should use a
accesss_token`=F(refresh_token,access_token,client_secret). In the second
case what does the F function consist on?
Access token refresh: The client send client_id, refresh_token and gets a
access_token (and a optional new refresh_token). Does the access_token
need the same conversion (whatever it be), as in the point 2?
Complete answers and concrete examples will be "bountied"
I'm implementing my own OAuth authentication system (with refresh_token
support) for an app and I have some questions about how to do it:
Client identification: The client is registered in the auth server and
gets a client_id and a client_secret. How do I generate it? is there some
kind of relation between both values?.
User authentication: The client sends the users_credentials
(username+password for example) + client_id and gets a refresh_token and
(temp?)access_token. That access_token is the one I should use in further
request or I should use a
accesss_token`=F(refresh_token,access_token,client_secret). In the second
case what does the F function consist on?
Access token refresh: The client send client_id, refresh_token and gets a
access_token (and a optional new refresh_token). Does the access_token
need the same conversion (whatever it be), as in the point 2?
Complete answers and concrete examples will be "bountied"
Performance difference in Jython and Java implementations of a turbo decoder
Performance difference in Jython and Java implementations of a turbo decoder
I'm currently making a Computer Science thesis on a multithreaded software
implementation of a turbo decoder. The basic problem is as follows:
let (y1, ..., yn) be the sequence of noisy bit received through a channel.
Two SISO decoders work in parallel (each one receiving the first bit of
the sequence and the parity bit y1j, j in {1,2}) - the objective is to
compute the LLR (log-likelyhood ratio, which gives info on the probability
that the current bit is either 0 or 1), which is then fed to the other
SISO decoder for the next iteration. Suppose the received bits are split
into shorter frames of data. (SISO means soft input, soft output, beacause
each encoder gets an estimation of the bit probabilities in input and
outputs its own estimation)
Each computation of the LLR requires lots of serialized ACS operations,
depending on the amount of the bits in each frames (and on the amount of
bits used by the encoder to make the parity bits for the initial
sequence). Such computation can be summed with these nested for cycles
(for each one of the two SISO decoders working in parallel):
for i=1 to N_FRAMES:
for j=1 to N_ELS_FRAMES:
for k=1 to 4:
for l=1 to N_STATES:
do_ops()
Note that the above loop doesn't actually appear in the algorithm, but it
does match quite closely the operations made for each iteration.
Generally, N_STATES is around 12 or 24 (it depends on the amount of bits
each encoder uses to compute the parity bits on the input sequence) and
do_ops() requires a sum, a max and a vector normalization.
At first I tried to make an implementation using Jython, but the result
was pretty disheartening: the operations in the nested loops above took -
with the multithreaded version - around 20 minutes (!) with a moderate (~2
mil) amount of bits.
On the other hand, a Java implementation requires ~1 sec with ~4 mil bits
using the single-threaded version of the algorithm.
Why is there such a huge difference?
I'm currently making a Computer Science thesis on a multithreaded software
implementation of a turbo decoder. The basic problem is as follows:
let (y1, ..., yn) be the sequence of noisy bit received through a channel.
Two SISO decoders work in parallel (each one receiving the first bit of
the sequence and the parity bit y1j, j in {1,2}) - the objective is to
compute the LLR (log-likelyhood ratio, which gives info on the probability
that the current bit is either 0 or 1), which is then fed to the other
SISO decoder for the next iteration. Suppose the received bits are split
into shorter frames of data. (SISO means soft input, soft output, beacause
each encoder gets an estimation of the bit probabilities in input and
outputs its own estimation)
Each computation of the LLR requires lots of serialized ACS operations,
depending on the amount of the bits in each frames (and on the amount of
bits used by the encoder to make the parity bits for the initial
sequence). Such computation can be summed with these nested for cycles
(for each one of the two SISO decoders working in parallel):
for i=1 to N_FRAMES:
for j=1 to N_ELS_FRAMES:
for k=1 to 4:
for l=1 to N_STATES:
do_ops()
Note that the above loop doesn't actually appear in the algorithm, but it
does match quite closely the operations made for each iteration.
Generally, N_STATES is around 12 or 24 (it depends on the amount of bits
each encoder uses to compute the parity bits on the input sequence) and
do_ops() requires a sum, a max and a vector normalization.
At first I tried to make an implementation using Jython, but the result
was pretty disheartening: the operations in the nested loops above took -
with the multithreaded version - around 20 minutes (!) with a moderate (~2
mil) amount of bits.
On the other hand, a Java implementation requires ~1 sec with ~4 mil bits
using the single-threaded version of the algorithm.
Why is there such a huge difference?
How to Create HTML Popup window on Joomla Homepage?
How to Create HTML Popup window on Joomla Homepage?
I need HTML popup in Joomla2.5 Home Page. Please refer suitable modules or
plugins in joomla2.5
I need HTML popup in Joomla2.5 Home Page. Please refer suitable modules or
plugins in joomla2.5
Thursday, 26 September 2013
Difference Between Gemfile and Gemfile.lock?
Difference Between Gemfile and Gemfile.lock?
I am a beginner in Ruby on Rails and I'm Using Rails4
What is the difference between Gemfile and Gemfile.lock in Rails?
I am a beginner in Ruby on Rails and I'm Using Rails4
What is the difference between Gemfile and Gemfile.lock in Rails?
Wednesday, 25 September 2013
How to Connect 3 PC's in one network
How to Connect 3 PC's in one network
I have 3 PC's, where one PC is meant for server, where my application is
running with dongle. The other 2 PC's are my clients, where as i need to
access the server and run the application.
I have 3 PC's, where one PC is meant for server, where my application is
running with dongle. The other 2 PC's are my clients, where as i need to
access the server and run the application.
Thursday, 19 September 2013
css animations inside inline blocks
css animations inside inline blocks
I am currently building a template that will be the foundation on my new
website and have reached the point of adding the animations and other
'special effects'. For basis to my template I am using the Boilerplate
h5bp template and my header element is built of inline-blocks thus -
<header>
<div class="box" id="head-one">
<h1>Your name here</h1>
<h2>Click to call <a
href="tel:your-phone-number">your-phone</a> or <a
href="mailto:you@your-domain.what.where?subject=Message%20subject%20here&body=Some%20text%20to%20add%20to%20the%20message%20body.">Email
Us</a></h2>
<nav>
<ul class="menu">
<li><a href="index.html">Page 1</a></li>
<li><a href="accordion.html">Page 2</a></li>
<li><a href="boxs.html">Page 3</a></li>
<li><a href="images.html">Page 4</a></li>
</ul>
</nav>
</div><!-- close class box id head-one
--><div class="box" id="head-two"><!--
--><img id="logo-head" src="images/logo.svg" alt="Logo for
your web site">
</div><!-- close class box id head-two -->
</header>
This is how I have done the css alignment (The colours being used are
purely to highlight box sizes and alignments at this stage) -
header
{
border: 0.5em solid blue;
box-sizing: border-box;
-moz-box-sizing: border-box;
text-align: justify;
padding: 1em 0.5em 0em 0.5em;
margin: 5px auto;
}
nav,
ul.menu,
ul.menu li
{
display: inline-block;
}
#logo-head
{
width: 200px;
height: 200px;
padding: 0.5em;
}
div.box#head-two
{
width: 100%;
height: 100%;
text-align:center;
display: inline-block;
animation:logo 5s linear 0.3s 3;
-webkit-animation:logo 5s linear 0.3s 3;
}
@keyframes logo
{
0% {transform:rotate(0deg);}
25% {transform:rotate(90deg);}
50% {transform:rotate(180deg);}
100% {transform:rotate(360deg);}
}
@-webkit-keyframes logo
{
0% {-webkit-transform:rotate(0deg);}
25% {-webkit-transform:rotate(90deg);}
50% {-webkit-transform:rotate(180deg);}
100% {-webkit-transform:rotate(360deg);}
}
div.box#head-one
{
width: 75%;
text-align: center;
}
header::after
{
content: '';
width: 100%;
display: inline-block;
}
header div.box#head-one::before
{
content: '';
height: 100%;
width: 100%;
vertical-align: middle;
}
However the animation is pushing the logo contained in 'header
div.box#head-two' to the bottom of the header box instead of up on the
right side, without the animation the logo sits nicely vertically aligned
- middle and to the right of the rest of the header content.
How can I stop this basic animation from breaking my structure, this is an
important problem for me to solve on this project as page layouts depend
on the inline-block display value.
I am currently building a template that will be the foundation on my new
website and have reached the point of adding the animations and other
'special effects'. For basis to my template I am using the Boilerplate
h5bp template and my header element is built of inline-blocks thus -
<header>
<div class="box" id="head-one">
<h1>Your name here</h1>
<h2>Click to call <a
href="tel:your-phone-number">your-phone</a> or <a
href="mailto:you@your-domain.what.where?subject=Message%20subject%20here&body=Some%20text%20to%20add%20to%20the%20message%20body.">Email
Us</a></h2>
<nav>
<ul class="menu">
<li><a href="index.html">Page 1</a></li>
<li><a href="accordion.html">Page 2</a></li>
<li><a href="boxs.html">Page 3</a></li>
<li><a href="images.html">Page 4</a></li>
</ul>
</nav>
</div><!-- close class box id head-one
--><div class="box" id="head-two"><!--
--><img id="logo-head" src="images/logo.svg" alt="Logo for
your web site">
</div><!-- close class box id head-two -->
</header>
This is how I have done the css alignment (The colours being used are
purely to highlight box sizes and alignments at this stage) -
header
{
border: 0.5em solid blue;
box-sizing: border-box;
-moz-box-sizing: border-box;
text-align: justify;
padding: 1em 0.5em 0em 0.5em;
margin: 5px auto;
}
nav,
ul.menu,
ul.menu li
{
display: inline-block;
}
#logo-head
{
width: 200px;
height: 200px;
padding: 0.5em;
}
div.box#head-two
{
width: 100%;
height: 100%;
text-align:center;
display: inline-block;
animation:logo 5s linear 0.3s 3;
-webkit-animation:logo 5s linear 0.3s 3;
}
@keyframes logo
{
0% {transform:rotate(0deg);}
25% {transform:rotate(90deg);}
50% {transform:rotate(180deg);}
100% {transform:rotate(360deg);}
}
@-webkit-keyframes logo
{
0% {-webkit-transform:rotate(0deg);}
25% {-webkit-transform:rotate(90deg);}
50% {-webkit-transform:rotate(180deg);}
100% {-webkit-transform:rotate(360deg);}
}
div.box#head-one
{
width: 75%;
text-align: center;
}
header::after
{
content: '';
width: 100%;
display: inline-block;
}
header div.box#head-one::before
{
content: '';
height: 100%;
width: 100%;
vertical-align: middle;
}
However the animation is pushing the logo contained in 'header
div.box#head-two' to the bottom of the header box instead of up on the
right side, without the animation the logo sits nicely vertically aligned
- middle and to the right of the rest of the header content.
How can I stop this basic animation from breaking my structure, this is an
important problem for me to solve on this project as page layouts depend
on the inline-block display value.
How to serialize an object that keeps pointers to other objects in C++?
How to serialize an object that keeps pointers to other objects in C++?
I'm looking for a way to serialize a large complex object in C++. I've
been thinking of using boost serialization api, but I'm not sure if it's
even possible to serialize an object implemented in such a way.
In my program I have the following objects:
typedef map<float, float> SignalData;
typedef pair<float,float> TimeValuePair;
class SignalDatabaseNG : public SignalDatabase
{
(...)
private:
vector<SingleSignal *> all_signals;
(...)
};
class SingleSignalAsStdMap: public SingleSignal{
private:
SignalData * signalData;
(...)
};
class IntegrationComparator : public Comparator {
private:
map<SignalData *, float> * preComputedIntegrals;
(...)
public:
IntegrationComparator();
float compare(SignalData *a, SignalData *b);
void preComputeIntegralsForAll(SignalDatabase * database);
(...)
};
SignalDatabase is a class whose most important role is to keep all the
data needed for the program. The signal is represented as a map of two
floats (time and value), and all the signals are kept inside a vector of
such maps.
It's being filled with data in the following way:
SignalDatabaseNG * signalDatabase = TestConfiguration::getSignalDatabase();
IntegrationComparator * integrationComparator = new IntegrationComparator();
integrationComparator->preComputeIntegralsForAll(signalDatabase);
TestConfiguration::getSignalDatabase() returns a database object that
contains the data needed for the computation of integrals (its read from
text files at the beginning of the program runtime). Then,
integrationComparator object is created and
preComputeIntegralsForAll(SignalDatabase * db) is called, which performs
the computation. In the end, map<SignalData *, float> *
preComputedIntegrals inside integrationComparator is filled with data.
This computation of integrals takes a huge amount of time (it's about 60
seconds for 10 signals, and I need to have it computed for ~220000
signals).
I'd like to be able to run it once, then serialize it, and then reuse it
with each program run (the data doesn't change often, so it would be a
huge time saver).
The problem is that the map maps the pointer to a signal object to the
integral value. But, in the next run, the database would be created from
scratch and all the addreses inside pointers would change. It's possible
to serialize both signal database and precomputed integrals database, but
then there's also no guarantee that after de-serialization signals in the
database would be at the same places in the memory, so the pointers inside
integralsComparator would also be completely wrong.
Has anybody got any idea how such serialization could be done (preferably,
without having to rewrite the whole structure of classes)?
I'm looking for a way to serialize a large complex object in C++. I've
been thinking of using boost serialization api, but I'm not sure if it's
even possible to serialize an object implemented in such a way.
In my program I have the following objects:
typedef map<float, float> SignalData;
typedef pair<float,float> TimeValuePair;
class SignalDatabaseNG : public SignalDatabase
{
(...)
private:
vector<SingleSignal *> all_signals;
(...)
};
class SingleSignalAsStdMap: public SingleSignal{
private:
SignalData * signalData;
(...)
};
class IntegrationComparator : public Comparator {
private:
map<SignalData *, float> * preComputedIntegrals;
(...)
public:
IntegrationComparator();
float compare(SignalData *a, SignalData *b);
void preComputeIntegralsForAll(SignalDatabase * database);
(...)
};
SignalDatabase is a class whose most important role is to keep all the
data needed for the program. The signal is represented as a map of two
floats (time and value), and all the signals are kept inside a vector of
such maps.
It's being filled with data in the following way:
SignalDatabaseNG * signalDatabase = TestConfiguration::getSignalDatabase();
IntegrationComparator * integrationComparator = new IntegrationComparator();
integrationComparator->preComputeIntegralsForAll(signalDatabase);
TestConfiguration::getSignalDatabase() returns a database object that
contains the data needed for the computation of integrals (its read from
text files at the beginning of the program runtime). Then,
integrationComparator object is created and
preComputeIntegralsForAll(SignalDatabase * db) is called, which performs
the computation. In the end, map<SignalData *, float> *
preComputedIntegrals inside integrationComparator is filled with data.
This computation of integrals takes a huge amount of time (it's about 60
seconds for 10 signals, and I need to have it computed for ~220000
signals).
I'd like to be able to run it once, then serialize it, and then reuse it
with each program run (the data doesn't change often, so it would be a
huge time saver).
The problem is that the map maps the pointer to a signal object to the
integral value. But, in the next run, the database would be created from
scratch and all the addreses inside pointers would change. It's possible
to serialize both signal database and precomputed integrals database, but
then there's also no guarantee that after de-serialization signals in the
database would be at the same places in the memory, so the pointers inside
integralsComparator would also be completely wrong.
Has anybody got any idea how such serialization could be done (preferably,
without having to rewrite the whole structure of classes)?
How to set string at a particular index to a textview
How to set string at a particular index to a textview
How to set string at a particular index to a textview. The below code is
not working for me.
TextView t1 = (TextView) findViewById(R.id.textView1);
String[] picname ={"abc","def"};
String data=picname[0];
t1.setText(data);
How to set string at a particular index to a textview. The below code is
not working for me.
TextView t1 = (TextView) findViewById(R.id.textView1);
String[] picname ={"abc","def"};
String data=picname[0];
t1.setText(data);
allow login with domain forwarding/masking
allow login with domain forwarding/masking
I have a client that has a domain registered through GoDaddy (e.g.,
http://www.godaddysite.com). He has the domain set to forward w/masking to
a page on our servers (eg.,
https://www.someuniversity.edu/someproject/loginpage.aspx).
When on our network (a university network) I can navigate to his domain,
the forwarding/masking works and I can log in without issue. However, any
off the university network, when visiting the client's site, cannot log
into the site. It forwards/masks as it should, accepts the user name and
password but stays on the login page after the credentials are accepted.
If they navigate directly to my site they have no issues.
I checked his GoDaddy settings and everything appears right. GoDaddy says
it is our configuration that is causing the problem (not allowing a
different domain mask the site). Is this true? Is there something I need
to change in IIS to allow people to login when they visit through the
GoDaddy site?
I have a client that has a domain registered through GoDaddy (e.g.,
http://www.godaddysite.com). He has the domain set to forward w/masking to
a page on our servers (eg.,
https://www.someuniversity.edu/someproject/loginpage.aspx).
When on our network (a university network) I can navigate to his domain,
the forwarding/masking works and I can log in without issue. However, any
off the university network, when visiting the client's site, cannot log
into the site. It forwards/masks as it should, accepts the user name and
password but stays on the login page after the credentials are accepted.
If they navigate directly to my site they have no issues.
I checked his GoDaddy settings and everything appears right. GoDaddy says
it is our configuration that is causing the problem (not allowing a
different domain mask the site). Is this true? Is there something I need
to change in IIS to allow people to login when they visit through the
GoDaddy site?
How to convert json array to individuals entry
How to convert json array to individuals entry
I have json data like following way:
[2, 1, ["55", "54"]]
How can i get 55 and 54
Thanks
I have json data like following way:
[2, 1, ["55", "54"]]
How can i get 55 and 54
Thanks
print a variable using another
print a variable using another
I have my script setup like this, i want to print switch names using loop.
swn1="something"
swn2="somethingelse"
for (( i=1; i<="$ii"; i++ ))
do
echo "$swn$i "
done
I have searched and searched but no luck, can anyone help me how to print
swn using for loop ?
I have my script setup like this, i want to print switch names using loop.
swn1="something"
swn2="somethingelse"
for (( i=1; i<="$ii"; i++ ))
do
echo "$swn$i "
done
I have searched and searched but no luck, can anyone help me how to print
swn using for loop ?
Wednesday, 18 September 2013
Date picker for Bootstrap 3
Date picker for Bootstrap 3
I was using http://eternicode.github.io/bootstrap-datepicker/ with the
previous Bootstrap version.
Anyone has a tip on a component that would work along with Bootstrap 3 ?
I was using http://eternicode.github.io/bootstrap-datepicker/ with the
previous Bootstrap version.
Anyone has a tip on a component that would work along with Bootstrap 3 ?
Assistance with ruby def
Assistance with ruby def
So, I'm new to ruby and very curious about it. I'm comming from python. in
python I would do this to see if something was present in a dictionary.
dictionary = dict()
dictionary['key'] = 5
def inDictionary(key):
if key in dictionary:
execute code
else:
other code
Rather simple for me, in ruby on the other hand how would I do this? i've
been trying stuff like
dictionary = Hash.new
dictionary['key'] = 5
def isDictionary(key)
if dictionary.has_key?(key)
puts 'has key'
end
end
I get the error, isDictionary undefined local variable or method
"dictionary". What am I doing wrong, and thanks in advance.
So, I'm new to ruby and very curious about it. I'm comming from python. in
python I would do this to see if something was present in a dictionary.
dictionary = dict()
dictionary['key'] = 5
def inDictionary(key):
if key in dictionary:
execute code
else:
other code
Rather simple for me, in ruby on the other hand how would I do this? i've
been trying stuff like
dictionary = Hash.new
dictionary['key'] = 5
def isDictionary(key)
if dictionary.has_key?(key)
puts 'has key'
end
end
I get the error, isDictionary undefined local variable or method
"dictionary". What am I doing wrong, and thanks in advance.
PHP Variable Statement At End of SQL Query Produces Error Flag SQL Dialects
PHP Variable Statement At End of SQL Query Produces Error Flag SQL Dialects
I have SQL Dialects enabled for my project. I am using the below code
There is a PHP variable that is set if a certain condition is met. SQL
Dialects thinks there is an error at the end of the SQL statement since it
expects either a GROUP BY, HAVING, or other SQL declaration after the
WHERE declaration. It underlines the variable and the entire file is
marked as having known syntax errors. Is there a way for me to create an
exception in SQL Dialects so this is ignored?
I have SQL Dialects enabled for my project. I am using the below code
There is a PHP variable that is set if a certain condition is met. SQL
Dialects thinks there is an error at the end of the SQL statement since it
expects either a GROUP BY, HAVING, or other SQL declaration after the
WHERE declaration. It underlines the variable and the entire file is
marked as having known syntax errors. Is there a way for me to create an
exception in SQL Dialects so this is ignored?
What went wrong in below code?
What went wrong in below code?
<?php
$retrive=mysql_query("SELECT * FROM oes.questions;");
$questions=mysql_fetch_array($retrive);
?>
<form action="delete.php" method="post">
<input type="checkbox" name="del" value=<?php $questions["q_no"] ?>
/><?php echo $questions["q_no"]; ?>
<input type="submit" value="submit"/>
<?php
if(isset($_POST["del"]))
{
echo $_POST["del"];
}
?>
I want to use delete ($_POST["del"]) function but for debugging I used
echo and found that it prints '/' .
<?php
$retrive=mysql_query("SELECT * FROM oes.questions;");
$questions=mysql_fetch_array($retrive);
?>
<form action="delete.php" method="post">
<input type="checkbox" name="del" value=<?php $questions["q_no"] ?>
/><?php echo $questions["q_no"]; ?>
<input type="submit" value="submit"/>
<?php
if(isset($_POST["del"]))
{
echo $_POST["del"];
}
?>
I want to use delete ($_POST["del"]) function but for debugging I used
echo and found that it prints '/' .
Is possible to have two concurrent transactions in one JDBC connection?
Is possible to have two concurrent transactions in one JDBC connection?
Right now I have two objects sharing a database connection to an Oracle
database in auto commit mode. But now both objects need to start their own
transaction to get their work done.
What is the consequence?
Is it necessary to give each object its own connection in order to have
concurrent transactions or is possible to keep the code as it is and use
the same connection for two concurrent transactions?
And what is the best practice, if I have 10000 objects instead of 2? How
many database connections do I need, if it may be possible for every
object to start a transaction. Do I need 10.000 database connections?
Right now I have two objects sharing a database connection to an Oracle
database in auto commit mode. But now both objects need to start their own
transaction to get their work done.
What is the consequence?
Is it necessary to give each object its own connection in order to have
concurrent transactions or is possible to keep the code as it is and use
the same connection for two concurrent transactions?
And what is the best practice, if I have 10000 objects instead of 2? How
many database connections do I need, if it may be possible for every
object to start a transaction. Do I need 10.000 database connections?
How do I remove the gap between these two div sections?
How do I remove the gap between these two div sections?
all. My html code looks a bit like this, and for some reason it keeps
misaligning or inserting an uncontrollable gap.
<div id="boxes1">
<ul>
<li>Justs the Facts</li>
</ul>
</div>
<div id="boxes2">
<ul>
<li>Visit Neptune</li>
</ul>
</div>
</section>
The relevant CSS is here:
#boxes{
width:700px;
background-color: #ffffff
}
#boxes1{
width: 350px;
float: left; }
#boxes2 {
width: 350px;
float: right;
}
This creates something like two blocks, with a gap in between. How could I
create it so that there's no margin or gap between the div section of
"boxes1" versus "boxes2"?
all. My html code looks a bit like this, and for some reason it keeps
misaligning or inserting an uncontrollable gap.
<div id="boxes1">
<ul>
<li>Justs the Facts</li>
</ul>
</div>
<div id="boxes2">
<ul>
<li>Visit Neptune</li>
</ul>
</div>
</section>
The relevant CSS is here:
#boxes{
width:700px;
background-color: #ffffff
}
#boxes1{
width: 350px;
float: left; }
#boxes2 {
width: 350px;
float: right;
}
This creates something like two blocks, with a gap in between. How could I
create it so that there's no margin or gap between the div section of
"boxes1" versus "boxes2"?
Pass Data from Listview to Edittext
Pass Data from Listview to Edittext
I have a CustomListView in which I have two textbox and two images. I need
to pass textbox data to the Edittext of another activity.
Thanks
I have a CustomListView in which I have two textbox and two images. I need
to pass textbox data to the Edittext of another activity.
Thanks
Getting one char from specified position
Getting one char from specified position
I'd to reach a char from a string in corona. Basically I want to:
local mystr = "corona"
print( mystr[3] )
But it always returns nil. How can I achieve that?
I'd to reach a char from a string in corona. Basically I want to:
local mystr = "corona"
print( mystr[3] )
But it always returns nil. How can I achieve that?
Tuesday, 17 September 2013
Form submitting despite validation LINQtoSQL
Form submitting despite validation LINQtoSQL
I am using Linq to SQL data annotation validations. I get the validation
messages if some fields are invalid. However if I hit save, the form still
submits (with the invalid values).
<input type="button" id="btnSave" name="submit" value="Save" />
$("#btnSave").on("click", saveRecord);
function saveRecord() {
//document.forms[0].submit();
$.ajax(
{ type: 'Post' ,
url: '@Url.Action("Save", "Orders")',
data: {
OrderID: '@Model.OrderID',
ShipName: $('.Name input').val(),
ShipAddress: '@Model.ShipAddress',
RequiredDate: '@Model.RequiredDate',
ShipPostalCode: '@Model.ShipPostalCode'
},
dataType: "html",
success: function (data){
//alert ('saved');
}
})
return false;
}
I am using Linq to SQL data annotation validations. I get the validation
messages if some fields are invalid. However if I hit save, the form still
submits (with the invalid values).
<input type="button" id="btnSave" name="submit" value="Save" />
$("#btnSave").on("click", saveRecord);
function saveRecord() {
//document.forms[0].submit();
$.ajax(
{ type: 'Post' ,
url: '@Url.Action("Save", "Orders")',
data: {
OrderID: '@Model.OrderID',
ShipName: $('.Name input').val(),
ShipAddress: '@Model.ShipAddress',
RequiredDate: '@Model.RequiredDate',
ShipPostalCode: '@Model.ShipPostalCode'
},
dataType: "html",
success: function (data){
//alert ('saved');
}
})
return false;
}
More efficient way to view changes on a mobile device without pushing rails app to heroku?
More efficient way to view changes on a mobile device without pushing
rails app to heroku?
Probably a dumb question:
Right now, to see changes made in development, I run rails s and see the
changes on the local version of my site. To see how changes look on my
phone, I currently commit to Git (no matter how small the changes) and
then push to heroku. This takes some time and results in lots of commits
and deployments for minor changes (i.e. CSS stuff).
What is a more efficient way to test changes for rails web apps on mobile?
NOTE: I am aware I can shrink my browser but it never fails I get
different outcomes on my phone.
Any help is appreciated.
rails app to heroku?
Probably a dumb question:
Right now, to see changes made in development, I run rails s and see the
changes on the local version of my site. To see how changes look on my
phone, I currently commit to Git (no matter how small the changes) and
then push to heroku. This takes some time and results in lots of commits
and deployments for minor changes (i.e. CSS stuff).
What is a more efficient way to test changes for rails web apps on mobile?
NOTE: I am aware I can shrink my browser but it never fails I get
different outcomes on my phone.
Any help is appreciated.
Unable to overwrite/replace existing cookie
Unable to overwrite/replace existing cookie
I am trying to overwrite $_COOKIE['stored_login_token'] with the code
below, but it doesn't seem to work. Basically, I have a table called
'logins' that is storing a userID, token, login date, and token expiration
date. The code below is properly updating the randomly-generated token in
the DB, but is not overwriting the cookie before redirecting to
"network_updates.php"
//generate a random string
function generateRandomString($length = 40) {
$characters =
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
//Login Script
$mysqli2 = new mysqli($db_host,$db_username,$db_password,$db_name);
$login_post_signup_token = generateRandomString();
$expiration_date = date('Y-m-d H:i:s', strtotime('+365 days'));
$suloginid = '';
$stmnt2 = $mysqli2->prepare("INSERT INTO logins (id, user, loginDate,
token, expiration) VALUES (?, ?, ?, ?, ?)");
$stmnt2->bind_param('issss',
$suloginid,
$uuid,
$date,
$login_post_signup_token,
$expiration_date
);
$stmnt2->execute();
$stmnt2->close();
$mysqli2->close();
setcookie(
"stored_login_token",
$login_post_signup_token,
time() + (10 * 365 * 24 * 60 * 60),
'/'
);
header('Location: network_updates.php');
exit();
I am trying to overwrite $_COOKIE['stored_login_token'] with the code
below, but it doesn't seem to work. Basically, I have a table called
'logins' that is storing a userID, token, login date, and token expiration
date. The code below is properly updating the randomly-generated token in
the DB, but is not overwriting the cookie before redirecting to
"network_updates.php"
//generate a random string
function generateRandomString($length = 40) {
$characters =
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
//Login Script
$mysqli2 = new mysqli($db_host,$db_username,$db_password,$db_name);
$login_post_signup_token = generateRandomString();
$expiration_date = date('Y-m-d H:i:s', strtotime('+365 days'));
$suloginid = '';
$stmnt2 = $mysqli2->prepare("INSERT INTO logins (id, user, loginDate,
token, expiration) VALUES (?, ?, ?, ?, ?)");
$stmnt2->bind_param('issss',
$suloginid,
$uuid,
$date,
$login_post_signup_token,
$expiration_date
);
$stmnt2->execute();
$stmnt2->close();
$mysqli2->close();
setcookie(
"stored_login_token",
$login_post_signup_token,
time() + (10 * 365 * 24 * 60 * 60),
'/'
);
header('Location: network_updates.php');
exit();
check for null fields in json python
check for null fields in json python
A very naive question but is there a robust or better way to do following.
Say it has nothing to do with json actually.
let say I have list (reading from file)
string_list = [ "foo",1,None, "null","[]","bar"]
Now, null and [] are essentially equivalent of null but different data
structures have different interpretation of "None"?? right?
So rather than me writing a regex for all these rules.. is there a better
way to convert "null","[]" etc to None.. ??
Thanks
A very naive question but is there a robust or better way to do following.
Say it has nothing to do with json actually.
let say I have list (reading from file)
string_list = [ "foo",1,None, "null","[]","bar"]
Now, null and [] are essentially equivalent of null but different data
structures have different interpretation of "None"?? right?
So rather than me writing a regex for all these rules.. is there a better
way to convert "null","[]" etc to None.. ??
Thanks
mysql/c++ connector error: libmysqlcppconn.so.7: cannot open sahred object file: No such file or directory
mysql/c++ connector error: libmysqlcppconn.so.7: cannot open sahred object
file: No such file or directory
I know there is a lot about this on the internet and I have tried most of
it without luck. Most solutions says that en environment variable is
missing aka (LD_LIBRARY_PATH) which i pointed it to the file in user and
root but it still does not pick it up. I am not sure what exactly is
looking for the library or how to fix this??
Any ideas?
EDIT ldd output:
linux-vdso.so.1 => (0x00007fffb97ff000)
libmysqlcppconn.so.7 => not found
libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6
(0x00007f002fdb3000)
libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007f002fb9c000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f002f7dd000)
libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f002f5c0000)
libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f002f2c3000)
/lib64/ld-linux-x86-64.so.2 (0x00007f00300c7000)
file: No such file or directory
I know there is a lot about this on the internet and I have tried most of
it without luck. Most solutions says that en environment variable is
missing aka (LD_LIBRARY_PATH) which i pointed it to the file in user and
root but it still does not pick it up. I am not sure what exactly is
looking for the library or how to fix this??
Any ideas?
EDIT ldd output:
linux-vdso.so.1 => (0x00007fffb97ff000)
libmysqlcppconn.so.7 => not found
libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6
(0x00007f002fdb3000)
libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007f002fb9c000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f002f7dd000)
libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f002f5c0000)
libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f002f2c3000)
/lib64/ld-linux-x86-64.so.2 (0x00007f00300c7000)
Sunday, 15 September 2013
SOAP Web service returning NullPointerException
SOAP Web service returning NullPointerException
I have created a SOAP web service inside a dynamic web project in eclipse,
it is working fine when called through local intranet, but when it is
hosted on internet server it is returning NullPointerException. What can
be the reason of this exception?
I have created a SOAP web service inside a dynamic web project in eclipse,
it is working fine when called through local intranet, but when it is
hosted on internet server it is returning NullPointerException. What can
be the reason of this exception?
PHP : print grouped results in tables
PHP : print grouped results in tables
I have a resultset of products which is ordered by an $id. I wrote a code
which separates results with the same id into groups and prints them
separately.
CODE (without tables):
category='';
foreach ($result as $each) {
if($each['id'] != $category) {
$category = $each['id'];
echo "<b>{$each['title']}</b><br/>";
}
echo $each['product'].'<br/>';
}
OUTPUT (without tables):
**title1**
product1
product2
product3
**title2**
product4
product5
product6
Ok now to the problem. What i want is to get all the product into tables
(to include some more information). I want to separate these tables with
div's which include title.
Something like this:
<div> title here </div>
<table> all the products here</table>
<div> second title here </div>
<table> all the products here </table>
etc.
The only problem is that i dont know how / where to properly include the
ending tags </tr></table> to make the structure complete.
What i tried:
category='';
foreach ($result as $each) {
if($each['id'] != $category) {
$category = $each['id'];
echo "<div>{$each['title']}</div>
<table>
<tr>";
}
echo "<td>{$each['product']}</td>
<td>{$each['price']}</td>";
}
# how/where should I include the ending tags?
I have a resultset of products which is ordered by an $id. I wrote a code
which separates results with the same id into groups and prints them
separately.
CODE (without tables):
category='';
foreach ($result as $each) {
if($each['id'] != $category) {
$category = $each['id'];
echo "<b>{$each['title']}</b><br/>";
}
echo $each['product'].'<br/>';
}
OUTPUT (without tables):
**title1**
product1
product2
product3
**title2**
product4
product5
product6
Ok now to the problem. What i want is to get all the product into tables
(to include some more information). I want to separate these tables with
div's which include title.
Something like this:
<div> title here </div>
<table> all the products here</table>
<div> second title here </div>
<table> all the products here </table>
etc.
The only problem is that i dont know how / where to properly include the
ending tags </tr></table> to make the structure complete.
What i tried:
category='';
foreach ($result as $each) {
if($each['id'] != $category) {
$category = $each['id'];
echo "<div>{$each['title']}</div>
<table>
<tr>";
}
echo "<td>{$each['product']}</td>
<td>{$each['price']}</td>";
}
# how/where should I include the ending tags?
Add a Text Link to a TextView
Add a Text Link to a TextView
Is it possible to add a text link into a TextView? I want the link to
perhaps behave like a button, where I can assign an action to it.
Is it possible to add a text link into a TextView? I want the link to
perhaps behave like a button, where I can assign an action to it.
How to dispose CountDownTimer
How to dispose CountDownTimer
I have main class called "MainActivity" and I'm lanuching it few times in
my App.
private static CountDownTimer timer;
private static final long startTime = 15 * 1000;
private static final long interval = 1 * 1000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timer = new StageCountDownTimer(startTime, interval);
}
private class StageCountDownTimer extends CountDownTimer {
public StageCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
@Override
public void onFinish() {
//STARTTING NEW ACTIVITY
}
@Override
public void onTick(long millisUntilFinished) {
}
}
Sometimes user need to close this activity before count down ends, and
return to the this activity again. And then new count down is launching
but the old one execute the code in onFinish() when previous count down
ends. Everything works great when I start this code once. How to
cancel/dispose/destroy this timer after exiting from activity? I tried
timer.cancel() and nothing happen.
I have main class called "MainActivity" and I'm lanuching it few times in
my App.
private static CountDownTimer timer;
private static final long startTime = 15 * 1000;
private static final long interval = 1 * 1000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timer = new StageCountDownTimer(startTime, interval);
}
private class StageCountDownTimer extends CountDownTimer {
public StageCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
@Override
public void onFinish() {
//STARTTING NEW ACTIVITY
}
@Override
public void onTick(long millisUntilFinished) {
}
}
Sometimes user need to close this activity before count down ends, and
return to the this activity again. And then new count down is launching
but the old one execute the code in onFinish() when previous count down
ends. Everything works great when I start this code once. How to
cancel/dispose/destroy this timer after exiting from activity? I tried
timer.cancel() and nothing happen.
C recalloc() function fails
C recalloc() function fails
Why does this code not work?
char *x=malloc(100);
x++;
x=realloc(x, 200);
I mean x is a valid string pointer, just incremented by one?
Why does this code not work?
char *x=malloc(100);
x++;
x=realloc(x, 200);
I mean x is a valid string pointer, just incremented by one?
How to make the content div scrollable without using javascript
How to make the content div scrollable without using javascript
I have a simple page. Here i want a fixed header and a fixed footer. The
body of the content to be scrollable.
HTML
<div class="container">
<div class="header">This is Header</div>
<div class="body">This is Body
<br/>This is Body
<br/>This is Body
<br/>This is Body
<br/>This is Body
<br/>This is Body
<br/>This is Body
<br/>This is Body
<br/>This is Body
<br/>This is Body
<br/>This is Body
<br/>This is Body
<br/>This is Body
<br/>This is Body
<br/>This is Body
<br/>This is Body
<br/>This is Body
<br/>This is Body
<br/>This is Body
<br/>This is Body
<br/>This is Body
<br/>This is Body</div>
<div class="footer">This is Footer</div>
</div>
CSS
* {
margin: 0;
padding: 0;
}
.container {
width: 100%;
height: 100%;
background: #DDD;
}
.header {
width: 100%;
height: 40px;
background: red;
position: absolute;
top: 0;
}
.footer {
width: 100%;
height: 40px;
background: green;
position: absolute;
bottom: 0;
}
.body {
width: 100%;
background: blue;
overflow: auto;
}
However when i scroll the whole page tends to scroll making my header and
footer move. I can resolve this using javascript, getting the height of
the screen and subtracting the header and footer height.
But is there any way we can achieve this only using css. If yes then how ?
I have a simple page. Here i want a fixed header and a fixed footer. The
body of the content to be scrollable.
HTML
<div class="container">
<div class="header">This is Header</div>
<div class="body">This is Body
<br/>This is Body
<br/>This is Body
<br/>This is Body
<br/>This is Body
<br/>This is Body
<br/>This is Body
<br/>This is Body
<br/>This is Body
<br/>This is Body
<br/>This is Body
<br/>This is Body
<br/>This is Body
<br/>This is Body
<br/>This is Body
<br/>This is Body
<br/>This is Body
<br/>This is Body
<br/>This is Body
<br/>This is Body
<br/>This is Body
<br/>This is Body</div>
<div class="footer">This is Footer</div>
</div>
CSS
* {
margin: 0;
padding: 0;
}
.container {
width: 100%;
height: 100%;
background: #DDD;
}
.header {
width: 100%;
height: 40px;
background: red;
position: absolute;
top: 0;
}
.footer {
width: 100%;
height: 40px;
background: green;
position: absolute;
bottom: 0;
}
.body {
width: 100%;
background: blue;
overflow: auto;
}
However when i scroll the whole page tends to scroll making my header and
footer move. I can resolve this using javascript, getting the height of
the screen and subtracting the header and footer height.
But is there any way we can achieve this only using css. If yes then how ?
How to use ruby method .present?
How to use ruby method .present?
I have a method like this in rails app:
def current_user
return @current_user if @current_user.present?
@current_user = current_user_session && current_user_session.record
end
I haven't used the .present? method before so I went into my interactive
ruby shell to play around with it.
Whenever I use xxx.present? it returns a NoMethodError. It doesn't matter
if xxx is a string, number, array anything.
How can I use this method?
I have a method like this in rails app:
def current_user
return @current_user if @current_user.present?
@current_user = current_user_session && current_user_session.record
end
I haven't used the .present? method before so I went into my interactive
ruby shell to play around with it.
Whenever I use xxx.present? it returns a NoMethodError. It doesn't matter
if xxx is a string, number, array anything.
How can I use this method?
Saturday, 14 September 2013
onActivityResult not getting called; all requirements met
onActivityResult not getting called; all requirements met
onActivityResult is not getting called after a child Activity call. I made
sure of these:
startActivityForResult is called from parent and NOT startActivity
setResult is called from child along with finish().
No singleInstance launchMode defined in Manifest.
What else could be going wrong?
Thanks.
onActivityResult is not getting called after a child Activity call. I made
sure of these:
startActivityForResult is called from parent and NOT startActivity
setResult is called from child along with finish().
No singleInstance launchMode defined in Manifest.
What else could be going wrong?
Thanks.
Why is this code compiled and linked without an error?
Why is this code compiled and linked without an error?
Isn't the extern keyword supposed to simply 'blind' the compiler? Here are
the codes that i can't understand why it is without an error.
struct A {
int a;
};
class B {
static A x;
public:
void f() { x.a=0 }
};
extern A B::x; // not allocated.
main() {
B z;
z.f();
}
As you already know, the static member should be instantiated manually.
However, i added the extern keyword, which means it's not actually
allocated. It is very weird that it compiles fine!
Isn't the extern keyword supposed to simply 'blind' the compiler? Here are
the codes that i can't understand why it is without an error.
struct A {
int a;
};
class B {
static A x;
public:
void f() { x.a=0 }
};
extern A B::x; // not allocated.
main() {
B z;
z.f();
}
As you already know, the static member should be instantiated manually.
However, i added the extern keyword, which means it's not actually
allocated. It is very weird that it compiles fine!
How to save a file from a url with php
How to save a file from a url with php
How can I save "example.mp4" from $url="http://videos.com/example.mp4" as
"56.mp4" using a variable $id=56 to /videos
How can I save "example.mp4" from $url="http://videos.com/example.mp4" as
"56.mp4" using a variable $id=56 to /videos
Can a single library binary be used as a static or shared?
Can a single library binary be used as a static or shared?
I ask this specifically regarding Unix-like systems (Linux, Mac OSX, etc).
On the next level of granularity, I'm referring to the library binary that
is included in a Mac Framework. For example, I'm trying to write a Qt
Library that wraps libspotify. The libspotify distribution I have is the
OSX Framework.
I'm curious as to whether or not I can simply remove the library and
header that I need and essentially just include it in the project. I want
to do this for portability purposes, e.g. a different build of libspotify
can be dropped in and the whole thing can be recompiled into a static
library or the Qt library can be used as a shared library that depends on
the shared libspotify. Either way, I'd just rather avoid having the Qt
.pro file depend on the OSX Framework directory semantics.
I'm aware that I can use conditional compilation in the .pro file, but
that's also something I'd rather avoid if possible. Thanks to all in
advance.
I ask this specifically regarding Unix-like systems (Linux, Mac OSX, etc).
On the next level of granularity, I'm referring to the library binary that
is included in a Mac Framework. For example, I'm trying to write a Qt
Library that wraps libspotify. The libspotify distribution I have is the
OSX Framework.
I'm curious as to whether or not I can simply remove the library and
header that I need and essentially just include it in the project. I want
to do this for portability purposes, e.g. a different build of libspotify
can be dropped in and the whole thing can be recompiled into a static
library or the Qt library can be used as a shared library that depends on
the shared libspotify. Either way, I'd just rather avoid having the Qt
.pro file depend on the OSX Framework directory semantics.
I'm aware that I can use conditional compilation in the .pro file, but
that's also something I'd rather avoid if possible. Thanks to all in
advance.
How to handle exceptions thrown in own ASP.NET user control?
How to handle exceptions thrown in own ASP.NET user control?
I have created a user control that is using a library I have created. The
library can throw a few exceptions, some which are of the kind that should
not cause a run-time issue. I am unsure how to best proceed from this
point in terms of handing those specific exceptions.
Do I include a label in my user control that will show a friendly message
when the exceptions mentioned above are thrown?
Do I avoid catching the exceptions and let the user of the control decide
what to do with them? Seems like this option would reveal information
about the workings of the control.
Do I create my own exception(s) and throw those when catching any of the
above mentioned exceptions?
Something else I have not thought about?
I have created a user control that is using a library I have created. The
library can throw a few exceptions, some which are of the kind that should
not cause a run-time issue. I am unsure how to best proceed from this
point in terms of handing those specific exceptions.
Do I include a label in my user control that will show a friendly message
when the exceptions mentioned above are thrown?
Do I avoid catching the exceptions and let the user of the control decide
what to do with them? Seems like this option would reveal information
about the workings of the control.
Do I create my own exception(s) and throw those when catching any of the
above mentioned exceptions?
Something else I have not thought about?
how to remove the short lines(horizontal lines) before the menu
how to remove the short lines(horizontal lines) before the menu
I created a header Navigation using images. I have separate images for all
the menus. But my problem is Some short lines appears before my each image
menu. I dont know why. I checked with the images but nothing wrong with
the images. I will paste my image screenshort please have a look at it and
tell me what i have to do to remove the short (horizontal line)
!file:///home/oomsys/Desktop/July%20Report/short.png
I created a header Navigation using images. I have separate images for all
the menus. But my problem is Some short lines appears before my each image
menu. I dont know why. I checked with the images but nothing wrong with
the images. I will paste my image screenshort please have a look at it and
tell me what i have to do to remove the short (horizontal line)
!file:///home/oomsys/Desktop/July%20Report/short.png
Why has an ASP.NET MVC project a WebApiConfig.cs
Why has an ASP.NET MVC project a WebApiConfig.cs
When I create a MVC4 project and choose basic mvc project I find WebApi
related code why this?
When I create a MVC4 project and choose basic mvc project I find WebApi
related code why this?
How can I show a value on the screen without blocking the UI and make it fade out with style in android activity?
How can I show a value on the screen without blocking the UI and make it
fade out with style in android activity?
I'm making a word game for android, and basically whenever a user enters
something right I'm updating the score in the application, and I want to
show the score on the screen to make it show in big then fade out slowly
and get smaller, how can I do that? and is it possible to implement it in
an AsyncTask class? This is the method I'm using to check if the word
entered is right.
public class checkWord extends AsyncTask<String, String, Void> {
private String c;
@Override
protected Void doInBackground(String... arg0) {
int size = correctWords.size();
String word = arg0[0];
for (int i = 0; i < size; i++) {
if (word.equalsIgnoreCase(correctWords.get(i))) {
publishProgress("bad");
}
}
try {
c = bufferedReader.readLine();
while (c != null && !c.equalsIgnoreCase(word)) {
c = bufferedReader.readLine();
}
if (c != null) {
correctWords.add(0, word);
score += word.length();
publishProgress("good");
} else {
incorrectWords.add(0, word);
publishProgress("bad");
}
} catch (IOException e) {
e.printStackTrace();
}
closeWordFile();
openWordFile();
return null;
}
So is there anyway I could pass a param to the publishProgress so that in
onProgressUpdate I draw the score they got, for example +3 then make it
fade out? This is my onProgressUpdate where I add seconds to the timer and
play a sound if it's a valid word or not
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
if (values[0].matches("bad"))
failureSound.start();
if (values[0].matches("good")) {
successSound.start();
if (countDownTimer != null) {
countDownTimer.cancel();
startTimer(countDownTime + c.length() / 2);
}
}
}
fade out with style in android activity?
I'm making a word game for android, and basically whenever a user enters
something right I'm updating the score in the application, and I want to
show the score on the screen to make it show in big then fade out slowly
and get smaller, how can I do that? and is it possible to implement it in
an AsyncTask class? This is the method I'm using to check if the word
entered is right.
public class checkWord extends AsyncTask<String, String, Void> {
private String c;
@Override
protected Void doInBackground(String... arg0) {
int size = correctWords.size();
String word = arg0[0];
for (int i = 0; i < size; i++) {
if (word.equalsIgnoreCase(correctWords.get(i))) {
publishProgress("bad");
}
}
try {
c = bufferedReader.readLine();
while (c != null && !c.equalsIgnoreCase(word)) {
c = bufferedReader.readLine();
}
if (c != null) {
correctWords.add(0, word);
score += word.length();
publishProgress("good");
} else {
incorrectWords.add(0, word);
publishProgress("bad");
}
} catch (IOException e) {
e.printStackTrace();
}
closeWordFile();
openWordFile();
return null;
}
So is there anyway I could pass a param to the publishProgress so that in
onProgressUpdate I draw the score they got, for example +3 then make it
fade out? This is my onProgressUpdate where I add seconds to the timer and
play a sound if it's a valid word or not
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
if (values[0].matches("bad"))
failureSound.start();
if (values[0].matches("good")) {
successSound.start();
if (countDownTimer != null) {
countDownTimer.cancel();
startTimer(countDownTime + c.length() / 2);
}
}
}
Friday, 13 September 2013
Not getting complete array while using it as variable
Not getting complete array while using it as variable
I newbie in Java and learning it. I got a question related to array, can
you please look into it?
I am getting following output: [[Ljava.lang.String;@7a982589 from below code:
String[][] multi = new String [][] {
{ "Scenarios", "Description", "1.0", "1.1", "1.2"},
{ "S1", "Verify hotel search", "Y", "Y", "Y"},
};
System.out.println(multi);
While if I place following:
System.out.println(multi[0][1]);
I am getting correct output. Description.
Now, why I am not getting entire array through "multi" variable.
I newbie in Java and learning it. I got a question related to array, can
you please look into it?
I am getting following output: [[Ljava.lang.String;@7a982589 from below code:
String[][] multi = new String [][] {
{ "Scenarios", "Description", "1.0", "1.1", "1.2"},
{ "S1", "Verify hotel search", "Y", "Y", "Y"},
};
System.out.println(multi);
While if I place following:
System.out.println(multi[0][1]);
I am getting correct output. Description.
Now, why I am not getting entire array through "multi" variable.
More Efficient Solution - Three Nested FOR Loops (Java)
More Efficient Solution - Three Nested FOR Loops (Java)
I was wondering if there is a more efficient solution to this problem
(some of the variable names have been changed):
for (Object obj: o){
//set the display part to obj
//get all of the items from the obj and place it in an array
for (int i = 0; i < array.size; i++){
if (array[i] instanceof Line){
for (int j = i + 1; j < array.size; j++){
if (array[j] instanceof Line){
//DO SOMETHING
}
}
}
}
}
So this is pseudo code more or less but basically what it is doing is:
Taking in a list of objects (outer for loop)
Getting all of the 'items' from that list with a seperate method and
placing it into an array that will be used in the next two for loops.
Then the second for loops begins going through the items in the array one
by one. If it finds one with the type "Line" then the third for loop
executes.
Finally, the third for loop goes through the same array item by item,
starting at the previous index + 1 (i+1) until it reaches the end of the
array. If it finds and item of type "Line" then it does some calculations
between the two.
Is there a more efficient way of doing this rather than having three
nested for loops? The code works fine and executes fine with a small input
(small object list) but I am worried than if (and when) the input list
gets to be larger this code will take a very long time to execute. Any
input is appreciated, thanks!
I was wondering if there is a more efficient solution to this problem
(some of the variable names have been changed):
for (Object obj: o){
//set the display part to obj
//get all of the items from the obj and place it in an array
for (int i = 0; i < array.size; i++){
if (array[i] instanceof Line){
for (int j = i + 1; j < array.size; j++){
if (array[j] instanceof Line){
//DO SOMETHING
}
}
}
}
}
So this is pseudo code more or less but basically what it is doing is:
Taking in a list of objects (outer for loop)
Getting all of the 'items' from that list with a seperate method and
placing it into an array that will be used in the next two for loops.
Then the second for loops begins going through the items in the array one
by one. If it finds one with the type "Line" then the third for loop
executes.
Finally, the third for loop goes through the same array item by item,
starting at the previous index + 1 (i+1) until it reaches the end of the
array. If it finds and item of type "Line" then it does some calculations
between the two.
Is there a more efficient way of doing this rather than having three
nested for loops? The code works fine and executes fine with a small input
(small object list) but I am worried than if (and when) the input list
gets to be larger this code will take a very long time to execute. Any
input is appreciated, thanks!
collectionView:cellForItemAtIndexPath: doesn't get called
collectionView:cellForItemAtIndexPath: doesn't get called
I want to add new cells in my collection view, but nothing shows up when I
add data.
I have a custom UICollectionViewLayout class, which has been working just
fine, and I've been keeping dummy data in my datasource to adjust the
layout. Now that I got rid of the dummy data, nothing's showing up.
Since the app didn't break and there weren't any warnings, it was
difficult to track down where the problem was, and here's where I found a
clue:
(UICollectionViewLayout class)
-(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
NSArray *array = [self.collectionView.visibleCells description];
...
}
Here, -visibleCells returns an empty array, even when I add data, call
-reloadData and invalidate the layout. So I placed a breakpoint in
-collectionView:cellForItemAtIndexPath:, and it turns out this method is
not called at all. How did the cells show up before?
Any help would be appreciated.
I want to add new cells in my collection view, but nothing shows up when I
add data.
I have a custom UICollectionViewLayout class, which has been working just
fine, and I've been keeping dummy data in my datasource to adjust the
layout. Now that I got rid of the dummy data, nothing's showing up.
Since the app didn't break and there weren't any warnings, it was
difficult to track down where the problem was, and here's where I found a
clue:
(UICollectionViewLayout class)
-(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
NSArray *array = [self.collectionView.visibleCells description];
...
}
Here, -visibleCells returns an empty array, even when I add data, call
-reloadData and invalidate the layout. So I placed a breakpoint in
-collectionView:cellForItemAtIndexPath:, and it turns out this method is
not called at all. How did the cells show up before?
Any help would be appreciated.
Exercise from lynda tutorial (notes app) show nothing
Exercise from lynda tutorial (notes app) show nothing
I'm doing the tutorial for the note taking app of lynda.com
(http://www.lynda.com/Android-tutorials/Building-Note-Taking-App-Android/122466-2.html),
until chapter 04 02 "data item", everything is working. But after this,
when i start getting info from the shared preferences, all i get is the
icon of the application. I even used the author's code without changes, to
no avail. But in the videos, everything works, and he gets a list of the
notes, as intended
In the log cat i have no infos, not a single info. I tried to use all
versions of the emulator, from 3.0 to 4.3
Here is the last code i managed to get working:
http://furioushamster.com/docs/04_05_getData.rar
Here all i have is "Hello from Plain olnotes"
thanks for any input
I'm doing the tutorial for the note taking app of lynda.com
(http://www.lynda.com/Android-tutorials/Building-Note-Taking-App-Android/122466-2.html),
until chapter 04 02 "data item", everything is working. But after this,
when i start getting info from the shared preferences, all i get is the
icon of the application. I even used the author's code without changes, to
no avail. But in the videos, everything works, and he gets a list of the
notes, as intended
In the log cat i have no infos, not a single info. I tried to use all
versions of the emulator, from 3.0 to 4.3
Here is the last code i managed to get working:
http://furioushamster.com/docs/04_05_getData.rar
Here all i have is "Hello from Plain olnotes"
thanks for any input
WP8 - Facebook Login Issue
WP8 - Facebook Login Issue
I am trying to authenticate a user on Facebook using the Facebook C# SDK
on Windows Phone 8. To do so I am following the code here:
FacebookLoginPage.xaml.cs
But the problem I am facing is that, whenever I input my username and
password into the dialog that opens to authenticate the user, I just get
the following page:
After this, my program does not redirect to the Landing page which is a
separate view. The other solutions I have seen that suggest hiding the
WebView are not applicable since the authentication is abstracted into a
single LoginAsync function call. Any suggestions on what to do?
I am trying to authenticate a user on Facebook using the Facebook C# SDK
on Windows Phone 8. To do so I am following the code here:
FacebookLoginPage.xaml.cs
But the problem I am facing is that, whenever I input my username and
password into the dialog that opens to authenticate the user, I just get
the following page:
After this, my program does not redirect to the Landing page which is a
separate view. The other solutions I have seen that suggest hiding the
WebView are not applicable since the authentication is abstracted into a
single LoginAsync function call. Any suggestions on what to do?
Have you tried protection of your source code and intellectual property [on hold]
Have you tried protection of your source code and intellectual property
[on hold]
Have anyone one tried protecting your source code which usually takes an
immense effort to prevent anyone to do the reverse engineering and alter
your application?
Here is what you need..
http://www.safenet-inc.com/software-monetization-solutions/
Let know if I can help.
Amit
[on hold]
Have anyone one tried protecting your source code which usually takes an
immense effort to prevent anyone to do the reverse engineering and alter
your application?
Here is what you need..
http://www.safenet-inc.com/software-monetization-solutions/
Let know if I can help.
Amit
Thursday, 12 September 2013
NODEJS: How to extract the "real" message with HTTP.get()
NODEJS: How to extract the "real" message with HTTP.get()
This is what I got so far. I do receive a response from http.get().
However, the response called res has many, many attributes and I can't
find where the useful information is...
Everywhere I check, the only thing people mention is res.statusCode, but
that's not really what I'm looking for.
This is the only information I have with the API.
http://services.runescape.com/m=rswiki/en/Grand_Exchange_APIs
This is the JSON I want to have as a variable:
http://services.runescape.com/m=itemdb_rs/api/catalogue/detail.json?item=555
Thanks.
var express = require('express');
var http = require('http');
var https = require("https");
var app = express();
var serv = http.createServer(app);
serv.listen(3000);
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
http.get('http://services.runescape.com/m=itemdb_rs/api/catalogue/detail.json?item=555',
function(res) {
console.log(res.statusCode); //200
console.log(res); //BIG OBJECT
//var whatIWant = res.?????
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
This is what I got so far. I do receive a response from http.get().
However, the response called res has many, many attributes and I can't
find where the useful information is...
Everywhere I check, the only thing people mention is res.statusCode, but
that's not really what I'm looking for.
This is the only information I have with the API.
http://services.runescape.com/m=rswiki/en/Grand_Exchange_APIs
This is the JSON I want to have as a variable:
http://services.runescape.com/m=itemdb_rs/api/catalogue/detail.json?item=555
Thanks.
var express = require('express');
var http = require('http');
var https = require("https");
var app = express();
var serv = http.createServer(app);
serv.listen(3000);
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
http.get('http://services.runescape.com/m=itemdb_rs/api/catalogue/detail.json?item=555',
function(res) {
console.log(res.statusCode); //200
console.log(res); //BIG OBJECT
//var whatIWant = res.?????
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
Matlab solution for implicit finite difference heat equation with kinetic reactions
Matlab solution for implicit finite difference heat equation with kinetic
reactions
I am trying to model heat conduction within a wood cylinder using implicit
finite difference methods. The general heat equation that I'm using for
cylindrical and spherical shapes is:
Where p is the shape factor, p = 1 for cylinder and p = 2 for sphere.
Boundary conditions include convection at the surface. For more details
about the model, please see the comments in the Matlab code below.
The main m-file is:
%--- main parameters
rhow = 650; % density of wood, kg/m^3
d = 0.02; % wood particle diameter, m
Ti = 300; % initial particle temp, K
Tinf = 673; % ambient temp, K
h = 60; % heat transfer coefficient, W/m^2*K
% A = pre-exponential factor, 1/s and E = activation energy, kJ/mol
A1 = 1.3e8; E1 = 140; % wood -> gas
A2 = 2e8; E2 = 133; % wood -> tar
A3 = 1.08e7; E3 = 121; % wood -> char
R = 0.008314; % universal gas constant, kJ/mol*K
%--- initial calculations
b = 1; % shape factor, b = 1 cylinder, b = 2 sphere
r = d/2; % particle radius, m
nt = 1000; % number of time steps
tmax = 840; % max time, s
dt = tmax/nt; % time step spacing, delta t
t = 0:dt:tmax; % time vector, s
m = 20; % number of radius nodes
steps = m-1; % number of radius steps
dr = r/steps; % radius step spacing, delta r
%--- build initial vectors for temperature and thermal properties
i = 1:m;
T(i,1) = Ti; % column vector of temperatures
TT(1,i) = Ti; % row vector to store temperatures
pw(1,i) = rhow; % initial density at each node is wood density, rhow
pg(1,i) = 0; % initial density of gas
pt(1,i) = 0; % inital density of tar
pc(1,i) = 0; % initial density of char
%--- solve system of equations [A][T]=[C] where T = A\C
for i = 2:nt+1
% kinetics at n
[rww, rwg, rwt, rwc] = funcY(A1,E1,A2,E2,A3,E3,R,T',pw(i-1,:));
pw(i,:) = pw(i-1,:) + rww.*dt; % update wood density
pg(i,:) = pg(i-1,:) + rwg.*dt; % update gas density
pt(i,:) = pt(i-1,:) + rwt.*dt; % update tar density
pc(i,:) = pc(i-1,:) + rwc.*dt; % update char density
Yw = pw(i,:)./(pw(i,:) + pc(i,:)); % wood fraction
Yc = pc(i,:)./(pw(i,:) + pc(i,:)); % char fraction
% thermal properties at n
cpw = 1112.0 + 4.85.*(T'-273.15); % wood heat capacity, J/(kg*K)
kw = 0.13 + (3e-4).*(T'-273.15); % wood thermal conductivity, W/(m*K)
cpc = 1003.2 + 2.09.*(T'-273.15); % char heat capacity, J/(kg*K)
kc = 0.08 - (1e-4).*(T'-273.15); % char thermal conductivity, W/(m*K)
cpbar = Yw.*cpw + Yc.*cpc; % effective heat capacity
kbar = Yw.*kw + Yc.*kc; % effective thermal conductivity
pbar = pw(i,:) + pc(i,:); % effective density
% temperature at n+1
Tn = funcACbar(pbar,cpbar,kbar,h,Tinf,b,m,dr,dt,T);
% kinetics at n+1
[rww, rwg, rwt, rwc] = funcY(A1,E1,A2,E2,A3,E3,R,Tn',pw(i-1,:));
pw(i,:) = pw(i-1,:) + rww.*dt;
pg(i,:) = pg(i-1,:) + rwg.*dt;
pt(i,:) = pt(i-1,:) + rwt.*dt;
pc(i,:) = pc(i-1,:) + rwc.*dt;
Yw = pw(i,:)./(pw(i,:) + pc(i,:));
Yc = pc(i,:)./(pw(i,:) + pc(i,:));
% thermal properties at n+1
cpw = 1112.0 + 4.85.*(Tn'-273.15);
kw = 0.13 + (3e-4).*(Tn'-273.15);
cpc = 1003.2 + 2.09.*(Tn'-273.15);
kc = 0.08 - (1e-4).*(Tn'-273.15);
cpbar = Yw.*cpw + Yc.*cpc;
kbar = Yw.*kw + Yc.*cpc;
pbar = pw(i,:) + pc(i,:);
% revise temperature at n+1
Tn = funcACbar(pbar,cpbar,kbar,h,Tinf,b,m,dr,dt,T);
% store temperature at n+1
T = Tn;
TT(i,:) = T';
end
%--- plot data
figure(1)
plot(t./60,TT(:,1),'-b',t./60,TT(:,m),'-r')
hold on
plot([0 tmax/60],[Tinf Tinf],':k')
hold off
xlabel('Time (min)'); ylabel('Temperature (K)');
sh = num2str(h); snt = num2str(nt); sm = num2str(m);
title(['Cylinder Model, d = 20mm, h = ',sh,', nt = ',snt,', m = ',sm])
legend('Tcenter','Tsurface',['T\infty =
',num2str(Tinf),'K'],'location','southeast')
figure(2)
plot(t./60,pw(:,1),'--',t./60,pw(:,m),'-','color',[0 0.7 0])
hold on
plot(t./60,pg(:,1),'--b',t./60,pg(:,m),'b')
hold on
plot(t./60,pt(:,1),'--k',t./60,pt(:,m),'k')
hold on
plot(t./60,pc(:,1),'--r',t./60,pc(:,m),'r')
hold off
xlabel('Time (min)'); ylabel('Density (kg/m^3)');
The function m-file, funcACbar, that creates the system of equations to
solve is:
% Finite difference equations for cylinder and sphere
% for 1D transient heat conduction with convection at surface
% general equation is:
% 1/alpha*dT/dt = d^2T/dr^2 + p/r*dT/dr for r ~= 0
% 1/alpha*dT/dt = (1 + p)*d^2T/dr^2 for r = 0
% where p is shape factor, p = 1 for cylinder, p = 2 for sphere
function T = funcACbar(pbar,cpbar,kbar,h,Tinf,b,m,dr,dt,T)
alpha = kbar./(pbar.*cpbar); % effective thermal diffusivity
Fo = alpha.*dt./(dr^2); % effective Fourier number
Bi = h.*dr./kbar; % effective Biot number
% [A] is coefficient matrix at time level n+1
% {C} is column vector at time level n
A(1,1) = 1 + 2*(1+b)*Fo(1);
A(1,2) = -2*(1+b)*Fo(2);
C(1,1) = T(1);
for k = 2:m-1
A(k,k-1) = -Fo(k-1)*(1 - b/(2*(k-1))); % Tm-1
A(k,k) = 1 + 2*Fo(k); % Tm
A(k,k+1) = -Fo(k+1)*(1 + b/(2*(k-1))); % Tm+1
C(k,1) = T(k);
end
A(m,m-1) = -2*Fo(m-1);
A(m,m) = 1 + 2*Fo(m)*(1 + Bi(m) + (b/(2*m))*Bi(m));
C(m,1) = T(m) + 2*Fo(m)*Bi(m)*(1 + b/(2*m))*Tinf;
% solve system of equations [A]{T} = {C} where temperature T = [A]\{C}
T = A\C;
end
And finally the function that deals with the kinetic reactions, funcY, is:
% Kinetic equations for reactions of wood, first-order, Arrhenious type
equations
% K = A*exp(-E/RT) where A = pre-exponential factor, 1/s
% and E = activation energy, kJ/mol
function [rww, rwg, rwt, rwc] = funcY(A1,E1,A2,E2,A3,E3,R,T,pww)
K1 = A1.*exp(-E1./(R.*T)); % wood -> gas (1/s)
K2 = A2.*exp(-E2./(R.*T)); % wood -> tar (1/s)
K3 = A3.*exp(-E3./(R.*T)); % wood -> char (1/s)
rww = -(K1+K2+K3).*pww; % rate of wood consumption (rho/s)
rwg = K1.*pww; % rate of gas production from wood (rho/s)
rwt = K2.*pww; % rate of tar production from wood (rho/s)
rwc = K3.*pww; % rate of char production from wood (rho/s)
end
Running the above code gives a temperature profile at the center and
surface of the wood cylinder:
As you can see from this plot, for some reason the center and surface
temperatures rapidly converge at the 2 min mark which isn't correct.
Any suggestions on how to fix this or create a more efficient way to solve
the problem?
reactions
I am trying to model heat conduction within a wood cylinder using implicit
finite difference methods. The general heat equation that I'm using for
cylindrical and spherical shapes is:
Where p is the shape factor, p = 1 for cylinder and p = 2 for sphere.
Boundary conditions include convection at the surface. For more details
about the model, please see the comments in the Matlab code below.
The main m-file is:
%--- main parameters
rhow = 650; % density of wood, kg/m^3
d = 0.02; % wood particle diameter, m
Ti = 300; % initial particle temp, K
Tinf = 673; % ambient temp, K
h = 60; % heat transfer coefficient, W/m^2*K
% A = pre-exponential factor, 1/s and E = activation energy, kJ/mol
A1 = 1.3e8; E1 = 140; % wood -> gas
A2 = 2e8; E2 = 133; % wood -> tar
A3 = 1.08e7; E3 = 121; % wood -> char
R = 0.008314; % universal gas constant, kJ/mol*K
%--- initial calculations
b = 1; % shape factor, b = 1 cylinder, b = 2 sphere
r = d/2; % particle radius, m
nt = 1000; % number of time steps
tmax = 840; % max time, s
dt = tmax/nt; % time step spacing, delta t
t = 0:dt:tmax; % time vector, s
m = 20; % number of radius nodes
steps = m-1; % number of radius steps
dr = r/steps; % radius step spacing, delta r
%--- build initial vectors for temperature and thermal properties
i = 1:m;
T(i,1) = Ti; % column vector of temperatures
TT(1,i) = Ti; % row vector to store temperatures
pw(1,i) = rhow; % initial density at each node is wood density, rhow
pg(1,i) = 0; % initial density of gas
pt(1,i) = 0; % inital density of tar
pc(1,i) = 0; % initial density of char
%--- solve system of equations [A][T]=[C] where T = A\C
for i = 2:nt+1
% kinetics at n
[rww, rwg, rwt, rwc] = funcY(A1,E1,A2,E2,A3,E3,R,T',pw(i-1,:));
pw(i,:) = pw(i-1,:) + rww.*dt; % update wood density
pg(i,:) = pg(i-1,:) + rwg.*dt; % update gas density
pt(i,:) = pt(i-1,:) + rwt.*dt; % update tar density
pc(i,:) = pc(i-1,:) + rwc.*dt; % update char density
Yw = pw(i,:)./(pw(i,:) + pc(i,:)); % wood fraction
Yc = pc(i,:)./(pw(i,:) + pc(i,:)); % char fraction
% thermal properties at n
cpw = 1112.0 + 4.85.*(T'-273.15); % wood heat capacity, J/(kg*K)
kw = 0.13 + (3e-4).*(T'-273.15); % wood thermal conductivity, W/(m*K)
cpc = 1003.2 + 2.09.*(T'-273.15); % char heat capacity, J/(kg*K)
kc = 0.08 - (1e-4).*(T'-273.15); % char thermal conductivity, W/(m*K)
cpbar = Yw.*cpw + Yc.*cpc; % effective heat capacity
kbar = Yw.*kw + Yc.*kc; % effective thermal conductivity
pbar = pw(i,:) + pc(i,:); % effective density
% temperature at n+1
Tn = funcACbar(pbar,cpbar,kbar,h,Tinf,b,m,dr,dt,T);
% kinetics at n+1
[rww, rwg, rwt, rwc] = funcY(A1,E1,A2,E2,A3,E3,R,Tn',pw(i-1,:));
pw(i,:) = pw(i-1,:) + rww.*dt;
pg(i,:) = pg(i-1,:) + rwg.*dt;
pt(i,:) = pt(i-1,:) + rwt.*dt;
pc(i,:) = pc(i-1,:) + rwc.*dt;
Yw = pw(i,:)./(pw(i,:) + pc(i,:));
Yc = pc(i,:)./(pw(i,:) + pc(i,:));
% thermal properties at n+1
cpw = 1112.0 + 4.85.*(Tn'-273.15);
kw = 0.13 + (3e-4).*(Tn'-273.15);
cpc = 1003.2 + 2.09.*(Tn'-273.15);
kc = 0.08 - (1e-4).*(Tn'-273.15);
cpbar = Yw.*cpw + Yc.*cpc;
kbar = Yw.*kw + Yc.*cpc;
pbar = pw(i,:) + pc(i,:);
% revise temperature at n+1
Tn = funcACbar(pbar,cpbar,kbar,h,Tinf,b,m,dr,dt,T);
% store temperature at n+1
T = Tn;
TT(i,:) = T';
end
%--- plot data
figure(1)
plot(t./60,TT(:,1),'-b',t./60,TT(:,m),'-r')
hold on
plot([0 tmax/60],[Tinf Tinf],':k')
hold off
xlabel('Time (min)'); ylabel('Temperature (K)');
sh = num2str(h); snt = num2str(nt); sm = num2str(m);
title(['Cylinder Model, d = 20mm, h = ',sh,', nt = ',snt,', m = ',sm])
legend('Tcenter','Tsurface',['T\infty =
',num2str(Tinf),'K'],'location','southeast')
figure(2)
plot(t./60,pw(:,1),'--',t./60,pw(:,m),'-','color',[0 0.7 0])
hold on
plot(t./60,pg(:,1),'--b',t./60,pg(:,m),'b')
hold on
plot(t./60,pt(:,1),'--k',t./60,pt(:,m),'k')
hold on
plot(t./60,pc(:,1),'--r',t./60,pc(:,m),'r')
hold off
xlabel('Time (min)'); ylabel('Density (kg/m^3)');
The function m-file, funcACbar, that creates the system of equations to
solve is:
% Finite difference equations for cylinder and sphere
% for 1D transient heat conduction with convection at surface
% general equation is:
% 1/alpha*dT/dt = d^2T/dr^2 + p/r*dT/dr for r ~= 0
% 1/alpha*dT/dt = (1 + p)*d^2T/dr^2 for r = 0
% where p is shape factor, p = 1 for cylinder, p = 2 for sphere
function T = funcACbar(pbar,cpbar,kbar,h,Tinf,b,m,dr,dt,T)
alpha = kbar./(pbar.*cpbar); % effective thermal diffusivity
Fo = alpha.*dt./(dr^2); % effective Fourier number
Bi = h.*dr./kbar; % effective Biot number
% [A] is coefficient matrix at time level n+1
% {C} is column vector at time level n
A(1,1) = 1 + 2*(1+b)*Fo(1);
A(1,2) = -2*(1+b)*Fo(2);
C(1,1) = T(1);
for k = 2:m-1
A(k,k-1) = -Fo(k-1)*(1 - b/(2*(k-1))); % Tm-1
A(k,k) = 1 + 2*Fo(k); % Tm
A(k,k+1) = -Fo(k+1)*(1 + b/(2*(k-1))); % Tm+1
C(k,1) = T(k);
end
A(m,m-1) = -2*Fo(m-1);
A(m,m) = 1 + 2*Fo(m)*(1 + Bi(m) + (b/(2*m))*Bi(m));
C(m,1) = T(m) + 2*Fo(m)*Bi(m)*(1 + b/(2*m))*Tinf;
% solve system of equations [A]{T} = {C} where temperature T = [A]\{C}
T = A\C;
end
And finally the function that deals with the kinetic reactions, funcY, is:
% Kinetic equations for reactions of wood, first-order, Arrhenious type
equations
% K = A*exp(-E/RT) where A = pre-exponential factor, 1/s
% and E = activation energy, kJ/mol
function [rww, rwg, rwt, rwc] = funcY(A1,E1,A2,E2,A3,E3,R,T,pww)
K1 = A1.*exp(-E1./(R.*T)); % wood -> gas (1/s)
K2 = A2.*exp(-E2./(R.*T)); % wood -> tar (1/s)
K3 = A3.*exp(-E3./(R.*T)); % wood -> char (1/s)
rww = -(K1+K2+K3).*pww; % rate of wood consumption (rho/s)
rwg = K1.*pww; % rate of gas production from wood (rho/s)
rwt = K2.*pww; % rate of tar production from wood (rho/s)
rwc = K3.*pww; % rate of char production from wood (rho/s)
end
Running the above code gives a temperature profile at the center and
surface of the wood cylinder:
As you can see from this plot, for some reason the center and surface
temperatures rapidly converge at the 2 min mark which isn't correct.
Any suggestions on how to fix this or create a more efficient way to solve
the problem?
AWS RDS Provisioned IOPS really worth it?
AWS RDS Provisioned IOPS really worth it?
As I understand it, RDS Provisioned IOPS is quite expensive compared to
standard I/O rate.
In Tokyo region, P-IOPS rate is 0.15$/GB, 0.12$/IOP for standard deployment.
Also, the minimum required storage is 100GB, IOP is 1000. Therefore,
starting cost for P-IOPS is 135$ excluding instance pricing.
For my case, using P-IOPS costs about 100X more than using standard I/O rate.
In the most optimized database for RDS P-IOPS, would the performance be
worth the price?
As I understand it, RDS Provisioned IOPS is quite expensive compared to
standard I/O rate.
In Tokyo region, P-IOPS rate is 0.15$/GB, 0.12$/IOP for standard deployment.
Also, the minimum required storage is 100GB, IOP is 1000. Therefore,
starting cost for P-IOPS is 135$ excluding instance pricing.
For my case, using P-IOPS costs about 100X more than using standard I/O rate.
In the most optimized database for RDS P-IOPS, would the performance be
worth the price?
I have to delete all browsing data every time I login to admin
I have to delete all browsing data every time I login to admin
I moved magento site from a sub-directory (http://mysite.com/magento) to
the parent directory (http://mysite.com). After successful transfer I
noticed that my site url does not have "www" So I added it up in the
Database in core_config_data in base and secure url fields.
That is before base and secure url were: http://mysite.com
After changing it: http://www.mysite.com (added www to it).
Then I removed everything from the Var folder and deleted browser history
with cookies and all other information of chrome.
There is no problem in frontend of the site, although I am not able to
login at admin side. It just returns me to login page without any error
but with a url like this
http://www.mysite.com/index.php/admin/index/index/key/b4f1cd105c9623c8d313c41e5c59f5b1/
I have browsed same questions asked at stackoverflow and some other forums
but all suggests to clean up cookies. But I think already did that, did I
miss something or need to do something more?
I moved magento site from a sub-directory (http://mysite.com/magento) to
the parent directory (http://mysite.com). After successful transfer I
noticed that my site url does not have "www" So I added it up in the
Database in core_config_data in base and secure url fields.
That is before base and secure url were: http://mysite.com
After changing it: http://www.mysite.com (added www to it).
Then I removed everything from the Var folder and deleted browser history
with cookies and all other information of chrome.
There is no problem in frontend of the site, although I am not able to
login at admin side. It just returns me to login page without any error
but with a url like this
http://www.mysite.com/index.php/admin/index/index/key/b4f1cd105c9623c8d313c41e5c59f5b1/
I have browsed same questions asked at stackoverflow and some other forums
but all suggests to clean up cookies. But I think already did that, did I
miss something or need to do something more?
How to extract last 2 characters before the extension of a filename in bash?
How to extract last 2 characters before the extension of a filename in bash?
What i would like to accomplish is to take a file name let's say
myfileRE.txt and return the new file name of myfile.txt. The extra two
characters will always be two characters and so what i tried to do was:
${filename%??.}
and my idea was "match the 2 characters that come right before the period
and rip those characters out" ..unfortunately that just returned the
entire filename.
I ended up doing this:
${filename%??????}.txt
but that's not very friendly and there must be a cleaner way to do it. Any
advice? Maybe something with regular expressions?
What i would like to accomplish is to take a file name let's say
myfileRE.txt and return the new file name of myfile.txt. The extra two
characters will always be two characters and so what i tried to do was:
${filename%??.}
and my idea was "match the 2 characters that come right before the period
and rip those characters out" ..unfortunately that just returned the
entire filename.
I ended up doing this:
${filename%??????}.txt
but that's not very friendly and there must be a cleaner way to do it. Any
advice? Maybe something with regular expressions?
Using Tipsy with Rails
Using Tipsy with Rails
I would like to know how to make use of plugins within my Rails app. For
example, while Tipsy (http://onehackoranother.com/projects/jquery/tipsy/)
does come in gem form it would be great if someone could show me how to
integrate it without the gem as I can then apply this to other plugins
that aren't in gem form.
A few questions: 1) Should I use the vendor folder? 2) Should I reference
the js and css before the application in my application layout file? 3)
Where does the image go and how do I reference the image from the Tipsy
css file?
I would like to know how to make use of plugins within my Rails app. For
example, while Tipsy (http://onehackoranother.com/projects/jquery/tipsy/)
does come in gem form it would be great if someone could show me how to
integrate it without the gem as I can then apply this to other plugins
that aren't in gem form.
A few questions: 1) Should I use the vendor folder? 2) Should I reference
the js and css before the application in my application layout file? 3)
Where does the image go and how do I reference the image from the Tipsy
css file?
Passing javascript variable to php function as parameter?
Passing javascript variable to php function as parameter?
I want to pass JavaScript variables to PHP using onchange event.
When I put the parameter directly like callT(3), it call the PHP function
callT($x) and return the value from PHP db and also print the value using
javascript. It is good.
If I pass the parameter through variable like the below source code, I
can't get the any result. Is there something wrong?
Here is the code:
<script type="text/javascript">
function calldata(){
var c=document.getElementById("bno").value;
var s="".concat("<?PHP callT(",c,"); ?>");
document.getElementById("dn").value= s;
}
</script>
<?PHP
FUNCTION callT($x)
{
$con=mysqli_connect("localhost","root","","books");
// Check connection
if (mysqli_connect_errno($con))
{
$msg = "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
$data = mysqli_query($con,"select * from books where BookId=".$x);
$row = mysqli_fetch_array($data);
echo $row[2];
}
mysqli_close($con);
}
?>
<html>
<body>
<form>
<select name="bno" id="bno" style="width:150px;"
onchange="calldata()">
<option>-</option>
<?php
$con=mysqli_connect("localhost","root","","books");
$data = mysqli_query($con, "SELECT bookid FROm
books");
while($row = mysqli_fetch_array($data))
{
echo " <option>" . $row[0] . " </option>";
}
?>
</select>
<br><br>
<input type="text" id="dn">
</form>
</body>
</html>
Please, help me. Thanks advance.
I want to pass JavaScript variables to PHP using onchange event.
When I put the parameter directly like callT(3), it call the PHP function
callT($x) and return the value from PHP db and also print the value using
javascript. It is good.
If I pass the parameter through variable like the below source code, I
can't get the any result. Is there something wrong?
Here is the code:
<script type="text/javascript">
function calldata(){
var c=document.getElementById("bno").value;
var s="".concat("<?PHP callT(",c,"); ?>");
document.getElementById("dn").value= s;
}
</script>
<?PHP
FUNCTION callT($x)
{
$con=mysqli_connect("localhost","root","","books");
// Check connection
if (mysqli_connect_errno($con))
{
$msg = "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
$data = mysqli_query($con,"select * from books where BookId=".$x);
$row = mysqli_fetch_array($data);
echo $row[2];
}
mysqli_close($con);
}
?>
<html>
<body>
<form>
<select name="bno" id="bno" style="width:150px;"
onchange="calldata()">
<option>-</option>
<?php
$con=mysqli_connect("localhost","root","","books");
$data = mysqli_query($con, "SELECT bookid FROm
books");
while($row = mysqli_fetch_array($data))
{
echo " <option>" . $row[0] . " </option>";
}
?>
</select>
<br><br>
<input type="text" id="dn">
</form>
</body>
</html>
Please, help me. Thanks advance.
solr, how to search two type data?
solr, how to search two type data?
My application has tow type( or more) data, just like following: 1- name:
nytimes news report, start_dt: 2013-09-13T 2- name: nytimes channel
I want to order result if has field start_dt, so I my qurey is:
q=nytimes+AND+start_dt:[NOW+TO+NOW/DAY%2B2DAY] but I want to get result of
Number 2 above, what I will do?
My application has tow type( or more) data, just like following: 1- name:
nytimes news report, start_dt: 2013-09-13T 2- name: nytimes channel
I want to order result if has field start_dt, so I my qurey is:
q=nytimes+AND+start_dt:[NOW+TO+NOW/DAY%2B2DAY] but I want to get result of
Number 2 above, what I will do?
Wednesday, 11 September 2013
Rendering html in Angular with Directive
Rendering html in Angular with Directive
I am storing html data in my database from the output of a WYSIWYG editor.
The html also stores the html for some directives. One of them being the
ui-bootstrap tooltip:
<span tooltip-placement="left" tooltip="On the Left!">Tooltip text
here</span>
I am able to get any other html elements to work by using the binding:
<div ng-bind-html-unsafe="html.content"></div>
But the html with the directive's reference doesn't interact with the
actual directive.
How can I get the directive to work?
Do I have to compile the html or something like that?
I am storing html data in my database from the output of a WYSIWYG editor.
The html also stores the html for some directives. One of them being the
ui-bootstrap tooltip:
<span tooltip-placement="left" tooltip="On the Left!">Tooltip text
here</span>
I am able to get any other html elements to work by using the binding:
<div ng-bind-html-unsafe="html.content"></div>
But the html with the directive's reference doesn't interact with the
actual directive.
How can I get the directive to work?
Do I have to compile the html or something like that?
#EANF#
#EANF#
Thanks for reviewing. I've found no fewer than 5 articles here and
reviewed all the tutorials on w3schools. There is no doubt in my mind that
this should be working, but alas it isn't. I need to dynamically add
options to a select box based upon a selection on a previous select box on
an HTML page. I'm using javascript because the wrapper for this page will
not support jquery. Here are requirements:
vent_pip must always start with an option having value "..." but blank
descriptor.
If selected option on vent select box is SIPAP, vent_pip should hold
values 4 thru 11 incrementing by 1.
If selected option on vent select box is Oscillator, vent_pip is not shown
and populating it is ignored.
If any other option is selected, vent_pip should hold values 12 through 30
incrementing by 2.
My javascript is properly populating the vent_pip select box with values
based upon selection from 'vent'.
THE PROBLEM: When the item in 'vent' is changed (ie picking CPAP first,
and then SIPAP) my javascript to wipe the values starting at position 1
(skipping '...' at position 0) from 'vent_pip' before adding new ones is
failing. Thus the 'vent_pip' select box will end up with something like
12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 4, 5, 6, 7, 8, 9, 10, 11.
Any help you can offer would be great. As I said I've tried to mimick
several of the posts here on SO as well as w3schools to no avail. Feel
free to link them but it's likely that I've already gone through. THANKS!
Pertinent function code:
var PIP = document.getElementById('vent_pip');
for(i=1;i<PIP.options.length-1;i++){
PIP.remove(i);
}
for(i=4;i<12;i++){
PIP.options[PIP.options.length] = new Option(i,i);
}
for(i=1;i<PIP.options.length-1;i++){
PIP.remove(i);
}
for(i=12;i<31;i++){
PIP.options[PIP.options.length] = new Option(i,i);
i++;
}
Larger Code block: (NOTE: This is not the entire file. I can provide it at
request.
<html>
<head>
<script type="text/javascript" language="javascript">
function showHide(sectionId,setting) {
document.getElementById(sectionId ).style.display = setting;
}
function checkSetting(vent){
var PIP = document.getElementById('vent_pip');
var i = 0;
if(document.getElementById(vent).value=="Oscillator"){
showHide('divOscSelect','block');
showHide('divNoOscSelect','none');
showHide('divSIPAPSelect','none');
showHide('divFiO2','block');
document.getElementById('cbx_vent').checked=true;
} else if(document.getElementById(vent).value=="SIPAP"){
showHide('divOscSelect','none');
showHide('divNoOscSelect','none');
showHide('divSIPAPSelect','block');
showHide('divFiO2','none');
for(i=1;i<PIP.options.length-1;i++){
PIP.remove(i);
}
for(i=4;i<12;i++){
PIP.options[PIP.options.length] = new Option(i,i);
}
document.getElementById('cbx_vent').checked=true;
} else {
showHide('divOscSelect','none');
showHide('divNoOscSelect','block');
showHide('divSIPAPSelect','block');
showHide('divFiO2','block');
for(i=1;i<PIP.options.length-1;i++){
PIP.remove(i);
}
for(i=12;i<31;i++){
PIP.options[PIP.options.length] = new Option(i,i);
i++;
}
document.getElementById('cbx_vent').checked=true;
}
if(document.getElementById(vent).value==""){
showHide('divOscSelect','none');
showHide('divNoOscSelect','none');
showHide('divSIPAPSelect','none');
showHide('divFiO2','none');
document.getElementById('cbx_vent').checked=false;
}
</script>
</head>
<body>
<form method="get" action="" name="common_admission">
<table width="100%">
<tr>
<td><input type="checkbox" name="cbx_vent" id="cbx_vent"
value="true"/>Ventilated Assistance</td>
</tr>
<tr>
<td width=145 valign="top" style="text-align:right">Mode:
</td>
<td>
<select name="vent" id="vent" onchange="checkSetting('vent');">
<option value=""></option>
<option value="Pressure Support Vent">PSV - Pressure Support
Vent</option>
<option value="Continuous Mandatory Vent">CMV - Continuous
Mandatory Vent</option>
<option value="Sync Intermittant Mandatory Vent">SIMV - Sync
Intermittant Mandatory Vent</option>
<option value="Assist Control Vent">AC - Assist Control Vent</option>
<option value="Cont Pos Air Pressure">CPAP - Cont Pos Air
Pressure</option>
<option value="Pressure Control Vent">Pressure Control Vent</option>
<option value="SIPAP">SIPAP</option>
<option value="Oscillator">Oscillator</option>
</select>
</td>
</tr>
</table>
<div id="divSIPAPSelect" style="display: none;">
<table width="100%">
<tr>
<td width="92%">PIP (cmH2O)
<select name="vent_pip" id="vent_pip">
<option value="..."></option>
</select>
</td>
</tr>
</table>
</form>
</body>
</html>
Thanks for reviewing. I've found no fewer than 5 articles here and
reviewed all the tutorials on w3schools. There is no doubt in my mind that
this should be working, but alas it isn't. I need to dynamically add
options to a select box based upon a selection on a previous select box on
an HTML page. I'm using javascript because the wrapper for this page will
not support jquery. Here are requirements:
vent_pip must always start with an option having value "..." but blank
descriptor.
If selected option on vent select box is SIPAP, vent_pip should hold
values 4 thru 11 incrementing by 1.
If selected option on vent select box is Oscillator, vent_pip is not shown
and populating it is ignored.
If any other option is selected, vent_pip should hold values 12 through 30
incrementing by 2.
My javascript is properly populating the vent_pip select box with values
based upon selection from 'vent'.
THE PROBLEM: When the item in 'vent' is changed (ie picking CPAP first,
and then SIPAP) my javascript to wipe the values starting at position 1
(skipping '...' at position 0) from 'vent_pip' before adding new ones is
failing. Thus the 'vent_pip' select box will end up with something like
12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 4, 5, 6, 7, 8, 9, 10, 11.
Any help you can offer would be great. As I said I've tried to mimick
several of the posts here on SO as well as w3schools to no avail. Feel
free to link them but it's likely that I've already gone through. THANKS!
Pertinent function code:
var PIP = document.getElementById('vent_pip');
for(i=1;i<PIP.options.length-1;i++){
PIP.remove(i);
}
for(i=4;i<12;i++){
PIP.options[PIP.options.length] = new Option(i,i);
}
for(i=1;i<PIP.options.length-1;i++){
PIP.remove(i);
}
for(i=12;i<31;i++){
PIP.options[PIP.options.length] = new Option(i,i);
i++;
}
Larger Code block: (NOTE: This is not the entire file. I can provide it at
request.
<html>
<head>
<script type="text/javascript" language="javascript">
function showHide(sectionId,setting) {
document.getElementById(sectionId ).style.display = setting;
}
function checkSetting(vent){
var PIP = document.getElementById('vent_pip');
var i = 0;
if(document.getElementById(vent).value=="Oscillator"){
showHide('divOscSelect','block');
showHide('divNoOscSelect','none');
showHide('divSIPAPSelect','none');
showHide('divFiO2','block');
document.getElementById('cbx_vent').checked=true;
} else if(document.getElementById(vent).value=="SIPAP"){
showHide('divOscSelect','none');
showHide('divNoOscSelect','none');
showHide('divSIPAPSelect','block');
showHide('divFiO2','none');
for(i=1;i<PIP.options.length-1;i++){
PIP.remove(i);
}
for(i=4;i<12;i++){
PIP.options[PIP.options.length] = new Option(i,i);
}
document.getElementById('cbx_vent').checked=true;
} else {
showHide('divOscSelect','none');
showHide('divNoOscSelect','block');
showHide('divSIPAPSelect','block');
showHide('divFiO2','block');
for(i=1;i<PIP.options.length-1;i++){
PIP.remove(i);
}
for(i=12;i<31;i++){
PIP.options[PIP.options.length] = new Option(i,i);
i++;
}
document.getElementById('cbx_vent').checked=true;
}
if(document.getElementById(vent).value==""){
showHide('divOscSelect','none');
showHide('divNoOscSelect','none');
showHide('divSIPAPSelect','none');
showHide('divFiO2','none');
document.getElementById('cbx_vent').checked=false;
}
</script>
</head>
<body>
<form method="get" action="" name="common_admission">
<table width="100%">
<tr>
<td><input type="checkbox" name="cbx_vent" id="cbx_vent"
value="true"/>Ventilated Assistance</td>
</tr>
<tr>
<td width=145 valign="top" style="text-align:right">Mode:
</td>
<td>
<select name="vent" id="vent" onchange="checkSetting('vent');">
<option value=""></option>
<option value="Pressure Support Vent">PSV - Pressure Support
Vent</option>
<option value="Continuous Mandatory Vent">CMV - Continuous
Mandatory Vent</option>
<option value="Sync Intermittant Mandatory Vent">SIMV - Sync
Intermittant Mandatory Vent</option>
<option value="Assist Control Vent">AC - Assist Control Vent</option>
<option value="Cont Pos Air Pressure">CPAP - Cont Pos Air
Pressure</option>
<option value="Pressure Control Vent">Pressure Control Vent</option>
<option value="SIPAP">SIPAP</option>
<option value="Oscillator">Oscillator</option>
</select>
</td>
</tr>
</table>
<div id="divSIPAPSelect" style="display: none;">
<table width="100%">
<tr>
<td width="92%">PIP (cmH2O)
<select name="vent_pip" id="vent_pip">
<option value="..."></option>
</select>
</td>
</tr>
</table>
</form>
</body>
</html>
Programatically add 100s of image overlays on video clip
Programatically add 100s of image overlays on video clip
I'm looking for a programmatic video editing solution which could provide
API for adding image and text overlays in specific times/frames at
specific coordinates on a video (1080p) clip, as well as resizing to 720p
etc.
I tried AviSynth but got blocked after ~400 overlays in total because of
"Out of Memory error" - see AviSynth Out of Memory Error (100s of image
overlays)
Is there anything else I could try?
I'm looking for a programmatic video editing solution which could provide
API for adding image and text overlays in specific times/frames at
specific coordinates on a video (1080p) clip, as well as resizing to 720p
etc.
I tried AviSynth but got blocked after ~400 overlays in total because of
"Out of Memory error" - see AviSynth Out of Memory Error (100s of image
overlays)
Is there anything else I could try?
mysql query - multiple counts using left join and where clause
mysql query - multiple counts using left join and where clause
I'm currently trying to get the following data:
UserName, UserImageURL, Total Games Played, Games Completed, Games Lost,
Average Won (as percentage) and Points of the user
And as well another set of data:
User Statistics data such as:
Most Games Played on League: 23 - Monster Killers
Games Most Won On: 19/23 - Monster Killers
Games Most Lost On: 3/32 - Frog Racers
Your Game Winning Accuracy (total from all games) - 68% accuracy
Site Stats:
Most Games Played on League: 650 - Helicopter Run
Top Game Played: 1200 - Monster Killers
Whole site winning accuracy: 82%
I have the following Tables:
-User Table-
userID (int-pk), userName (varchar), userImageUrl (text)
-Games table-
gameId (int-pk), gameName (varchar), gameUserID (int), gameLeagueId (int),
score1 (int), score2 (int), gameResultOut (0 or 1), gameWon (0 or 1)
-UserBalance table-
ubId(int-pk) userId (int) balance (int)
-League table- leagueId (int-pk) leagueName (varchar)
Just to give you a heads up on what's happening, when a user plays a game
and chooses some results a row is inserted into the games table. Since the
game is time based, when the results are out, there is a check that checks
if there are any games which have that id and will update the
gameResultOut to 1 and gameWon to 1 or 0 according to what the user had
selected as a score.
I tried the following:
SELECT u.userID, u.userName, u.userImageUrl, l.leagueName ,
COUNT(g.gameId) AS predTotal,
(SELECT COUNT(g.gameId) FROM games AS g WHERE g.gameResultOut = 1 AND
g.gameWon = 1) AS gamesWon,
(SELECT COUNT(g.gameId) FROM games AS g WHERE g.gameResultOut = 1 AND
g.gameWon = 0) AS gamesLost,
ub.balance
FROM games AS g
LEFT JOIN league AS l ON l.leagueId = g.gameLeagueId
LEFT JOIN user AS u ON u.user_id = g.gameUserID
LEFT JOIN user_balance AS ub ON ub.userId = u.userID
WHERE l.leagueId = 4
GROUP BY u.userId
ORDER BY ub.balance DESC
I can calculate easily the win percentage after the query so that's not a
problem, but the result for the Wins and Lost are all the same and even
when it comes to changing the leageId, the results are still the same
which is not what I want.
Can anyone help?
Thanks & Regards, Necron
I'm currently trying to get the following data:
UserName, UserImageURL, Total Games Played, Games Completed, Games Lost,
Average Won (as percentage) and Points of the user
And as well another set of data:
User Statistics data such as:
Most Games Played on League: 23 - Monster Killers
Games Most Won On: 19/23 - Monster Killers
Games Most Lost On: 3/32 - Frog Racers
Your Game Winning Accuracy (total from all games) - 68% accuracy
Site Stats:
Most Games Played on League: 650 - Helicopter Run
Top Game Played: 1200 - Monster Killers
Whole site winning accuracy: 82%
I have the following Tables:
-User Table-
userID (int-pk), userName (varchar), userImageUrl (text)
-Games table-
gameId (int-pk), gameName (varchar), gameUserID (int), gameLeagueId (int),
score1 (int), score2 (int), gameResultOut (0 or 1), gameWon (0 or 1)
-UserBalance table-
ubId(int-pk) userId (int) balance (int)
-League table- leagueId (int-pk) leagueName (varchar)
Just to give you a heads up on what's happening, when a user plays a game
and chooses some results a row is inserted into the games table. Since the
game is time based, when the results are out, there is a check that checks
if there are any games which have that id and will update the
gameResultOut to 1 and gameWon to 1 or 0 according to what the user had
selected as a score.
I tried the following:
SELECT u.userID, u.userName, u.userImageUrl, l.leagueName ,
COUNT(g.gameId) AS predTotal,
(SELECT COUNT(g.gameId) FROM games AS g WHERE g.gameResultOut = 1 AND
g.gameWon = 1) AS gamesWon,
(SELECT COUNT(g.gameId) FROM games AS g WHERE g.gameResultOut = 1 AND
g.gameWon = 0) AS gamesLost,
ub.balance
FROM games AS g
LEFT JOIN league AS l ON l.leagueId = g.gameLeagueId
LEFT JOIN user AS u ON u.user_id = g.gameUserID
LEFT JOIN user_balance AS ub ON ub.userId = u.userID
WHERE l.leagueId = 4
GROUP BY u.userId
ORDER BY ub.balance DESC
I can calculate easily the win percentage after the query so that's not a
problem, but the result for the Wins and Lost are all the same and even
when it comes to changing the leageId, the results are still the same
which is not what I want.
Can anyone help?
Thanks & Regards, Necron
how to set template page and load it using Eztemplate of Codeigniter
how to set template page and load it using Eztemplate of Codeigniter
I am new to CI and i just want to set the default template page, I am now
using a library called Eztemplatei tried to load the view by using the
following code:
`$this->template
->set('title','Home')
->load('view','index')
->render();`
but it's not working and it seems that all the files haven't been loaded.
Any help would be much appreciated
I am new to CI and i just want to set the default template page, I am now
using a library called Eztemplatei tried to load the view by using the
following code:
`$this->template
->set('title','Home')
->load('view','index')
->render();`
but it's not working and it seems that all the files haven't been loaded.
Any help would be much appreciated
Tuesday, 10 September 2013
How to hide Credit Card Payment Method on Magento with Onepage Checkout enable?
How to hide Credit Card Payment Method on Magento with Onepage Checkout
enable?
I want to keep Onepage Checkout enable (YES), but just one to offer the
standar on Paypal site payment. By default once Onepage Checkout is
activated, Payment page will show the Credit Card option. My question is:
How to hide the Credit Card Payment Option even with Onepage Checkout
enable, just to offer Paypal site payment (standar) ?? My engine is
Magento 1.7.0.2. Please let me know files and codes to change. Thanks in
advance. Hergonof
enable?
I want to keep Onepage Checkout enable (YES), but just one to offer the
standar on Paypal site payment. By default once Onepage Checkout is
activated, Payment page will show the Credit Card option. My question is:
How to hide the Credit Card Payment Option even with Onepage Checkout
enable, just to offer Paypal site payment (standar) ?? My engine is
Magento 1.7.0.2. Please let me know files and codes to change. Thanks in
advance. Hergonof
Compare string array with a single string entered by user , it also tell that it is found 2times &at that position
Compare string array with a single string entered by user , it also tell
that it is found 2times &at that position
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
clrscr();
char str[3][10], search[10];
int i, t = 0, k;
cout << "Enter 3 Names Of Fruit" << endl;
for (i = 0; i < 3; i++)
cin >> str[i];
cout << "Enter Fruit Name To Search" << endl;
cin >> search;
for (i = 0; i < 3; i++)
{
if (search == str[i]) // if statement is not giving true
{
t++;
k = i;
}
}
cout << "The " << search << " is found " << t <<
" times and is at position " << k << endl;
getch();
}
that it is found 2times &at that position
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
clrscr();
char str[3][10], search[10];
int i, t = 0, k;
cout << "Enter 3 Names Of Fruit" << endl;
for (i = 0; i < 3; i++)
cin >> str[i];
cout << "Enter Fruit Name To Search" << endl;
cin >> search;
for (i = 0; i < 3; i++)
{
if (search == str[i]) // if statement is not giving true
{
t++;
k = i;
}
}
cout << "The " << search << " is found " << t <<
" times and is at position " << k << endl;
getch();
}
How do i query a database that stores times in utc, with ruby?
How do i query a database that stores times in utc, with ruby?
I am in the Central timezone (ENV['TZ'] = America/Chicago) but all my
MongoDB entries are stored in UTC format. So if I want to query entries
for all of yesterday, I have to overcompensate for the timezone:
tz = 5.hours
d1 = Date.yesterday.at_midnight + tz
d2 = d1 + 1.day
Entry.where(:created_at.gte => d1, :created_at.lt => d2)
I'm pretty sure that this is a major hack, but I'm not sure how to fix
this correctly? Should it be on the database end, or in the code. Are
there some reading resources that teach how to do this correctly?
I am in the Central timezone (ENV['TZ'] = America/Chicago) but all my
MongoDB entries are stored in UTC format. So if I want to query entries
for all of yesterday, I have to overcompensate for the timezone:
tz = 5.hours
d1 = Date.yesterday.at_midnight + tz
d2 = d1 + 1.day
Entry.where(:created_at.gte => d1, :created_at.lt => d2)
I'm pretty sure that this is a major hack, but I'm not sure how to fix
this correctly? Should it be on the database end, or in the code. Are
there some reading resources that teach how to do this correctly?
What programming language to choose for Windows' future? [on hold]
What programming language to choose for Windows' future? [on hold]
I looked through some already answered questions here and didn't really
find what I am looking for. I want to start getting intro programming in
Windows 8 / Windows Phone 8 area, but I'm really not into forgetting about
anything else out there. I can't decide between going with C# or
HTML5/Javascript. What I am looking for is something to use in the future
and slightly migrate to web maybe someday ? From what I see HTML5 is
beginning to take place everywhere, from games to web apps and pretty much
it's expanding. I want to be there when it's gonna boom like Opa Gangman
Style did, lol.
I did some C++ in high school and recently watched some tutorials on C#.
Have to say, everything looks kinda familiar, which is not a surprise.
So is HTML5/Javascript going to be a good set of skills to have for future
development or should I stick to C# since it's easier for me ? I want to
be prepared for the future.
I looked through some already answered questions here and didn't really
find what I am looking for. I want to start getting intro programming in
Windows 8 / Windows Phone 8 area, but I'm really not into forgetting about
anything else out there. I can't decide between going with C# or
HTML5/Javascript. What I am looking for is something to use in the future
and slightly migrate to web maybe someday ? From what I see HTML5 is
beginning to take place everywhere, from games to web apps and pretty much
it's expanding. I want to be there when it's gonna boom like Opa Gangman
Style did, lol.
I did some C++ in high school and recently watched some tutorials on C#.
Have to say, everything looks kinda familiar, which is not a surprise.
So is HTML5/Javascript going to be a good set of skills to have for future
development or should I stick to C# since it's easier for me ? I want to
be prepared for the future.
Issue with Redirect not functioning in Rail 2
Issue with Redirect not functioning in Rail 2
I have this redirection in the middle of my controller so if something
isn't there, it will redirect you to a new area of the site if needed.
Here is the problem. It is just ignoring the redirect in the code. It
looks like this.
if conditions
redirect_to "/new/address"
end
I can't even figure out why it won't redirect, but I know it makes it into
the conditional and literally just ignores the redirect. What am I missing
here!?
I am using Rails 2 and Ruby 1.8
I have this redirection in the middle of my controller so if something
isn't there, it will redirect you to a new area of the site if needed.
Here is the problem. It is just ignoring the redirect in the code. It
looks like this.
if conditions
redirect_to "/new/address"
end
I can't even figure out why it won't redirect, but I know it makes it into
the conditional and literally just ignores the redirect. What am I missing
here!?
I am using Rails 2 and Ruby 1.8
Doctrine 2 - Mapping multiple inheritance type from a single Entity
Doctrine 2 - Mapping multiple inheritance type from a single Entity
It's possible to set a multiple inheritance type from a single Entity?
I have this Entity
namespace Oilproject\ContentBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\InheritanceType("SINGLE_TABLE")
* @ORM\DiscriminatorColumn(name="type", type="integer")
* @ORM\DiscriminatorMap({"5" = "ContentAnswer"})
* @ORM\HasLifecycleCallbacks
* @ORM\Table(name="content")
*/
class Content
{
//My attributes
}
and i want to extend this Entity with another Entity but with "JOIN"
inheritance type. It's possible?
It's possible to set a multiple inheritance type from a single Entity?
I have this Entity
namespace Oilproject\ContentBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\InheritanceType("SINGLE_TABLE")
* @ORM\DiscriminatorColumn(name="type", type="integer")
* @ORM\DiscriminatorMap({"5" = "ContentAnswer"})
* @ORM\HasLifecycleCallbacks
* @ORM\Table(name="content")
*/
class Content
{
//My attributes
}
and i want to extend this Entity with another Entity but with "JOIN"
inheritance type. It's possible?
Alertview with integer
Alertview with integer
Hello to everyone i would like to place my thinking about an alertview. I
am thinking to create an Uialertview which will prompt the user to input
two integers. Then i would like to retrieve these two integers and put the
one on a timer and the second in an sql statement. So if anyone can help
on how to implement that i would apreciate it. Thank you all.
Here is my code until now
UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"info"
message:@"Set time For The Game." delegate:nil cancelButtonTitle:@"OK"
otherButtonTitles:@"cancel", nil];
alertView.alertViewStyle=UIAlertViewStylePlainTextInput;
NSLog(@"Entered: %@", [[alertView textFieldAtIndex:0] text]);
[alertView show];
Hello to everyone i would like to place my thinking about an alertview. I
am thinking to create an Uialertview which will prompt the user to input
two integers. Then i would like to retrieve these two integers and put the
one on a timer and the second in an sql statement. So if anyone can help
on how to implement that i would apreciate it. Thank you all.
Here is my code until now
UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"info"
message:@"Set time For The Game." delegate:nil cancelButtonTitle:@"OK"
otherButtonTitles:@"cancel", nil];
alertView.alertViewStyle=UIAlertViewStylePlainTextInput;
NSLog(@"Entered: %@", [[alertView textFieldAtIndex:0] text]);
[alertView show];
Registering multiple typed factories in the Castle Windsor container
Registering multiple typed factories in the Castle Windsor container
I am trying to register all of my typed factories in Castle Windsor using
a single registration. All of my factories implement IModelFactory so I
would like to be able to write something like:
container.Register(Types.FromThisAssembly()
.BasedOn<IModelFactory>()
.AsFactory());
The BasedOn method returns a type BasedOnDescriptor which does not allow
me to call the AsFactory() extension method.
Do I really need to register all typed factories one by one?
I am trying to register all of my typed factories in Castle Windsor using
a single registration. All of my factories implement IModelFactory so I
would like to be able to write something like:
container.Register(Types.FromThisAssembly()
.BasedOn<IModelFactory>()
.AsFactory());
The BasedOn method returns a type BasedOnDescriptor which does not allow
me to call the AsFactory() extension method.
Do I really need to register all typed factories one by one?
Monday, 9 September 2013
How to add objects to NSMutableArray from another array
How to add objects to NSMutableArray from another array
I have an array "names" which contains names starting with letters a, b
and c.(like anju,chandu,basha,chitra,amith,baskar)
I have three NS mutable arrays as,bs and cs.
Now the question is how to get the names from "names" array assign the
names starting with letter 'a' to 'as' mutable array, names starting with
letter 'b' to 'bs' mutable array and names starting with letter 'c' to
'cs' mutable array?
Could anyone please help..
Thank you.
I have an array "names" which contains names starting with letters a, b
and c.(like anju,chandu,basha,chitra,amith,baskar)
I have three NS mutable arrays as,bs and cs.
Now the question is how to get the names from "names" array assign the
names starting with letter 'a' to 'as' mutable array, names starting with
letter 'b' to 'bs' mutable array and names starting with letter 'c' to
'cs' mutable array?
Could anyone please help..
Thank you.
How to check a combination of 3 keys pressed at same time c#
How to check a combination of 3 keys pressed at same time c#
there is a posibility to check if 3 keys are pressed at the same time. For
example "sdf" or we can only check for one at the time?
there is a posibility to check if 3 keys are pressed at the same time. For
example "sdf" or we can only check for one at the time?
Res folders. Read file manually
Res folders. Read file manually
I have String.xml files organized by language inside my res folder like:
res/values
res/values-de
res/values-es
res/values-fr
res/values-ga
res/values-hi
res/values-it
...
By default the app make a choose according to device's language or by
finding Best Match. Now, I want to include a language selector to let the
user choose any of them. Is there a way to read those files without moving
them to assets folder or any other place? Is it something it can be done
once or should I do it by every activity?
I found some "solutions", but they are not permanent nor clean since they
need to be done on each activity.
I have String.xml files organized by language inside my res folder like:
res/values
res/values-de
res/values-es
res/values-fr
res/values-ga
res/values-hi
res/values-it
...
By default the app make a choose according to device's language or by
finding Best Match. Now, I want to include a language selector to let the
user choose any of them. Is there a way to read those files without moving
them to assets folder or any other place? Is it something it can be done
once or should I do it by every activity?
I found some "solutions", but they are not permanent nor clean since they
need to be done on each activity.
Indrustry standard UI design program
Indrustry standard UI design program
I want to know what is the industry standard for UI design? Like for icons
it's Adobe Illustrator, for video editing Adobe Premiere pro, but what's
the industry standard for UI design (not for implementing functionality,
just sketching the UI and adding fine detail).
Thanks!
I want to know what is the industry standard for UI design? Like for icons
it's Adobe Illustrator, for video editing Adobe Premiere pro, but what's
the industry standard for UI design (not for implementing functionality,
just sketching the UI and adding fine detail).
Thanks!
Read out elements of a string in specific order
Read out elements of a string in specific order
For some reasons I have to use a specific string in my project. This is
the text file (it's a JSON File):
{"algorithm":
[
{ "key": "onGapLeft", "value" : "moveLeft" },
{ "key": "onGapFront", "value" : "moveForward" },
{ "key": "onGapRight", "value" : "moveRight" },
{ "key": "default", "value" : "moveBackward" }
]
}
I've defined it in JAVA like this:
static String input = "{\"algorithm\": \n"+
"[ \n" +
"{ \"key\": \"onGapLeft\", \"value\" : \"moveLeft\" }, \n" +
"{ \"key\": \"onGapFront\", \"value\" : \"moveForward\" }, \n" +
"{ \"key\": \"onGapRight\", \"value\" : \"moveRight\" }, \n" +
"{ \"key\": \"default\", \"value\" : \"moveBackward\" } \n" +
"] \n" +
"}";
Now I have to isolate the keys and values in an array:
key[0] = onGapLeft; value[0] = moveLeft;
key[1] = onGapFront; value[1] = moveForward;
key[2] = onGapRight; value[2] = moveRight;
key[3] = default; value[3] = moveBackward;
I'm new to JAVA and don't understand the string class very well. Is there
an easy way to get to that result? You would help me really!
Thanks!
UPDATE: I didn't explained it well enough, sorry. This program will run on
a LEGO NXT Robot. JSON won't work there as I want it to so I have to
interpret this JSON File as a normal STRING! Hope that explains what I
want :)
For some reasons I have to use a specific string in my project. This is
the text file (it's a JSON File):
{"algorithm":
[
{ "key": "onGapLeft", "value" : "moveLeft" },
{ "key": "onGapFront", "value" : "moveForward" },
{ "key": "onGapRight", "value" : "moveRight" },
{ "key": "default", "value" : "moveBackward" }
]
}
I've defined it in JAVA like this:
static String input = "{\"algorithm\": \n"+
"[ \n" +
"{ \"key\": \"onGapLeft\", \"value\" : \"moveLeft\" }, \n" +
"{ \"key\": \"onGapFront\", \"value\" : \"moveForward\" }, \n" +
"{ \"key\": \"onGapRight\", \"value\" : \"moveRight\" }, \n" +
"{ \"key\": \"default\", \"value\" : \"moveBackward\" } \n" +
"] \n" +
"}";
Now I have to isolate the keys and values in an array:
key[0] = onGapLeft; value[0] = moveLeft;
key[1] = onGapFront; value[1] = moveForward;
key[2] = onGapRight; value[2] = moveRight;
key[3] = default; value[3] = moveBackward;
I'm new to JAVA and don't understand the string class very well. Is there
an easy way to get to that result? You would help me really!
Thanks!
UPDATE: I didn't explained it well enough, sorry. This program will run on
a LEGO NXT Robot. JSON won't work there as I want it to so I have to
interpret this JSON File as a normal STRING! Hope that explains what I
want :)
Bind "insertion into DOM event" for not-yet-appended element
Bind "insertion into DOM event" for not-yet-appended element
I'm looking for something like this:
var div = document.createElement('div');
div.id = 'proprioceptiveDiv';
$(div).on('appendedToDOM', function() {
// ...
});
document.body.appendChild(div); // triggers above handler
Does this exist? I'm using jQuery and would rather not import a whole
plugin or another library just for this ability, so I'm only interested in
a short solution.
I'm looking for something like this:
var div = document.createElement('div');
div.id = 'proprioceptiveDiv';
$(div).on('appendedToDOM', function() {
// ...
});
document.body.appendChild(div); // triggers above handler
Does this exist? I'm using jQuery and would rather not import a whole
plugin or another library just for this ability, so I'm only interested in
a short solution.
Can I burn VirtualBox VM into real environment?
Can I burn VirtualBox VM into real environment?
I haven't found a lot by googling but was thinking about burning virtual
machine image into a real system instead of a virtual one to have exact
copy but not inside a VM.
From theory it should be really possible and quite easy as OS would just
detect hardware changes. However in practise, I am not sure how to
accomplish that.
I would appreciate any help about this topic.
I haven't found a lot by googling but was thinking about burning virtual
machine image into a real system instead of a virtual one to have exact
copy but not inside a VM.
From theory it should be really possible and quite easy as OS would just
detect hardware changes. However in practise, I am not sure how to
accomplish that.
I would appreciate any help about this topic.
Sunday, 8 September 2013
Show different content based on radius of IP location?
Show different content based on radius of IP location?
I need to show a different phone number on the homepage based on the
user's ip location. It will be for a dynamic and changing number of store
locations. So if a user visits the site and their ip location is within 50
miles of one of our stores, that store number will be displayed. If we do
not have a store within 50 miles of their location, the default number
will be displayed. When we open a new store, we will add the phone number
and city (or zip, whatever is needed) into a custom field within
Wordpress. This data is what I need to use to do the geotargeting.
I have read countless articles and know I need to connect to a database
like max mind, but I can't figure out how to do the radius part. Can
anyone point me in the right direction? A plugin or free service that can
get me most of the way there?
Thank you.
I need to show a different phone number on the homepage based on the
user's ip location. It will be for a dynamic and changing number of store
locations. So if a user visits the site and their ip location is within 50
miles of one of our stores, that store number will be displayed. If we do
not have a store within 50 miles of their location, the default number
will be displayed. When we open a new store, we will add the phone number
and city (or zip, whatever is needed) into a custom field within
Wordpress. This data is what I need to use to do the geotargeting.
I have read countless articles and know I need to connect to a database
like max mind, but I can't figure out how to do the radius part. Can
anyone point me in the right direction? A plugin or free service that can
get me most of the way there?
Thank you.
Godaddy Laravel 4 deployment errors
Godaddy Laravel 4 deployment errors
Ok I finished my laravel application and uploaded onto my godaddy shared
hosting account.
The very first error I got was:
syntax error, unexpected '['
and it points at these bits:
Route::get("/", [
"uses" => "HomeController@showWelcome"
]);
Does it have anything to do with the version of php? I was developing the
app using 5.4.1 and tried to deploy it using PHP Version 5.3.24
Ok I finished my laravel application and uploaded onto my godaddy shared
hosting account.
The very first error I got was:
syntax error, unexpected '['
and it points at these bits:
Route::get("/", [
"uses" => "HomeController@showWelcome"
]);
Does it have anything to do with the version of php? I was developing the
app using 5.4.1 and tried to deploy it using PHP Version 5.3.24
Pin Annotation with UIAlertView
Pin Annotation with UIAlertView
I created a button in a "bottom bar." When the user presses the button, I
am trying to show a UIAlertView, so the user can enter an address which
will result in a blue pin being shown on the map. This pin should then be
saved to NSUserDefaults, so that the location is saved each time the app
is restarted.
Here is what I have so far. The user can enter the address in the
UIAlertView, but nothing happens...
- (IBAction)selectHq:(UIBarButtonItem *)sender
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Select
Headquarters"
message:@"Enter Address"
delegate:self
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"Ok", nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[[alert textFieldAtIndex:0]
setKeyboardType:UIKeyboardTypeNumbersAndPunctuation];
[alert show];
UITextField *field = [alert textFieldAtIndex:0];
field.placeholder = @"Enter HQ Address";
if (!self.geocoder)
{
self.geocoder = [[CLGeocoder alloc] init];
}
NSString *hqAddress = [NSString stringWithFormat:@"%@", field.text];
[self.geocoder geocodeAddressString:hqAddress
completionHandler:^(NSArray *placemarks, NSError *error) {
if ([placemarks count] > 0)
{
CLPlacemark *placemark = [placemarks objectAtIndex:0];
CLLocation *location = placemark.location;
CLLocationCoordinate2D hqCoordinate = location.coordinate;
NSLog (@"%f %f", hqCoordinate.latitude, hqCoordinate.longitude);
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta = 0.01;
span.longitudeDelta = 0.01;
region.span = span;
region.center = hqCoordinate;
MKPointAnnotation *hqAnnotation = [[MKPointAnnotation alloc]
init];
[hqAnnotation setCoordinate:hqCoordinate];
[hqAnnotation setTitle:@"HQ"];
[[self mapView] addAnnotation:hqAnnotation];
[self.mapView setRegion:region animated:TRUE];
[self.mapView regionThatFits:region];
}
}];
[[NSUserDefaults standardUserDefaults] setObject:field.text
forKey:HQ_KEY];
[[NSUserDefaults standardUserDefaults] synchronize];
I created a button in a "bottom bar." When the user presses the button, I
am trying to show a UIAlertView, so the user can enter an address which
will result in a blue pin being shown on the map. This pin should then be
saved to NSUserDefaults, so that the location is saved each time the app
is restarted.
Here is what I have so far. The user can enter the address in the
UIAlertView, but nothing happens...
- (IBAction)selectHq:(UIBarButtonItem *)sender
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Select
Headquarters"
message:@"Enter Address"
delegate:self
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"Ok", nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[[alert textFieldAtIndex:0]
setKeyboardType:UIKeyboardTypeNumbersAndPunctuation];
[alert show];
UITextField *field = [alert textFieldAtIndex:0];
field.placeholder = @"Enter HQ Address";
if (!self.geocoder)
{
self.geocoder = [[CLGeocoder alloc] init];
}
NSString *hqAddress = [NSString stringWithFormat:@"%@", field.text];
[self.geocoder geocodeAddressString:hqAddress
completionHandler:^(NSArray *placemarks, NSError *error) {
if ([placemarks count] > 0)
{
CLPlacemark *placemark = [placemarks objectAtIndex:0];
CLLocation *location = placemark.location;
CLLocationCoordinate2D hqCoordinate = location.coordinate;
NSLog (@"%f %f", hqCoordinate.latitude, hqCoordinate.longitude);
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta = 0.01;
span.longitudeDelta = 0.01;
region.span = span;
region.center = hqCoordinate;
MKPointAnnotation *hqAnnotation = [[MKPointAnnotation alloc]
init];
[hqAnnotation setCoordinate:hqCoordinate];
[hqAnnotation setTitle:@"HQ"];
[[self mapView] addAnnotation:hqAnnotation];
[self.mapView setRegion:region animated:TRUE];
[self.mapView regionThatFits:region];
}
}];
[[NSUserDefaults standardUserDefaults] setObject:field.text
forKey:HQ_KEY];
[[NSUserDefaults standardUserDefaults] synchronize];
Ajax load via jquery, content not shown
Ajax load via jquery, content not shown
hi i have a html file which use ajax for loading contents from other html
files in the same server. for some reason it does not work?? i have no
clue as i am new to ajax.
here is the index.html(default home page)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="demo.css" />
<script type="text/javascript" src="../jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head><body><div id="rounded">
<img src="img/top_bg.gif" alt="top" /><div id="main" class="container">
<h1>ajax example</h1>
<h2>ajax jquery</h2>
<ul id="navigation">
<li><a href="#info">Page_1</a></li>
<li><a href="#page2">Page2</a></li>
<li><a href="#page3">Page_3</a></li>
<li><a href="#page4">Page_4</a></li>
<li><img id="loading" src="img/ajax_load.gif" alt="loading" /></li>
</ul>
<div class="clear"></div>
<div id="pageContent">
it is a test</div>
</div><div class="clear"></div>
<img src="img/bottom_bg.gif" alt="bottom" /></div>
</body>
</html>
script.js(for adding hash in the url and enable back button and also
loading content)
var default_content="";
$(document).ready(function(){
checkURL();
$('ul li a').click(function (e){
checkURL(this.hash);
});
default_content = $('#pageContent').html();
setInterval("checkURL()",250);
});
var lasturl="";
function checkURL(hash)
{
if(!hash) hash=window.location.hash;
if(hash != lasturl)
{
lasturl=hash;
if(hash=="")
$('#pageContent').html(default_content);
else
loadPage(hash);
}
}
function loadPage(url)
{
var datastring=url.replace('#','');
$('#loading').css('visibility','visible');
$.ajax({
type: "POST",
url: "load_page.php",
data: 'datastring='+datastring,
dataType: "html",
async: false,
success: function(msg){
if(parseInt(msg)!=0)
{
$('#content').html(msg);
$('#loading').css('visibility','hidden');
}
}
});
}
and load_page.php
<?php
$url = $_REQUEST['datastring'];
echo $url;
if(file_exists(''.$url.'.html')){
echo file_get_contents(''.$url.'.html');
}
else{
echo 'There is no such page!';
}
?>
need help! as you can see when the ajax calls the "pagecontent" div loads
the content from the requested page, but nothing happens here! what am i
doing wrong?
hi i have a html file which use ajax for loading contents from other html
files in the same server. for some reason it does not work?? i have no
clue as i am new to ajax.
here is the index.html(default home page)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="demo.css" />
<script type="text/javascript" src="../jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head><body><div id="rounded">
<img src="img/top_bg.gif" alt="top" /><div id="main" class="container">
<h1>ajax example</h1>
<h2>ajax jquery</h2>
<ul id="navigation">
<li><a href="#info">Page_1</a></li>
<li><a href="#page2">Page2</a></li>
<li><a href="#page3">Page_3</a></li>
<li><a href="#page4">Page_4</a></li>
<li><img id="loading" src="img/ajax_load.gif" alt="loading" /></li>
</ul>
<div class="clear"></div>
<div id="pageContent">
it is a test</div>
</div><div class="clear"></div>
<img src="img/bottom_bg.gif" alt="bottom" /></div>
</body>
</html>
script.js(for adding hash in the url and enable back button and also
loading content)
var default_content="";
$(document).ready(function(){
checkURL();
$('ul li a').click(function (e){
checkURL(this.hash);
});
default_content = $('#pageContent').html();
setInterval("checkURL()",250);
});
var lasturl="";
function checkURL(hash)
{
if(!hash) hash=window.location.hash;
if(hash != lasturl)
{
lasturl=hash;
if(hash=="")
$('#pageContent').html(default_content);
else
loadPage(hash);
}
}
function loadPage(url)
{
var datastring=url.replace('#','');
$('#loading').css('visibility','visible');
$.ajax({
type: "POST",
url: "load_page.php",
data: 'datastring='+datastring,
dataType: "html",
async: false,
success: function(msg){
if(parseInt(msg)!=0)
{
$('#content').html(msg);
$('#loading').css('visibility','hidden');
}
}
});
}
and load_page.php
<?php
$url = $_REQUEST['datastring'];
echo $url;
if(file_exists(''.$url.'.html')){
echo file_get_contents(''.$url.'.html');
}
else{
echo 'There is no such page!';
}
?>
need help! as you can see when the ajax calls the "pagecontent" div loads
the content from the requested page, but nothing happens here! what am i
doing wrong?
How to Emulate Statement Exprs GNU extension on Standard C++
How to Emulate Statement Exprs GNU extension on Standard C++
I need to automatically translate from certain language to C++. The source
language has the equivalent of Statement Exprs and I'm having a lot of
difficulty replicating that on standard C++ (C++11, actually).
At first I considered lambdas, but the result is very ugly (with lambdas
within lambdas within lambdas...) and possibly would bring the compiler to
its knees when applied to large sources.
How could I replicate that GNU extension? It is imperative that semantics
about construction/destruction/copying/etc are maintained, so translating
this:
Foo foo( { ... declarations and statements ... } );
into this:
Foo foo;
... declarations and statements ...
foo = last result;
is not correct (as Foo is being constructed with default constructor and
then assigned, instead of being constructed with the last value of the
block of statements. Also, objects created inside the block of statements
have a different lifetime on each case.)
Please note that this question also applies for the case where a program
that uses that extension needs to be translated to Standard C++.
I need to automatically translate from certain language to C++. The source
language has the equivalent of Statement Exprs and I'm having a lot of
difficulty replicating that on standard C++ (C++11, actually).
At first I considered lambdas, but the result is very ugly (with lambdas
within lambdas within lambdas...) and possibly would bring the compiler to
its knees when applied to large sources.
How could I replicate that GNU extension? It is imperative that semantics
about construction/destruction/copying/etc are maintained, so translating
this:
Foo foo( { ... declarations and statements ... } );
into this:
Foo foo;
... declarations and statements ...
foo = last result;
is not correct (as Foo is being constructed with default constructor and
then assigned, instead of being constructed with the last value of the
block of statements. Also, objects created inside the block of statements
have a different lifetime on each case.)
Please note that this question also applies for the case where a program
that uses that extension needs to be translated to Standard C++.
Explicitly defaulted and deleted constructor: is there any similar functionality available in VS2012?
Explicitly defaulted and deleted constructor: is there any similar
functionality available in VS2012?
In VS2012, the "Explicitly defaulted and deleted special member functions"
feature
(http://en.wikipedia.org/wiki/C++0x#Explicitly_defaulted_and_deleted_special_member_functions
, http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2346.htm) isn't
yet available
(http://msdn.microsoft.com/en-us/library/vstudio/hh567368.aspx ). Is there
any workaround to use such functionality, even if very very verbose? In
practice, can I translate this
struct NonCopyable {
NonCopyable() = default;
NonCopyable(const NonCopyable&) = delete;
NonCopyable & operator=(const NonCopyable&) = delete;
};
to something with the same functionality, but without using default and
delete? How?
functionality available in VS2012?
In VS2012, the "Explicitly defaulted and deleted special member functions"
feature
(http://en.wikipedia.org/wiki/C++0x#Explicitly_defaulted_and_deleted_special_member_functions
, http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2346.htm) isn't
yet available
(http://msdn.microsoft.com/en-us/library/vstudio/hh567368.aspx ). Is there
any workaround to use such functionality, even if very very verbose? In
practice, can I translate this
struct NonCopyable {
NonCopyable() = default;
NonCopyable(const NonCopyable&) = delete;
NonCopyable & operator=(const NonCopyable&) = delete;
};
to something with the same functionality, but without using default and
delete? How?
Subscribe to:
Comments (Atom)