Tuesday, May 22, 2012

PDO get the last ID had inserted

I have a query and i want to get the last ID had inserted , the filed ID is primary key and auto increment



i know that i have to use this statement



LAST_INSERT_ID()


That statement works with me when the query like this



$query = "INSERT INTO `cell-place` (ID) VALUES (LAST_INSERT_ID())";


But if i want to get that ID using this statement



$ID = LAST_INSERT_ID();


I have got this error



Fatal error: Call to undefined function LAST_INSERT_ID()


What am i doing wrong please





A program worked fine on my computer but when I sent it on another one with a Dutch Windows it has problems with the DateTimePicker

The program is with C# WinForms and SQL Server 2008. When I want to enter data that includes the value from a DateTimePicker I can see that the wording is in Dutch and then I get an error about converting of the value. Is there any way to pre-program it to get around this? I've caught the error and here it is.



error



        try
{
SqlConnection connect = new SqlConnection("Data Source=Localhost\\SQLExpress;Initial Catalog=DataBase;Integrated Security=True");
SqlDataAdapter da = new SqlDataAdapter();

/******************** Inserting ********************/
string query = "INSERT INTO spending VALUES (";
query += "'" + date_dateTimePicker.Value + "', "; // Date
query += "'" + Convert.ToDecimal(amount_spent_textBox.Text) + "', "; // Amount spent
query += "'" + spent_on_textBox.Text + "')"; // Spent on
connect.Open();
da.InsertCommand = new SqlCommand(query, connect);
da.InsertCommand.ExecuteNonQuery();

connect.Close();
}

catch (Exception error)
{
MessageBox.Show(error.ToString());
}


Things are getting thick.. I got this error while trying to insert a dateTimePicker value into the database the same way I did with the code above. It worked perfectly fine on my computer but it won't work here. Can someone explain? Here is the error:



error



Code used:



string update = "UPDATE table SET the_date = '" + the_date_dateTimePicker.Value + "' WHERE instance_ID = 1";
connect.Open();
da.InsertCommand = new SqlCommand(update, connect);
da.InsertCommand.ExecuteNonQuery();
connect.Close();




Set focus to UI element using XAMl or MVVM

I want to set focus to the ui elemt when i press any key in the text box. i wnt it purely on XAML sid or by using mvvm.





Inserting a List<> in SQL Table

I have an entity "report" whose values i want to insert in a Database table. Following attributes of the Report have to be inserted -



reportID - int
RoleID - int
Created_BY = SYSTEM(default)
CURRENT_TIMESTAMP


Now the problem is with the 2nd attribute. I have a report with the LIST<ROLES> attributes. ROLES is a well defined entity which has an ID and a NAME. From this list I have to extract every role and insert each role's ID into the table.



So my query presently looks as below :



INSERT INTO REPORT_MARJORIE_ROLE(REPORT_ID, ROLE_ID, CREATED_BY, CREATED)
VALUES({0}, {1}, 'SYSTEM', CURRENT_TIMESTAMP)


The C# code from where I am parsing these values is as follows :



try
{
StringBuilder _objSQL = new StringBuilder();
_objSQL.AppendFormat(Queries.Report.ReportQueries.ADD_NEW_ROLES, report.ID, "report.MarjorieRoles.Add(MarjorieRole"));
_objDBWriteConnection.ExecuteQuery(_objSQL.ToString());
_objDBWriteConnection.Commit();
_IsRolesAdded = true;
}


So please guide me how to add roles from C# function





plupload Codeigniter file upload issue-IO error 2032

i am using plupload script with codeigniter to upload files.I included all required files to make it work but now the issue is if i am trying to upload a image file large than 20 Kb than it will uploaded to the specific folder successfully but if you go and check the image file than only around 25% part of the image is visible other part is shown as a grey color.



and sometimes plupload shows IO error 2032 also.



I check my max post size and file upload size both are large enough to upload a 20 kb image file.



my script is:



    <script type="text/javascript">
// Convert divs to queue widgets when the DOM is ready
$(function() {
var cct = $.cookie("<?php echo $this->config->item("csrf_cookie_name"); ?>");
$("#uploader").pluploadQueue({
// General settings
runtimes : 'gears,flash,silverlight,browserplus,html5',
url : '<?php echo base_url();?>index.php/uploadphoto',
max_file_size : '5mb',
chunk_size : '1mb',
unique_names : true,
multipart:true,
multipart_params:{'<?php echo $this->security->get_csrf_token_name(); ?>': cct},


// Specify what files to browse for
filters : [
{title : "Image files", extensions : "jpg,gif,png,bmp,jpeg"}
],

// Flash settings
flash_swf_url : '<?php echo base_url();?>js/plupload.flash.swf',

// Silverlight settings
silverlight_xap_url : '<?php echo base_url();?>js/plupload.silverlight.xap'
});

});
</script>


and my controller upload photo is like this:



    $upload_path_url = './uploads/';



$config['upload_path'] =$upload_path_url;
$config['allowed_types'] = 'gif|jpg|png|bmp|jpeg';
$config['max_size'] = '5500';

$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('file'))
{
$error = array('error' => $this->upload->display_errors());
//$this->load->view('upload', $error);
}
else
{
$data = $this->upload->data();
}


so give me any suggestion to solve this issue.



-Thanks in advance





Error while loading the data from server to core data model using restkit

i am using restkit in my project. i can sucessfully load data using the restkit and can store to data base by manually passing the loaded data to the coredata objects. Later i modified it to the restkit coredata model then i am getting the error like this. when run first time



reason = "The model used to open the store is incompatible with the one used to create the store";


my core data was set correctly and its working fine when i pass the data to keys manually.



i got a solution to delete the app or delete the app data from simulator file,
so i deleated the app from the simulator and again run it.this time i got the this error



 2012-05-18 17:38:45.610 MAW[85942:15203] W restkit.network:RKObjectLoader.m:281 Unable to find parser for MIME Type 'text/html'
2012-05-18 17:38:45.612 MAW[85942:15203] W restkit.network:RKObjectLoader.m:309 Encountered unexpected response with status code: 200 (MIME Type: text/html -> URL: http://api.artworkmanager.com/v1auth?username=anuj.gakhar%40gmail.com&password=1234 -- http://api.artworkmanager.com/v1 -- http://api.artworkmanager.com/v1 -- http://api.artworkmanager.com/v1)
2012-05-18 17:38:45.614 MAW[85942:15203] Encountered an error: Error Domain=org.restkit.RestKit.ErrorDomain Code=4 "The operation couldn't be completed. (org.restkit.RestKit.ErrorDomain error 4.)"


Hear is my code



// Initialize RestKit
RKObjectManager* objectManager = [RKObjectManager objectManagerWithBaseURLString:@"http://api.artworkmanager.com/v1"];
objectManager.client.requestQueue.showsNetworkActivityIndicatorWhenBusy = YES;

RKManagedObjectStore* objectStore = [RKManagedObjectStore objectStoreWithStoreFilename:@"MAW.sqlite"];

RKManagedObjectMapping* customerMapping = [RKManagedObjectMapping mappingForClass:[Customer class]inManagedObjectStore:objectStore];
[customerMapping mapKeyPath:@"phone" toAttribute:@"phone"];
[customerMapping mapKeyPath:@"organization" toAttribute:@"organization"];
[customerMapping mapKeyPath:@"siteAdministrator" toAttribute:@"siteAdministrator"];
[customerMapping mapKeyPath:@"customerType" toAttribute:@"customerType"];
[customerMapping mapKeyPath:@"id" toAttribute:@"id"];

RKManagedObjectMapping* articleMapping = [RKManagedObjectMapping mappingForClass:[User class]inManagedObjectStore:objectStore];
[articleMapping mapKeyPath:@"email" toAttribute:@"email"];
[articleMapping mapKeyPath:@"fullname" toAttribute:@"fullname"];
[articleMapping mapKeyPath:@"id" toAttribute:@"id"];

// relationship mapping
[articleMapping mapKeyPath:@"customer" toRelationship:@"customer" withMapping:customerMapping];

[[RKObjectManager sharedManager].mappingProvider addObjectMapping:articleMapping] ;

[self loadData];


my delegate methods



-(void)loadData{
// fetch your mapping
RKObjectMapping *customerMapping = [[RKObjectManager sharedManager].mappingProvider objectMappingForClass:[Customer class]];
//request data
[[RKObjectManager sharedManager] loadObjectsAtResourcePath:@"auth?password=1234&username=anuj.gakhar@gmail.com/customer" objectMapping:customerMapping delegate:self];
}
- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)objects {
RKLogInfo(@"Load collection of: %@", objects);

}
- (void)objectLoader:(RKObjectLoader*)objectLoader didFailWithError:(NSError*)error {
NSLog(@"Encountered an error: %@", error);

}
- (void)request:(RKRequest*)request didLoadResponse:
(RKResponse*)response {
if ([request isGET]) {
if ([response isOK]) {
NSLog(@"Retrieved JSON: %@", [response bodyAsString]);
}
} else if ([request isPOST]) {
if ([response isJSON]) {
NSLog(@"Got a JSON response back from our POST!");
}
}
}


can any one help me how can i solve this. and also suggest me in using restkit. As i am new to iphone feeling little bit difficult to with rest kit. Shall i continue with this or suggest any other alternatives i will go them. if not suggest me a good resorce to follow restkit. now i am going through this restkit in github https://github.com/RestKit/RestKit/blob/master/Docs/Object%20Mapping.md



EDIT
I have tried by running the example twiter code provided in the restkit https://github.com/RestKit/RestKit/tree/master/Examples/RKTwitterCoreData . It is also giving the same error, what might be the problem????(either ios / restkit) i have found an issue here https://github.com/RestKit/RestKit/issues/321. any ideas? thank you...





Spinlock Versus Semaphore!

What is the basic differences between Semaphores & Spinlock? & In what best situations or conditions, we can use these.





static content not working on virtual directories in IIS on XP

I have a strange problem with IIS on XP.



I have a ASP.MVC web application with a virtual directory pointing to it.



The application works OK, I see the generated html pages.
The problem is that I get 404 errors for all the static content files (css,js and image files).



The really strange thing is that if I create an application directly on the directory the static content is served, but I can't get the static content from a virtual directory pointing to the same directory!.



BTW, the static content is served OK from the virtual directory created by VS2010 for the application.



I can't find any differences in the configuration in the IIS between the virtual directory created by VS2010 (that works) and the one that does not work.



I anybody got any ideas, I would be VERY gratefull...



Thanks,



Nadav





Delete this from a javascript object in a jQuery .each()

I am having trouble deleting this from the following javascript object, when this is from a jquery .each() loop.



weatherData:



{
"events":{
"Birthday":{
"type":"Annual",
"date":"20120523",
"weatherType":"clouds",
"high":"40",
"low":"30",
"speed":"15",
"direction":"0",
"humidity":"0"
},
"Move Out Day":{
"type":"One Time",
"date":"20120601",
"weatherType":"storm",
"high":"80",
"low":"76",
"speed":"15",
"direction":"56",
"humidity":"100"
}
},
"dates":{
"default":{
"type":"clouds",
"high":"40",
"low":"30",
"speed":"15",
"direction":"0",
"humidity":"0"
},
"20120521":{
"type":"clear",
"high":"60",
"low":"55",
"speed":"10",
"direction":"56",
"humidity":"25"
}
}
}


This is a shrunken version of the .each() loop:



$.each(weatherData.events, function(i){
if(this.type == "One Time"){
delete weatherData.events[this];
}
})




Transfer Focus From One Component To Other In JFrame

I am working on a JFrame with few Text Fields and JTables and have defined the Focus order of components with the tab Key using the example!



I have also inhereted the jtable Class with following changes
The problem is that on reaching the jtable and when i press the Tab key the focus is not transfered to the other Component.



public class FocusTransferableJTable extends JTable {
public boolean isFocusTraversable() {
return false;
}
}


And also using the following code for jtable and jtxtArea



public static void patch(Component c) {
Set<KeyStroke>
strokes = new HashSet<KeyStroke>(Arrays.asList(KeyStroke.getKeyStroke("pressed TAB")));
c.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, strokes);
strokes = new HashSet<KeyStroke>(Arrays.asList(KeyStroke.getKeyStroke("shift pressed TAB")));
c.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, strokes);
}


Now it is working fine for jtable and jtxtArea i now need help in jTabPane and it's sub tabs and the component inside them.
Question edited with SSCCE!





Best Facebook Library for Android

I have checked the official Facebook Library, I do not want to use it, I want to know if there are any alternatives or rather the best alternatives.





AttributeError: 'WSGIRequest' object has no attribute 'session'

I keep getting this error at random times and whenever I touch the django.wsgi file, it gets fixed only to happen again after a few hours. I'm lost as to what to do. my middleware_classes is as follows:



MIDDLEWARE_CLASSES = (
'django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.csrf.CsrfResponseMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.facebookConnectMiddleware.FacebookConnectMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
).



The error always occurs in the facebook middleware when i do an "if request.session" statement.
Thanks





Watchdog fires on high interrupt rate

I am working on a customized/proprietary RTOS provided by my client.



The RTOS uses round robin scheduling with priority preemption.



Scenario is -





  1. The Renesas H8S controller is running at 20 MHz

  2. I have configured interrupt for ethernet interrupt (A LAN9221 chip is interrupting)

  3. A task which reads the data from LAN controller is running at highest priority in OS

  4. Another task TCP which is second highest priority task in system




I have generated network traffic to simulate bombarding condition on the network.
Problem is at high data rates (more than 500 packets/second) on ethernet ISR watchdog is getting fired which is configured for 1 second.



Watchdog is configured to be serviced by a lower priority task of OS to detect any problem in OS functionality.



I doubt the frequency of ISR and higher priority tasks are not letting the watchdog task to be scheduled. To confirm my doubt i have serviced the watchdog in ISR itself and found working till 2000 packets/second.



Could you please suggest how can handle the situation so the watchdog should not fire even on higher data/interrupt rate.



Thanks
Vikas





Dialog that returns an Object

Is it possible to create a JDialog in swing that would return an object when OK button is clicked?



For example the Dialog box has text fields that have components that make up an adress ( street name, country etc.)



When the OK button is clicked an Address object is returned.



Why I thought this to be possible was because of this. But what I want is something like I mentioned above.



Any pointers on how to get this done would be very helpful.





Creating a lock screen dialog for an app

I want to create a dialog on an app that is the same as the android pattern lock screen you see when you try to enter the phone.



I've read around and i'm trying to view the android code for this section, but I cant seem to find it nor find out how to implement what I'm trying to do.



Any tips?





What's the theoretical complexity of this algorithm?

fun(double x, int y){
if (int == 0){
return 1.0;
} else {
return fun(x, y/2) * fun(x, y/2);
}
}


How can I find the theoretical complexity?
+ What's the difference between the big O and the theta-notation?



Thanks





High-Order ScalaCheck

Consider the following definition of a category:



trait Category[~>[_, _]] {
def id[A]: A ~> A
def compose[A, B, C](f: A ~> B)(g: B ~> C): A ~> C
}


Here's an instance for unary functions:



object Category {
implicit def fCat = new Category[Function1] {
def id[A] = identity
def compose[A, B, C](f: A => B)(g: B => C) = g.compose(f)
}
}


Now, categories are subject to some laws. Relating composition (.) and identity (id):



forall f: categoryArrow -> id . f == f . id == f


I want to test this with ScalaCheck. Let's try for functions over integers:



"Categories" should {
import Category._

val intG = { (_ : Int) - 5 }

"left identity" ! check {
forAll { (a: Int) => fCat.compose(fCat.id[Int])(intG)(a) == intG(a) }
}

"right identity" ! check {
forAll { (a: Int) => fCat.compose(intG)(fCat.id)(a) == intG(a) }
}
}


But these are quantified over (i) a specific type (Int), and (ii) a specific function (intG). So here's my question: how far can I go in terms of generalizing the above tests, and how? Or, in other words, would it be possible to create a generator of arbitrary A => B functions, and provide those to ScalaCheck?





jquery shows wrong page

This is the jquery



$(document).on('change', '.ui-slider-switch', function () {

if ($(this).val() == 'on') {
$("#content1").hide();
$("#content2").show();

} else {
$("#content1").show();
$("#content2").hide();
}

});


My HTML



<div id="switch" data-role="fieldcontain">      
<select name="slider" id="flip-a" data-role="slider">
<option value="off"></option>
<option value="on"></option>
</select>
</div>


In my site I sometimes use a custom URL (And get data out of it with $ _GET).
When the page reload I'm always getting $("#content2").show(); instead of $("#content1").show();





How to change gallery's scrollview

MyGallery gallery = (MyGallery)findViewById(R.id.gallery_photo);
PhonePhotoViewerAdapter = new PhonePhotoViewerAdapter(this, FilePath);
gallery.setAdapter(PhonePhotoViewerAdapter);
gallery.setSelection(0);


Above is my code to show photo with scrollview.

But if I want to focus on next, I have to move finger on screen with a larger distance.

I want to let it change focus while a smaller distance moved

How can I do it?

I had modify class Gallery as below:



@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if (e1.getX() - e2.getX() > 50 && Math.abs(velocityX) > 100) {
// Fling left
} else if (e2.getX() - e1.getX() > 50 && Math.abs(velocityX) > 100) {
// Fling right
}
return false;
}


Below code is my modify:



gallery.setLongClickable(false);
gallery.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
int action = event.getAction();
if((action == MotionEvent.ACTION_DOWN) && !Clicking) {
StartX = event.getX();
StartIndex = gallery.getSelectedItemPosition();
Clicking = true;
}
else if((action == MotionEvent.ACTION_UP) && Clicking) {
EndX = event.getX();
EndIndex = gallery.getSelectedItemPosition();
Clicking = false;
if(((EndX - StartX) > 50) && (StartIndex == EndIndex)) {
if(EndIndex > 0) {
gallery.setSelection(EndIndex - 1);
}
}
else if(((StartX - EndX) > 50) && (StartIndex == EndIndex)) {
if(EndIndex < count - 1) {
gallery.setSelection(EndIndex + 1);
}
}
}
return false;
}
});


But there are some abnormal in showing.





Upload external file to AWS S3 bucket using PHP SDK

I want to upload a file from an external URL directly to an Amazon S3 bucket using the PHP SDK. I managed to do this with the following code:



$s3 = new AmazonS3();
$response = $s3->create_object($bucket, $destination, array(
'fileUpload' => $source,
'length' => remote_filesize($source),
'contentType' => 'image/jpeg'
));


Where the function remote_filesize is the following:



function remote_filesize($url) {
ob_start();
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
$ok = curl_exec($ch);
curl_close($ch);
$head = ob_get_contents();
ob_end_clean();
$regex = '/Content-Length:\s([0-9].+?)\s/';
$count = preg_match($regex, $head, $matches);
return isset($matches[1]) ? $matches[1] : "unknown";
}


However, it would be nice if I could skip setting the filesize when uploading to Amazon since this would save me a trip to my own server. But if I remove setting the 'length' property in the $s3->create_object function, I get an error saying that the 'The stream size for the streaming upload cannot be determined.' Any ideas how to solve this problem?