question_id
int64
4
6.31M
answer_id
int64
7
6.31M
title
stringlengths
9
150
question_body
stringlengths
0
28.8k
answer_body
stringlengths
60
27.2k
question_text
stringlengths
40
28.9k
combined_text
stringlengths
124
39.6k
tags
listlengths
1
6
question_score
int64
0
26.3k
answer_score
int64
0
28.8k
view_count
int64
15
14M
answer_count
int64
0
182
favorite_count
int64
0
32
question_creation_date
stringdate
2008-07-31 21:42:52
2011-06-10 18:12:18
answer_creation_date
stringdate
2008-07-31 22:17:57
2011-06-10 18:14:17
6,309,077
6,309,204
Can I run package.skeleton without parsing functions into separate files?
Is it possible to run package.skeleton('pkgname') and have all of the.R files end up in a single file or set of files rather than one file per function? A developer I am working with asked me why I had each function in a separate file and my only rationale was 'that is the default behavior`.
If you specify a file containing several functions in the code_files argument to package.skeleton, that should just be copied to the R directory in the package. So, yes.
Can I run package.skeleton without parsing functions into separate files? Is it possible to run package.skeleton('pkgname') and have all of the.R files end up in a single file or set of files rather than one file per function? A developer I am working with asked me why I had each function in a separate file and my only rationale was 'that is the default behavior`.
TITLE: Can I run package.skeleton without parsing functions into separate files? QUESTION: Is it possible to run package.skeleton('pkgname') and have all of the.R files end up in a single file or set of files rather than one file per function? A developer I am working with asked me why I had each function in a separate file and my only rationale was 'that is the default behavior`. ANSWER: If you specify a file containing several functions in the code_files argument to package.skeleton, that should just be copied to the R directory in the package. So, yes.
[ "r", "package" ]
12
10
405
2
0
2011-06-10T16:07:42.863000
2011-06-10T16:17:30.230000
6,309,080
6,309,153
Detect completion of multiple async javascript $.ajax calls
I have a javascript function that enters a loop and issues an asynchronous ajax call for each loop. I need to know when ALL the ajax calls have returned and been processed, because I want to update the UI at that point. The loop is as follows: function sync_SyncLocalStorageToServer() { if (helper_IsAppOnline()) { $.log('sync_SyncLocalStorageToServer detects app is ONLINE'); // Post each cached entry to the server - this is the main sync function for (var i = 0, len = localStorage.length; i < len; i++) { var lskey = localStorage.key(i); if (lskey.substr(0, 8) === 'response') { $.log('Sync found response with key=' + lskey); var postdata = localStorage.getItem(lskey); // Get the form data $.log('Calling server with ls response:' + postdata); var localkey = lskey; $.ajax({ type: "POST", dataType: 'json', url: "/Profile/PostForm", data: { jsonpost: postdata }, success: function (data) { if (data.rc == "success") { localStorage.removeItem(data.localStorageKey); // Remove the relevant localStorage entry $.log('ServerSuccess:' + data.message + ',removed localStorageKey=' + data.localStorageKey); } else { $.log('ServerUnhappy:' + data.message + ',did not remove localStorageKey=' + data.localStorageKey); } }, error: function (data) { $.log('ERR:' + data); } }); } } } else { $.log('sync_SyncLocalStorageToServer detects app is OFFLINE'); } } What is the easiest way for me to call my UI refresh function when the very last async ajax call has eventually returned from the server? Thanks.
Count how many times you execute an AJAX request, and then, count the number of times you have seen a call to the completed callback. Once the callback completed count equals the number of times you issued ajax calls, you know you are done. var total = arr.length; var count = 0; for(var i = 0; i < arr.length; i++){ $.ajax({ // other options complete: function(){ count++; if(count == total){ // all finished! } } }); } Note that I use the 'complete' callback, not 'success', since if one of the requests fail 'success' will not be called, but 'complete' will. Also, I declared the expected amount in 'total' first, instead of counting up in this example. This just avoid the unlikely (though technically possible) scenario of having all of the pending ajax requests finish before you've posted all of them, and therefore having a matching count.
Detect completion of multiple async javascript $.ajax calls I have a javascript function that enters a loop and issues an asynchronous ajax call for each loop. I need to know when ALL the ajax calls have returned and been processed, because I want to update the UI at that point. The loop is as follows: function sync_SyncLocalStorageToServer() { if (helper_IsAppOnline()) { $.log('sync_SyncLocalStorageToServer detects app is ONLINE'); // Post each cached entry to the server - this is the main sync function for (var i = 0, len = localStorage.length; i < len; i++) { var lskey = localStorage.key(i); if (lskey.substr(0, 8) === 'response') { $.log('Sync found response with key=' + lskey); var postdata = localStorage.getItem(lskey); // Get the form data $.log('Calling server with ls response:' + postdata); var localkey = lskey; $.ajax({ type: "POST", dataType: 'json', url: "/Profile/PostForm", data: { jsonpost: postdata }, success: function (data) { if (data.rc == "success") { localStorage.removeItem(data.localStorageKey); // Remove the relevant localStorage entry $.log('ServerSuccess:' + data.message + ',removed localStorageKey=' + data.localStorageKey); } else { $.log('ServerUnhappy:' + data.message + ',did not remove localStorageKey=' + data.localStorageKey); } }, error: function (data) { $.log('ERR:' + data); } }); } } } else { $.log('sync_SyncLocalStorageToServer detects app is OFFLINE'); } } What is the easiest way for me to call my UI refresh function when the very last async ajax call has eventually returned from the server? Thanks.
TITLE: Detect completion of multiple async javascript $.ajax calls QUESTION: I have a javascript function that enters a loop and issues an asynchronous ajax call for each loop. I need to know when ALL the ajax calls have returned and been processed, because I want to update the UI at that point. The loop is as follows: function sync_SyncLocalStorageToServer() { if (helper_IsAppOnline()) { $.log('sync_SyncLocalStorageToServer detects app is ONLINE'); // Post each cached entry to the server - this is the main sync function for (var i = 0, len = localStorage.length; i < len; i++) { var lskey = localStorage.key(i); if (lskey.substr(0, 8) === 'response') { $.log('Sync found response with key=' + lskey); var postdata = localStorage.getItem(lskey); // Get the form data $.log('Calling server with ls response:' + postdata); var localkey = lskey; $.ajax({ type: "POST", dataType: 'json', url: "/Profile/PostForm", data: { jsonpost: postdata }, success: function (data) { if (data.rc == "success") { localStorage.removeItem(data.localStorageKey); // Remove the relevant localStorage entry $.log('ServerSuccess:' + data.message + ',removed localStorageKey=' + data.localStorageKey); } else { $.log('ServerUnhappy:' + data.message + ',did not remove localStorageKey=' + data.localStorageKey); } }, error: function (data) { $.log('ERR:' + data); } }); } } } else { $.log('sync_SyncLocalStorageToServer detects app is OFFLINE'); } } What is the easiest way for me to call my UI refresh function when the very last async ajax call has eventually returned from the server? Thanks. ANSWER: Count how many times you execute an AJAX request, and then, count the number of times you have seen a call to the completed callback. Once the callback completed count equals the number of times you issued ajax calls, you know you are done. var total = arr.length; var count = 0; for(var i = 0; i < arr.length; i++){ $.ajax({ // other options complete: function(){ count++; if(count == total){ // all finished! } } }); } Note that I use the 'complete' callback, not 'success', since if one of the requests fail 'success' will not be called, but 'complete' will. Also, I declared the expected amount in 'total' first, instead of counting up in this example. This just avoid the unlikely (though technically possible) scenario of having all of the pending ajax requests finish before you've posted all of them, and therefore having a matching count.
[ "javascript", "jquery", "ajax", "asynchronous" ]
4
7
4,385
2
0
2011-06-10T16:07:52.567000
2011-06-10T16:13:34.847000
6,309,091
6,309,434
Zend form element for customized currency
How to extend zend form element to create customized currency field. For example: $amount = new Example_Form_Element_Currency(1234); The out put should be like this: $1,234.00. I want a custom helper for currency.
Sounds like you're looking to apply a filter. I don't think there's a built-in currency filter however it wouldn't be difficult to create one to run the submitted value through number_format() or similar. class My_Filter_Currency implements Zend_Filter_Interface { public function filter($value) { return '$'. number_format($value, 2); } }
Zend form element for customized currency How to extend zend form element to create customized currency field. For example: $amount = new Example_Form_Element_Currency(1234); The out put should be like this: $1,234.00. I want a custom helper for currency.
TITLE: Zend form element for customized currency QUESTION: How to extend zend form element to create customized currency field. For example: $amount = new Example_Form_Element_Currency(1234); The out put should be like this: $1,234.00. I want a custom helper for currency. ANSWER: Sounds like you're looking to apply a filter. I don't think there's a built-in currency filter however it wouldn't be difficult to create one to run the submitted value through number_format() or similar. class My_Filter_Currency implements Zend_Filter_Interface { public function filter($value) { return '$'. number_format($value, 2); } }
[ "php", "zend-form", "currency", "zend-form-element" ]
0
0
781
2
0
2011-06-10T16:08:40.303000
2011-06-10T16:35:11.847000
6,309,092
6,309,111
jquery: div hide/show on focus issue
Thanks to inti's code I was able to figure out the answer! jQuery: $(document).ready(function(){ $("body").click(function(e) { //checks to see if the tag you clicked has the #login //div as a parent. if($(e.target).closest("#login").size() == 0) { //makes exception for the #login's tag (id of a_login) if((e.target.id) == 'a_login') { $("#login").show(); } else { $("#login").hide(); } //if target has #login as parent, keep it visible } else { $("#login").show(); } }); }); Working jsfiddle example: http://jsfiddle.net/SuperPhil/3CmE7/ Thanks! I am trying to have a login screen similar to the http://dropbox.com login. Where a user clicks on the login link and a div appears (CSS) and when focus out, disappears. Here is my jQuery $('#login').bind('click', function() { $('#login').addClass("clicked").focusout(function() { $('#login').removeClass('clicked'); }); }); This doesn't work. Can anyone help me out? EDIT: $('#login').click(function() { $('#login div').addClass("clicked").blur(function() { $('#login div').removeClass('clicked'); }); });
The event you are looking for is.blur() not.focusout(). Edit: click out of #mydiv to hide it: $("body").click(function(e) { if ($(e.target).closest("#mydiv").size() == 0) { $("#mydiv").hide(); } }); This hides #mydiv if what you clicked doesn't have it as one of it's parents.
jquery: div hide/show on focus issue Thanks to inti's code I was able to figure out the answer! jQuery: $(document).ready(function(){ $("body").click(function(e) { //checks to see if the tag you clicked has the #login //div as a parent. if($(e.target).closest("#login").size() == 0) { //makes exception for the #login's tag (id of a_login) if((e.target.id) == 'a_login') { $("#login").show(); } else { $("#login").hide(); } //if target has #login as parent, keep it visible } else { $("#login").show(); } }); }); Working jsfiddle example: http://jsfiddle.net/SuperPhil/3CmE7/ Thanks! I am trying to have a login screen similar to the http://dropbox.com login. Where a user clicks on the login link and a div appears (CSS) and when focus out, disappears. Here is my jQuery $('#login').bind('click', function() { $('#login').addClass("clicked").focusout(function() { $('#login').removeClass('clicked'); }); }); This doesn't work. Can anyone help me out? EDIT: $('#login').click(function() { $('#login div').addClass("clicked").blur(function() { $('#login div').removeClass('clicked'); }); });
TITLE: jquery: div hide/show on focus issue QUESTION: Thanks to inti's code I was able to figure out the answer! jQuery: $(document).ready(function(){ $("body").click(function(e) { //checks to see if the tag you clicked has the #login //div as a parent. if($(e.target).closest("#login").size() == 0) { //makes exception for the #login's tag (id of a_login) if((e.target.id) == 'a_login') { $("#login").show(); } else { $("#login").hide(); } //if target has #login as parent, keep it visible } else { $("#login").show(); } }); }); Working jsfiddle example: http://jsfiddle.net/SuperPhil/3CmE7/ Thanks! I am trying to have a login screen similar to the http://dropbox.com login. Where a user clicks on the login link and a div appears (CSS) and when focus out, disappears. Here is my jQuery $('#login').bind('click', function() { $('#login').addClass("clicked").focusout(function() { $('#login').removeClass('clicked'); }); }); This doesn't work. Can anyone help me out? EDIT: $('#login').click(function() { $('#login div').addClass("clicked").blur(function() { $('#login div').removeClass('clicked'); }); }); ANSWER: The event you are looking for is.blur() not.focusout(). Edit: click out of #mydiv to hide it: $("body").click(function(e) { if ($(e.target).closest("#mydiv").size() == 0) { $("#mydiv").hide(); } }); This hides #mydiv if what you clicked doesn't have it as one of it's parents.
[ "jquery" ]
0
3
3,233
2
0
2011-06-10T16:08:40.270000
2011-06-10T16:10:09.090000
6,309,104
6,309,289
better integration with asp.net entity framework or Nhibernate
I'm have a lot of time using hibernate (JPA) in java, but i recently am in a new job in which had used the platform of.net and they ask me to develop and application with certain standards and one of the them requirements are related with the using of ORM, but i have seen looking for resources and frameworks that exit's two first the nhibernate and second the entity framework. So my question it's what of two have the best integration with.net (Visual Studio 2008) and also give's the best performance to manage the info. Edit Notice that my application it's mvc app
ADO.NET Entity Framework integrates better with Visual Studio 2008+ in terms of visual class designer etc. Even though the Entity Framework supports "Peristence Ignorance" like NHibernate/Hibernate does, NHibernate is much more mature. If you don't need a clean separation of concerns regarding data access layer and the domain layer, the Entity Framework allows you more rapid development, since you can generate classes from your database from within Visual Studio. Data contexts for persistence purposes will already be set up and ready to use. If you need to setup a professional environment with a persistent ignorant domain layer, dependency injection, etc., I would go for nHibernate. Since you already have experience with that and its more mature (more features).
better integration with asp.net entity framework or Nhibernate I'm have a lot of time using hibernate (JPA) in java, but i recently am in a new job in which had used the platform of.net and they ask me to develop and application with certain standards and one of the them requirements are related with the using of ORM, but i have seen looking for resources and frameworks that exit's two first the nhibernate and second the entity framework. So my question it's what of two have the best integration with.net (Visual Studio 2008) and also give's the best performance to manage the info. Edit Notice that my application it's mvc app
TITLE: better integration with asp.net entity framework or Nhibernate QUESTION: I'm have a lot of time using hibernate (JPA) in java, but i recently am in a new job in which had used the platform of.net and they ask me to develop and application with certain standards and one of the them requirements are related with the using of ORM, but i have seen looking for resources and frameworks that exit's two first the nhibernate and second the entity framework. So my question it's what of two have the best integration with.net (Visual Studio 2008) and also give's the best performance to manage the info. Edit Notice that my application it's mvc app ANSWER: ADO.NET Entity Framework integrates better with Visual Studio 2008+ in terms of visual class designer etc. Even though the Entity Framework supports "Peristence Ignorance" like NHibernate/Hibernate does, NHibernate is much more mature. If you don't need a clean separation of concerns regarding data access layer and the domain layer, the Entity Framework allows you more rapid development, since you can generate classes from your database from within Visual Studio. Data contexts for persistence purposes will already be set up and ready to use. If you need to setup a professional environment with a persistent ignorant domain layer, dependency injection, etc., I would go for nHibernate. Since you already have experience with that and its more mature (more features).
[ ".net", "nhibernate", "entity-framework-4" ]
0
2
107
1
0
2011-06-10T16:09:27.700000
2011-06-10T16:23:24.363000
6,309,105
6,309,134
Cross-OS distributed computing in C++, rand() issue
I'm working on a small distributed computing project. The server can't handle the calculations without crashing Apache in the process, so I'm giving these calculations to the users. The basic idea is that I run the calculations 3 times, and the results need to be exactly the same. However, the application will need to run on Mac, Linux and Windows. Basically this means that I can't use rand(). I'm probably looking for a replacement generator which accepts a seed value (provided by the server) and gives the same results on every platform. My question is: is that indeed what I am looking for and do you have a good recommendation, or should I be doing this in a different way?
Take a look at the Boost.Random facilities. They give you a broad choice of algorithms that are guaranteed to give the same results, always.
Cross-OS distributed computing in C++, rand() issue I'm working on a small distributed computing project. The server can't handle the calculations without crashing Apache in the process, so I'm giving these calculations to the users. The basic idea is that I run the calculations 3 times, and the results need to be exactly the same. However, the application will need to run on Mac, Linux and Windows. Basically this means that I can't use rand(). I'm probably looking for a replacement generator which accepts a seed value (provided by the server) and gives the same results on every platform. My question is: is that indeed what I am looking for and do you have a good recommendation, or should I be doing this in a different way?
TITLE: Cross-OS distributed computing in C++, rand() issue QUESTION: I'm working on a small distributed computing project. The server can't handle the calculations without crashing Apache in the process, so I'm giving these calculations to the users. The basic idea is that I run the calculations 3 times, and the results need to be exactly the same. However, the application will need to run on Mac, Linux and Windows. Basically this means that I can't use rand(). I'm probably looking for a replacement generator which accepts a seed value (provided by the server) and gives the same results on every platform. My question is: is that indeed what I am looking for and do you have a good recommendation, or should I be doing this in a different way? ANSWER: Take a look at the Boost.Random facilities. They give you a broad choice of algorithms that are guaranteed to give the same results, always.
[ "c++", "random", "distributed-computing", "srand" ]
1
7
426
3
0
2011-06-10T16:09:29.620000
2011-06-10T16:11:28.607000
6,309,113
6,309,145
Collections.unmodifiablemap() and collections where reads also modify
This is more a curiosity question than anything. Say I supply a LinkedHashMap with access ordering set to true to Collections.unmodifiableMap(). Since reads are actually modifying the map. Does it mean there are cases where the view returned by unmodifiableMap() is actually modifiable? public class MyApp { /** * @param args */ public static void main(String[] args) { Map m = new LinkedHashMap (16,.75f,true); Collections.unmodifiableMap(m); } }
The Map is modifying itself. Collections.unmodifiableMap() only provides a decorator for the Map which disallows modifications, it does not make the Map itself unmodifiable.
Collections.unmodifiablemap() and collections where reads also modify This is more a curiosity question than anything. Say I supply a LinkedHashMap with access ordering set to true to Collections.unmodifiableMap(). Since reads are actually modifying the map. Does it mean there are cases where the view returned by unmodifiableMap() is actually modifiable? public class MyApp { /** * @param args */ public static void main(String[] args) { Map m = new LinkedHashMap (16,.75f,true); Collections.unmodifiableMap(m); } }
TITLE: Collections.unmodifiablemap() and collections where reads also modify QUESTION: This is more a curiosity question than anything. Say I supply a LinkedHashMap with access ordering set to true to Collections.unmodifiableMap(). Since reads are actually modifying the map. Does it mean there are cases where the view returned by unmodifiableMap() is actually modifiable? public class MyApp { /** * @param args */ public static void main(String[] args) { Map m = new LinkedHashMap (16,.75f,true); Collections.unmodifiableMap(m); } } ANSWER: The Map is modifying itself. Collections.unmodifiableMap() only provides a decorator for the Map which disallows modifications, it does not make the Map itself unmodifiable.
[ "java", "collections" ]
4
5
3,105
2
0
2011-06-10T16:10:21.893000
2011-06-10T16:12:40.863000
6,309,122
6,309,167
Launch screen on iPad
I have an iPhone app. When I run it on the iPad everything looks great (but small) except for the launch screen that also is small (not full screen) and not really proportional. I have read the documentation, but I'm not sure where I've gone wrong. I have added Default-Portrait.png and Default-Landscape.png, but it doesn't change anything. I don't really mind about how it is, more than I don't want it to be rejected in App Store because of that. Edit: My info.plist (if you see other weird things, please let me know. I'm submitting today) CFBundleDevelopmentRegion en CFBundleDisplayName ${PRODUCT_NAME} CFBundleDocumentTypes CFBundleExecutable ${EXECUTABLE_NAME} CFBundleIconFile CFBundleIconFiles Icon.png Icon@2x.png Icon-72.png Icon-Small-50.png Icon-Small.png Icon-Small@2x.png Icon-72.png Icon-72.png CFBundleIdentifier com.xx.xxx CFBundleInfoDictionaryVersion 6.0 CFBundleName ${PRODUCT_NAME} CFBundlePackageType APPL CFBundleShortVersionString 1.0 CFBundleSignature???? CFBundleURLTypes CFBundleURLName CFBundleURLSchemes fb1234 CFBundleVersion 1.0 LSRequiresIPhoneOS NSMainNibFile MainWindow SHKFacebookKey 1234 SHKFacebookSecret 1234 SHKMyAppName xxx SHKMyAppURL http://itunes.apple.com/xxx UIInterfaceOrientation UIInterfaceOrientationPortrait UIInterfaceOrientation~ipad UIInterfaceOrientationPortrait UIStatusBarHidden UISupportedInterfaceOrientations UIInterfaceOrientationPortrait UISupportedInterfaceOrientations~ipad UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight UTExportedTypeDeclarations UTImportedTypeDeclarations
Make sure to add these into your Info.plist file UISupportedInterfaceOrientations~ipad UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight Even of your orientations work properly without, it's absolutely imperative to have these to select a proper launch screen. BTW You won't be rejected. It's just a matter of good programming ethics.
Launch screen on iPad I have an iPhone app. When I run it on the iPad everything looks great (but small) except for the launch screen that also is small (not full screen) and not really proportional. I have read the documentation, but I'm not sure where I've gone wrong. I have added Default-Portrait.png and Default-Landscape.png, but it doesn't change anything. I don't really mind about how it is, more than I don't want it to be rejected in App Store because of that. Edit: My info.plist (if you see other weird things, please let me know. I'm submitting today) CFBundleDevelopmentRegion en CFBundleDisplayName ${PRODUCT_NAME} CFBundleDocumentTypes CFBundleExecutable ${EXECUTABLE_NAME} CFBundleIconFile CFBundleIconFiles Icon.png Icon@2x.png Icon-72.png Icon-Small-50.png Icon-Small.png Icon-Small@2x.png Icon-72.png Icon-72.png CFBundleIdentifier com.xx.xxx CFBundleInfoDictionaryVersion 6.0 CFBundleName ${PRODUCT_NAME} CFBundlePackageType APPL CFBundleShortVersionString 1.0 CFBundleSignature???? CFBundleURLTypes CFBundleURLName CFBundleURLSchemes fb1234 CFBundleVersion 1.0 LSRequiresIPhoneOS NSMainNibFile MainWindow SHKFacebookKey 1234 SHKFacebookSecret 1234 SHKMyAppName xxx SHKMyAppURL http://itunes.apple.com/xxx UIInterfaceOrientation UIInterfaceOrientationPortrait UIInterfaceOrientation~ipad UIInterfaceOrientationPortrait UIStatusBarHidden UISupportedInterfaceOrientations UIInterfaceOrientationPortrait UISupportedInterfaceOrientations~ipad UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight UTExportedTypeDeclarations UTImportedTypeDeclarations
TITLE: Launch screen on iPad QUESTION: I have an iPhone app. When I run it on the iPad everything looks great (but small) except for the launch screen that also is small (not full screen) and not really proportional. I have read the documentation, but I'm not sure where I've gone wrong. I have added Default-Portrait.png and Default-Landscape.png, but it doesn't change anything. I don't really mind about how it is, more than I don't want it to be rejected in App Store because of that. Edit: My info.plist (if you see other weird things, please let me know. I'm submitting today) CFBundleDevelopmentRegion en CFBundleDisplayName ${PRODUCT_NAME} CFBundleDocumentTypes CFBundleExecutable ${EXECUTABLE_NAME} CFBundleIconFile CFBundleIconFiles Icon.png Icon@2x.png Icon-72.png Icon-Small-50.png Icon-Small.png Icon-Small@2x.png Icon-72.png Icon-72.png CFBundleIdentifier com.xx.xxx CFBundleInfoDictionaryVersion 6.0 CFBundleName ${PRODUCT_NAME} CFBundlePackageType APPL CFBundleShortVersionString 1.0 CFBundleSignature???? CFBundleURLTypes CFBundleURLName CFBundleURLSchemes fb1234 CFBundleVersion 1.0 LSRequiresIPhoneOS NSMainNibFile MainWindow SHKFacebookKey 1234 SHKFacebookSecret 1234 SHKMyAppName xxx SHKMyAppURL http://itunes.apple.com/xxx UIInterfaceOrientation UIInterfaceOrientationPortrait UIInterfaceOrientation~ipad UIInterfaceOrientationPortrait UIStatusBarHidden UISupportedInterfaceOrientations UIInterfaceOrientationPortrait UISupportedInterfaceOrientations~ipad UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight UTExportedTypeDeclarations UTImportedTypeDeclarations ANSWER: Make sure to add these into your Info.plist file UISupportedInterfaceOrientations~ipad UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight Even of your orientations work properly without, it's absolutely imperative to have these to select a proper launch screen. BTW You won't be rejected. It's just a matter of good programming ethics.
[ "iphone", "ipad", "splash-screen", "launch" ]
0
1
584
1
0
2011-06-10T16:10:54.980000
2011-06-10T16:14:31.263000
6,309,136
6,309,241
How to save Facebook UID in Devise?
I am using Devise and I have it so a User clicks "log in with facebook". Once they confirm this, it then takes them to the registration url "http://0.0.0.0:3000/users/sign_up". In here I then populate the name and email fields with the ones I got from Facebook. They now just have to pick a password to sign up. I also want to save the user's Facebook UID and their Facebook url. How do I pass this into my User model once the user clicks on the sign up button? (I updated my model to include these extra fields). Edit: I currently also store their Facebook hash data in a session that I got from Ominauth so that I can retrieve it later.
Using the auth hash provided by Omniauth you should be able to retrieve the user information. For example the hash has a structure that looks like this. You can pull the user information like this: facebook_uid = user_auth.uid facebook_url = user.user_info.urls
How to save Facebook UID in Devise? I am using Devise and I have it so a User clicks "log in with facebook". Once they confirm this, it then takes them to the registration url "http://0.0.0.0:3000/users/sign_up". In here I then populate the name and email fields with the ones I got from Facebook. They now just have to pick a password to sign up. I also want to save the user's Facebook UID and their Facebook url. How do I pass this into my User model once the user clicks on the sign up button? (I updated my model to include these extra fields). Edit: I currently also store their Facebook hash data in a session that I got from Ominauth so that I can retrieve it later.
TITLE: How to save Facebook UID in Devise? QUESTION: I am using Devise and I have it so a User clicks "log in with facebook". Once they confirm this, it then takes them to the registration url "http://0.0.0.0:3000/users/sign_up". In here I then populate the name and email fields with the ones I got from Facebook. They now just have to pick a password to sign up. I also want to save the user's Facebook UID and their Facebook url. How do I pass this into my User model once the user clicks on the sign up button? (I updated my model to include these extra fields). Edit: I currently also store their Facebook hash data in a session that I got from Ominauth so that I can retrieve it later. ANSWER: Using the auth hash provided by Omniauth you should be able to retrieve the user information. For example the hash has a structure that looks like this. You can pull the user information like this: facebook_uid = user_auth.uid facebook_url = user.user_info.urls
[ "ruby-on-rails", "ruby-on-rails-3", "facebook-graph-api", "devise" ]
0
0
436
1
0
2011-06-10T16:11:49.710000
2011-06-10T16:20:31.097000
6,309,154
6,309,334
How to intercept WCF faults and return custom response instead?
Consider the following very basic WCF service implementation: public enum TransactionStatus { Success = 0, Error = 1 } public class TransactionResponse { public TransactionStatus Status { get; set; } public string Message { get; set; } } [ServiceContract] [XmlSerializerFormat] public interface ITestService { [OperationContract] TransactionResponse DoSomething(string data); } public class TestService: ITestService { public TransactionResponse DoSomething(string data) { var result = ProcessData(data); // may throw InvalidOperationException return new TransactionResponse() { Status = TransactionStatus.Success, Message = result }; } private string ProcessData(string data) { if (data = "foobar") throw new InvalidOperationException(); return data; } } In the instance that the DoSomething method does throw an InvalidOperationException, I would like to intercept the fault and return a TransactionResponse object, rather than have WCF raise a FaultException with the client. How can I do this without surrounding each method body in a huge try catch statement? Is there some where I can hook into? Can I do this with some sort of attribute or something? An example of how I would like to handle it can be demonstrated using ASP.NET MVC: public class ApiController: BaseController { protected override void OnException(ExceptionContext filterContext) { var ex = filterContext.Exception; var message = HttpContext.IsDebuggingEnabled? ex.ToString(): ex.Message; _logger.Error("Error processing request for controller {0}, action {1}", filterContext.RequestContext.RouteData.Values["controller"], filterContext.RequestContext.RouteData.Values["action"]); _logger.Error(ex.ToString()); filterContext.ExceptionHandled = true; filterContext.Result = ToXml(new ApiResult(false) { Message = message }); } //... } Using the above method in MVC, I can ensure that no matter which controller action throws an exception, I can handle it and return an appropriately formatted ActionResult containing the necessary info. Is there a way to do this kind of thing with WCF?
Check out the WCF IErrorHandler interface - it allows you to centrally define one way in your service implementation to catch all exceptions and either swallow them, or convert them to WCF-friendly SOAP exceptions. This will make sure the channel between the client and the server isn't faulted, e.g. it can still be used after this call failed. I don't understand why you'd want to "catch" the SOAP faults and convert those to something else, though.... nor do I know of any support that WCF would give you. The basic assumption is: catch.NET exceptions and convert them into interoperable SOAP faults
How to intercept WCF faults and return custom response instead? Consider the following very basic WCF service implementation: public enum TransactionStatus { Success = 0, Error = 1 } public class TransactionResponse { public TransactionStatus Status { get; set; } public string Message { get; set; } } [ServiceContract] [XmlSerializerFormat] public interface ITestService { [OperationContract] TransactionResponse DoSomething(string data); } public class TestService: ITestService { public TransactionResponse DoSomething(string data) { var result = ProcessData(data); // may throw InvalidOperationException return new TransactionResponse() { Status = TransactionStatus.Success, Message = result }; } private string ProcessData(string data) { if (data = "foobar") throw new InvalidOperationException(); return data; } } In the instance that the DoSomething method does throw an InvalidOperationException, I would like to intercept the fault and return a TransactionResponse object, rather than have WCF raise a FaultException with the client. How can I do this without surrounding each method body in a huge try catch statement? Is there some where I can hook into? Can I do this with some sort of attribute or something? An example of how I would like to handle it can be demonstrated using ASP.NET MVC: public class ApiController: BaseController { protected override void OnException(ExceptionContext filterContext) { var ex = filterContext.Exception; var message = HttpContext.IsDebuggingEnabled? ex.ToString(): ex.Message; _logger.Error("Error processing request for controller {0}, action {1}", filterContext.RequestContext.RouteData.Values["controller"], filterContext.RequestContext.RouteData.Values["action"]); _logger.Error(ex.ToString()); filterContext.ExceptionHandled = true; filterContext.Result = ToXml(new ApiResult(false) { Message = message }); } //... } Using the above method in MVC, I can ensure that no matter which controller action throws an exception, I can handle it and return an appropriately formatted ActionResult containing the necessary info. Is there a way to do this kind of thing with WCF?
TITLE: How to intercept WCF faults and return custom response instead? QUESTION: Consider the following very basic WCF service implementation: public enum TransactionStatus { Success = 0, Error = 1 } public class TransactionResponse { public TransactionStatus Status { get; set; } public string Message { get; set; } } [ServiceContract] [XmlSerializerFormat] public interface ITestService { [OperationContract] TransactionResponse DoSomething(string data); } public class TestService: ITestService { public TransactionResponse DoSomething(string data) { var result = ProcessData(data); // may throw InvalidOperationException return new TransactionResponse() { Status = TransactionStatus.Success, Message = result }; } private string ProcessData(string data) { if (data = "foobar") throw new InvalidOperationException(); return data; } } In the instance that the DoSomething method does throw an InvalidOperationException, I would like to intercept the fault and return a TransactionResponse object, rather than have WCF raise a FaultException with the client. How can I do this without surrounding each method body in a huge try catch statement? Is there some where I can hook into? Can I do this with some sort of attribute or something? An example of how I would like to handle it can be demonstrated using ASP.NET MVC: public class ApiController: BaseController { protected override void OnException(ExceptionContext filterContext) { var ex = filterContext.Exception; var message = HttpContext.IsDebuggingEnabled? ex.ToString(): ex.Message; _logger.Error("Error processing request for controller {0}, action {1}", filterContext.RequestContext.RouteData.Values["controller"], filterContext.RequestContext.RouteData.Values["action"]); _logger.Error(ex.ToString()); filterContext.ExceptionHandled = true; filterContext.Result = ToXml(new ApiResult(false) { Message = message }); } //... } Using the above method in MVC, I can ensure that no matter which controller action throws an exception, I can handle it and return an appropriately formatted ActionResult containing the necessary info. Is there a way to do this kind of thing with WCF? ANSWER: Check out the WCF IErrorHandler interface - it allows you to centrally define one way in your service implementation to catch all exceptions and either swallow them, or convert them to WCF-friendly SOAP exceptions. This will make sure the channel between the client and the server isn't faulted, e.g. it can still be used after this call failed. I don't understand why you'd want to "catch" the SOAP faults and convert those to something else, though.... nor do I know of any support that WCF would give you. The basic assumption is: catch.NET exceptions and convert them into interoperable SOAP faults
[ "wcf", "exception" ]
5
7
4,656
1
0
2011-06-10T16:13:37.907000
2011-06-10T16:27:17.133000
6,309,155
6,309,335
Sage notebook not opening
I installed the sagemath software on an ubuntu machine and nothing executes. I type sage: notebook() NameError: name 'notebook' is not defined sage: 2+3 --------------------------------------------------------------------------- NameError Traceback (most recent call last) /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/bin/ in () NameError: name 'Integer' is not defined On opening sage I get the following message ---------------------------------------------------------------------- | Sage Version 4.7, Release Date: 2011-05-23 | | Type notebook() for the GUI, and license() for information. | ---------------------------------------------------------------------- --------------------------------------------------------------------------- ImportError Traceback (most recent call last) /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/IPython/ipmaker.pyc in force_import(modname) 64 reload(sys.modules[modname]) 65 else: ---> 66 __import__(modname) 67 68 /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/bin/ipy_profile_sage.py in () 5 preparser(True) 6 ----> 7 import sage.all_cmdline 8 sage.all_cmdline._init_cmdline(globals()) 9 /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/sage/all_cmdline.py in () 12 try: 13 ---> 14 from sage.all import * 15 from sage.calculus.predefined import x 16 preparser(on=True) /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/sage/all.py in () 89 from sage.algebras.all import * 90 from sage.modular.all import * ---> 91 from sage.schemes.all import * 92 from sage.graphs.all import * 93 from sage.groups.all import * /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/sage/schemes/all.py in () 23 from jacobians.all import * 24 ---> 25 from hyperelliptic_curves.all import * 26 27 from plane_curves.all import * /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/sage/schemes/hyperelliptic_curves/all.py in () ----> 1 2 3 from constructor import HyperellipticCurve 4 from hyperelliptic_generic import is_HyperellipticCurve 5 from kummer_surface import KummerSurface 6 from invariants import (igusa_clebsch_invariants, 7 absolute_igusa_invariants_kohel, /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/sage/schemes/hyperelliptic_curves/constructor.py in () 9 #***************************************************************************** 10 ---> 11 from sage.schemes.generic.all import ProjectiveSpace 12 13 from hyperelliptic_generic import HyperellipticCurve_generic /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/sage/schemes/generic/all.py in () 2 3 from spec import Spec, is_Spec ----> 4 from affine_space import AffineSpace, is_AffineSpace 5 from algebraic_scheme import is_AlgebraicScheme 6 from ambient_space import is_AmbientSpace /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/sage/schemes/generic/affine_space.pyc in () 22 from sage.misc.all import latex 23 ---> 24 import algebraic_scheme 25 26 import ambient_space /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/sage/schemes/generic/algebraic_scheme.pyc in () 141 import affine_space 142 import projective_space --> 143 import toric_variety 144 import morphism 145 import scheme /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/sage/schemes/generic/toric_variety.py in () 234 import sys 235 --> 236 from sage.geometry.cone import Cone, is_Cone 237 from sage.geometry.fan import Fan 238 from sage.matrix.all import matrix /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/sage/geometry/cone.py in () 173 174 from sage.combinat.posets.posets import FinitePoset --> 175 from sage.geometry.lattice_polytope import LatticePolytope 176 from sage.geometry.polyhedra import Polyhedron, Hasse_diagram_from_incidences 177 from sage.geometry.toric_lattice import ToricLattice, is_ToricLattice /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/sage/geometry/lattice_polytope.py in () 110 from sage.plot.plot import hue 111 from sage.plot.plot3d.index_face_set import IndexFaceSet --> 112 from sage.plot.plot3d.all import line3d, point3d 113 from sage.plot.plot3d.shapes2 import text3d 114 from sage.plot.plot3d.tachyon import Tachyon /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/sage/plot/plot3d/all.py in () 3 from parametric_plot3d import parametric_plot3d 4 from plot_field3d import plot_vector_field3d ----> 5 from implicit_plot3d import implicit_plot3d 6 from list_plot3d import list_plot3d 7 from revolution_plot3d import revolution_plot3d /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/sage/plot/plot3d/implicit_plot3d.py in () 3 """ 4 ----> 5 from implicit_surface import ImplicitSurface 6 7 def implicit_plot3d(f, xrange, yrange, zrange, **kwds): /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/bin/numpy.pxd in init sage.plot.plot3d.implicit_surface (sage/plot/plot3d/implicit_surface.c:29094)() /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/numpy/__init__.pyc in () 134 return loader(*packages, **options) 135 --> 136 import add_newdocs 137 __all__ = ['add_newdocs'] 138 /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/numpy/add_newdocs.py in () 7 # core/fromnumeric.py, core/defmatrix.py up-to-date. 8 ----> 9 from numpy.lib import add_newdoc 10 11 ############################################################################### /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/numpy/lib/__init__.py in () 11 12 import scimath as emath ---> 13 from polynomial import * 14 #import convertcode 15 from utils import * /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/numpy/lib/polynomial.py in () 15 from numpy.lib.function_base import trim_zeros, sort_complex 16 from numpy.lib.type_check import iscomplex, real, imag ---> 17 from numpy.linalg import eigvals, lstsq 18 19 class RankWarning(UserWarning): /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/numpy/linalg/__init__.py in () 46 from info import __doc__ 47 ---> 48 from linalg import * 49 50 from numpy.testing import Tester /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/numpy/linalg/linalg.py in () 21 isfinite, size, finfo, absolute, log, exp 22 from numpy.lib import triu ---> 23 from numpy.linalg import lapack_lite 24 from numpy.matrixlib.defmatrix import matrix_power 25 from numpy.compat import asbytes ImportError: libgfortran.so.3: cannot open shared object file: No such file or directory Error importing ipy_profile_sage - perhaps you should run %upgrade? WARNING: Loading of ipy_profile_sage failed. sage: notebook() --------------------------------------------------------------------------- NameError Traceback (most recent call last) /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/bin/ in () NameError: name 'notebook' is not defined sage: notebook() --------------------------------------------------------------------------- NameError Traceback (most recent call last) /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/bin/ in ()
I think the line ImportError: libgfortran.so.3: cannot open shared object file: No such file or directory is the source of the problem. That error message seemed familiar, and I thought I'd seen it relatively recently: turns out that I was right, it was on a sage-support thread.. Try installing gfortran. On Ubuntu: sudo apt-get install libgfortran3
Sage notebook not opening I installed the sagemath software on an ubuntu machine and nothing executes. I type sage: notebook() NameError: name 'notebook' is not defined sage: 2+3 --------------------------------------------------------------------------- NameError Traceback (most recent call last) /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/bin/ in () NameError: name 'Integer' is not defined On opening sage I get the following message ---------------------------------------------------------------------- | Sage Version 4.7, Release Date: 2011-05-23 | | Type notebook() for the GUI, and license() for information. | ---------------------------------------------------------------------- --------------------------------------------------------------------------- ImportError Traceback (most recent call last) /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/IPython/ipmaker.pyc in force_import(modname) 64 reload(sys.modules[modname]) 65 else: ---> 66 __import__(modname) 67 68 /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/bin/ipy_profile_sage.py in () 5 preparser(True) 6 ----> 7 import sage.all_cmdline 8 sage.all_cmdline._init_cmdline(globals()) 9 /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/sage/all_cmdline.py in () 12 try: 13 ---> 14 from sage.all import * 15 from sage.calculus.predefined import x 16 preparser(on=True) /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/sage/all.py in () 89 from sage.algebras.all import * 90 from sage.modular.all import * ---> 91 from sage.schemes.all import * 92 from sage.graphs.all import * 93 from sage.groups.all import * /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/sage/schemes/all.py in () 23 from jacobians.all import * 24 ---> 25 from hyperelliptic_curves.all import * 26 27 from plane_curves.all import * /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/sage/schemes/hyperelliptic_curves/all.py in () ----> 1 2 3 from constructor import HyperellipticCurve 4 from hyperelliptic_generic import is_HyperellipticCurve 5 from kummer_surface import KummerSurface 6 from invariants import (igusa_clebsch_invariants, 7 absolute_igusa_invariants_kohel, /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/sage/schemes/hyperelliptic_curves/constructor.py in () 9 #***************************************************************************** 10 ---> 11 from sage.schemes.generic.all import ProjectiveSpace 12 13 from hyperelliptic_generic import HyperellipticCurve_generic /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/sage/schemes/generic/all.py in () 2 3 from spec import Spec, is_Spec ----> 4 from affine_space import AffineSpace, is_AffineSpace 5 from algebraic_scheme import is_AlgebraicScheme 6 from ambient_space import is_AmbientSpace /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/sage/schemes/generic/affine_space.pyc in () 22 from sage.misc.all import latex 23 ---> 24 import algebraic_scheme 25 26 import ambient_space /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/sage/schemes/generic/algebraic_scheme.pyc in () 141 import affine_space 142 import projective_space --> 143 import toric_variety 144 import morphism 145 import scheme /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/sage/schemes/generic/toric_variety.py in () 234 import sys 235 --> 236 from sage.geometry.cone import Cone, is_Cone 237 from sage.geometry.fan import Fan 238 from sage.matrix.all import matrix /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/sage/geometry/cone.py in () 173 174 from sage.combinat.posets.posets import FinitePoset --> 175 from sage.geometry.lattice_polytope import LatticePolytope 176 from sage.geometry.polyhedra import Polyhedron, Hasse_diagram_from_incidences 177 from sage.geometry.toric_lattice import ToricLattice, is_ToricLattice /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/sage/geometry/lattice_polytope.py in () 110 from sage.plot.plot import hue 111 from sage.plot.plot3d.index_face_set import IndexFaceSet --> 112 from sage.plot.plot3d.all import line3d, point3d 113 from sage.plot.plot3d.shapes2 import text3d 114 from sage.plot.plot3d.tachyon import Tachyon /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/sage/plot/plot3d/all.py in () 3 from parametric_plot3d import parametric_plot3d 4 from plot_field3d import plot_vector_field3d ----> 5 from implicit_plot3d import implicit_plot3d 6 from list_plot3d import list_plot3d 7 from revolution_plot3d import revolution_plot3d /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/sage/plot/plot3d/implicit_plot3d.py in () 3 """ 4 ----> 5 from implicit_surface import ImplicitSurface 6 7 def implicit_plot3d(f, xrange, yrange, zrange, **kwds): /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/bin/numpy.pxd in init sage.plot.plot3d.implicit_surface (sage/plot/plot3d/implicit_surface.c:29094)() /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/numpy/__init__.pyc in () 134 return loader(*packages, **options) 135 --> 136 import add_newdocs 137 __all__ = ['add_newdocs'] 138 /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/numpy/add_newdocs.py in () 7 # core/fromnumeric.py, core/defmatrix.py up-to-date. 8 ----> 9 from numpy.lib import add_newdoc 10 11 ############################################################################### /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/numpy/lib/__init__.py in () 11 12 import scimath as emath ---> 13 from polynomial import * 14 #import convertcode 15 from utils import * /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/numpy/lib/polynomial.py in () 15 from numpy.lib.function_base import trim_zeros, sort_complex 16 from numpy.lib.type_check import iscomplex, real, imag ---> 17 from numpy.linalg import eigvals, lstsq 18 19 class RankWarning(UserWarning): /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/numpy/linalg/__init__.py in () 46 from info import __doc__ 47 ---> 48 from linalg import * 49 50 from numpy.testing import Tester /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/numpy/linalg/linalg.py in () 21 isfinite, size, finfo, absolute, log, exp 22 from numpy.lib import triu ---> 23 from numpy.linalg import lapack_lite 24 from numpy.matrixlib.defmatrix import matrix_power 25 from numpy.compat import asbytes ImportError: libgfortran.so.3: cannot open shared object file: No such file or directory Error importing ipy_profile_sage - perhaps you should run %upgrade? WARNING: Loading of ipy_profile_sage failed. sage: notebook() --------------------------------------------------------------------------- NameError Traceback (most recent call last) /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/bin/ in () NameError: name 'notebook' is not defined sage: notebook() --------------------------------------------------------------------------- NameError Traceback (most recent call last) /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/bin/ in ()
TITLE: Sage notebook not opening QUESTION: I installed the sagemath software on an ubuntu machine and nothing executes. I type sage: notebook() NameError: name 'notebook' is not defined sage: 2+3 --------------------------------------------------------------------------- NameError Traceback (most recent call last) /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/bin/ in () NameError: name 'Integer' is not defined On opening sage I get the following message ---------------------------------------------------------------------- | Sage Version 4.7, Release Date: 2011-05-23 | | Type notebook() for the GUI, and license() for information. | ---------------------------------------------------------------------- --------------------------------------------------------------------------- ImportError Traceback (most recent call last) /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/IPython/ipmaker.pyc in force_import(modname) 64 reload(sys.modules[modname]) 65 else: ---> 66 __import__(modname) 67 68 /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/bin/ipy_profile_sage.py in () 5 preparser(True) 6 ----> 7 import sage.all_cmdline 8 sage.all_cmdline._init_cmdline(globals()) 9 /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/sage/all_cmdline.py in () 12 try: 13 ---> 14 from sage.all import * 15 from sage.calculus.predefined import x 16 preparser(on=True) /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/sage/all.py in () 89 from sage.algebras.all import * 90 from sage.modular.all import * ---> 91 from sage.schemes.all import * 92 from sage.graphs.all import * 93 from sage.groups.all import * /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/sage/schemes/all.py in () 23 from jacobians.all import * 24 ---> 25 from hyperelliptic_curves.all import * 26 27 from plane_curves.all import * /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/sage/schemes/hyperelliptic_curves/all.py in () ----> 1 2 3 from constructor import HyperellipticCurve 4 from hyperelliptic_generic import is_HyperellipticCurve 5 from kummer_surface import KummerSurface 6 from invariants import (igusa_clebsch_invariants, 7 absolute_igusa_invariants_kohel, /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/sage/schemes/hyperelliptic_curves/constructor.py in () 9 #***************************************************************************** 10 ---> 11 from sage.schemes.generic.all import ProjectiveSpace 12 13 from hyperelliptic_generic import HyperellipticCurve_generic /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/sage/schemes/generic/all.py in () 2 3 from spec import Spec, is_Spec ----> 4 from affine_space import AffineSpace, is_AffineSpace 5 from algebraic_scheme import is_AlgebraicScheme 6 from ambient_space import is_AmbientSpace /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/sage/schemes/generic/affine_space.pyc in () 22 from sage.misc.all import latex 23 ---> 24 import algebraic_scheme 25 26 import ambient_space /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/sage/schemes/generic/algebraic_scheme.pyc in () 141 import affine_space 142 import projective_space --> 143 import toric_variety 144 import morphism 145 import scheme /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/sage/schemes/generic/toric_variety.py in () 234 import sys 235 --> 236 from sage.geometry.cone import Cone, is_Cone 237 from sage.geometry.fan import Fan 238 from sage.matrix.all import matrix /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/sage/geometry/cone.py in () 173 174 from sage.combinat.posets.posets import FinitePoset --> 175 from sage.geometry.lattice_polytope import LatticePolytope 176 from sage.geometry.polyhedra import Polyhedron, Hasse_diagram_from_incidences 177 from sage.geometry.toric_lattice import ToricLattice, is_ToricLattice /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/sage/geometry/lattice_polytope.py in () 110 from sage.plot.plot import hue 111 from sage.plot.plot3d.index_face_set import IndexFaceSet --> 112 from sage.plot.plot3d.all import line3d, point3d 113 from sage.plot.plot3d.shapes2 import text3d 114 from sage.plot.plot3d.tachyon import Tachyon /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/sage/plot/plot3d/all.py in () 3 from parametric_plot3d import parametric_plot3d 4 from plot_field3d import plot_vector_field3d ----> 5 from implicit_plot3d import implicit_plot3d 6 from list_plot3d import list_plot3d 7 from revolution_plot3d import revolution_plot3d /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/sage/plot/plot3d/implicit_plot3d.py in () 3 """ 4 ----> 5 from implicit_surface import ImplicitSurface 6 7 def implicit_plot3d(f, xrange, yrange, zrange, **kwds): /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/bin/numpy.pxd in init sage.plot.plot3d.implicit_surface (sage/plot/plot3d/implicit_surface.c:29094)() /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/numpy/__init__.pyc in () 134 return loader(*packages, **options) 135 --> 136 import add_newdocs 137 __all__ = ['add_newdocs'] 138 /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/numpy/add_newdocs.py in () 7 # core/fromnumeric.py, core/defmatrix.py up-to-date. 8 ----> 9 from numpy.lib import add_newdoc 10 11 ############################################################################### /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/numpy/lib/__init__.py in () 11 12 import scimath as emath ---> 13 from polynomial import * 14 #import convertcode 15 from utils import * /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/numpy/lib/polynomial.py in () 15 from numpy.lib.function_base import trim_zeros, sort_complex 16 from numpy.lib.type_check import iscomplex, real, imag ---> 17 from numpy.linalg import eigvals, lstsq 18 19 class RankWarning(UserWarning): /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/numpy/linalg/__init__.py in () 46 from info import __doc__ 47 ---> 48 from linalg import * 49 50 from numpy.testing import Tester /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/lib/python2.6/site-packages/numpy/linalg/linalg.py in () 21 isfinite, size, finfo, absolute, log, exp 22 from numpy.lib import triu ---> 23 from numpy.linalg import lapack_lite 24 from numpy.matrixlib.defmatrix import matrix_power 25 from numpy.compat import asbytes ImportError: libgfortran.so.3: cannot open shared object file: No such file or directory Error importing ipy_profile_sage - perhaps you should run %upgrade? WARNING: Loading of ipy_profile_sage failed. sage: notebook() --------------------------------------------------------------------------- NameError Traceback (most recent call last) /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/bin/ in () NameError: name 'notebook' is not defined sage: notebook() --------------------------------------------------------------------------- NameError Traceback (most recent call last) /home/myusername/Downloads/sage-4.7-linux-32bit-ubuntu_10.04_lts-i686-Linux/local/bin/ in () ANSWER: I think the line ImportError: libgfortran.so.3: cannot open shared object file: No such file or directory is the source of the problem. That error message seemed familiar, and I thought I'd seen it relatively recently: turns out that I was right, it was on a sage-support thread.. Try installing gfortran. On Ubuntu: sudo apt-get install libgfortran3
[ "sage" ]
1
1
827
1
0
2011-06-10T16:13:41.617000
2011-06-10T16:27:31.537000
6,309,157
6,309,227
The Stored Procedures Feud
Possible Duplicate: What are the pros and cons to keeping SQL in Stored Procs versus Code I was listening to Hanselminutes podcast "Rise of The Micro ORM," where one of the guests (Sam Saffron and Rob Conery) outlined the classic reasons that DBA's insist on stored procedures: They are pre-compiled, which gives them an execution speed advantage They hide the underlying database scheme, which allows a separation of interface and implementation that prevents brittleness. A guest then said these aren't good arguments, and suggested the real reason the DBA's will insist on stored procs is because they simply want to protect themselves from the ignorance of the middle-tier developers. I found that statement to be a bit on the extreme side. Certainly I can agree that argument #2 is flawed, but I thought it was well known that sending arbitrary (uncompiled) SQL to the database was a performance hit. Is there something I'm missing that would explain why argument #1 is not really true? My own answer, as just a guess, is that there is a performance hit - but it rarely matters. It is perhaps analogous to a developer who attempts to optimize every loop he writes, even though only 1% of the loops written ever benefit from the tuning. Am I capturing the thought correctly?
"but I thought it was well known that sending arbitrary (uncompiled) SQL to the database was a performance hit." The distinction you're making between stored procs and other sql statements regarding precompilation hasn't existed since SQL 6.5. Stored Procedures and Execution Plans In SQL Server version 6.5 and earlier, stored procedures were a way to partially precompile an execution plan. At the time the stored procedure was created, a partially compiled execution plan was stored in a system table. Executing a stored procedure was more efficient than executing an SQL statement because SQL Server did not have to compile an execution plan completely, it only had to finish optimizing the stored plan for the procedure. Also, the fully compiled execution plan for the stored procedure was retained in the SQL Server procedure cache, meaning that subsequent executions of the stored procedure could use the precompiled execution plan. SQL Server 2000 and SQL Server version 7.0 incorporate a number of changes to statement processing that extend many of the performance benefits of stored procedures to all SQL statements. SQL Server 2000 and SQL Server 7.0 do not save a partially compiled plan for stored procedures when they are created. A stored procedure is compiled at execution time, like any other Transact-SQL statement. SQL Server 2000 and SQL Server 7.0 retain execution plans for all SQL statements in the procedure cache, not just stored procedure execution plans. The database engine uses an efficient algorithm for comparing new Transact-SQL statements with the Transact-SQL statements of existing execution plans. If the database engine determines that a new Transact-SQL statement matches the Transact-SQL statement of an existing execution plan, it reuses the plan. This reduces the relative performance benefit of precompiling stored procedures by extending execution plan reuse to all SQL statements. http://msdn.microsoft.com/en-us/library/aa174792%28v=sql.80%29.aspx
The Stored Procedures Feud Possible Duplicate: What are the pros and cons to keeping SQL in Stored Procs versus Code I was listening to Hanselminutes podcast "Rise of The Micro ORM," where one of the guests (Sam Saffron and Rob Conery) outlined the classic reasons that DBA's insist on stored procedures: They are pre-compiled, which gives them an execution speed advantage They hide the underlying database scheme, which allows a separation of interface and implementation that prevents brittleness. A guest then said these aren't good arguments, and suggested the real reason the DBA's will insist on stored procs is because they simply want to protect themselves from the ignorance of the middle-tier developers. I found that statement to be a bit on the extreme side. Certainly I can agree that argument #2 is flawed, but I thought it was well known that sending arbitrary (uncompiled) SQL to the database was a performance hit. Is there something I'm missing that would explain why argument #1 is not really true? My own answer, as just a guess, is that there is a performance hit - but it rarely matters. It is perhaps analogous to a developer who attempts to optimize every loop he writes, even though only 1% of the loops written ever benefit from the tuning. Am I capturing the thought correctly?
TITLE: The Stored Procedures Feud QUESTION: Possible Duplicate: What are the pros and cons to keeping SQL in Stored Procs versus Code I was listening to Hanselminutes podcast "Rise of The Micro ORM," where one of the guests (Sam Saffron and Rob Conery) outlined the classic reasons that DBA's insist on stored procedures: They are pre-compiled, which gives them an execution speed advantage They hide the underlying database scheme, which allows a separation of interface and implementation that prevents brittleness. A guest then said these aren't good arguments, and suggested the real reason the DBA's will insist on stored procs is because they simply want to protect themselves from the ignorance of the middle-tier developers. I found that statement to be a bit on the extreme side. Certainly I can agree that argument #2 is flawed, but I thought it was well known that sending arbitrary (uncompiled) SQL to the database was a performance hit. Is there something I'm missing that would explain why argument #1 is not really true? My own answer, as just a guess, is that there is a performance hit - but it rarely matters. It is perhaps analogous to a developer who attempts to optimize every loop he writes, even though only 1% of the loops written ever benefit from the tuning. Am I capturing the thought correctly? ANSWER: "but I thought it was well known that sending arbitrary (uncompiled) SQL to the database was a performance hit." The distinction you're making between stored procs and other sql statements regarding precompilation hasn't existed since SQL 6.5. Stored Procedures and Execution Plans In SQL Server version 6.5 and earlier, stored procedures were a way to partially precompile an execution plan. At the time the stored procedure was created, a partially compiled execution plan was stored in a system table. Executing a stored procedure was more efficient than executing an SQL statement because SQL Server did not have to compile an execution plan completely, it only had to finish optimizing the stored plan for the procedure. Also, the fully compiled execution plan for the stored procedure was retained in the SQL Server procedure cache, meaning that subsequent executions of the stored procedure could use the precompiled execution plan. SQL Server 2000 and SQL Server version 7.0 incorporate a number of changes to statement processing that extend many of the performance benefits of stored procedures to all SQL statements. SQL Server 2000 and SQL Server 7.0 do not save a partially compiled plan for stored procedures when they are created. A stored procedure is compiled at execution time, like any other Transact-SQL statement. SQL Server 2000 and SQL Server 7.0 retain execution plans for all SQL statements in the procedure cache, not just stored procedure execution plans. The database engine uses an efficient algorithm for comparing new Transact-SQL statements with the Transact-SQL statements of existing execution plans. If the database engine determines that a new Transact-SQL statement matches the Transact-SQL statement of an existing execution plan, it reuses the plan. This reduces the relative performance benefit of precompiling stored procedures by extending execution plan reuse to all SQL statements. http://msdn.microsoft.com/en-us/library/aa174792%28v=sql.80%29.aspx
[ "c#", "database", "performance", "stored-procedures", "orm" ]
4
8
493
3
0
2011-06-10T16:13:55.247000
2011-06-10T16:19:23.920000
6,309,179
6,309,371
How to tell if a file is an EXE or a DLL?
If you've gotten the file extensions messed up, how can you tell an executable apart from a DLL? They both seem to have entry points and everything...
Look at this article for a good explanation of a portable executable on windows. And then look at the section about the PE header. Also the code there-in shows in C the way to open and examine a PE file using Win32. This information you are looking for is stored in the IMAGE_FILE_HEADER. Specifically in the Characteristics field which would include the flag IMAGE_FILE_DLL 0x2000 if it is a dll. That should give you enough information to create a small utility that makes the determination of a bunch of files if that is what you are looking for. The most relevant bits of code for reference purposes, copied from the article above and edited to remove extraneous detail/error handling. void DumpFile(LPWSTR filename) { HANDLE hFile = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); HANDLE hFileMapping = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL); LPVOID lpFileBase = MapViewOfFile(hFileMapping, FILE_MAP_READ, 0, 0, 0); PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)lpFileBase; PIMAGE_NT_HEADERS pNTHeader = (PIMAGE_NT_HEADERS)((DWORD)pDosHeader + (DWORD)pDosHeader->e_lfanew); if ((pNTHeader->FileHeader.Characteristics & IMAGE_FILE_DLL)) printf("dll"); if ((pNTHeader->FileHeader.Characteristics & IMAGE_FILE_EXECUTABLE_IMAGE)) printf("exe"); else printf("????"); UnmapViewOfFile(lpFileBase); CloseHandle(hFileMapping); CloseHandle(hFile); }
How to tell if a file is an EXE or a DLL? If you've gotten the file extensions messed up, how can you tell an executable apart from a DLL? They both seem to have entry points and everything...
TITLE: How to tell if a file is an EXE or a DLL? QUESTION: If you've gotten the file extensions messed up, how can you tell an executable apart from a DLL? They both seem to have entry points and everything... ANSWER: Look at this article for a good explanation of a portable executable on windows. And then look at the section about the PE header. Also the code there-in shows in C the way to open and examine a PE file using Win32. This information you are looking for is stored in the IMAGE_FILE_HEADER. Specifically in the Characteristics field which would include the flag IMAGE_FILE_DLL 0x2000 if it is a dll. That should give you enough information to create a small utility that makes the determination of a bunch of files if that is what you are looking for. The most relevant bits of code for reference purposes, copied from the article above and edited to remove extraneous detail/error handling. void DumpFile(LPWSTR filename) { HANDLE hFile = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); HANDLE hFileMapping = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL); LPVOID lpFileBase = MapViewOfFile(hFileMapping, FILE_MAP_READ, 0, 0, 0); PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)lpFileBase; PIMAGE_NT_HEADERS pNTHeader = (PIMAGE_NT_HEADERS)((DWORD)pDosHeader + (DWORD)pDosHeader->e_lfanew); if ((pNTHeader->FileHeader.Characteristics & IMAGE_FILE_DLL)) printf("dll"); if ((pNTHeader->FileHeader.Characteristics & IMAGE_FILE_EXECUTABLE_IMAGE)) printf("exe"); else printf("????"); UnmapViewOfFile(lpFileBase); CloseHandle(hFileMapping); CloseHandle(hFile); }
[ "dll", "executable", "file-extension", "portable-executable" ]
15
5
15,551
5
0
2011-06-10T16:15:21.477000
2011-06-10T16:30:58.277000
6,309,181
6,309,247
php array returned from preg_split not working
I am currently writing a php script that validates a username and password. I am working by testing things little by little and right now I have a password file with only one line in it: user:0011 I am using preg_split to parse the lines in this file and have the following code in my php script: "; echo $login[1]." "; print_r($login); if($usr == $login[0] && $pass == $login[1]) { echo "in if "; $auth = true; break; } } if($auth) echo "success"; else echo "fail!"; /*$test = preg_split("/:/","me:you"); echo $test[0];*/ fclose($f);?> The problem is that this is the output it give me is: user 0011 Array ( [0] => user [1] => 0011 ) Notice: Undefined offset: 1 in /srv/www/htdocs/PHP/val.php on line 20 Array ( [0] => ) fail! This error doesn't make sense to me because it is implying that the array is not long enough to have a value at index 1, but I just printed that value and even in the result from print_r it shows there being a value at that index. Does anyone have any idea what is causing this error?
You're on the second iteration of the while loop is my guess; try throwing in a simple counter to check. If you have a newline in the file that would do it. try doing this at the top: $lrec = trim(fgets($f)); if (empty($lrec)) { continue; } $login = preg_split("/:/",$lrec);
php array returned from preg_split not working I am currently writing a php script that validates a username and password. I am working by testing things little by little and right now I have a password file with only one line in it: user:0011 I am using preg_split to parse the lines in this file and have the following code in my php script: "; echo $login[1]." "; print_r($login); if($usr == $login[0] && $pass == $login[1]) { echo "in if "; $auth = true; break; } } if($auth) echo "success"; else echo "fail!"; /*$test = preg_split("/:/","me:you"); echo $test[0];*/ fclose($f);?> The problem is that this is the output it give me is: user 0011 Array ( [0] => user [1] => 0011 ) Notice: Undefined offset: 1 in /srv/www/htdocs/PHP/val.php on line 20 Array ( [0] => ) fail! This error doesn't make sense to me because it is implying that the array is not long enough to have a value at index 1, but I just printed that value and even in the result from print_r it shows there being a value at that index. Does anyone have any idea what is causing this error?
TITLE: php array returned from preg_split not working QUESTION: I am currently writing a php script that validates a username and password. I am working by testing things little by little and right now I have a password file with only one line in it: user:0011 I am using preg_split to parse the lines in this file and have the following code in my php script: "; echo $login[1]." "; print_r($login); if($usr == $login[0] && $pass == $login[1]) { echo "in if "; $auth = true; break; } } if($auth) echo "success"; else echo "fail!"; /*$test = preg_split("/:/","me:you"); echo $test[0];*/ fclose($f);?> The problem is that this is the output it give me is: user 0011 Array ( [0] => user [1] => 0011 ) Notice: Undefined offset: 1 in /srv/www/htdocs/PHP/val.php on line 20 Array ( [0] => ) fail! This error doesn't make sense to me because it is implying that the array is not long enough to have a value at index 1, but I just printed that value and even in the result from print_r it shows there being a value at that index. Does anyone have any idea what is causing this error? ANSWER: You're on the second iteration of the while loop is my guess; try throwing in a simple counter to check. If you have a newline in the file that would do it. try doing this at the top: $lrec = trim(fgets($f)); if (empty($lrec)) { continue; } $login = preg_split("/:/",$lrec);
[ "php", "arrays", "string-parsing" ]
0
3
1,158
1
0
2011-06-10T16:15:22.393000
2011-06-10T16:20:53.793000
6,309,187
6,309,348
How do I use ajax to auto refresh a section of page without manually invoking a function within javascript?
var xmlhttp; //Set up ajax first so he knows which guy to play with function loadXMLDoc(url,cfunc) { //Code to catch modern browsers if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); } //Code to catch crap browsers else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } //Set up xmlhttp.onreadystatechange=cfunc; xmlhttp.open("GET",url,true); xmlhttp.send(); } //Set a function to deploy when something calls myFunction() function myFunction() { loadXMLDoc("../../../support/ajaxTest.txt",function() { //Fires off when button pressed if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("statusRefresh").innerHTML=xmlhttp.responseText; setInterval( "alert('Hello I did something but i needed to be invoked by a button first')", 5000 ); } }); } I want to call restful java service to refresh a 'status'. I need ajax to auto refresh the this status once the page has been hit. The Refresh method isnt instantaneous, for it has to talk with other machines.
function autoRefresh() { var url = "../../../support/ajaxTest.txt"; var target = document.getElementById("statusRefresh"); var doRefresh = function() { loadXMLDoc(url, function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { target.innerHTML=xmlhttp.responseText; } } }); setInterval( doRefresh, 5000 ); } and document.onload = autoRefresh;
How do I use ajax to auto refresh a section of page without manually invoking a function within javascript? var xmlhttp; //Set up ajax first so he knows which guy to play with function loadXMLDoc(url,cfunc) { //Code to catch modern browsers if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); } //Code to catch crap browsers else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } //Set up xmlhttp.onreadystatechange=cfunc; xmlhttp.open("GET",url,true); xmlhttp.send(); } //Set a function to deploy when something calls myFunction() function myFunction() { loadXMLDoc("../../../support/ajaxTest.txt",function() { //Fires off when button pressed if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("statusRefresh").innerHTML=xmlhttp.responseText; setInterval( "alert('Hello I did something but i needed to be invoked by a button first')", 5000 ); } }); } I want to call restful java service to refresh a 'status'. I need ajax to auto refresh the this status once the page has been hit. The Refresh method isnt instantaneous, for it has to talk with other machines.
TITLE: How do I use ajax to auto refresh a section of page without manually invoking a function within javascript? QUESTION: var xmlhttp; //Set up ajax first so he knows which guy to play with function loadXMLDoc(url,cfunc) { //Code to catch modern browsers if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); } //Code to catch crap browsers else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } //Set up xmlhttp.onreadystatechange=cfunc; xmlhttp.open("GET",url,true); xmlhttp.send(); } //Set a function to deploy when something calls myFunction() function myFunction() { loadXMLDoc("../../../support/ajaxTest.txt",function() { //Fires off when button pressed if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("statusRefresh").innerHTML=xmlhttp.responseText; setInterval( "alert('Hello I did something but i needed to be invoked by a button first')", 5000 ); } }); } I want to call restful java service to refresh a 'status'. I need ajax to auto refresh the this status once the page has been hit. The Refresh method isnt instantaneous, for it has to talk with other machines. ANSWER: function autoRefresh() { var url = "../../../support/ajaxTest.txt"; var target = document.getElementById("statusRefresh"); var doRefresh = function() { loadXMLDoc(url, function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { target.innerHTML=xmlhttp.responseText; } } }); setInterval( doRefresh, 5000 ); } and document.onload = autoRefresh;
[ "javascript", "ajax" ]
0
2
9,818
2
0
2011-06-10T16:15:53.467000
2011-06-10T16:28:34.527000
6,309,194
6,309,245
img attribute question re: IE --> won't display native width of images, reverts to 1px wide
This question regards my personal photography website. I use the following javascript to generate random image sequences each time the page is loaded or refreshed: My html and css both validate (css has border radius warnings for three buttons) and the site looks good on everything except any version of IE. The problem is that the width of each image varies and cannot be specified (heights are all consistent at 550px --the site scrolls left to right.) IE displays each image as a line, 550px high by 1px wide. I'd like to find a value that will allow the images to display properly or force IE to use a different html page that will have a fixed layout (remove the random image generator javascript) where I can add the values as appropriate. I don't know how to force one browser to use a different html file. Any help would be greatly appreciated. I'm not really familiar with javascript, but found this in a library and modified it as best as I could to fit my needs. Thanks, Matt
You should remove width="". If I remember correctly, that screws up IE. Testing it here: http://jsfiddle.net/4pE7E/ In IE9/8/7, it does indeed cause the image to be 1px wide.
img attribute question re: IE --> won't display native width of images, reverts to 1px wide This question regards my personal photography website. I use the following javascript to generate random image sequences each time the page is loaded or refreshed: My html and css both validate (css has border radius warnings for three buttons) and the site looks good on everything except any version of IE. The problem is that the width of each image varies and cannot be specified (heights are all consistent at 550px --the site scrolls left to right.) IE displays each image as a line, 550px high by 1px wide. I'd like to find a value that will allow the images to display properly or force IE to use a different html page that will have a fixed layout (remove the random image generator javascript) where I can add the values as appropriate. I don't know how to force one browser to use a different html file. Any help would be greatly appreciated. I'm not really familiar with javascript, but found this in a library and modified it as best as I could to fit my needs. Thanks, Matt
TITLE: img attribute question re: IE --> won't display native width of images, reverts to 1px wide QUESTION: This question regards my personal photography website. I use the following javascript to generate random image sequences each time the page is loaded or refreshed: My html and css both validate (css has border radius warnings for three buttons) and the site looks good on everything except any version of IE. The problem is that the width of each image varies and cannot be specified (heights are all consistent at 550px --the site scrolls left to right.) IE displays each image as a line, 550px high by 1px wide. I'd like to find a value that will allow the images to display properly or force IE to use a different html page that will have a fixed layout (remove the random image generator javascript) where I can add the values as appropriate. I don't know how to force one browser to use a different html file. Any help would be greatly appreciated. I'm not really familiar with javascript, but found this in a library and modified it as best as I could to fit my needs. Thanks, Matt ANSWER: You should remove width="". If I remember correctly, that screws up IE. Testing it here: http://jsfiddle.net/4pE7E/ In IE9/8/7, it does indeed cause the image to be 1px wide.
[ "javascript", "html", "css" ]
0
0
102
1
0
2011-06-10T16:16:31.977000
2011-06-10T16:20:47.140000
6,309,197
6,309,294
Fetching invisible uitableviewcell
I have a tableview with each cell loaded from a xib. It is in the format UILabel some space and UITextField. On a button click somewhere on the view I need the action to fetch all the textfield values in the UITableView with the labels in a dictionary. The problem is when I alloc a cell and fetch the values from there using indexPath, the code crashes exactly at the indexPath of the cell which is invisible (out of screen bounds). I would appreciate any good ideas on how to fetch those cells which are not visible on screen. Thanks!
UITableViewCells are reused when they scroll out of view, so that's probably why it won't let you access attributes of UITableViewCells that are not visible. An NSDictionary might be your best bet: Set a tag for each cell's UITextField based on the indexPath.row value during cell creation. Set the delegate for each UITextField to your view controller. In the delegate method textFieldDidEndEditing, update your dictionary as such: [dictionary setObject:textField.text forKey:[NSNumber numberWithInt:textField.tag]] And now you can access an array of your textField values with [dictionary allValues].
Fetching invisible uitableviewcell I have a tableview with each cell loaded from a xib. It is in the format UILabel some space and UITextField. On a button click somewhere on the view I need the action to fetch all the textfield values in the UITableView with the labels in a dictionary. The problem is when I alloc a cell and fetch the values from there using indexPath, the code crashes exactly at the indexPath of the cell which is invisible (out of screen bounds). I would appreciate any good ideas on how to fetch those cells which are not visible on screen. Thanks!
TITLE: Fetching invisible uitableviewcell QUESTION: I have a tableview with each cell loaded from a xib. It is in the format UILabel some space and UITextField. On a button click somewhere on the view I need the action to fetch all the textfield values in the UITableView with the labels in a dictionary. The problem is when I alloc a cell and fetch the values from there using indexPath, the code crashes exactly at the indexPath of the cell which is invisible (out of screen bounds). I would appreciate any good ideas on how to fetch those cells which are not visible on screen. Thanks! ANSWER: UITableViewCells are reused when they scroll out of view, so that's probably why it won't let you access attributes of UITableViewCells that are not visible. An NSDictionary might be your best bet: Set a tag for each cell's UITextField based on the indexPath.row value during cell creation. Set the delegate for each UITextField to your view controller. In the delegate method textFieldDidEndEditing, update your dictionary as such: [dictionary setObject:textField.text forKey:[NSNumber numberWithInt:textField.tag]] And now you can access an array of your textField values with [dictionary allValues].
[ "iphone", "uitableview" ]
3
4
2,405
1
0
2011-06-10T16:16:51.730000
2011-06-10T16:23:56.513000
6,309,201
6,309,318
Sending TCP data from Android (as client) - no data being sent?
I'm trying to send data from my Android app to my PC over TCP. The code is as follows: Socket socket = new Socket("10.0.78.75", 50505); OutputStream out = socket.getOutputStream(); PrintWriter output = new PrintWriter(out); mStatusText.setText("Sending Data to PC"); output.println("Hello from Android"); mStatusText.setText("Data sent to PC"); socket.close(); mStatusText.setText("Socket closed"); I don't get any errors at all while doing this, however, the server application (written in C#) does not get any data. It sees the client connect to it, and sees that data is being sent, however, the data string comes out empty... And thoughts on why this is happening? PS: The server code is copied from the following site and has been tested with a C# TCP client. http://www.switchonthecode.com/tutorials/csharp-tutorial-simple-threaded-tcp-server
Try putting an out.flush();out.close(); after the println(..);
Sending TCP data from Android (as client) - no data being sent? I'm trying to send data from my Android app to my PC over TCP. The code is as follows: Socket socket = new Socket("10.0.78.75", 50505); OutputStream out = socket.getOutputStream(); PrintWriter output = new PrintWriter(out); mStatusText.setText("Sending Data to PC"); output.println("Hello from Android"); mStatusText.setText("Data sent to PC"); socket.close(); mStatusText.setText("Socket closed"); I don't get any errors at all while doing this, however, the server application (written in C#) does not get any data. It sees the client connect to it, and sees that data is being sent, however, the data string comes out empty... And thoughts on why this is happening? PS: The server code is copied from the following site and has been tested with a C# TCP client. http://www.switchonthecode.com/tutorials/csharp-tutorial-simple-threaded-tcp-server
TITLE: Sending TCP data from Android (as client) - no data being sent? QUESTION: I'm trying to send data from my Android app to my PC over TCP. The code is as follows: Socket socket = new Socket("10.0.78.75", 50505); OutputStream out = socket.getOutputStream(); PrintWriter output = new PrintWriter(out); mStatusText.setText("Sending Data to PC"); output.println("Hello from Android"); mStatusText.setText("Data sent to PC"); socket.close(); mStatusText.setText("Socket closed"); I don't get any errors at all while doing this, however, the server application (written in C#) does not get any data. It sees the client connect to it, and sees that data is being sent, however, the data string comes out empty... And thoughts on why this is happening? PS: The server code is copied from the following site and has been tested with a C# TCP client. http://www.switchonthecode.com/tutorials/csharp-tutorial-simple-threaded-tcp-server ANSWER: Try putting an out.flush();out.close(); after the println(..);
[ "android", "sockets", "tcp", "client", "communication" ]
13
18
46,053
3
0
2011-06-10T16:17:10.307000
2011-06-10T16:25:31.773000
6,309,207
6,309,357
Does after_commit actually run?
I'm on rails 3.0.8 and trying to use the after_commit callback. It's defined here: https://github.com/rails/rails/blob/v3.0.8/activerecord/lib/active_record/transactions.rb#L210 It's mentioned as one of the callbacks here: https://github.com/rails/rails/blob/v3.0.8/activerecord/lib/active_record/callbacks.rb#L22 Consider this: class Car < ActiveRecord::Base after_commit do # this doesn't execute end after_commit:please_run def please_run # nor does this end end Any ideas why it doesn't work? I assume I'm using it correctly.
If you're experimenting with this in your test suite, you'll have to set self.use_transactional_fixtures = false for that class. By default, Rails executes a test suite inside a transaction and does a rollback at the end to clean up. It makes your tests fast, but if you rely on controlling transactions yourself or this callback, it doesn't work.
Does after_commit actually run? I'm on rails 3.0.8 and trying to use the after_commit callback. It's defined here: https://github.com/rails/rails/blob/v3.0.8/activerecord/lib/active_record/transactions.rb#L210 It's mentioned as one of the callbacks here: https://github.com/rails/rails/blob/v3.0.8/activerecord/lib/active_record/callbacks.rb#L22 Consider this: class Car < ActiveRecord::Base after_commit do # this doesn't execute end after_commit:please_run def please_run # nor does this end end Any ideas why it doesn't work? I assume I'm using it correctly.
TITLE: Does after_commit actually run? QUESTION: I'm on rails 3.0.8 and trying to use the after_commit callback. It's defined here: https://github.com/rails/rails/blob/v3.0.8/activerecord/lib/active_record/transactions.rb#L210 It's mentioned as one of the callbacks here: https://github.com/rails/rails/blob/v3.0.8/activerecord/lib/active_record/callbacks.rb#L22 Consider this: class Car < ActiveRecord::Base after_commit do # this doesn't execute end after_commit:please_run def please_run # nor does this end end Any ideas why it doesn't work? I assume I'm using it correctly. ANSWER: If you're experimenting with this in your test suite, you'll have to set self.use_transactional_fixtures = false for that class. By default, Rails executes a test suite inside a transaction and does a rollback at the end to clean up. It makes your tests fast, but if you rely on controlling transactions yourself or this callback, it doesn't work.
[ "ruby-on-rails", "ruby", "activerecord" ]
4
5
1,008
2
0
2011-06-10T16:17:39.770000
2011-06-10T16:29:19.877000
6,309,212
6,309,386
Does div with certain content exist
If I have a container div called #container which has a bunch of.inside divs in it, how would I go about checking whether a certain.inside div with a specified content (just a string of English text) exists or not? I'm doing this to prevent duplicates in a notification system I'm setting up for a website. I don't need the actual text - just whether it exists. Also, being able to modify the content of the.inside div if it's found would be good, so I can increment and show the number of times that message has occurred (grouping, if you like). Thanks, James
To check existence $("#container.inside:contains('old text')").size() > 0 To modify the text $("#container.inside:contains('old text')").text('new text');
Does div with certain content exist If I have a container div called #container which has a bunch of.inside divs in it, how would I go about checking whether a certain.inside div with a specified content (just a string of English text) exists or not? I'm doing this to prevent duplicates in a notification system I'm setting up for a website. I don't need the actual text - just whether it exists. Also, being able to modify the content of the.inside div if it's found would be good, so I can increment and show the number of times that message has occurred (grouping, if you like). Thanks, James
TITLE: Does div with certain content exist QUESTION: If I have a container div called #container which has a bunch of.inside divs in it, how would I go about checking whether a certain.inside div with a specified content (just a string of English text) exists or not? I'm doing this to prevent duplicates in a notification system I'm setting up for a website. I don't need the actual text - just whether it exists. Also, being able to modify the content of the.inside div if it's found would be good, so I can increment and show the number of times that message has occurred (grouping, if you like). Thanks, James ANSWER: To check existence $("#container.inside:contains('old text')").size() > 0 To modify the text $("#container.inside:contains('old text')").text('new text');
[ "javascript", "jquery" ]
0
1
174
4
0
2011-06-10T16:17:56.663000
2011-06-10T16:31:45.960000
6,309,214
6,309,420
Why use a form tag when you're submitting via ajax?
Philosophical question: Say I've got a web app that requires javascript and a modern browser, so progressive enhancement is not an issue. If my form is being built via javascript, and my data updates are all being done via ajax POSTs & PUTs, is there really any reason to wrap my controls in a form tag? If I'm still going to use the tag, say for semantic or structural reasons, is there any reason to have action and method params that I'm going to ignore? It kind of feels like a hold-over from an earlier era to me.
There is at least one important user-experience feature provided specifically by wrapping inputs inside a form tag: The enter key will submit the form. In fact, in Mobile Safari, this is how you get the "Go" button to appear on the keyboard. Without a form wrapping the inputs, there is nothing to submit. You can of course provide enter-key behavior through a keypress event, but I don't know about if this works for mobile devices. I don't know about you, but I'd rather work with the semantics provided by the browser than have to imitate them with events. In your case, you would simply provide an onsubmit event handler for the form, which would do your AJAX submit, then return false, canceling the actual submit. You can simply provide action="" (which means "self"), and method is not required — it defaults to GET.
Why use a form tag when you're submitting via ajax? Philosophical question: Say I've got a web app that requires javascript and a modern browser, so progressive enhancement is not an issue. If my form is being built via javascript, and my data updates are all being done via ajax POSTs & PUTs, is there really any reason to wrap my controls in a form tag? If I'm still going to use the tag, say for semantic or structural reasons, is there any reason to have action and method params that I'm going to ignore? It kind of feels like a hold-over from an earlier era to me.
TITLE: Why use a form tag when you're submitting via ajax? QUESTION: Philosophical question: Say I've got a web app that requires javascript and a modern browser, so progressive enhancement is not an issue. If my form is being built via javascript, and my data updates are all being done via ajax POSTs & PUTs, is there really any reason to wrap my controls in a form tag? If I'm still going to use the tag, say for semantic or structural reasons, is there any reason to have action and method params that I'm going to ignore? It kind of feels like a hold-over from an earlier era to me. ANSWER: There is at least one important user-experience feature provided specifically by wrapping inputs inside a form tag: The enter key will submit the form. In fact, in Mobile Safari, this is how you get the "Go" button to appear on the keyboard. Without a form wrapping the inputs, there is nothing to submit. You can of course provide enter-key behavior through a keypress event, but I don't know about if this works for mobile devices. I don't know about you, but I'd rather work with the semantics provided by the browser than have to imitate them with events. In your case, you would simply provide an onsubmit event handler for the form, which would do your AJAX submit, then return false, canceling the actual submit. You can simply provide action="" (which means "self"), and method is not required — it defaults to GET.
[ "javascript", "html", "ajax", "forms" ]
78
74
16,366
7
0
2011-06-10T16:18:04.600000
2011-06-10T16:34:13.970000
6,309,220
6,309,454
What playlist format does Android 2.2 support to stream?
Hello i am trying to get my android 2.2 app stream music. So far I have been able to stream from a radio station via the mediaPlayer.setDataSource("STREAM HERE") I have tried with a m3u file and it won't work (unless my m3u file is wrong). Can it support xspf or what other file types? How could i go about solving this problem? thanks a lot
The setDataSource() method on the media player will accept file or URIs for a media source. Look at this list to see what media formats the media player accepts: http://developer.android.com/guide/appendix/media-formats.html I am fairly certain that the media player will not play playlist files like M3U. You would have to create your own M3U player, which could be accomplished via the MediaPlayer method: setOnCompletionListener(MediaPlayer.OnCompletionListener listener) Register a callback to be invoked when the end of a media source has been reached during playback. When playback is done, you could start playing the next media resource in your playlist.
What playlist format does Android 2.2 support to stream? Hello i am trying to get my android 2.2 app stream music. So far I have been able to stream from a radio station via the mediaPlayer.setDataSource("STREAM HERE") I have tried with a m3u file and it won't work (unless my m3u file is wrong). Can it support xspf or what other file types? How could i go about solving this problem? thanks a lot
TITLE: What playlist format does Android 2.2 support to stream? QUESTION: Hello i am trying to get my android 2.2 app stream music. So far I have been able to stream from a radio station via the mediaPlayer.setDataSource("STREAM HERE") I have tried with a m3u file and it won't work (unless my m3u file is wrong). Can it support xspf or what other file types? How could i go about solving this problem? thanks a lot ANSWER: The setDataSource() method on the media player will accept file or URIs for a media source. Look at this list to see what media formats the media player accepts: http://developer.android.com/guide/appendix/media-formats.html I am fairly certain that the media player will not play playlist files like M3U. You would have to create your own M3U player, which could be accomplished via the MediaPlayer method: setOnCompletionListener(MediaPlayer.OnCompletionListener listener) Register a callback to be invoked when the end of a media source has been reached during playback. When playback is done, you could start playing the next media resource in your playlist.
[ "android", "stream", "audio-streaming", "playlist" ]
0
1
3,403
1
0
2011-06-10T16:18:53.380000
2011-06-10T16:37:02.237000
6,309,225
6,309,314
UIButton won't gray out
Isn't UIButton supposed to become grayish/grayer when enabled=NO? I have a simple UIButton on a blackbackground (no custom images, no custom nothing, just dragged it with IB and changed size and title). And when I set it programatically to become disabled it stays white as hell! For now I'm using a small stupid workaround: hidden blackbg 0,5 alpha UIView on top of the button that becomes hidden=NO when I need to disable the button... but I would like to set the button properly... Any thoughts?
There is no way to make a UIButton "grayer". But you can use that trick: UIButton *myButton; myButton.alpha = 0.4; myButton.enabled = NO; So your UIButton looks like unusable;)
UIButton won't gray out Isn't UIButton supposed to become grayish/grayer when enabled=NO? I have a simple UIButton on a blackbackground (no custom images, no custom nothing, just dragged it with IB and changed size and title). And when I set it programatically to become disabled it stays white as hell! For now I'm using a small stupid workaround: hidden blackbg 0,5 alpha UIView on top of the button that becomes hidden=NO when I need to disable the button... but I would like to set the button properly... Any thoughts?
TITLE: UIButton won't gray out QUESTION: Isn't UIButton supposed to become grayish/grayer when enabled=NO? I have a simple UIButton on a blackbackground (no custom images, no custom nothing, just dragged it with IB and changed size and title). And when I set it programatically to become disabled it stays white as hell! For now I'm using a small stupid workaround: hidden blackbg 0,5 alpha UIView on top of the button that becomes hidden=NO when I need to disable the button... but I would like to set the button properly... Any thoughts? ANSWER: There is no way to make a UIButton "grayer". But you can use that trick: UIButton *myButton; myButton.alpha = 0.4; myButton.enabled = NO; So your UIButton looks like unusable;)
[ "iphone", "ios", "uibutton" ]
36
44
17,950
5
0
2011-06-10T16:19:17.820000
2011-06-10T16:25:21.640000
6,309,237
6,309,485
How would you declare DLL import signature?
this is a follow-up post of Using pHash from.NET How would you declare following C++ declaration in.NET? int ph_dct_imagehash(const char* file,ulong64 &hash); So far i have [DllImport(@"pHash.dll")] public static extern int ph_dct_imagehash(string file, ref ulong hash); But I am now getting following error for ulong hash1 = 0, hash2 = 0; string firstImage = @"C:\Users\dance2die\Pictures\2011-01-23\177.JPG"; string secondImage = @"C:\Users\dance2die\Pictures\2011-01-23\176.JPG"; ph_dct_imagehash(firstImage, ref hash1); ph_dct_imagehash(secondImage, ref hash2); It basically says that my declartion of ph_dtc_imagehash is wrong. What am I doing wrong here?
Stack imbalance indicates that the C++ code uses cdecl and your C# uses stdcall calling convention. Change your DLLImport to this: [DLLImport(@"pHash.dll", CallingConvention=CallingConvention.Cdecl)] The function signature in C# (return value and parameters) is otherwise correct.
How would you declare DLL import signature? this is a follow-up post of Using pHash from.NET How would you declare following C++ declaration in.NET? int ph_dct_imagehash(const char* file,ulong64 &hash); So far i have [DllImport(@"pHash.dll")] public static extern int ph_dct_imagehash(string file, ref ulong hash); But I am now getting following error for ulong hash1 = 0, hash2 = 0; string firstImage = @"C:\Users\dance2die\Pictures\2011-01-23\177.JPG"; string secondImage = @"C:\Users\dance2die\Pictures\2011-01-23\176.JPG"; ph_dct_imagehash(firstImage, ref hash1); ph_dct_imagehash(secondImage, ref hash2); It basically says that my declartion of ph_dtc_imagehash is wrong. What am I doing wrong here?
TITLE: How would you declare DLL import signature? QUESTION: this is a follow-up post of Using pHash from.NET How would you declare following C++ declaration in.NET? int ph_dct_imagehash(const char* file,ulong64 &hash); So far i have [DllImport(@"pHash.dll")] public static extern int ph_dct_imagehash(string file, ref ulong hash); But I am now getting following error for ulong hash1 = 0, hash2 = 0; string firstImage = @"C:\Users\dance2die\Pictures\2011-01-23\177.JPG"; string secondImage = @"C:\Users\dance2die\Pictures\2011-01-23\176.JPG"; ph_dct_imagehash(firstImage, ref hash1); ph_dct_imagehash(secondImage, ref hash2); It basically says that my declartion of ph_dtc_imagehash is wrong. What am I doing wrong here? ANSWER: Stack imbalance indicates that the C++ code uses cdecl and your C# uses stdcall calling convention. Change your DLLImport to this: [DLLImport(@"pHash.dll", CallingConvention=CallingConvention.Cdecl)] The function signature in C# (return value and parameters) is otherwise correct.
[ "c#", ".net", "c++", "dllimport" ]
6
11
7,670
3
0
2011-06-10T16:20:05.400000
2011-06-10T16:39:33.870000
6,309,254
6,309,306
A way to pretty print a C# object
I have a text box and I want to display a C# object in it in a human-readable way, just for debugging reasons. I don't want to use external libraries if possible. How do I do this?
Serialize it to JSON. It can be done in the ToString() method like others suggested, but I don't think that is appropriate if you are going to use that for debugging only.
A way to pretty print a C# object I have a text box and I want to display a C# object in it in a human-readable way, just for debugging reasons. I don't want to use external libraries if possible. How do I do this?
TITLE: A way to pretty print a C# object QUESTION: I have a text box and I want to display a C# object in it in a human-readable way, just for debugging reasons. I don't want to use external libraries if possible. How do I do this? ANSWER: Serialize it to JSON. It can be done in the ToString() method like others suggested, but I don't think that is appropriate if you are going to use that for debugging only.
[ "c#", "pretty-print" ]
80
25
84,882
10
0
2011-06-10T16:21:18.787000
2011-06-10T16:24:53.123000
6,309,255
6,309,343
Display query in view codeigniter
lets say the query from my controller is $query. how to display the data other than using this kind of code? foreach($query as $row){ echo $row->student_id; } any other than this coz the query only have one row any way that can i access the returned array like this? $query['student_id'];
let's say your table have the following fields student_id and student_name have your model or controller return only one row. function get_first_student() { $query = this->db->select('*')->from('student')-where('student_id','1')->limit(1); $data['stuff'] = $query->row_array(); // or $query->row() which returns an object $this->load->view('whatever',$data) } then in your view student name: student id:
Display query in view codeigniter lets say the query from my controller is $query. how to display the data other than using this kind of code? foreach($query as $row){ echo $row->student_id; } any other than this coz the query only have one row any way that can i access the returned array like this? $query['student_id'];
TITLE: Display query in view codeigniter QUESTION: lets say the query from my controller is $query. how to display the data other than using this kind of code? foreach($query as $row){ echo $row->student_id; } any other than this coz the query only have one row any way that can i access the returned array like this? $query['student_id']; ANSWER: let's say your table have the following fields student_id and student_name have your model or controller return only one row. function get_first_student() { $query = this->db->select('*')->from('student')-where('student_id','1')->limit(1); $data['stuff'] = $query->row_array(); // or $query->row() which returns an object $this->load->view('whatever',$data) } then in your view student name: student id:
[ "codeigniter" ]
3
2
7,510
3
0
2011-06-10T16:21:20.587000
2011-06-10T16:28:24.627000
6,309,256
6,309,388
How to use Cursor's in non Activity Classes
I wan't to get data's from CallLog.Calls.CONTENT_URI in non Activity classes. Am using cursor to get these data's from CallLog. But in non activity class cursor shows some error so how i can how i can do this? Presently am doing like this, public class CallReceiver extends Activity { @Override public void onCreate(Bundle bundle) { super.onCreate(bundle); Cursor cursor = managedQuery(android.provider.CallLog.Calls.CONTENT_URI,null,null,null,null); startManagingCursor(cursor);
Cursor c = context.getContentResolver().query(uri, projection, selection, null, sortOrder); if (c.moveToFirst()) {... } c.close();
How to use Cursor's in non Activity Classes I wan't to get data's from CallLog.Calls.CONTENT_URI in non Activity classes. Am using cursor to get these data's from CallLog. But in non activity class cursor shows some error so how i can how i can do this? Presently am doing like this, public class CallReceiver extends Activity { @Override public void onCreate(Bundle bundle) { super.onCreate(bundle); Cursor cursor = managedQuery(android.provider.CallLog.Calls.CONTENT_URI,null,null,null,null); startManagingCursor(cursor);
TITLE: How to use Cursor's in non Activity Classes QUESTION: I wan't to get data's from CallLog.Calls.CONTENT_URI in non Activity classes. Am using cursor to get these data's from CallLog. But in non activity class cursor shows some error so how i can how i can do this? Presently am doing like this, public class CallReceiver extends Activity { @Override public void onCreate(Bundle bundle) { super.onCreate(bundle); Cursor cursor = managedQuery(android.provider.CallLog.Calls.CONTENT_URI,null,null,null,null); startManagingCursor(cursor); ANSWER: Cursor c = context.getContentResolver().query(uri, projection, selection, null, sortOrder); if (c.moveToFirst()) {... } c.close();
[ "android", "calllog", "android-cursor" ]
1
10
4,004
1
0
2011-06-10T16:21:30.033000
2011-06-10T16:31:55.970000
6,309,261
6,309,297
what is the height of a normal webpage
I'm experimenting with this sample page on jsbin: http://jsbin.com/igeca4/edit The height right now is 741px however, at the bottom there is still some white space left. I can keep doing trial and error witht the height pixels but whatever the user viewing the page has a large monitor. My page will then look half empty from the bottom. Is there a trick that can be used to take up all the height in a webpage?
There is no standard height of a webpage; you can't even assume the user has his/her browser maximized. If you are going to have a footer or page-bottom content, you want to make your page the full height of the browser. Here is a link on having 100% height in CSS. Basically, you need to set the html and body objects to height: 100%;. (Most people don't think of html as an element to stylize.) You may need to make other adjustments based on the situation. http://www.dave-woods.co.uk/?p=144 For more information, you can also refer to these. They should also be helpful: http://css-discuss.incutio.com/wiki/Hundred_Percent_Height http://www.thefutureoftheweb.com/blog/100-percent-height-interface
what is the height of a normal webpage I'm experimenting with this sample page on jsbin: http://jsbin.com/igeca4/edit The height right now is 741px however, at the bottom there is still some white space left. I can keep doing trial and error witht the height pixels but whatever the user viewing the page has a large monitor. My page will then look half empty from the bottom. Is there a trick that can be used to take up all the height in a webpage?
TITLE: what is the height of a normal webpage QUESTION: I'm experimenting with this sample page on jsbin: http://jsbin.com/igeca4/edit The height right now is 741px however, at the bottom there is still some white space left. I can keep doing trial and error witht the height pixels but whatever the user viewing the page has a large monitor. My page will then look half empty from the bottom. Is there a trick that can be used to take up all the height in a webpage? ANSWER: There is no standard height of a webpage; you can't even assume the user has his/her browser maximized. If you are going to have a footer or page-bottom content, you want to make your page the full height of the browser. Here is a link on having 100% height in CSS. Basically, you need to set the html and body objects to height: 100%;. (Most people don't think of html as an element to stylize.) You may need to make other adjustments based on the situation. http://www.dave-woods.co.uk/?p=144 For more information, you can also refer to these. They should also be helpful: http://css-discuss.incutio.com/wiki/Hundred_Percent_Height http://www.thefutureoftheweb.com/blog/100-percent-height-interface
[ "html", "css" ]
1
2
3,172
3
0
2011-06-10T16:21:43.767000
2011-06-10T16:24:01.383000
6,309,271
6,309,504
Which are the Error tracking tools that can be used with NetBeans 7.0?
I am new to enterprise Java development.. Most of the time I am busy working with Spring, Hibernate, JSF, Maven and Glassfish server 3.x.. My problem is that NetBeans sucks my mind most of the time by showing errors which are hard to debug. Can anyone tell me which are the tools that I can use for tracking errors. Which will give me the exact line of error? I have heard something about bugzila but not sure whether it will serve my purpose or not. Thanks in advance,
Bugzilla is an incident tracking tool which helps analysts, developers and QA manage incidents for a software product. I don't think it's what you're looking for. When you say the errors are hard to debug in Netbeans, do you mean that similar errors are easier in another IDE such as Eclipse? If not, I think instead of looking for a tool to show you the exact line of error you need more understanding of how Java development errors are generated and reported. Some searches on that type of understanding should produce quite a few results.
Which are the Error tracking tools that can be used with NetBeans 7.0? I am new to enterprise Java development.. Most of the time I am busy working with Spring, Hibernate, JSF, Maven and Glassfish server 3.x.. My problem is that NetBeans sucks my mind most of the time by showing errors which are hard to debug. Can anyone tell me which are the tools that I can use for tracking errors. Which will give me the exact line of error? I have heard something about bugzila but not sure whether it will serve my purpose or not. Thanks in advance,
TITLE: Which are the Error tracking tools that can be used with NetBeans 7.0? QUESTION: I am new to enterprise Java development.. Most of the time I am busy working with Spring, Hibernate, JSF, Maven and Glassfish server 3.x.. My problem is that NetBeans sucks my mind most of the time by showing errors which are hard to debug. Can anyone tell me which are the tools that I can use for tracking errors. Which will give me the exact line of error? I have heard something about bugzila but not sure whether it will serve my purpose or not. Thanks in advance, ANSWER: Bugzilla is an incident tracking tool which helps analysts, developers and QA manage incidents for a software product. I don't think it's what you're looking for. When you say the errors are hard to debug in Netbeans, do you mean that similar errors are easier in another IDE such as Eclipse? If not, I think instead of looking for a tool to show you the exact line of error you need more understanding of how Java development errors are generated and reported. Some searches on that type of understanding should produce quite a few results.
[ "hibernate", "spring", "netbeans", "jakarta-ee", "maven-3" ]
0
1
71
1
0
2011-06-10T16:22:12.763000
2011-06-10T16:41:21.193000
6,309,276
6,309,360
HTTP Request from c# program, requiring no response
I've done some socket work where I had to send a request because I wanted a response back, but I need to write something in C# that's just going to call an old web page which takes about 10 seconds to respond, and not wait for the response (the failures will flag up with DB calls). Is there a simple way to do this?
Try this thread: Async HttpWebRequest with no wait from within a web application (This kind of approach is sometimes known as "fire and forget")
HTTP Request from c# program, requiring no response I've done some socket work where I had to send a request because I wanted a response back, but I need to write something in C# that's just going to call an old web page which takes about 10 seconds to respond, and not wait for the response (the failures will flag up with DB calls). Is there a simple way to do this?
TITLE: HTTP Request from c# program, requiring no response QUESTION: I've done some socket work where I had to send a request because I wanted a response back, but I need to write something in C# that's just going to call an old web page which takes about 10 seconds to respond, and not wait for the response (the failures will flag up with DB calls). Is there a simple way to do this? ANSWER: Try this thread: Async HttpWebRequest with no wait from within a web application (This kind of approach is sometimes known as "fire and forget")
[ "c#" ]
6
6
15,137
6
0
2011-06-10T16:22:38.333000
2011-06-10T16:29:38.740000
6,309,291
6,309,482
Structural type
I have found for self is very interesting a fact. For example i've wrote: type A = { val st: Set[Any] val start: Set[Any] val Sigma: Set[Char] def tr(f: (Tuple2[Any, Any])=>Boolean): Set[Any] } class Fon { val st: Set[Any] val start: Set[Any] val Sigma: Set[Char] def tr(f: (Tuple2[Any, Any])=>Boolean): Set[Any] = Set(out) def out: String = "is just example" } val a: A = new Fon a.tr(f(Tuple2('a',0))) But if i will try do call a.out - i get an error, that the type A have not exist 'out' What happening to this, how this to work? Thanks.
There is no such method as A.out, because of how you've defined the A type. Thus, when you try to call a method called out on an object of type A, the compiler correctly tells you that no such method exists. This is not related to structural typing, by the way - if you had made A a trait and had Fon extend it, you'd run into exactly the same problems. Moreover, this is just how static typing systems work - the compiler can't guarantee that your code is typesafe so it won't compile it. If you want to call the out method, then you'll need to refer to that object via a Fon variable: val a: Fon = new Fon println(a.out) // works fine, since a is guaranteed to be a Fon and thus have the method
Structural type I have found for self is very interesting a fact. For example i've wrote: type A = { val st: Set[Any] val start: Set[Any] val Sigma: Set[Char] def tr(f: (Tuple2[Any, Any])=>Boolean): Set[Any] } class Fon { val st: Set[Any] val start: Set[Any] val Sigma: Set[Char] def tr(f: (Tuple2[Any, Any])=>Boolean): Set[Any] = Set(out) def out: String = "is just example" } val a: A = new Fon a.tr(f(Tuple2('a',0))) But if i will try do call a.out - i get an error, that the type A have not exist 'out' What happening to this, how this to work? Thanks.
TITLE: Structural type QUESTION: I have found for self is very interesting a fact. For example i've wrote: type A = { val st: Set[Any] val start: Set[Any] val Sigma: Set[Char] def tr(f: (Tuple2[Any, Any])=>Boolean): Set[Any] } class Fon { val st: Set[Any] val start: Set[Any] val Sigma: Set[Char] def tr(f: (Tuple2[Any, Any])=>Boolean): Set[Any] = Set(out) def out: String = "is just example" } val a: A = new Fon a.tr(f(Tuple2('a',0))) But if i will try do call a.out - i get an error, that the type A have not exist 'out' What happening to this, how this to work? Thanks. ANSWER: There is no such method as A.out, because of how you've defined the A type. Thus, when you try to call a method called out on an object of type A, the compiler correctly tells you that no such method exists. This is not related to structural typing, by the way - if you had made A a trait and had Fon extend it, you'd run into exactly the same problems. Moreover, this is just how static typing systems work - the compiler can't guarantee that your code is typesafe so it won't compile it. If you want to call the out method, then you'll need to refer to that object via a Fon variable: val a: Fon = new Fon println(a.out) // works fine, since a is guaranteed to be a Fon and thus have the method
[ "scala" ]
1
5
296
3
0
2011-06-10T16:23:30.543000
2011-06-10T16:39:21.210000
6,309,299
6,309,405
Struts2: Showing and handling a form in one action (post back to the same action)
Coming from frameworks like Django and RoR I am used to show and handle forms from one action. (posting back to the action that shows the form) Is this possible in Struts2 as well? I'd like the following behavior: 1) "users/xyz/edit" gets called 2) HTTP GET -> showing the form 3) HTTP POST -> form validation -> saving data and redirect or return to the form All the examples I have looked at work with two actions which I dislike. Is there any solution or do I have to accept the Struts2 way of doing it?
Yes you can use the same Action class. Though its not as elegant as both those frameworks you mentioned since they encapsulate the REST principle at a framework level. Using the base Struts 2 framework, just add an actionType hidden parameter to your page and form, update it according to next expected action (display->validate->save->display). Or alternatively you can use the REST plugin for Struts 2: http://struts.apache.org/2.x/docs/rest-plugin.html Hope that helps.
Struts2: Showing and handling a form in one action (post back to the same action) Coming from frameworks like Django and RoR I am used to show and handle forms from one action. (posting back to the action that shows the form) Is this possible in Struts2 as well? I'd like the following behavior: 1) "users/xyz/edit" gets called 2) HTTP GET -> showing the form 3) HTTP POST -> form validation -> saving data and redirect or return to the form All the examples I have looked at work with two actions which I dislike. Is there any solution or do I have to accept the Struts2 way of doing it?
TITLE: Struts2: Showing and handling a form in one action (post back to the same action) QUESTION: Coming from frameworks like Django and RoR I am used to show and handle forms from one action. (posting back to the action that shows the form) Is this possible in Struts2 as well? I'd like the following behavior: 1) "users/xyz/edit" gets called 2) HTTP GET -> showing the form 3) HTTP POST -> form validation -> saving data and redirect or return to the form All the examples I have looked at work with two actions which I dislike. Is there any solution or do I have to accept the Struts2 way of doing it? ANSWER: Yes you can use the same Action class. Though its not as elegant as both those frameworks you mentioned since they encapsulate the REST principle at a framework level. Using the base Struts 2 framework, just add an actionType hidden parameter to your page and form, update it according to next expected action (display->validate->save->display). Or alternatively you can use the REST plugin for Struts 2: http://struts.apache.org/2.x/docs/rest-plugin.html Hope that helps.
[ "struts2" ]
0
1
1,277
1
0
2011-06-10T16:24:20.627000
2011-06-10T16:33:26.810000
6,309,313
6,310,358
Caching API data, should I serialize the data into a single column? Or other approach?
I am implementing a Twitter app, where the app needs to cache details of users coming from Twitter. Would it be wise to serialize the data into a column called data? Or, in my User model, should I create a column for each field that is returned by the API request? Reading about (ActiveRecord::Base) serialize. If I go with the latter approach, I would end up with a lot of fields in my User model and if the Twitter API decides to add or remove fields in the future, then we would have to update our columns in our db respectively. However, one advantage I can think of with this approach, is if each column was stored in the db. I could say, search for all twitter users based on location. I could also index the location column for faster queries. How does this compare to the serialized approach? One will suggest: "Don't search serialized data, just don't do it". So I guess, I can have two columns: data (for serialized data), and location, no? But lets add a few more twists: The app needs to sort users out by registered date. Not with our app, but with Twitter. The app should be able to search users by Twitter screen name or Twitter id. The app should be able to sort users out by followers, friends and statuses count. Does this mean, I would need 8 columns in my db: data, location, twitter_created_at, twitter_screen_name, twitter_id, followers_count, friends_count and statuses_count? At this point, would it still be better to go for a mix-column-type approach, or just single each field to its own column. Would you save the data returned from the API into a single column: data, or save each field in its own respective column, or have a mix of both (as described above)? Your thoughts will be appreciated.
So assume for a moment that you have a table with the following three columns: user_id, api_field_name, api_field_value In this table you can add a row for each api field you want to persist. For example: user_d api_field_name api_field_value 1 "meaning_of_life" 42 1 "swallow_type" "africa" This means that user number 1 has these two custom parameters that are tied to the api...if the api changes later on and "swallow_type" is removed, you can get rid of that row. New api fields can be added on the fly. This is an easy way to handle custom parameters that can and do change periodically. It saves you from having to restructure a table each time the api changes. This is the point where I duck to avoid the incoming flak from DB purists...
Caching API data, should I serialize the data into a single column? Or other approach? I am implementing a Twitter app, where the app needs to cache details of users coming from Twitter. Would it be wise to serialize the data into a column called data? Or, in my User model, should I create a column for each field that is returned by the API request? Reading about (ActiveRecord::Base) serialize. If I go with the latter approach, I would end up with a lot of fields in my User model and if the Twitter API decides to add or remove fields in the future, then we would have to update our columns in our db respectively. However, one advantage I can think of with this approach, is if each column was stored in the db. I could say, search for all twitter users based on location. I could also index the location column for faster queries. How does this compare to the serialized approach? One will suggest: "Don't search serialized data, just don't do it". So I guess, I can have two columns: data (for serialized data), and location, no? But lets add a few more twists: The app needs to sort users out by registered date. Not with our app, but with Twitter. The app should be able to search users by Twitter screen name or Twitter id. The app should be able to sort users out by followers, friends and statuses count. Does this mean, I would need 8 columns in my db: data, location, twitter_created_at, twitter_screen_name, twitter_id, followers_count, friends_count and statuses_count? At this point, would it still be better to go for a mix-column-type approach, or just single each field to its own column. Would you save the data returned from the API into a single column: data, or save each field in its own respective column, or have a mix of both (as described above)? Your thoughts will be appreciated.
TITLE: Caching API data, should I serialize the data into a single column? Or other approach? QUESTION: I am implementing a Twitter app, where the app needs to cache details of users coming from Twitter. Would it be wise to serialize the data into a column called data? Or, in my User model, should I create a column for each field that is returned by the API request? Reading about (ActiveRecord::Base) serialize. If I go with the latter approach, I would end up with a lot of fields in my User model and if the Twitter API decides to add or remove fields in the future, then we would have to update our columns in our db respectively. However, one advantage I can think of with this approach, is if each column was stored in the db. I could say, search for all twitter users based on location. I could also index the location column for faster queries. How does this compare to the serialized approach? One will suggest: "Don't search serialized data, just don't do it". So I guess, I can have two columns: data (for serialized data), and location, no? But lets add a few more twists: The app needs to sort users out by registered date. Not with our app, but with Twitter. The app should be able to search users by Twitter screen name or Twitter id. The app should be able to sort users out by followers, friends and statuses count. Does this mean, I would need 8 columns in my db: data, location, twitter_created_at, twitter_screen_name, twitter_id, followers_count, friends_count and statuses_count? At this point, would it still be better to go for a mix-column-type approach, or just single each field to its own column. Would you save the data returned from the API into a single column: data, or save each field in its own respective column, or have a mix of both (as described above)? Your thoughts will be appreciated. ANSWER: So assume for a moment that you have a table with the following three columns: user_id, api_field_name, api_field_value In this table you can add a row for each api field you want to persist. For example: user_d api_field_name api_field_value 1 "meaning_of_life" 42 1 "swallow_type" "africa" This means that user number 1 has these two custom parameters that are tied to the api...if the api changes later on and "swallow_type" is removed, you can get rid of that row. New api fields can be added on the fly. This is an easy way to handle custom parameters that can and do change periodically. It saves you from having to restructure a table each time the api changes. This is the point where I duck to avoid the incoming flak from DB purists...
[ "ruby-on-rails", "ruby-on-rails-3", "twitter" ]
0
1
440
1
0
2011-06-10T16:25:16.863000
2011-06-10T18:06:00.993000
6,309,325
6,309,411
Common managed C++ gotchas
What are some of the most common issues to look out for when writing managed-C++ for the first time after almost exclusively working with unmanaged C++?
When you convert a managed delegate to a pointer-to-function using the built-in IJW (It Just Works) technology, the pointer-to-function is not holding a reference to the object that the delegate was from. If you don't arrange to hold a reference some other way, the managed object may be collected, and then when you call the function, you'll get a NullReferenceException. You run into this a lot if you are making a C-library that takes callbacks, and you want to wrap it in a Managed class. The client to the managed class will provide a delegate, which you convert to the callback. You must also keep a reference to the delegate or target object. This is true in Managed C++ and C++/CLI.
Common managed C++ gotchas What are some of the most common issues to look out for when writing managed-C++ for the first time after almost exclusively working with unmanaged C++?
TITLE: Common managed C++ gotchas QUESTION: What are some of the most common issues to look out for when writing managed-C++ for the first time after almost exclusively working with unmanaged C++? ANSWER: When you convert a managed delegate to a pointer-to-function using the built-in IJW (It Just Works) technology, the pointer-to-function is not holding a reference to the object that the delegate was from. If you don't arrange to hold a reference some other way, the managed object may be collected, and then when you call the function, you'll get a NullReferenceException. You run into this a lot if you are making a C-library that takes callbacks, and you want to wrap it in a Managed class. The client to the managed class will provide a delegate, which you convert to the callback. You must also keep a reference to the delegate or target object. This is true in Managed C++ and C++/CLI.
[ "c++-cli", "managed-c++" ]
2
2
388
4
0
2011-06-10T16:26:01.420000
2011-06-10T16:33:36.953000
6,309,340
6,310,236
How to add System.ComponentModel.Composition.dll in VS2010 IDE?
With command line, I use /r: to add reference with VS2010 as follows. csc Program.cs /r:System.ComponentModel.Composition.dll /r:SharedLibrary.dll How can I add reference in VS2010 IDE? I tried to right click on the Solution Explorer, then clicked "Add Reference...", but I can't find the System.ComponentModel.Composition.
The Add Reference Dialog from the Productivity Power Tools is filtering for 3.5 framework assemblies because you're application is undoubtedly targeting 3.5. The System.ComponentModel.Composition.dll is a 4.0 Framework dll. You can add the reference by browsing to the 4.0 framework folder but this will stop your application from compiling. Instead you should change the target of your application to 4.0 if you want to use 4.0 features
How to add System.ComponentModel.Composition.dll in VS2010 IDE? With command line, I use /r: to add reference with VS2010 as follows. csc Program.cs /r:System.ComponentModel.Composition.dll /r:SharedLibrary.dll How can I add reference in VS2010 IDE? I tried to right click on the Solution Explorer, then clicked "Add Reference...", but I can't find the System.ComponentModel.Composition.
TITLE: How to add System.ComponentModel.Composition.dll in VS2010 IDE? QUESTION: With command line, I use /r: to add reference with VS2010 as follows. csc Program.cs /r:System.ComponentModel.Composition.dll /r:SharedLibrary.dll How can I add reference in VS2010 IDE? I tried to right click on the Solution Explorer, then clicked "Add Reference...", but I can't find the System.ComponentModel.Composition. ANSWER: The Add Reference Dialog from the Productivity Power Tools is filtering for 3.5 framework assemblies because you're application is undoubtedly targeting 3.5. The System.ComponentModel.Composition.dll is a 4.0 Framework dll. You can add the reference by browsing to the 4.0 framework folder but this will stop your application from compiling. Instead you should change the target of your application to 4.0 if you want to use 4.0 features
[ "visual-studio", "visual-studio-2010", "mef" ]
3
8
11,154
1
0
2011-06-10T16:27:54.257000
2011-06-10T17:52:31.627000
6,309,358
6,309,401
"instance of" "type of" What is the use case of this?
While doing some casual reading I came across an interesting quote by Scott Meyers Anytime you find yourself writing code of the form "if the object is of type T1, then do something, but if it's of type T2, then do something else," slap yourself. I was just wondering why Java has "instance of" operator when you could do the same thing by overridden methods? When is it actually used?
Sometimes you have to use objects whose behavior (e.g. source code) you do not control so you cannot always rely on object-oriented solutions to type-related matters. (Especially consider that authors of libraries cannot anticipate every use case you might have; of course, you could argue that extension and implementation provide workarounds but they require much more effort than direct type checking.) The "instanceof" operator gives you a way to inspect the type of an object and act conditionally.
"instance of" "type of" What is the use case of this? While doing some casual reading I came across an interesting quote by Scott Meyers Anytime you find yourself writing code of the form "if the object is of type T1, then do something, but if it's of type T2, then do something else," slap yourself. I was just wondering why Java has "instance of" operator when you could do the same thing by overridden methods? When is it actually used?
TITLE: "instance of" "type of" What is the use case of this? QUESTION: While doing some casual reading I came across an interesting quote by Scott Meyers Anytime you find yourself writing code of the form "if the object is of type T1, then do something, but if it's of type T2, then do something else," slap yourself. I was just wondering why Java has "instance of" operator when you could do the same thing by overridden methods? When is it actually used? ANSWER: Sometimes you have to use objects whose behavior (e.g. source code) you do not control so you cannot always rely on object-oriented solutions to type-related matters. (Especially consider that authors of libraries cannot anticipate every use case you might have; of course, you could argue that extension and implementation provide workarounds but they require much more effort than direct type checking.) The "instanceof" operator gives you a way to inspect the type of an object and act conditionally.
[ "java" ]
6
3
345
6
0
2011-06-10T16:29:24.707000
2011-06-10T16:33:06.113000
6,309,359
6,309,397
Why won't Html.ListBoxFor() highlight current selected items?
I am trying to understand why my Html.ListBoxFor() is not highlighting current selected items when the view loads. I have a database model: public class Issue { [Key] public int IssueId { get; set; } public int Number { get; set; } public string Title { get; set; } public DateTime Date { get; set; } public virtual ICollection Creators { get; set; } } public class Creator { [Key] public int CreatorId { get; set; } public string FirstName { get; set; } public string MiddleName { get; set; } public string LastName { get; set; } public virtual ICollection Issues { get; set; } } public class Icbd: DbContext { public DbSet Issues { get; set; } public DbSet Creators { get; set; } } I then have an editing model: public class IssueEditModel { public Issue Issue { get; set; } public IEnumerable Creators { get; set; } public IEnumerable SelectedCreators { get {return Issue.Creators;} } } Then, in my controller I populate IssueEditModel: public ActionResult EditIssue( int id = 0 ) { IssueEditModel issueEdit = new IssueEditModel{ Creators = db.Creators.ToList(), Issue = new Issue{ Creators = new List ()}, }; if (id > 0) { issueEdit.Issue = db.Issues.Include("Creators").Where(x => x.IssueId == id).Single(); } return View(issueEdit); } This populates all objects correctly (as far as I can tell, anyway.) In my View, I am writing a listbox like this: <%: Html.ListBoxFor( x => x.SelectedCreators, new SelectList( Model.Creators, "CreatorId", "LastName" ) )%> This lists all the options correctly, but I cannot get the currently select items to highlight. I almost want to write my own Html Helper because this is such a simple operation, I don't understand why this is being so difficult. Why wont the Html Helper highlight the current items?
You need a list of scalar types as first argument to the ListBoxFor helper which will map to the creator ids that you want preselected: public class IssueEditModel { public IEnumerable Creators { get; set; } public IEnumerable SelectedCreatorIds { get; set; } } and then: IssueEditModel issueEdit = new IssueEditModel { Creators = db.Creators, SelectedCreatorIds = db.Creators.Select(x => x.CreatorId) }; and in the view: <%: Html.ListBoxFor( x => x.SelectedCreatorIds, new SelectList( Model.Creators, "CreatorId", "LastName" ) ) %>
Why won't Html.ListBoxFor() highlight current selected items? I am trying to understand why my Html.ListBoxFor() is not highlighting current selected items when the view loads. I have a database model: public class Issue { [Key] public int IssueId { get; set; } public int Number { get; set; } public string Title { get; set; } public DateTime Date { get; set; } public virtual ICollection Creators { get; set; } } public class Creator { [Key] public int CreatorId { get; set; } public string FirstName { get; set; } public string MiddleName { get; set; } public string LastName { get; set; } public virtual ICollection Issues { get; set; } } public class Icbd: DbContext { public DbSet Issues { get; set; } public DbSet Creators { get; set; } } I then have an editing model: public class IssueEditModel { public Issue Issue { get; set; } public IEnumerable Creators { get; set; } public IEnumerable SelectedCreators { get {return Issue.Creators;} } } Then, in my controller I populate IssueEditModel: public ActionResult EditIssue( int id = 0 ) { IssueEditModel issueEdit = new IssueEditModel{ Creators = db.Creators.ToList(), Issue = new Issue{ Creators = new List ()}, }; if (id > 0) { issueEdit.Issue = db.Issues.Include("Creators").Where(x => x.IssueId == id).Single(); } return View(issueEdit); } This populates all objects correctly (as far as I can tell, anyway.) In my View, I am writing a listbox like this: <%: Html.ListBoxFor( x => x.SelectedCreators, new SelectList( Model.Creators, "CreatorId", "LastName" ) )%> This lists all the options correctly, but I cannot get the currently select items to highlight. I almost want to write my own Html Helper because this is such a simple operation, I don't understand why this is being so difficult. Why wont the Html Helper highlight the current items?
TITLE: Why won't Html.ListBoxFor() highlight current selected items? QUESTION: I am trying to understand why my Html.ListBoxFor() is not highlighting current selected items when the view loads. I have a database model: public class Issue { [Key] public int IssueId { get; set; } public int Number { get; set; } public string Title { get; set; } public DateTime Date { get; set; } public virtual ICollection Creators { get; set; } } public class Creator { [Key] public int CreatorId { get; set; } public string FirstName { get; set; } public string MiddleName { get; set; } public string LastName { get; set; } public virtual ICollection Issues { get; set; } } public class Icbd: DbContext { public DbSet Issues { get; set; } public DbSet Creators { get; set; } } I then have an editing model: public class IssueEditModel { public Issue Issue { get; set; } public IEnumerable Creators { get; set; } public IEnumerable SelectedCreators { get {return Issue.Creators;} } } Then, in my controller I populate IssueEditModel: public ActionResult EditIssue( int id = 0 ) { IssueEditModel issueEdit = new IssueEditModel{ Creators = db.Creators.ToList(), Issue = new Issue{ Creators = new List ()}, }; if (id > 0) { issueEdit.Issue = db.Issues.Include("Creators").Where(x => x.IssueId == id).Single(); } return View(issueEdit); } This populates all objects correctly (as far as I can tell, anyway.) In my View, I am writing a listbox like this: <%: Html.ListBoxFor( x => x.SelectedCreators, new SelectList( Model.Creators, "CreatorId", "LastName" ) )%> This lists all the options correctly, but I cannot get the currently select items to highlight. I almost want to write my own Html Helper because this is such a simple operation, I don't understand why this is being so difficult. Why wont the Html Helper highlight the current items? ANSWER: You need a list of scalar types as first argument to the ListBoxFor helper which will map to the creator ids that you want preselected: public class IssueEditModel { public IEnumerable Creators { get; set; } public IEnumerable SelectedCreatorIds { get; set; } } and then: IssueEditModel issueEdit = new IssueEditModel { Creators = db.Creators, SelectedCreatorIds = db.Creators.Select(x => x.CreatorId) }; and in the view: <%: Html.ListBoxFor( x => x.SelectedCreatorIds, new SelectList( Model.Creators, "CreatorId", "LastName" ) ) %>
[ "asp.net", "asp.net-mvc", "asp.net-mvc-3" ]
0
3
4,241
2
0
2011-06-10T16:29:37.727000
2011-06-10T16:32:58.177000
6,309,370
6,309,458
PHP header redirection not working as expected
I have the following issue. I collect some user input and then write it to a text file using PHP. After this is done I want to redirect to another web page - here www.google.com. I am having difficulty. $myFile = "testFile.txt"; $fh = fopen($myFile, 'a'); $IP = $_SERVER["REMOTE_ADDR"].','; $logdetails= $IP.date("F j, Y, g:i a O T"); $stringTimeout = $_POST['_delay']; $stringData1 = $_POST['userChoices']; $s = ','; $postData = $s.$stringTimeout.$s.$stringData1"\n"; fwrite($fh,$logdetails.$postData); fclose($fh); header("Location: http://www.google.com");
what if you try your redirect part first in another PHP. divide and conquer!:) hey and If that does not work, check your html headers, I remember that I had issues with the html headers trying to use: header("Location: http://www.google.com ");
PHP header redirection not working as expected I have the following issue. I collect some user input and then write it to a text file using PHP. After this is done I want to redirect to another web page - here www.google.com. I am having difficulty. $myFile = "testFile.txt"; $fh = fopen($myFile, 'a'); $IP = $_SERVER["REMOTE_ADDR"].','; $logdetails= $IP.date("F j, Y, g:i a O T"); $stringTimeout = $_POST['_delay']; $stringData1 = $_POST['userChoices']; $s = ','; $postData = $s.$stringTimeout.$s.$stringData1"\n"; fwrite($fh,$logdetails.$postData); fclose($fh); header("Location: http://www.google.com");
TITLE: PHP header redirection not working as expected QUESTION: I have the following issue. I collect some user input and then write it to a text file using PHP. After this is done I want to redirect to another web page - here www.google.com. I am having difficulty. $myFile = "testFile.txt"; $fh = fopen($myFile, 'a'); $IP = $_SERVER["REMOTE_ADDR"].','; $logdetails= $IP.date("F j, Y, g:i a O T"); $stringTimeout = $_POST['_delay']; $stringData1 = $_POST['userChoices']; $s = ','; $postData = $s.$stringTimeout.$s.$stringData1"\n"; fwrite($fh,$logdetails.$postData); fclose($fh); header("Location: http://www.google.com"); ANSWER: what if you try your redirect part first in another PHP. divide and conquer!:) hey and If that does not work, check your html headers, I remember that I had issues with the html headers trying to use: header("Location: http://www.google.com ");
[ "php", "redirect" ]
2
0
727
7
0
2011-06-10T16:30:52.230000
2011-06-10T16:37:20.243000
6,309,376
6,309,508
Graph database query
I have undertaken a project that tracks shops from where a user can buy an item. I have decided to use Neo4j as the database. This is a part of the database that I have in mind: There is a node for each shop, and each of these nodes has child-nodes that store items available in that store. Consider this scenario: Now a particular user (who always goes to one particular shop to buy all his items) wants to know alternative shops from where he can get all (or maximum) number of the items he wants to purchase. The problem is that an exhaustive search of all the shops and all their items, followed by their matching will take a lot of space/time. Is there any procedure/algorithm that could help me solve this problem with minimum space/time cost? P.S.: Please note that I would like to stick with Neo4j only, because it solves many of the other database problems very efficiently.
your use case is actually perfect for a graph db. Could I recommend you implement your items as primary nodes and connect them to your stores? Index your store nodes using Indexing Service. That will give you quick lookup for store and then any particular item is one traversal away. Getting all other stores for an item will also just be edge traversals at that point. Hope this helps.
Graph database query I have undertaken a project that tracks shops from where a user can buy an item. I have decided to use Neo4j as the database. This is a part of the database that I have in mind: There is a node for each shop, and each of these nodes has child-nodes that store items available in that store. Consider this scenario: Now a particular user (who always goes to one particular shop to buy all his items) wants to know alternative shops from where he can get all (or maximum) number of the items he wants to purchase. The problem is that an exhaustive search of all the shops and all their items, followed by their matching will take a lot of space/time. Is there any procedure/algorithm that could help me solve this problem with minimum space/time cost? P.S.: Please note that I would like to stick with Neo4j only, because it solves many of the other database problems very efficiently.
TITLE: Graph database query QUESTION: I have undertaken a project that tracks shops from where a user can buy an item. I have decided to use Neo4j as the database. This is a part of the database that I have in mind: There is a node for each shop, and each of these nodes has child-nodes that store items available in that store. Consider this scenario: Now a particular user (who always goes to one particular shop to buy all his items) wants to know alternative shops from where he can get all (or maximum) number of the items he wants to purchase. The problem is that an exhaustive search of all the shops and all their items, followed by their matching will take a lot of space/time. Is there any procedure/algorithm that could help me solve this problem with minimum space/time cost? P.S.: Please note that I would like to stick with Neo4j only, because it solves many of the other database problems very efficiently. ANSWER: your use case is actually perfect for a graph db. Could I recommend you implement your items as primary nodes and connect them to your stores? Index your store nodes using Indexing Service. That will give you quick lookup for store and then any particular item is one traversal away. Getting all other stores for an item will also just be edge traversals at that point. Hope this helps.
[ "database", "search", "graph", "neo4j", "graph-databases" ]
2
3
1,085
1
0
2011-06-10T16:31:21.573000
2011-06-10T16:41:37.573000
6,309,379
6,309,439
How to check for a valid Base64 encoded string
Is there a way in C# to see if a string is Base 64 encoded other than just trying to convert it and see if there is an error? I have code code like this: // Convert base64-encoded hash value into a byte array. byte[] HashBytes = Convert.FromBase64String(Value); I want to avoid the "Invalid character in a Base-64 string" exception that happens if the value is not valid base 64 string. I want to just check and return false instead of handling an exception because I expect that sometimes this value is not going to be a base 64 string. Is there some way to check before using the Convert.FromBase64String function?
Update: For newer versions of C#, there's a much better alternative, please refer to the answer by Tomas here: https://stackoverflow.com/a/54143400/125981. It's pretty easy to recognize a Base64 string, as it will only be composed of characters 'A'..'Z', 'a'..'z', '0'..'9', '+', '/' and it is often padded at the end with up to three '=', to make the length a multiple of 4. But instead of comparing these, you'd be better off ignoring the exception, if it occurs.
How to check for a valid Base64 encoded string Is there a way in C# to see if a string is Base 64 encoded other than just trying to convert it and see if there is an error? I have code code like this: // Convert base64-encoded hash value into a byte array. byte[] HashBytes = Convert.FromBase64String(Value); I want to avoid the "Invalid character in a Base-64 string" exception that happens if the value is not valid base 64 string. I want to just check and return false instead of handling an exception because I expect that sometimes this value is not going to be a base 64 string. Is there some way to check before using the Convert.FromBase64String function?
TITLE: How to check for a valid Base64 encoded string QUESTION: Is there a way in C# to see if a string is Base 64 encoded other than just trying to convert it and see if there is an error? I have code code like this: // Convert base64-encoded hash value into a byte array. byte[] HashBytes = Convert.FromBase64String(Value); I want to avoid the "Invalid character in a Base-64 string" exception that happens if the value is not valid base 64 string. I want to just check and return false instead of handling an exception because I expect that sometimes this value is not going to be a base 64 string. Is there some way to check before using the Convert.FromBase64String function? ANSWER: Update: For newer versions of C#, there's a much better alternative, please refer to the answer by Tomas here: https://stackoverflow.com/a/54143400/125981. It's pretty easy to recognize a Base64 string, as it will only be composed of characters 'A'..'Z', 'a'..'z', '0'..'9', '+', '/' and it is often padded at the end with up to three '=', to make the length a multiple of 4. But instead of comparing these, you'd be better off ignoring the exception, if it occurs.
[ "c#", "validation", "base64" ]
179
56
233,740
20
0
2011-06-10T16:31:29.597000
2011-06-10T16:35:41.027000
6,309,384
6,309,436
How do I store multiple fields within one field in a MYSQL database
I'm sorry if this a stupid question, but I am new to this. I want to store all the information from all my customers' different contact forms in a database so they can retrieve the information later. Each contact form has a different number of fields. Ideally I'd store all of this info in one MYSQL table, but as I said each customer's contact form has a different number of fields. I was thinking of creating a database with the following fields ID, customerID, dateTime, data The data would be the html of the contact form. However I am sure that's not best practice. Also it wouldn't allow me to offer a download option to the customer of all their contact forms as a csv or similar. I don't want to have a different table for each customer either, and I am sure having a table with 'field1', 'field2', 'field3' etc isn't that good either. Any ideas?
If you don't need it to be relational, that would be fine. You wouldn't be able to query it very easily. You could store the answers in another table using keys to link back to the form and field. Or use a KeyValue store type DB like MongDB, and you could store all your data without worrying about the schema.
How do I store multiple fields within one field in a MYSQL database I'm sorry if this a stupid question, but I am new to this. I want to store all the information from all my customers' different contact forms in a database so they can retrieve the information later. Each contact form has a different number of fields. Ideally I'd store all of this info in one MYSQL table, but as I said each customer's contact form has a different number of fields. I was thinking of creating a database with the following fields ID, customerID, dateTime, data The data would be the html of the contact form. However I am sure that's not best practice. Also it wouldn't allow me to offer a download option to the customer of all their contact forms as a csv or similar. I don't want to have a different table for each customer either, and I am sure having a table with 'field1', 'field2', 'field3' etc isn't that good either. Any ideas?
TITLE: How do I store multiple fields within one field in a MYSQL database QUESTION: I'm sorry if this a stupid question, but I am new to this. I want to store all the information from all my customers' different contact forms in a database so they can retrieve the information later. Each contact form has a different number of fields. Ideally I'd store all of this info in one MYSQL table, but as I said each customer's contact form has a different number of fields. I was thinking of creating a database with the following fields ID, customerID, dateTime, data The data would be the html of the contact form. However I am sure that's not best practice. Also it wouldn't allow me to offer a download option to the customer of all their contact forms as a csv or similar. I don't want to have a different table for each customer either, and I am sure having a table with 'field1', 'field2', 'field3' etc isn't that good either. Any ideas? ANSWER: If you don't need it to be relational, that would be fine. You wouldn't be able to query it very easily. You could store the answers in another table using keys to link back to the form and field. Or use a KeyValue store type DB like MongDB, and you could store all your data without worrying about the schema.
[ "php", "mysql", "contact-form" ]
1
1
2,358
3
0
2011-06-10T16:31:38.457000
2011-06-10T16:35:24.010000
6,309,398
6,309,502
How to make this simple SQL query into a Linq Statement?
I have the following SQL statement which is going through a table and selecting out a group of results based on the the data definition. From that group, I get the single result with the highest revision for that group. Now the SQL has been easy, but translating this into Linq so far has yielded nothing which I can use. Can anyone help with this? select * from datasheet ds where ds.revisionnum = (select max(revisionnum) from datasheet where datadefinitionid = 34) and ds.isparent = 1 -- is parent will be true for this query This is about as far as I get with the Linq Statement before I stumbled: var query = from ds in context.DataSheets where ds.IsParent == true && ds.RevisionNum ---????? Thanks in advance! Code Update After fumbling around for a while, this is what we came up with: var dataSheet = _dataSheetRepository.All.Where( d => d.DataDefinitionID == i.ID && d.IsParent == true); var currentDataSheet = (from ds in dataSheet where (ds.RevisionNum == (from s in dataSheet select s.RevisionNum).Max()) select ds).SingleOrDefault(); Using two variables gave us the ability to narrow down which sheet collection we were looking for, and then using the linq query on the second var, we were able to narrow down which actual revision number of that collection we wanted.
try something like that var query = from ds in context.DataSheets where ds.IsParent == true && ds.RevisionNum == context.DataSheets.Where( ds => ds.DataDefinitionId == 34).Max( ds => ds.RevisionNum) subquery could be converted into linq expression as well
How to make this simple SQL query into a Linq Statement? I have the following SQL statement which is going through a table and selecting out a group of results based on the the data definition. From that group, I get the single result with the highest revision for that group. Now the SQL has been easy, but translating this into Linq so far has yielded nothing which I can use. Can anyone help with this? select * from datasheet ds where ds.revisionnum = (select max(revisionnum) from datasheet where datadefinitionid = 34) and ds.isparent = 1 -- is parent will be true for this query This is about as far as I get with the Linq Statement before I stumbled: var query = from ds in context.DataSheets where ds.IsParent == true && ds.RevisionNum ---????? Thanks in advance! Code Update After fumbling around for a while, this is what we came up with: var dataSheet = _dataSheetRepository.All.Where( d => d.DataDefinitionID == i.ID && d.IsParent == true); var currentDataSheet = (from ds in dataSheet where (ds.RevisionNum == (from s in dataSheet select s.RevisionNum).Max()) select ds).SingleOrDefault(); Using two variables gave us the ability to narrow down which sheet collection we were looking for, and then using the linq query on the second var, we were able to narrow down which actual revision number of that collection we wanted.
TITLE: How to make this simple SQL query into a Linq Statement? QUESTION: I have the following SQL statement which is going through a table and selecting out a group of results based on the the data definition. From that group, I get the single result with the highest revision for that group. Now the SQL has been easy, but translating this into Linq so far has yielded nothing which I can use. Can anyone help with this? select * from datasheet ds where ds.revisionnum = (select max(revisionnum) from datasheet where datadefinitionid = 34) and ds.isparent = 1 -- is parent will be true for this query This is about as far as I get with the Linq Statement before I stumbled: var query = from ds in context.DataSheets where ds.IsParent == true && ds.RevisionNum ---????? Thanks in advance! Code Update After fumbling around for a while, this is what we came up with: var dataSheet = _dataSheetRepository.All.Where( d => d.DataDefinitionID == i.ID && d.IsParent == true); var currentDataSheet = (from ds in dataSheet where (ds.RevisionNum == (from s in dataSheet select s.RevisionNum).Max()) select ds).SingleOrDefault(); Using two variables gave us the ability to narrow down which sheet collection we were looking for, and then using the linq query on the second var, we were able to narrow down which actual revision number of that collection we wanted. ANSWER: try something like that var query = from ds in context.DataSheets where ds.IsParent == true && ds.RevisionNum == context.DataSheets.Where( ds => ds.DataDefinitionId == 34).Max( ds => ds.RevisionNum) subquery could be converted into linq expression as well
[ "c#", "sql", "linq" ]
0
3
160
2
0
2011-06-10T16:32:58.540000
2011-06-10T16:41:05.407000
6,309,407
6,310,284
Remove Top-Level Container on Runtime
Unfortunately, it looks like this recently closed question was not well understood. Here is the typical output: run: Trying to Remove JDialog Remove Cycle Done:-) Checking if still exists any of TopLayoutContainers JFrame JDialog Will Try Remove Dialog again, CycleNo. 1 ----------------------------------------------------------- Trying to Remove JDialog Remove Cycle Done:-) Checking if still exists any of TopLayoutContainers JFrame JDialog Will Try Remove Dialog again, CycleNo. 2 ----------------------------------------------------------- Trying to Remove JDialog Remove Cycle Done:-) Checking if still exists any of TopLayoutContainers JFrame JDialog Will Try Remove Dialog again, CycleNo. 3 ----------------------------------------------------------- Trying to Remove JDialog Remove Cycle Done:-) Checking if still exists any of TopLayoutContainers JFrame JDialog *** End of Cycle Without Success, Exit App *** BUILD SUCCESSFUL (total time: 13 seconds) I'll try asking this question again: How can I k i l*l on Runtime the first-opened top-Level Container, and help with closing for me one of Swing NightMares? import java.awt.*; import java.awt.event.WindowEvent; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.*; public class RemoveDialogOnRuntime extends JFrame { private static final long serialVersionUID = 1L; private int contID = 1; private boolean runProcess; private int top = 20; private int left = 20; private int maxLoop = 0; public RemoveDialogOnRuntime() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setPreferredSize(new Dimension(300, 300)); setTitle("Remove Dialog On Runtime"); setLocation(150, 150); pack(); setVisible(true); Point loc = this.getLocation(); top += loc.x; left += loc.y; AddNewDialog(); } private void AddNewDialog() { DialogRemove firstDialog = new DialogRemove(); remWins(); } private void remWins() { runProcess = true; Thread th = new Thread(new RemTask()); th.setDaemon(false); th.setPriority(Thread.MIN_PRIORITY); th.start(); } private class RemTask implements Runnable { @Override public void run() { while (runProcess) { Window[] wins = Window.getWindows(); for (int i = 0; i < wins.length; i++) { if (wins[i] instanceof JDialog) { System.out.println(" Trying to Remove JDialog"); wins[i].setVisible(false); wins[i].dispose(); WindowEvent windowClosing = new WindowEvent(wins[i], WindowEvent.WINDOW_CLOSING); wins[i].dispatchEvent(windowClosing); Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(windowClosing); Runtime runtime = Runtime.getRuntime(); runtime.gc(); runtime.runFinalization(); } try { Thread.sleep(1000); } catch (InterruptedException ex) { Logger.getLogger(RemoveDialogOnRuntime.class.getName()).log(Level.SEVERE, null, ex); } } wins = null; SwingUtilities.invokeLater(new Runnable() { @Override public void run() { System.out.println(" Remove Cycle Done:-)"); Runtime.getRuntime().runFinalization(); Runtime.getRuntime().gc(); runProcess = false; } }); } pastRemWins(); } } private void pastRemWins() { System.out.println(" Checking if still exists any of TopLayoutContainers"); Window[] wins = Window.getWindows(); for (int i = 0; i < wins.length; i++) { if (wins[i] instanceof JFrame) { System.out.println("JFrame"); wins[i].setVisible(true); } else if (wins[i] instanceof JDialog) { System.out.println("JDialog"); wins[i].setVisible(true); } } if (wins.length > 1) { wins = null; maxLoop++; if (maxLoop <= 3) { System.out.println(" Will Try Remove Dialog again, CycleNo. " + maxLoop); System.out.println(" -----------------------------------------------------------"); remWins(); } else { System.out.println(" -----------------------------------------------------------"); System.out.println("*** End of Cycle Without Success, Exit App ***"); closeMe(); } } } private void closeMe() { EventQueue.invokeLater(new Runnable() { @Override public void run() { System.exit(0); } }); } private class DialogRemove extends JDialog { private static final long serialVersionUID = 1L; DialogRemove(final Frame parent) { super(parent, "SecondDialog " + (contID++)); setLocation(top, left); top += 20; left += 20; setPreferredSize(new Dimension(200, 200)); setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); setModalityType(Dialog.ModalityType.MODELESS); pack(); setVisible(true); } private DialogRemove() { setTitle("SecondDialog " + (contID++)); setLocation(top, left); top += 20; left += 20; setPreferredSize(new Dimension(200, 200)); setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); setModalityType(Dialog.ModalityType.MODELESS); pack(); setVisible(true); } } public static void main(String args[]) { EventQueue.invokeLater(new Runnable() { @Override public void run() { RemoveDialogOnRuntime superConstructor = new RemoveDialogOnRuntime(); } }); } }
Invoking dispose() allows the host platform to reclaim memory consumed by the heavyweight peer, but it can't do so until after the WINDOW_CLOSING event is processed on the EventQueue. Even then, gc() is a suggestion. Addendum: Another way to see the nightmare is via a profiler. Running the example below with jvisualvm, one can see that periodic collection never quite returns to baseline. I've exaggerated the vertical axis by starting with an artificially small heap. Additional examples are shown here. When memory is very limited, I've used two approaches: Emergent: Loop from the command line, starting a new VM each time. Urgent: Eliminate the heavyweight component entirely, running headless and composing in a BufferedImage using 2D graphics and lightweight components only. import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.WindowEvent; import javax.swing.JDialog; /** @see https://stackoverflow.com/questions/6309407 */ public class DialogClose extends JDialog { public DialogClose(int i) { this.setTitle("Dialog " + String.valueOf(i)); this.setPreferredSize(new Dimension(320, 200)); } private void display() { this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); this.pack(); this.setLocationRelativeTo(null); this.setVisible(true); passSomeTime(); this.setVisible(false); this.dispatchEvent(new WindowEvent( this, WindowEvent.WINDOW_CLOSING)); this.dispose(); passSomeTime(); } private void passSomeTime() { try { Thread.sleep(100); } catch (InterruptedException ie) { ie.printStackTrace(System.err); } } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { int count = 0; while (true) { new DialogClose(count++).display(); } } }); } }
Remove Top-Level Container on Runtime Unfortunately, it looks like this recently closed question was not well understood. Here is the typical output: run: Trying to Remove JDialog Remove Cycle Done:-) Checking if still exists any of TopLayoutContainers JFrame JDialog Will Try Remove Dialog again, CycleNo. 1 ----------------------------------------------------------- Trying to Remove JDialog Remove Cycle Done:-) Checking if still exists any of TopLayoutContainers JFrame JDialog Will Try Remove Dialog again, CycleNo. 2 ----------------------------------------------------------- Trying to Remove JDialog Remove Cycle Done:-) Checking if still exists any of TopLayoutContainers JFrame JDialog Will Try Remove Dialog again, CycleNo. 3 ----------------------------------------------------------- Trying to Remove JDialog Remove Cycle Done:-) Checking if still exists any of TopLayoutContainers JFrame JDialog *** End of Cycle Without Success, Exit App *** BUILD SUCCESSFUL (total time: 13 seconds) I'll try asking this question again: How can I k i l*l on Runtime the first-opened top-Level Container, and help with closing for me one of Swing NightMares? import java.awt.*; import java.awt.event.WindowEvent; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.*; public class RemoveDialogOnRuntime extends JFrame { private static final long serialVersionUID = 1L; private int contID = 1; private boolean runProcess; private int top = 20; private int left = 20; private int maxLoop = 0; public RemoveDialogOnRuntime() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setPreferredSize(new Dimension(300, 300)); setTitle("Remove Dialog On Runtime"); setLocation(150, 150); pack(); setVisible(true); Point loc = this.getLocation(); top += loc.x; left += loc.y; AddNewDialog(); } private void AddNewDialog() { DialogRemove firstDialog = new DialogRemove(); remWins(); } private void remWins() { runProcess = true; Thread th = new Thread(new RemTask()); th.setDaemon(false); th.setPriority(Thread.MIN_PRIORITY); th.start(); } private class RemTask implements Runnable { @Override public void run() { while (runProcess) { Window[] wins = Window.getWindows(); for (int i = 0; i < wins.length; i++) { if (wins[i] instanceof JDialog) { System.out.println(" Trying to Remove JDialog"); wins[i].setVisible(false); wins[i].dispose(); WindowEvent windowClosing = new WindowEvent(wins[i], WindowEvent.WINDOW_CLOSING); wins[i].dispatchEvent(windowClosing); Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(windowClosing); Runtime runtime = Runtime.getRuntime(); runtime.gc(); runtime.runFinalization(); } try { Thread.sleep(1000); } catch (InterruptedException ex) { Logger.getLogger(RemoveDialogOnRuntime.class.getName()).log(Level.SEVERE, null, ex); } } wins = null; SwingUtilities.invokeLater(new Runnable() { @Override public void run() { System.out.println(" Remove Cycle Done:-)"); Runtime.getRuntime().runFinalization(); Runtime.getRuntime().gc(); runProcess = false; } }); } pastRemWins(); } } private void pastRemWins() { System.out.println(" Checking if still exists any of TopLayoutContainers"); Window[] wins = Window.getWindows(); for (int i = 0; i < wins.length; i++) { if (wins[i] instanceof JFrame) { System.out.println("JFrame"); wins[i].setVisible(true); } else if (wins[i] instanceof JDialog) { System.out.println("JDialog"); wins[i].setVisible(true); } } if (wins.length > 1) { wins = null; maxLoop++; if (maxLoop <= 3) { System.out.println(" Will Try Remove Dialog again, CycleNo. " + maxLoop); System.out.println(" -----------------------------------------------------------"); remWins(); } else { System.out.println(" -----------------------------------------------------------"); System.out.println("*** End of Cycle Without Success, Exit App ***"); closeMe(); } } } private void closeMe() { EventQueue.invokeLater(new Runnable() { @Override public void run() { System.exit(0); } }); } private class DialogRemove extends JDialog { private static final long serialVersionUID = 1L; DialogRemove(final Frame parent) { super(parent, "SecondDialog " + (contID++)); setLocation(top, left); top += 20; left += 20; setPreferredSize(new Dimension(200, 200)); setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); setModalityType(Dialog.ModalityType.MODELESS); pack(); setVisible(true); } private DialogRemove() { setTitle("SecondDialog " + (contID++)); setLocation(top, left); top += 20; left += 20; setPreferredSize(new Dimension(200, 200)); setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); setModalityType(Dialog.ModalityType.MODELESS); pack(); setVisible(true); } } public static void main(String args[]) { EventQueue.invokeLater(new Runnable() { @Override public void run() { RemoveDialogOnRuntime superConstructor = new RemoveDialogOnRuntime(); } }); } }
TITLE: Remove Top-Level Container on Runtime QUESTION: Unfortunately, it looks like this recently closed question was not well understood. Here is the typical output: run: Trying to Remove JDialog Remove Cycle Done:-) Checking if still exists any of TopLayoutContainers JFrame JDialog Will Try Remove Dialog again, CycleNo. 1 ----------------------------------------------------------- Trying to Remove JDialog Remove Cycle Done:-) Checking if still exists any of TopLayoutContainers JFrame JDialog Will Try Remove Dialog again, CycleNo. 2 ----------------------------------------------------------- Trying to Remove JDialog Remove Cycle Done:-) Checking if still exists any of TopLayoutContainers JFrame JDialog Will Try Remove Dialog again, CycleNo. 3 ----------------------------------------------------------- Trying to Remove JDialog Remove Cycle Done:-) Checking if still exists any of TopLayoutContainers JFrame JDialog *** End of Cycle Without Success, Exit App *** BUILD SUCCESSFUL (total time: 13 seconds) I'll try asking this question again: How can I k i l*l on Runtime the first-opened top-Level Container, and help with closing for me one of Swing NightMares? import java.awt.*; import java.awt.event.WindowEvent; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.*; public class RemoveDialogOnRuntime extends JFrame { private static final long serialVersionUID = 1L; private int contID = 1; private boolean runProcess; private int top = 20; private int left = 20; private int maxLoop = 0; public RemoveDialogOnRuntime() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setPreferredSize(new Dimension(300, 300)); setTitle("Remove Dialog On Runtime"); setLocation(150, 150); pack(); setVisible(true); Point loc = this.getLocation(); top += loc.x; left += loc.y; AddNewDialog(); } private void AddNewDialog() { DialogRemove firstDialog = new DialogRemove(); remWins(); } private void remWins() { runProcess = true; Thread th = new Thread(new RemTask()); th.setDaemon(false); th.setPriority(Thread.MIN_PRIORITY); th.start(); } private class RemTask implements Runnable { @Override public void run() { while (runProcess) { Window[] wins = Window.getWindows(); for (int i = 0; i < wins.length; i++) { if (wins[i] instanceof JDialog) { System.out.println(" Trying to Remove JDialog"); wins[i].setVisible(false); wins[i].dispose(); WindowEvent windowClosing = new WindowEvent(wins[i], WindowEvent.WINDOW_CLOSING); wins[i].dispatchEvent(windowClosing); Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(windowClosing); Runtime runtime = Runtime.getRuntime(); runtime.gc(); runtime.runFinalization(); } try { Thread.sleep(1000); } catch (InterruptedException ex) { Logger.getLogger(RemoveDialogOnRuntime.class.getName()).log(Level.SEVERE, null, ex); } } wins = null; SwingUtilities.invokeLater(new Runnable() { @Override public void run() { System.out.println(" Remove Cycle Done:-)"); Runtime.getRuntime().runFinalization(); Runtime.getRuntime().gc(); runProcess = false; } }); } pastRemWins(); } } private void pastRemWins() { System.out.println(" Checking if still exists any of TopLayoutContainers"); Window[] wins = Window.getWindows(); for (int i = 0; i < wins.length; i++) { if (wins[i] instanceof JFrame) { System.out.println("JFrame"); wins[i].setVisible(true); } else if (wins[i] instanceof JDialog) { System.out.println("JDialog"); wins[i].setVisible(true); } } if (wins.length > 1) { wins = null; maxLoop++; if (maxLoop <= 3) { System.out.println(" Will Try Remove Dialog again, CycleNo. " + maxLoop); System.out.println(" -----------------------------------------------------------"); remWins(); } else { System.out.println(" -----------------------------------------------------------"); System.out.println("*** End of Cycle Without Success, Exit App ***"); closeMe(); } } } private void closeMe() { EventQueue.invokeLater(new Runnable() { @Override public void run() { System.exit(0); } }); } private class DialogRemove extends JDialog { private static final long serialVersionUID = 1L; DialogRemove(final Frame parent) { super(parent, "SecondDialog " + (contID++)); setLocation(top, left); top += 20; left += 20; setPreferredSize(new Dimension(200, 200)); setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); setModalityType(Dialog.ModalityType.MODELESS); pack(); setVisible(true); } private DialogRemove() { setTitle("SecondDialog " + (contID++)); setLocation(top, left); top += 20; left += 20; setPreferredSize(new Dimension(200, 200)); setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); setModalityType(Dialog.ModalityType.MODELESS); pack(); setVisible(true); } } public static void main(String args[]) { EventQueue.invokeLater(new Runnable() { @Override public void run() { RemoveDialogOnRuntime superConstructor = new RemoveDialogOnRuntime(); } }); } } ANSWER: Invoking dispose() allows the host platform to reclaim memory consumed by the heavyweight peer, but it can't do so until after the WINDOW_CLOSING event is processed on the EventQueue. Even then, gc() is a suggestion. Addendum: Another way to see the nightmare is via a profiler. Running the example below with jvisualvm, one can see that periodic collection never quite returns to baseline. I've exaggerated the vertical axis by starting with an artificially small heap. Additional examples are shown here. When memory is very limited, I've used two approaches: Emergent: Loop from the command line, starting a new VM each time. Urgent: Eliminate the heavyweight component entirely, running headless and composing in a BufferedImage using 2D graphics and lightweight components only. import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.WindowEvent; import javax.swing.JDialog; /** @see https://stackoverflow.com/questions/6309407 */ public class DialogClose extends JDialog { public DialogClose(int i) { this.setTitle("Dialog " + String.valueOf(i)); this.setPreferredSize(new Dimension(320, 200)); } private void display() { this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); this.pack(); this.setLocationRelativeTo(null); this.setVisible(true); passSomeTime(); this.setVisible(false); this.dispatchEvent(new WindowEvent( this, WindowEvent.WINDOW_CLOSING)); this.dispose(); passSomeTime(); } private void passSomeTime() { try { Thread.sleep(100); } catch (InterruptedException ie) { ie.printStackTrace(System.err); } } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { int count = 0; while (true) { new DialogClose(count++).display(); } } }); } }
[ "java", "swing", "runtime", "jdialog" ]
20
21
12,499
5
0
2011-06-10T16:33:28.810000
2011-06-10T17:57:00.417000
6,309,422
6,309,455
Output two-dimensional array
Ok, I'm still struggling with my arrays... I have created a two-dimensional array and saved into a session to get results on another page: $_SESSION['myARRAY'] print_r($_SESSION['myARRAY']); // will output: Array ( [Car] => Array ( [0] => 1 [1] => 9 [2] => 0 ) [Truck] => Array ( [0] => 2 [1] => 10 [2] => 0 ) [Bus] => Array ( [0] => 1 [1] => 8 [2] => 2 )) Now I need to output the data into the following format: $xls->addRow(Array("Car",1,9,0)); $xls->addRow(Array("Truck",2,10,0)); $xls->addRow(Array("Bus",1,8,2)); I tried to do something like this: foreach($_SESSION['myARRAY'] AS $key => $value) { $arr[$key] = $key; foreach($value AS $k => $v) { $arr[$key] = $v; } $xls->addRow($arr[$key]); } but it did not really work. I think I'm close but not quite there...
$value is already an array. Now you only need to prepend the $key to it. You could use array_unshift: foreach($_SESSION['myARRAY'] AS $key => $value) { array_unshift($value, $key); $xls->addRow($value); } Of course if you do this more than once, you should consider storing the consolidated array.
Output two-dimensional array Ok, I'm still struggling with my arrays... I have created a two-dimensional array and saved into a session to get results on another page: $_SESSION['myARRAY'] print_r($_SESSION['myARRAY']); // will output: Array ( [Car] => Array ( [0] => 1 [1] => 9 [2] => 0 ) [Truck] => Array ( [0] => 2 [1] => 10 [2] => 0 ) [Bus] => Array ( [0] => 1 [1] => 8 [2] => 2 )) Now I need to output the data into the following format: $xls->addRow(Array("Car",1,9,0)); $xls->addRow(Array("Truck",2,10,0)); $xls->addRow(Array("Bus",1,8,2)); I tried to do something like this: foreach($_SESSION['myARRAY'] AS $key => $value) { $arr[$key] = $key; foreach($value AS $k => $v) { $arr[$key] = $v; } $xls->addRow($arr[$key]); } but it did not really work. I think I'm close but not quite there...
TITLE: Output two-dimensional array QUESTION: Ok, I'm still struggling with my arrays... I have created a two-dimensional array and saved into a session to get results on another page: $_SESSION['myARRAY'] print_r($_SESSION['myARRAY']); // will output: Array ( [Car] => Array ( [0] => 1 [1] => 9 [2] => 0 ) [Truck] => Array ( [0] => 2 [1] => 10 [2] => 0 ) [Bus] => Array ( [0] => 1 [1] => 8 [2] => 2 )) Now I need to output the data into the following format: $xls->addRow(Array("Car",1,9,0)); $xls->addRow(Array("Truck",2,10,0)); $xls->addRow(Array("Bus",1,8,2)); I tried to do something like this: foreach($_SESSION['myARRAY'] AS $key => $value) { $arr[$key] = $key; foreach($value AS $k => $v) { $arr[$key] = $v; } $xls->addRow($arr[$key]); } but it did not really work. I think I'm close but not quite there... ANSWER: $value is already an array. Now you only need to prepend the $key to it. You could use array_unshift: foreach($_SESSION['myARRAY'] AS $key => $value) { array_unshift($value, $key); $xls->addRow($value); } Of course if you do this more than once, you should consider storing the consolidated array.
[ "php", "multidimensional-array" ]
1
5
393
2
0
2011-06-10T16:34:15.607000
2011-06-10T16:37:12.047000
6,309,424
6,309,467
C# Exception: NullReferenceException
I am getting the following message whilt running my test. Message: Test method Automation.Test1.General threw exception: System.NullReferenceException: Object reference not set to an instance of an object. Automation.Library.CheckLogIn() in C:\Documents and Settings\Administrator\My Documents\Visual Studio 2010\Projects\Automation\Automation\Library.cs: line 152 Automation.Test1.General() in C:\Documents and Settings\Administrator\My Documents\Visual Studio 2010\Projects\Automation\Automation\Test1.cs: line 72 Library.cs (superclass) using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Microsoft.VisualStudio.TestTools.UnitTesting; using Selenium; using System.IO; using System.Reflection; using System.Net; using System.Configuration; namespace Automation { [TestClass] public class Library { public ISelenium Sel; // Open browser public void OpenBrowser(out ISelenium selenium, out StringBuilder verificationErrors) { selenium = new DefaultSelenium(GetAppConfig("TestMachine"), 4444, GetAppConfig("Browser"), GetAppConfig("URL")); selenium.Start(); selenium.Open(GetAppConfig("URL")); verificationErrors = new StringBuilder(); } // Returns the value of the passed key from App.config public string GetAppConfig(string key) { return ConfigurationManager.AppSettings[key].ToString(); } // Check for Login public void CheckLogIn() { if (Sel.IsElementPresent(GetAppConfig("SignOn"))) { Sel.Type(GetAppConfig("UserNameField"), GetAppConfig("UserName")); Sel.Type(GetAppConfig("PWDField"), GetAppConfig("PWD")); Sel.Click(GetAppConfig("Go")); } else { // do nothing } } } } Test1.cs (sub class) using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Microsoft.VisualStudio.TestTools.UnitTesting; using Selenium; using System.IO; using System.Reflection; using System.Net; using System.Configuration; namespace Automation { [TestClass] public class Test1 { public ISelenium Sel; public StringBuilder Err; Boolean bNextFlag = false; Library Lib = new Library(); // Constructor public Test1() { // Launch browser with application URL Lib.OpenBrowser(out Sel, out Err); Sel.WindowMaximize(); Lib.CheckLogIn(); } [TestMethod] public void General() { // Verify Tab if (Sel.IsElementPresent(Lib.GetAppConfig("TAB"))) { Sel.Click(Lib.GetAppConfig("TAB")); bNextFlag = true; } else { // do something } } } } app.config.xml
Well I don't really see a question in your post, so I suppose I will point out the obvious... Your error is telling you that you have a NullReferenceException being thrown somewhere in this method: public void CheckLogIn() { if (Sel.IsElementPresent(GetAppConfig("SignOn"))) { Sel.Type(GetAppConfig("UserNameField"), GetAppConfig("UserName")); Sel.Type(GetAppConfig("PWDField"), GetAppConfig("PWD")); Sel.Click(GetAppConfig("Go")); } else { // do nothing } } Sel is null. Nowhere in your code do you actually initialize it. You'll need to initialize it somewhere like: Sel = new SomeTypeThatImplementsISelenium(); Also, GetAppConfig is deprecated per the docs.
C# Exception: NullReferenceException I am getting the following message whilt running my test. Message: Test method Automation.Test1.General threw exception: System.NullReferenceException: Object reference not set to an instance of an object. Automation.Library.CheckLogIn() in C:\Documents and Settings\Administrator\My Documents\Visual Studio 2010\Projects\Automation\Automation\Library.cs: line 152 Automation.Test1.General() in C:\Documents and Settings\Administrator\My Documents\Visual Studio 2010\Projects\Automation\Automation\Test1.cs: line 72 Library.cs (superclass) using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Microsoft.VisualStudio.TestTools.UnitTesting; using Selenium; using System.IO; using System.Reflection; using System.Net; using System.Configuration; namespace Automation { [TestClass] public class Library { public ISelenium Sel; // Open browser public void OpenBrowser(out ISelenium selenium, out StringBuilder verificationErrors) { selenium = new DefaultSelenium(GetAppConfig("TestMachine"), 4444, GetAppConfig("Browser"), GetAppConfig("URL")); selenium.Start(); selenium.Open(GetAppConfig("URL")); verificationErrors = new StringBuilder(); } // Returns the value of the passed key from App.config public string GetAppConfig(string key) { return ConfigurationManager.AppSettings[key].ToString(); } // Check for Login public void CheckLogIn() { if (Sel.IsElementPresent(GetAppConfig("SignOn"))) { Sel.Type(GetAppConfig("UserNameField"), GetAppConfig("UserName")); Sel.Type(GetAppConfig("PWDField"), GetAppConfig("PWD")); Sel.Click(GetAppConfig("Go")); } else { // do nothing } } } } Test1.cs (sub class) using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Microsoft.VisualStudio.TestTools.UnitTesting; using Selenium; using System.IO; using System.Reflection; using System.Net; using System.Configuration; namespace Automation { [TestClass] public class Test1 { public ISelenium Sel; public StringBuilder Err; Boolean bNextFlag = false; Library Lib = new Library(); // Constructor public Test1() { // Launch browser with application URL Lib.OpenBrowser(out Sel, out Err); Sel.WindowMaximize(); Lib.CheckLogIn(); } [TestMethod] public void General() { // Verify Tab if (Sel.IsElementPresent(Lib.GetAppConfig("TAB"))) { Sel.Click(Lib.GetAppConfig("TAB")); bNextFlag = true; } else { // do something } } } } app.config.xml
TITLE: C# Exception: NullReferenceException QUESTION: I am getting the following message whilt running my test. Message: Test method Automation.Test1.General threw exception: System.NullReferenceException: Object reference not set to an instance of an object. Automation.Library.CheckLogIn() in C:\Documents and Settings\Administrator\My Documents\Visual Studio 2010\Projects\Automation\Automation\Library.cs: line 152 Automation.Test1.General() in C:\Documents and Settings\Administrator\My Documents\Visual Studio 2010\Projects\Automation\Automation\Test1.cs: line 72 Library.cs (superclass) using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Microsoft.VisualStudio.TestTools.UnitTesting; using Selenium; using System.IO; using System.Reflection; using System.Net; using System.Configuration; namespace Automation { [TestClass] public class Library { public ISelenium Sel; // Open browser public void OpenBrowser(out ISelenium selenium, out StringBuilder verificationErrors) { selenium = new DefaultSelenium(GetAppConfig("TestMachine"), 4444, GetAppConfig("Browser"), GetAppConfig("URL")); selenium.Start(); selenium.Open(GetAppConfig("URL")); verificationErrors = new StringBuilder(); } // Returns the value of the passed key from App.config public string GetAppConfig(string key) { return ConfigurationManager.AppSettings[key].ToString(); } // Check for Login public void CheckLogIn() { if (Sel.IsElementPresent(GetAppConfig("SignOn"))) { Sel.Type(GetAppConfig("UserNameField"), GetAppConfig("UserName")); Sel.Type(GetAppConfig("PWDField"), GetAppConfig("PWD")); Sel.Click(GetAppConfig("Go")); } else { // do nothing } } } } Test1.cs (sub class) using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Microsoft.VisualStudio.TestTools.UnitTesting; using Selenium; using System.IO; using System.Reflection; using System.Net; using System.Configuration; namespace Automation { [TestClass] public class Test1 { public ISelenium Sel; public StringBuilder Err; Boolean bNextFlag = false; Library Lib = new Library(); // Constructor public Test1() { // Launch browser with application URL Lib.OpenBrowser(out Sel, out Err); Sel.WindowMaximize(); Lib.CheckLogIn(); } [TestMethod] public void General() { // Verify Tab if (Sel.IsElementPresent(Lib.GetAppConfig("TAB"))) { Sel.Click(Lib.GetAppConfig("TAB")); bNextFlag = true; } else { // do something } } } } app.config.xml ANSWER: Well I don't really see a question in your post, so I suppose I will point out the obvious... Your error is telling you that you have a NullReferenceException being thrown somewhere in this method: public void CheckLogIn() { if (Sel.IsElementPresent(GetAppConfig("SignOn"))) { Sel.Type(GetAppConfig("UserNameField"), GetAppConfig("UserName")); Sel.Type(GetAppConfig("PWDField"), GetAppConfig("PWD")); Sel.Click(GetAppConfig("Go")); } else { // do nothing } } Sel is null. Nowhere in your code do you actually initialize it. You'll need to initialize it somewhere like: Sel = new SomeTypeThatImplementsISelenium(); Also, GetAppConfig is deprecated per the docs.
[ "c#", "selenium" ]
0
2
3,952
3
0
2011-06-10T16:34:32.983000
2011-06-10T16:38:07.870000
6,309,444
6,309,509
Problem with PHP MYsql Delete syntax with timestamp comparison
All I am trying to do is delete rows in a column that have a timestamp more than 2 days old. I have tried a lot of things I have seen on here, but none of them seem to be working. This is the code: $delquery = $tapeDB->query('DELETE FROM newsItems WHERE news_date < TIMESTAMPADD(DAY,-2,NOW()); These are the errors I am getting on that line: Warning: Unexpected character in input: ''' (ASCII=39) state=1 in... Parse error: syntax error, unexpected T_STRING in... This should be really easy but I can't figure out what I am doing wrong.
you forgot the closing quote $delquery = $tapeDB->query('DELETE FROM newsItems WHERE news_date < TIMESTAMPADD(DAY,-2,NOW()');
Problem with PHP MYsql Delete syntax with timestamp comparison All I am trying to do is delete rows in a column that have a timestamp more than 2 days old. I have tried a lot of things I have seen on here, but none of them seem to be working. This is the code: $delquery = $tapeDB->query('DELETE FROM newsItems WHERE news_date < TIMESTAMPADD(DAY,-2,NOW()); These are the errors I am getting on that line: Warning: Unexpected character in input: ''' (ASCII=39) state=1 in... Parse error: syntax error, unexpected T_STRING in... This should be really easy but I can't figure out what I am doing wrong.
TITLE: Problem with PHP MYsql Delete syntax with timestamp comparison QUESTION: All I am trying to do is delete rows in a column that have a timestamp more than 2 days old. I have tried a lot of things I have seen on here, but none of them seem to be working. This is the code: $delquery = $tapeDB->query('DELETE FROM newsItems WHERE news_date < TIMESTAMPADD(DAY,-2,NOW()); These are the errors I am getting on that line: Warning: Unexpected character in input: ''' (ASCII=39) state=1 in... Parse error: syntax error, unexpected T_STRING in... This should be really easy but I can't figure out what I am doing wrong. ANSWER: you forgot the closing quote $delquery = $tapeDB->query('DELETE FROM newsItems WHERE news_date < TIMESTAMPADD(DAY,-2,NOW()');
[ "php", "mysql" ]
0
4
275
1
0
2011-06-10T16:36:22.940000
2011-06-10T16:41:42.033000
6,310,083
6,310,105
C# SQL: How can I increment an integer value in a database by one on multiple records?
I am looking for the best way to update the value I store on the following structure: Table: Pages Fields: id (int) bookid (int) pageorder (int) filename (string/varchar) So I have the book order and a page number. I need to insert a page before the page number I have, lets say 25, and update all the other pages to have 1 added to their pageorder value. Can I do this without pulling a list and cycling threw it running updates, or is that the best way to go about it? Thanks!
declare @newpage int set @newpage = 25 update pages set pageorder = pageorder +1 where pageorder >= @newpage and bookid = @bookid something like that?
C# SQL: How can I increment an integer value in a database by one on multiple records? I am looking for the best way to update the value I store on the following structure: Table: Pages Fields: id (int) bookid (int) pageorder (int) filename (string/varchar) So I have the book order and a page number. I need to insert a page before the page number I have, lets say 25, and update all the other pages to have 1 added to their pageorder value. Can I do this without pulling a list and cycling threw it running updates, or is that the best way to go about it? Thanks!
TITLE: C# SQL: How can I increment an integer value in a database by one on multiple records? QUESTION: I am looking for the best way to update the value I store on the following structure: Table: Pages Fields: id (int) bookid (int) pageorder (int) filename (string/varchar) So I have the book order and a page number. I need to insert a page before the page number I have, lets say 25, and update all the other pages to have 1 added to their pageorder value. Can I do this without pulling a list and cycling threw it running updates, or is that the best way to go about it? Thanks! ANSWER: declare @newpage int set @newpage = 25 update pages set pageorder = pageorder +1 where pageorder >= @newpage and bookid = @bookid something like that?
[ "c#", "sql" ]
1
7
2,372
2
0
2011-06-10T17:38:45.773000
2011-06-10T17:40:29.413000
6,310,095
6,310,130
Adding preference screen to Widget in Android
I want to know how to add preference to widget. What are the changes required in manifest file? Anyone can help?
Koder, You want to create an App Widget Configuration Activity. See the following link: http://developer.android.com/guide/topics/appwidgets/index.html#Configuring
Adding preference screen to Widget in Android I want to know how to add preference to widget. What are the changes required in manifest file? Anyone can help?
TITLE: Adding preference screen to Widget in Android QUESTION: I want to know how to add preference to widget. What are the changes required in manifest file? Anyone can help? ANSWER: Koder, You want to create an App Widget Configuration Activity. See the following link: http://developer.android.com/guide/topics/appwidgets/index.html#Configuring
[ "android", "android-widget", "android-preferences" ]
0
1
1,081
1
0
2011-06-10T17:39:48.653000
2011-06-10T17:43:12.953000
6,310,098
6,310,117
HTML div element
I have a div element that is defined on the top of the page and I have this another div element that is defined at the bottom of the page.... is there any way that I can define the first div element (at the top) as a child of the div element that is at the bottom. The problem is I need a div in header in the header file (header.php) this div acts as a container for an JS, but once the data is loaded I want it to be displayed inside another div. Would postponing the loading of JS till the middle section of page is advisable...
Yes: make the top div a child of the bottom div by placing the child within the markup of the parent, and use absolute positioning to move the child to the top.
HTML div element I have a div element that is defined on the top of the page and I have this another div element that is defined at the bottom of the page.... is there any way that I can define the first div element (at the top) as a child of the div element that is at the bottom. The problem is I need a div in header in the header file (header.php) this div acts as a container for an JS, but once the data is loaded I want it to be displayed inside another div. Would postponing the loading of JS till the middle section of page is advisable...
TITLE: HTML div element QUESTION: I have a div element that is defined on the top of the page and I have this another div element that is defined at the bottom of the page.... is there any way that I can define the first div element (at the top) as a child of the div element that is at the bottom. The problem is I need a div in header in the header file (header.php) this div acts as a container for an JS, but once the data is loaded I want it to be displayed inside another div. Would postponing the loading of JS till the middle section of page is advisable... ANSWER: Yes: make the top div a child of the bottom div by placing the child within the markup of the parent, and use absolute positioning to move the child to the top.
[ "html" ]
1
1
134
4
0
2011-06-10T17:39:55.440000
2011-06-10T17:41:39.770000
6,310,106
6,310,154
Implementing a templated interface
I'm trying to write this more generically: public static CormantRadDock RecreateDock(RadDockSetting settings) { CormantRadDock dock = new CormantRadDock(); settings.SetSettings(dock); Logger.DebugFormat("Recreated dock {0}", dock.ID); return dock; } I have this: public static T Recreate () where T: new() { T _control = new T(); //settings.SetSettings(dock); Logger.DebugFormat("Recreated control {0}", (_control as Control).ID); return _control; } Generic Solution: public interface ISetting { void SetSettings(T obj); } public void SetSettings(CormantRadDock dock) { // do stuff with dock } Thanks!
Is this what you're trying to do? // move the generic type parameter up here so the interface is generic // and not the method definition public interface ISetting { void SetSettings(T obj); } Then you can implement it successfully in a class: public class SomeClass: ISetting { public void SetSettings(YourSettingType obj) {... } }
Implementing a templated interface I'm trying to write this more generically: public static CormantRadDock RecreateDock(RadDockSetting settings) { CormantRadDock dock = new CormantRadDock(); settings.SetSettings(dock); Logger.DebugFormat("Recreated dock {0}", dock.ID); return dock; } I have this: public static T Recreate () where T: new() { T _control = new T(); //settings.SetSettings(dock); Logger.DebugFormat("Recreated control {0}", (_control as Control).ID); return _control; } Generic Solution: public interface ISetting { void SetSettings(T obj); } public void SetSettings(CormantRadDock dock) { // do stuff with dock } Thanks!
TITLE: Implementing a templated interface QUESTION: I'm trying to write this more generically: public static CormantRadDock RecreateDock(RadDockSetting settings) { CormantRadDock dock = new CormantRadDock(); settings.SetSettings(dock); Logger.DebugFormat("Recreated dock {0}", dock.ID); return dock; } I have this: public static T Recreate () where T: new() { T _control = new T(); //settings.SetSettings(dock); Logger.DebugFormat("Recreated control {0}", (_control as Control).ID); return _control; } Generic Solution: public interface ISetting { void SetSettings(T obj); } public void SetSettings(CormantRadDock dock) { // do stuff with dock } Thanks! ANSWER: Is this what you're trying to do? // move the generic type parameter up here so the interface is generic // and not the method definition public interface ISetting { void SetSettings(T obj); } Then you can implement it successfully in a class: public class SomeClass: ISetting { public void SetSettings(YourSettingType obj) {... } }
[ "c#", "interface", "refactoring" ]
0
2
199
3
0
2011-06-10T17:40:29.543000
2011-06-10T17:45:41.347000
6,310,124
6,310,225
Using ' in Shellscript (wget)
I'm trying to get wget to work with a post-request and a special password. It contains ' and it's like this: wget --save-cookie cookie.txt --post-data "user=Abraham&password=--my'precious!" http://localhost/login.php But when I use the tick in with wget I get strange errors. Does anybody know how to get it to work?
The backtick in your request is a straightforward issue, although you may have a second one lurking in there. The word you are looking for is 'escape' - the backtick has a special meaning on the commandline and you need to escape it so that it is not interpreted as such. In the bash shell (typical linux console) the escape character is \ - if you put that in front of the backtick, it will no longer get interpreted. The second potential issue is with the way you are using wget - are you certain that is the request you are meant to send? Are you trying to authenticate with the server using a web form or with Basic, Digest or some other form of HTTP authentication? If this is the manner in which you should be authenticating, then you will also need to percent encode the --post-data as wget will not do this for you.
Using ' in Shellscript (wget) I'm trying to get wget to work with a post-request and a special password. It contains ' and it's like this: wget --save-cookie cookie.txt --post-data "user=Abraham&password=--my'precious!" http://localhost/login.php But when I use the tick in with wget I get strange errors. Does anybody know how to get it to work?
TITLE: Using ' in Shellscript (wget) QUESTION: I'm trying to get wget to work with a post-request and a special password. It contains ' and it's like this: wget --save-cookie cookie.txt --post-data "user=Abraham&password=--my'precious!" http://localhost/login.php But when I use the tick in with wget I get strange errors. Does anybody know how to get it to work? ANSWER: The backtick in your request is a straightforward issue, although you may have a second one lurking in there. The word you are looking for is 'escape' - the backtick has a special meaning on the commandline and you need to escape it so that it is not interpreted as such. In the bash shell (typical linux console) the escape character is \ - if you put that in front of the backtick, it will no longer get interpreted. The second potential issue is with the way you are using wget - are you certain that is the request you are meant to send? Are you trying to authenticate with the server using a web form or with Basic, Digest or some other form of HTTP authentication? If this is the manner in which you should be authenticating, then you will also need to percent encode the --post-data as wget will not do this for you.
[ "linux", "wget" ]
0
2
1,004
1
0
2011-06-10T17:42:26.873000
2011-06-10T17:51:32.700000
6,310,129
6,310,389
Basic SQL Insert statement approach
Given that I have two tables Customer (id int, username varchar) Order (customer_id int, order_date datetime) Now I want to insert into Order table based on customer information which is available in Customer table. There are a couple of ways I can approch this problem. First - I can query the customer information into a variable and then use it in an INSERT statement. DECLARE @Customer_ID int SELECT @Customer_ID = id FROM Customer where username = 'john.smith' INSERT INTO Orders (customer_id, order_date) VALUES (@Customer_ID, GETDATE()) Second Approach is to use a combination of INSERT and SELECT query. INSERT INTO Orders (customer_id, order_date) SELECT id, GETDATE() FROM Customers WHERE username = 'john.smith' So my question is that which is a better way to proceed in terms of speed and overhead and why? I know if we have a lot of information getting queried from Customer table then the second approach is much better. p.s. I was asked this question in one of the technical interviews.
The second approach is better. The first approach will fail if the customer is not found. No check is being done to make sure the customer id has been returned. The second approach will do nothing if the customer is not found. From an overhead approach why create variables if they are not needed. Set based sql is usually the better approach.
Basic SQL Insert statement approach Given that I have two tables Customer (id int, username varchar) Order (customer_id int, order_date datetime) Now I want to insert into Order table based on customer information which is available in Customer table. There are a couple of ways I can approch this problem. First - I can query the customer information into a variable and then use it in an INSERT statement. DECLARE @Customer_ID int SELECT @Customer_ID = id FROM Customer where username = 'john.smith' INSERT INTO Orders (customer_id, order_date) VALUES (@Customer_ID, GETDATE()) Second Approach is to use a combination of INSERT and SELECT query. INSERT INTO Orders (customer_id, order_date) SELECT id, GETDATE() FROM Customers WHERE username = 'john.smith' So my question is that which is a better way to proceed in terms of speed and overhead and why? I know if we have a lot of information getting queried from Customer table then the second approach is much better. p.s. I was asked this question in one of the technical interviews.
TITLE: Basic SQL Insert statement approach QUESTION: Given that I have two tables Customer (id int, username varchar) Order (customer_id int, order_date datetime) Now I want to insert into Order table based on customer information which is available in Customer table. There are a couple of ways I can approch this problem. First - I can query the customer information into a variable and then use it in an INSERT statement. DECLARE @Customer_ID int SELECT @Customer_ID = id FROM Customer where username = 'john.smith' INSERT INTO Orders (customer_id, order_date) VALUES (@Customer_ID, GETDATE()) Second Approach is to use a combination of INSERT and SELECT query. INSERT INTO Orders (customer_id, order_date) SELECT id, GETDATE() FROM Customers WHERE username = 'john.smith' So my question is that which is a better way to proceed in terms of speed and overhead and why? I know if we have a lot of information getting queried from Customer table then the second approach is much better. p.s. I was asked this question in one of the technical interviews. ANSWER: The second approach is better. The first approach will fail if the customer is not found. No check is being done to make sure the customer id has been returned. The second approach will do nothing if the customer is not found. From an overhead approach why create variables if they are not needed. Set based sql is usually the better approach.
[ "sql", "sql-server" ]
1
4
146
4
0
2011-06-10T17:43:07.793000
2011-06-10T18:09:40.990000
6,310,138
6,310,221
Compiling but crashing android app. something to do with intent? help
It keeps crashing. I think it has something to do with the Intent. Please help. package com.SMARTlab.twitterapp; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import twitter4j.*; public class TwitterApp extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button search = (Button)findViewById(R.id.search_button); search.setOnClickListener(search_OnClickListener); } public void onClick(View v) { switch (v.getId()) { case R.id.search_button: Intent i = new Intent(this, com.SMARTlab.twitterapp.TwitterApp.class); startActivity(i); break; } } @SuppressWarnings("deprecation") private Button.OnClickListener search_OnClickListener = new Button.OnClickListener() { int queryRank = 0; private boolean evaluateRank(int rank) { if (rank > 10) return true; return false; } @Override public void onClick(View v) { Twitter t = new TwitterFactory().getInstance(); EditText ed = (EditText)findViewById(R.id.search_box); TextView txt = (TextView)findViewById(R.id.text_box); Query q = new Query(ed.getText().toString()); QueryResult res = null; try { res = t.search(q); txt.setText(""); } catch(TwitterException ex) {System.out.println(ex.toString());} for (Tweet tw: res.getTweets()) { try { long[] id = t.getRetweetedByIDs(tw.getId()).getIDs(); for (int x = 0; x < id.length; x++) queryRank += 1; } catch(TwitterException te) {} if (evaluateRank(queryRank)) { txt.append((String)"[" + tw.getFromUser() + "] " + tw.getText() + "\n"); } } } }; } Here is the LogCat. 06-10 12:44:08.145: DEBUG/AndroidRuntime(416): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<< 06-10 12:44:08.145: DEBUG/AndroidRuntime(416): CheckJNI is ON 06-10 12:44:08.365: DEBUG/AndroidRuntime(416): --- registering native functions --- 06-10 12:44:09.285: DEBUG/dalvikvm(253): GC_EXPLICIT freed 176 objects / 8856 bytes in 55ms 06-10 12:44:10.446: DEBUG/PackageParser(59): Scanning package: /data/app/vmdl44188.tmp 06-10 12:44:10.647: INFO/PackageManager(59): Removing non-system package:com.SMARTlab.twitter 06-10 12:44:10.647: INFO/ActivityManager(59): Force stopping package com.SMARTlab.twitter uid=10039 06-10 12:44:11.455: DEBUG/PackageManager(59): Scanning package com.SMARTlab.twitter 06-10 12:44:11.465: INFO/PackageManager(59): Package com.SMARTlab.twitter codePath changed from /data/app/com.SMARTlab.twitter-2.apk to /data/app/com.SMARTlab.twitter-1.apk; Retaining data and using new 06-10 12:44:11.475: INFO/PackageManager(59): /data/app/com.SMARTlab.twitter-1.apk changed; unpacking 06-10 12:44:11.556: DEBUG/installd(35): DexInv: --- BEGIN '/data/app/com.SMARTlab.twitter-1.apk' --- 06-10 12:44:14.765: DEBUG/dalvikvm(423): DexOpt: load 105ms, verify 473ms, opt 23ms 06-10 12:44:16.048: DEBUG/installd(35): DexInv: --- END '/data/app/com.SMARTlab.twitter-1.apk' (success) --- 06-10 12:44:16.246: DEBUG/dalvikvm(59): GC_FOR_MALLOC freed 9625 objects / 558632 bytes in 176ms 06-10 12:44:16.246: WARN/PackageManager(59): Code path for pkg: com.SMARTlab.twitter changing from /data/app/com.SMARTlab.twitter-2.apk to /data/app/com.SMARTlab.twitter-1.apk 06-10 12:44:16.246: WARN/PackageManager(59): Resource path for pkg: com.SMARTlab.twitter changing from /data/app/com.SMARTlab.twitter-2.apk to /data/app/com.SMARTlab.twitter-1.apk 06-10 12:44:16.246: DEBUG/PackageManager(59): Activities: com.SMARTlab.twitter.Twitter 06-10 12:44:16.288: INFO/ActivityManager(59): Force stopping package com.SMARTlab.twitter uid=10039 06-10 12:44:17.117: INFO/installd(35): move /data/dalvik-cache/data@app@com.SMARTlab.twitter-1.apk@classes.dex -> /data/dalvik-cache/data@app@com.SMARTlab.twitter-1.apk@classes.dex 06-10 12:44:17.117: DEBUG/PackageManager(59): New package installed in /data/app/com.SMARTlab.twitter-1.apk 06-10 12:44:17.975: INFO/ActivityManager(59): Force stopping package com.SMARTlab.twitter uid=10039 06-10 12:44:18.065: DEBUG/dalvikvm(124): GC_EXPLICIT freed 910 objects / 48976 bytes in 67ms 06-10 12:44:18.166: DEBUG/dalvikvm(151): GC_EXPLICIT freed 1750 objects / 89136 bytes in 89ms 06-10 12:44:18.456: WARN/RecognitionManagerService(59): no available voice recognition services found 06-10 12:44:18.775: DEBUG/dalvikvm(59): GC_EXPLICIT freed 5654 objects / 334424 bytes in 261ms 06-10 12:44:19.115: INFO/installd(35): unlink /data/dalvik-cache/data@app@com.SMARTlab.twitter-2.apk@classes.dex 06-10 12:44:19.196: DEBUG/AndroidRuntime(416): Shutting down VM 06-10 12:44:19.216: DEBUG/dalvikvm(416): Debugger has detached; object registry had 1 entries 06-10 12:44:19.236: INFO/AndroidRuntime(416): NOTE: attach of thread 'Binder Thread #3' failed 06-10 12:44:19.955: DEBUG/AndroidRuntime(429): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<< 06-10 12:44:19.955: DEBUG/AndroidRuntime(429): CheckJNI is ON 06-10 12:44:20.175: DEBUG/AndroidRuntime(429): --- registering native functions --- 06-10 12:44:21.025: INFO/ActivityManager(59): Starting activity: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.SMARTlab.twitter/.Twitter } 06-10 12:44:21.135: DEBUG/AndroidRuntime(429): Shutting down VM 06-10 12:44:21.175: DEBUG/dalvikvm(429): Debugger has detached; object registry had 1 entries 06-10 12:44:21.215: INFO/ActivityManager(59): Start proc com.SMARTlab.twitter for activity com.SMARTlab.twitter/.Twitter: pid=435 uid=10039 gids={} 06-10 12:44:21.255: INFO/AndroidRuntime(429): NOTE: attach of thread 'Binder Thread #3' failed 06-10 12:44:21.446: DEBUG/dalvikvm(33): GC_EXPLICIT freed 264 objects / 10144 bytes in 203ms 06-10 12:44:21.656: DEBUG/dalvikvm(33): GC_EXPLICIT freed 22 objects / 968 bytes in 163ms 06-10 12:44:21.786: DEBUG/dalvikvm(33): GC_EXPLICIT freed 2 objects / 64 bytes in 115ms 06-10 12:44:22.175: DEBUG/AndroidRuntime(435): Shutting down VM 06-10 12:44:22.175: WARN/dalvikvm(435): threadid=1: thread exiting with uncaught exception (group=0x4001d800) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): FATAL EXCEPTION: main 06-10 12:44:22.195: ERROR/AndroidRuntime(435): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.SMARTlab.twitter/com.SMARTlab.twitter.Twitter}: java.lang.ClassNotFoundException: com.SMARTlab.twitter.Twitter in loader dalvik.system.PathClassLoader[/data/app/com.SMARTlab.twitter-1.apk] 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at android.app.ActivityThread.access$2300(ActivityThread.java:125) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at android.os.Handler.dispatchMessage(Handler.java:99) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at android.os.Looper.loop(Looper.java:123) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at android.app.ActivityThread.main(ActivityThread.java:4627) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at java.lang.reflect.Method.invokeNative(Native Method) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at java.lang.reflect.Method.invoke(Method.java:521) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at dalvik.system.NativeStart.main(Native Method) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): Caused by: java.lang.ClassNotFoundException: com.SMARTlab.twitter.Twitter in loader dalvik.system.PathClassLoader[/data/app/com.SMARTlab.twitter-1.apk] 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:243) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at java.lang.ClassLoader.loadClass(ClassLoader.java:573) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at java.lang.ClassLoader.loadClass(ClassLoader.java:532) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at android.app.Instrumentation.newActivity(Instrumentation.java:1021) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2577) 06-10 12:44:22.195: ERROR/AndroidRuntime(435):... 11 more 06-10 12:44:22.205: WARN/ActivityManager(59): Force finishing activity com.SMARTlab.twitter/.Twitter 06-10 12:44:22.716: WARN/ActivityManager(59): Activity pause timeout for HistoryRecord{44ff66d0 com.SMARTlab.twitter/.Twitter} 06-10 12:44:25.756: WARN/InputManagerService(59): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@44eb2308 06-10 12:44:26.025: INFO/Process(435): Sending signal. PID: 435 SIG: 9 06-10 12:44:26.155: INFO/ActivityManager(59): Process com.SMARTlab.twitter (pid 435) has died. 06-10 12:44:28.866: DEBUG/dalvikvm(261): GC_EXPLICIT freed 45 objects / 2120 bytes in 63ms 06-10 12:44:33.570: WARN/ActivityManager(59): Activity destroy timeout for HistoryRecord{44ff66d0 com.SMARTlab.twitter/.Twitter} 06-10 12:45:37.688: DEBUG/SntpClient(59): request time failed: java.net.SocketException: Address family not supported by protocol Here is the AndroidManifest.xml contents.
Make sure Twitter is registered in your AndroidManifest as an Activity.
Compiling but crashing android app. something to do with intent? help It keeps crashing. I think it has something to do with the Intent. Please help. package com.SMARTlab.twitterapp; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import twitter4j.*; public class TwitterApp extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button search = (Button)findViewById(R.id.search_button); search.setOnClickListener(search_OnClickListener); } public void onClick(View v) { switch (v.getId()) { case R.id.search_button: Intent i = new Intent(this, com.SMARTlab.twitterapp.TwitterApp.class); startActivity(i); break; } } @SuppressWarnings("deprecation") private Button.OnClickListener search_OnClickListener = new Button.OnClickListener() { int queryRank = 0; private boolean evaluateRank(int rank) { if (rank > 10) return true; return false; } @Override public void onClick(View v) { Twitter t = new TwitterFactory().getInstance(); EditText ed = (EditText)findViewById(R.id.search_box); TextView txt = (TextView)findViewById(R.id.text_box); Query q = new Query(ed.getText().toString()); QueryResult res = null; try { res = t.search(q); txt.setText(""); } catch(TwitterException ex) {System.out.println(ex.toString());} for (Tweet tw: res.getTweets()) { try { long[] id = t.getRetweetedByIDs(tw.getId()).getIDs(); for (int x = 0; x < id.length; x++) queryRank += 1; } catch(TwitterException te) {} if (evaluateRank(queryRank)) { txt.append((String)"[" + tw.getFromUser() + "] " + tw.getText() + "\n"); } } } }; } Here is the LogCat. 06-10 12:44:08.145: DEBUG/AndroidRuntime(416): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<< 06-10 12:44:08.145: DEBUG/AndroidRuntime(416): CheckJNI is ON 06-10 12:44:08.365: DEBUG/AndroidRuntime(416): --- registering native functions --- 06-10 12:44:09.285: DEBUG/dalvikvm(253): GC_EXPLICIT freed 176 objects / 8856 bytes in 55ms 06-10 12:44:10.446: DEBUG/PackageParser(59): Scanning package: /data/app/vmdl44188.tmp 06-10 12:44:10.647: INFO/PackageManager(59): Removing non-system package:com.SMARTlab.twitter 06-10 12:44:10.647: INFO/ActivityManager(59): Force stopping package com.SMARTlab.twitter uid=10039 06-10 12:44:11.455: DEBUG/PackageManager(59): Scanning package com.SMARTlab.twitter 06-10 12:44:11.465: INFO/PackageManager(59): Package com.SMARTlab.twitter codePath changed from /data/app/com.SMARTlab.twitter-2.apk to /data/app/com.SMARTlab.twitter-1.apk; Retaining data and using new 06-10 12:44:11.475: INFO/PackageManager(59): /data/app/com.SMARTlab.twitter-1.apk changed; unpacking 06-10 12:44:11.556: DEBUG/installd(35): DexInv: --- BEGIN '/data/app/com.SMARTlab.twitter-1.apk' --- 06-10 12:44:14.765: DEBUG/dalvikvm(423): DexOpt: load 105ms, verify 473ms, opt 23ms 06-10 12:44:16.048: DEBUG/installd(35): DexInv: --- END '/data/app/com.SMARTlab.twitter-1.apk' (success) --- 06-10 12:44:16.246: DEBUG/dalvikvm(59): GC_FOR_MALLOC freed 9625 objects / 558632 bytes in 176ms 06-10 12:44:16.246: WARN/PackageManager(59): Code path for pkg: com.SMARTlab.twitter changing from /data/app/com.SMARTlab.twitter-2.apk to /data/app/com.SMARTlab.twitter-1.apk 06-10 12:44:16.246: WARN/PackageManager(59): Resource path for pkg: com.SMARTlab.twitter changing from /data/app/com.SMARTlab.twitter-2.apk to /data/app/com.SMARTlab.twitter-1.apk 06-10 12:44:16.246: DEBUG/PackageManager(59): Activities: com.SMARTlab.twitter.Twitter 06-10 12:44:16.288: INFO/ActivityManager(59): Force stopping package com.SMARTlab.twitter uid=10039 06-10 12:44:17.117: INFO/installd(35): move /data/dalvik-cache/data@app@com.SMARTlab.twitter-1.apk@classes.dex -> /data/dalvik-cache/data@app@com.SMARTlab.twitter-1.apk@classes.dex 06-10 12:44:17.117: DEBUG/PackageManager(59): New package installed in /data/app/com.SMARTlab.twitter-1.apk 06-10 12:44:17.975: INFO/ActivityManager(59): Force stopping package com.SMARTlab.twitter uid=10039 06-10 12:44:18.065: DEBUG/dalvikvm(124): GC_EXPLICIT freed 910 objects / 48976 bytes in 67ms 06-10 12:44:18.166: DEBUG/dalvikvm(151): GC_EXPLICIT freed 1750 objects / 89136 bytes in 89ms 06-10 12:44:18.456: WARN/RecognitionManagerService(59): no available voice recognition services found 06-10 12:44:18.775: DEBUG/dalvikvm(59): GC_EXPLICIT freed 5654 objects / 334424 bytes in 261ms 06-10 12:44:19.115: INFO/installd(35): unlink /data/dalvik-cache/data@app@com.SMARTlab.twitter-2.apk@classes.dex 06-10 12:44:19.196: DEBUG/AndroidRuntime(416): Shutting down VM 06-10 12:44:19.216: DEBUG/dalvikvm(416): Debugger has detached; object registry had 1 entries 06-10 12:44:19.236: INFO/AndroidRuntime(416): NOTE: attach of thread 'Binder Thread #3' failed 06-10 12:44:19.955: DEBUG/AndroidRuntime(429): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<< 06-10 12:44:19.955: DEBUG/AndroidRuntime(429): CheckJNI is ON 06-10 12:44:20.175: DEBUG/AndroidRuntime(429): --- registering native functions --- 06-10 12:44:21.025: INFO/ActivityManager(59): Starting activity: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.SMARTlab.twitter/.Twitter } 06-10 12:44:21.135: DEBUG/AndroidRuntime(429): Shutting down VM 06-10 12:44:21.175: DEBUG/dalvikvm(429): Debugger has detached; object registry had 1 entries 06-10 12:44:21.215: INFO/ActivityManager(59): Start proc com.SMARTlab.twitter for activity com.SMARTlab.twitter/.Twitter: pid=435 uid=10039 gids={} 06-10 12:44:21.255: INFO/AndroidRuntime(429): NOTE: attach of thread 'Binder Thread #3' failed 06-10 12:44:21.446: DEBUG/dalvikvm(33): GC_EXPLICIT freed 264 objects / 10144 bytes in 203ms 06-10 12:44:21.656: DEBUG/dalvikvm(33): GC_EXPLICIT freed 22 objects / 968 bytes in 163ms 06-10 12:44:21.786: DEBUG/dalvikvm(33): GC_EXPLICIT freed 2 objects / 64 bytes in 115ms 06-10 12:44:22.175: DEBUG/AndroidRuntime(435): Shutting down VM 06-10 12:44:22.175: WARN/dalvikvm(435): threadid=1: thread exiting with uncaught exception (group=0x4001d800) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): FATAL EXCEPTION: main 06-10 12:44:22.195: ERROR/AndroidRuntime(435): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.SMARTlab.twitter/com.SMARTlab.twitter.Twitter}: java.lang.ClassNotFoundException: com.SMARTlab.twitter.Twitter in loader dalvik.system.PathClassLoader[/data/app/com.SMARTlab.twitter-1.apk] 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at android.app.ActivityThread.access$2300(ActivityThread.java:125) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at android.os.Handler.dispatchMessage(Handler.java:99) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at android.os.Looper.loop(Looper.java:123) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at android.app.ActivityThread.main(ActivityThread.java:4627) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at java.lang.reflect.Method.invokeNative(Native Method) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at java.lang.reflect.Method.invoke(Method.java:521) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at dalvik.system.NativeStart.main(Native Method) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): Caused by: java.lang.ClassNotFoundException: com.SMARTlab.twitter.Twitter in loader dalvik.system.PathClassLoader[/data/app/com.SMARTlab.twitter-1.apk] 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:243) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at java.lang.ClassLoader.loadClass(ClassLoader.java:573) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at java.lang.ClassLoader.loadClass(ClassLoader.java:532) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at android.app.Instrumentation.newActivity(Instrumentation.java:1021) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2577) 06-10 12:44:22.195: ERROR/AndroidRuntime(435):... 11 more 06-10 12:44:22.205: WARN/ActivityManager(59): Force finishing activity com.SMARTlab.twitter/.Twitter 06-10 12:44:22.716: WARN/ActivityManager(59): Activity pause timeout for HistoryRecord{44ff66d0 com.SMARTlab.twitter/.Twitter} 06-10 12:44:25.756: WARN/InputManagerService(59): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@44eb2308 06-10 12:44:26.025: INFO/Process(435): Sending signal. PID: 435 SIG: 9 06-10 12:44:26.155: INFO/ActivityManager(59): Process com.SMARTlab.twitter (pid 435) has died. 06-10 12:44:28.866: DEBUG/dalvikvm(261): GC_EXPLICIT freed 45 objects / 2120 bytes in 63ms 06-10 12:44:33.570: WARN/ActivityManager(59): Activity destroy timeout for HistoryRecord{44ff66d0 com.SMARTlab.twitter/.Twitter} 06-10 12:45:37.688: DEBUG/SntpClient(59): request time failed: java.net.SocketException: Address family not supported by protocol Here is the AndroidManifest.xml contents.
TITLE: Compiling but crashing android app. something to do with intent? help QUESTION: It keeps crashing. I think it has something to do with the Intent. Please help. package com.SMARTlab.twitterapp; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import twitter4j.*; public class TwitterApp extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button search = (Button)findViewById(R.id.search_button); search.setOnClickListener(search_OnClickListener); } public void onClick(View v) { switch (v.getId()) { case R.id.search_button: Intent i = new Intent(this, com.SMARTlab.twitterapp.TwitterApp.class); startActivity(i); break; } } @SuppressWarnings("deprecation") private Button.OnClickListener search_OnClickListener = new Button.OnClickListener() { int queryRank = 0; private boolean evaluateRank(int rank) { if (rank > 10) return true; return false; } @Override public void onClick(View v) { Twitter t = new TwitterFactory().getInstance(); EditText ed = (EditText)findViewById(R.id.search_box); TextView txt = (TextView)findViewById(R.id.text_box); Query q = new Query(ed.getText().toString()); QueryResult res = null; try { res = t.search(q); txt.setText(""); } catch(TwitterException ex) {System.out.println(ex.toString());} for (Tweet tw: res.getTweets()) { try { long[] id = t.getRetweetedByIDs(tw.getId()).getIDs(); for (int x = 0; x < id.length; x++) queryRank += 1; } catch(TwitterException te) {} if (evaluateRank(queryRank)) { txt.append((String)"[" + tw.getFromUser() + "] " + tw.getText() + "\n"); } } } }; } Here is the LogCat. 06-10 12:44:08.145: DEBUG/AndroidRuntime(416): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<< 06-10 12:44:08.145: DEBUG/AndroidRuntime(416): CheckJNI is ON 06-10 12:44:08.365: DEBUG/AndroidRuntime(416): --- registering native functions --- 06-10 12:44:09.285: DEBUG/dalvikvm(253): GC_EXPLICIT freed 176 objects / 8856 bytes in 55ms 06-10 12:44:10.446: DEBUG/PackageParser(59): Scanning package: /data/app/vmdl44188.tmp 06-10 12:44:10.647: INFO/PackageManager(59): Removing non-system package:com.SMARTlab.twitter 06-10 12:44:10.647: INFO/ActivityManager(59): Force stopping package com.SMARTlab.twitter uid=10039 06-10 12:44:11.455: DEBUG/PackageManager(59): Scanning package com.SMARTlab.twitter 06-10 12:44:11.465: INFO/PackageManager(59): Package com.SMARTlab.twitter codePath changed from /data/app/com.SMARTlab.twitter-2.apk to /data/app/com.SMARTlab.twitter-1.apk; Retaining data and using new 06-10 12:44:11.475: INFO/PackageManager(59): /data/app/com.SMARTlab.twitter-1.apk changed; unpacking 06-10 12:44:11.556: DEBUG/installd(35): DexInv: --- BEGIN '/data/app/com.SMARTlab.twitter-1.apk' --- 06-10 12:44:14.765: DEBUG/dalvikvm(423): DexOpt: load 105ms, verify 473ms, opt 23ms 06-10 12:44:16.048: DEBUG/installd(35): DexInv: --- END '/data/app/com.SMARTlab.twitter-1.apk' (success) --- 06-10 12:44:16.246: DEBUG/dalvikvm(59): GC_FOR_MALLOC freed 9625 objects / 558632 bytes in 176ms 06-10 12:44:16.246: WARN/PackageManager(59): Code path for pkg: com.SMARTlab.twitter changing from /data/app/com.SMARTlab.twitter-2.apk to /data/app/com.SMARTlab.twitter-1.apk 06-10 12:44:16.246: WARN/PackageManager(59): Resource path for pkg: com.SMARTlab.twitter changing from /data/app/com.SMARTlab.twitter-2.apk to /data/app/com.SMARTlab.twitter-1.apk 06-10 12:44:16.246: DEBUG/PackageManager(59): Activities: com.SMARTlab.twitter.Twitter 06-10 12:44:16.288: INFO/ActivityManager(59): Force stopping package com.SMARTlab.twitter uid=10039 06-10 12:44:17.117: INFO/installd(35): move /data/dalvik-cache/data@app@com.SMARTlab.twitter-1.apk@classes.dex -> /data/dalvik-cache/data@app@com.SMARTlab.twitter-1.apk@classes.dex 06-10 12:44:17.117: DEBUG/PackageManager(59): New package installed in /data/app/com.SMARTlab.twitter-1.apk 06-10 12:44:17.975: INFO/ActivityManager(59): Force stopping package com.SMARTlab.twitter uid=10039 06-10 12:44:18.065: DEBUG/dalvikvm(124): GC_EXPLICIT freed 910 objects / 48976 bytes in 67ms 06-10 12:44:18.166: DEBUG/dalvikvm(151): GC_EXPLICIT freed 1750 objects / 89136 bytes in 89ms 06-10 12:44:18.456: WARN/RecognitionManagerService(59): no available voice recognition services found 06-10 12:44:18.775: DEBUG/dalvikvm(59): GC_EXPLICIT freed 5654 objects / 334424 bytes in 261ms 06-10 12:44:19.115: INFO/installd(35): unlink /data/dalvik-cache/data@app@com.SMARTlab.twitter-2.apk@classes.dex 06-10 12:44:19.196: DEBUG/AndroidRuntime(416): Shutting down VM 06-10 12:44:19.216: DEBUG/dalvikvm(416): Debugger has detached; object registry had 1 entries 06-10 12:44:19.236: INFO/AndroidRuntime(416): NOTE: attach of thread 'Binder Thread #3' failed 06-10 12:44:19.955: DEBUG/AndroidRuntime(429): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<< 06-10 12:44:19.955: DEBUG/AndroidRuntime(429): CheckJNI is ON 06-10 12:44:20.175: DEBUG/AndroidRuntime(429): --- registering native functions --- 06-10 12:44:21.025: INFO/ActivityManager(59): Starting activity: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.SMARTlab.twitter/.Twitter } 06-10 12:44:21.135: DEBUG/AndroidRuntime(429): Shutting down VM 06-10 12:44:21.175: DEBUG/dalvikvm(429): Debugger has detached; object registry had 1 entries 06-10 12:44:21.215: INFO/ActivityManager(59): Start proc com.SMARTlab.twitter for activity com.SMARTlab.twitter/.Twitter: pid=435 uid=10039 gids={} 06-10 12:44:21.255: INFO/AndroidRuntime(429): NOTE: attach of thread 'Binder Thread #3' failed 06-10 12:44:21.446: DEBUG/dalvikvm(33): GC_EXPLICIT freed 264 objects / 10144 bytes in 203ms 06-10 12:44:21.656: DEBUG/dalvikvm(33): GC_EXPLICIT freed 22 objects / 968 bytes in 163ms 06-10 12:44:21.786: DEBUG/dalvikvm(33): GC_EXPLICIT freed 2 objects / 64 bytes in 115ms 06-10 12:44:22.175: DEBUG/AndroidRuntime(435): Shutting down VM 06-10 12:44:22.175: WARN/dalvikvm(435): threadid=1: thread exiting with uncaught exception (group=0x4001d800) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): FATAL EXCEPTION: main 06-10 12:44:22.195: ERROR/AndroidRuntime(435): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.SMARTlab.twitter/com.SMARTlab.twitter.Twitter}: java.lang.ClassNotFoundException: com.SMARTlab.twitter.Twitter in loader dalvik.system.PathClassLoader[/data/app/com.SMARTlab.twitter-1.apk] 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at android.app.ActivityThread.access$2300(ActivityThread.java:125) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at android.os.Handler.dispatchMessage(Handler.java:99) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at android.os.Looper.loop(Looper.java:123) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at android.app.ActivityThread.main(ActivityThread.java:4627) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at java.lang.reflect.Method.invokeNative(Native Method) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at java.lang.reflect.Method.invoke(Method.java:521) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at dalvik.system.NativeStart.main(Native Method) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): Caused by: java.lang.ClassNotFoundException: com.SMARTlab.twitter.Twitter in loader dalvik.system.PathClassLoader[/data/app/com.SMARTlab.twitter-1.apk] 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:243) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at java.lang.ClassLoader.loadClass(ClassLoader.java:573) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at java.lang.ClassLoader.loadClass(ClassLoader.java:532) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at android.app.Instrumentation.newActivity(Instrumentation.java:1021) 06-10 12:44:22.195: ERROR/AndroidRuntime(435): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2577) 06-10 12:44:22.195: ERROR/AndroidRuntime(435):... 11 more 06-10 12:44:22.205: WARN/ActivityManager(59): Force finishing activity com.SMARTlab.twitter/.Twitter 06-10 12:44:22.716: WARN/ActivityManager(59): Activity pause timeout for HistoryRecord{44ff66d0 com.SMARTlab.twitter/.Twitter} 06-10 12:44:25.756: WARN/InputManagerService(59): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@44eb2308 06-10 12:44:26.025: INFO/Process(435): Sending signal. PID: 435 SIG: 9 06-10 12:44:26.155: INFO/ActivityManager(59): Process com.SMARTlab.twitter (pid 435) has died. 06-10 12:44:28.866: DEBUG/dalvikvm(261): GC_EXPLICIT freed 45 objects / 2120 bytes in 63ms 06-10 12:44:33.570: WARN/ActivityManager(59): Activity destroy timeout for HistoryRecord{44ff66d0 com.SMARTlab.twitter/.Twitter} 06-10 12:45:37.688: DEBUG/SntpClient(59): request time failed: java.net.SocketException: Address family not supported by protocol Here is the AndroidManifest.xml contents. ANSWER: Make sure Twitter is registered in your AndroidManifest as an Activity.
[ "java", "android", "twitter", "mobile" ]
0
4
732
2
0
2011-06-10T17:43:56.090000
2011-06-10T17:51:21.463000
6,310,147
6,310,171
mysql error inner join
I used a query like select a.email,b.vuid from user a,inner join group b on a.uid = b.uid where a.email='xx@xx.de' and a.kid=1 and b.vid=29 limit 1 but I always get this error. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'inner join group b on a.uid = b.uid where a.email='xx@xx.de' at line 1 I think its because the inner join but I don't know really.. Could someone help me?
Remove the, after from user a. Your query should be: select a.email,b.vuid from user a inner join group b on a.uid = b.uid where a.email='xx@xx.de' and a.kid=1 and b.vid=29 limit 1
mysql error inner join I used a query like select a.email,b.vuid from user a,inner join group b on a.uid = b.uid where a.email='xx@xx.de' and a.kid=1 and b.vid=29 limit 1 but I always get this error. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'inner join group b on a.uid = b.uid where a.email='xx@xx.de' at line 1 I think its because the inner join but I don't know really.. Could someone help me?
TITLE: mysql error inner join QUESTION: I used a query like select a.email,b.vuid from user a,inner join group b on a.uid = b.uid where a.email='xx@xx.de' and a.kid=1 and b.vid=29 limit 1 but I always get this error. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'inner join group b on a.uid = b.uid where a.email='xx@xx.de' at line 1 I think its because the inner join but I don't know really.. Could someone help me? ANSWER: Remove the, after from user a. Your query should be: select a.email,b.vuid from user a inner join group b on a.uid = b.uid where a.email='xx@xx.de' and a.kid=1 and b.vid=29 limit 1
[ "mysql", "sql", "join" ]
0
4
116
2
0
2011-06-10T17:44:55.547000
2011-06-10T17:47:18.653000
6,310,156
6,310,334
Hide hours and mins if they are zero in the function provided
The function below outputs hours:0 whether the time is <1 hour or mins:0 when mins<1. How can I show only the variables that are not zero? Thank you. function time_difference($endtime){ $hours =date("G",$endtime); $mins =date("i",$endtime); $secs =date("s",$endtime); $diff="'hours': ".$hours.",'mins': ".$mins.",'sec': ".$secs; return $diff; } $end_time =strtotime("+7 hours") - strtotime($entry->pubDate); $difference = time_difference($end_time); echo $difference;
Another possible approach: function time_difference($endtime){ $times=array( 'hours' => date("G",$endtime), 'mins' => date("i",$endtime), 'secs' => date("s",$endtime), ); //added a "just a moment ago" feature for you if (intval($times['hours'], 10) == 0 && intval($times['mins'], 10) == 0) { return "just a moment ago"; } $diff=''; foreach ($times as $k=>$v) { $diff.=empty($diff)? '': ','; $diff.=intval($v, 10) == 0? '': "'$k':$v"; } return $diff; }
Hide hours and mins if they are zero in the function provided The function below outputs hours:0 whether the time is <1 hour or mins:0 when mins<1. How can I show only the variables that are not zero? Thank you. function time_difference($endtime){ $hours =date("G",$endtime); $mins =date("i",$endtime); $secs =date("s",$endtime); $diff="'hours': ".$hours.",'mins': ".$mins.",'sec': ".$secs; return $diff; } $end_time =strtotime("+7 hours") - strtotime($entry->pubDate); $difference = time_difference($end_time); echo $difference;
TITLE: Hide hours and mins if they are zero in the function provided QUESTION: The function below outputs hours:0 whether the time is <1 hour or mins:0 when mins<1. How can I show only the variables that are not zero? Thank you. function time_difference($endtime){ $hours =date("G",$endtime); $mins =date("i",$endtime); $secs =date("s",$endtime); $diff="'hours': ".$hours.",'mins': ".$mins.",'sec': ".$secs; return $diff; } $end_time =strtotime("+7 hours") - strtotime($entry->pubDate); $difference = time_difference($end_time); echo $difference; ANSWER: Another possible approach: function time_difference($endtime){ $times=array( 'hours' => date("G",$endtime), 'mins' => date("i",$endtime), 'secs' => date("s",$endtime), ); //added a "just a moment ago" feature for you if (intval($times['hours'], 10) == 0 && intval($times['mins'], 10) == 0) { return "just a moment ago"; } $diff=''; foreach ($times as $k=>$v) { $diff.=empty($diff)? '': ','; $diff.=intval($v, 10) == 0? '': "'$k':$v"; } return $diff; }
[ "php", "date", "string", "if-statement" ]
2
3
1,652
3
0
2011-06-10T17:45:57.647000
2011-06-10T18:02:38.160000
6,310,160
6,310,267
Before insert trigger
I want to disable in before insert trigger inserting into table when some condition is true create or replace trigger CHECK_FOR_MAX_ENTRANTS before insert on application declare entrants_count number; max_entrants number; begin select count(*) into entrants_count from application where id_speciality =:new.id_speciality; select max_students_number into max_entrants from speciality s where s.id_speciality =:new.id_speciality; IF entrants_count >= max_entrants THEN **disable this insert** end; How can i do this?
Assuming you're talking about Oracle, then, in place of disable this insert you could: IF entrants_count >= max_entrants THEN raise_application_error(-21010, 'Max number of Entrants Reached'); END IF; See: http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/errors.htm#sthref2006 EDIT: It's generally a bad idea to have inserts fail silently (what you're asking for). You also may run into mutating table errors if you try to delete the record in an after insert trigger. Instead, just don't insert the record to begin with. One way you could probably achieve this is to add something like this to the end of your insert statement: WHERE EXISTS SELECT null FROM (SELECT COUNT(*) entrants_count FROM application WHERE id_speciality =:new.id_speciality) a, (SELECT max_students_number max_entrants FROM speciality WHERE id_speciality =:new.id_speciality) s WHERE a.entrants_count < s.max_entrants This should only execute the insert statement when entrants_count < max_entrants (what you want).
Before insert trigger I want to disable in before insert trigger inserting into table when some condition is true create or replace trigger CHECK_FOR_MAX_ENTRANTS before insert on application declare entrants_count number; max_entrants number; begin select count(*) into entrants_count from application where id_speciality =:new.id_speciality; select max_students_number into max_entrants from speciality s where s.id_speciality =:new.id_speciality; IF entrants_count >= max_entrants THEN **disable this insert** end; How can i do this?
TITLE: Before insert trigger QUESTION: I want to disable in before insert trigger inserting into table when some condition is true create or replace trigger CHECK_FOR_MAX_ENTRANTS before insert on application declare entrants_count number; max_entrants number; begin select count(*) into entrants_count from application where id_speciality =:new.id_speciality; select max_students_number into max_entrants from speciality s where s.id_speciality =:new.id_speciality; IF entrants_count >= max_entrants THEN **disable this insert** end; How can i do this? ANSWER: Assuming you're talking about Oracle, then, in place of disable this insert you could: IF entrants_count >= max_entrants THEN raise_application_error(-21010, 'Max number of Entrants Reached'); END IF; See: http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/errors.htm#sthref2006 EDIT: It's generally a bad idea to have inserts fail silently (what you're asking for). You also may run into mutating table errors if you try to delete the record in an after insert trigger. Instead, just don't insert the record to begin with. One way you could probably achieve this is to add something like this to the end of your insert statement: WHERE EXISTS SELECT null FROM (SELECT COUNT(*) entrants_count FROM application WHERE id_speciality =:new.id_speciality) a, (SELECT max_students_number max_entrants FROM speciality WHERE id_speciality =:new.id_speciality) s WHERE a.entrants_count < s.max_entrants This should only execute the insert statement when entrants_count < max_entrants (what you want).
[ "oracle", "plsql", "triggers" ]
0
3
4,863
2
0
2011-06-10T17:46:19.847000
2011-06-10T17:55:22.947000
6,310,164
6,310,360
Relative url mapping for images in django imagefield
I am using imagefield to render images. These are the urls; (r'^site_media/(?P.*)$', 'django.views.static.serve', {'document_root': site_media}), (r'^$', 'webapp.blog.views.index'), url( r'^blog/view/(?P [^\.]+).html', 'webapp.blog.views.view_post', name='view_blog_post'), These are the views: def index(request): return render_to_response('index.html', { 'categories': Category.objects.all(), 'posts': Blog.objects.all()[:5] }) def view_post(request, slug): return render_to_response('view_post.html', { 'post': get_object_or_404(Blog, slug=slug), }) If I call a image object in the index page with {{ posts.photos.url }} it properly maps to http://127.0.0.1/site_media/images/image.jpg. But if I call the image object on view_post template it gets mapped to http://127.0.0.1/blog/view/site_media/images/image.jpg. How can I make view_post function map image urls to the proper http://127.0.0.1/site_media/images/image.jpg url.
This is not a function of your urlconf, but how you are displaying the images in your template. You are probably doing something like this: when you should be doing... note the initial slash. Alternatively, if you're using STATIC_URL or MEDIA_URL, make sure they're defined with the initial slash in your settings.py.
Relative url mapping for images in django imagefield I am using imagefield to render images. These are the urls; (r'^site_media/(?P.*)$', 'django.views.static.serve', {'document_root': site_media}), (r'^$', 'webapp.blog.views.index'), url( r'^blog/view/(?P [^\.]+).html', 'webapp.blog.views.view_post', name='view_blog_post'), These are the views: def index(request): return render_to_response('index.html', { 'categories': Category.objects.all(), 'posts': Blog.objects.all()[:5] }) def view_post(request, slug): return render_to_response('view_post.html', { 'post': get_object_or_404(Blog, slug=slug), }) If I call a image object in the index page with {{ posts.photos.url }} it properly maps to http://127.0.0.1/site_media/images/image.jpg. But if I call the image object on view_post template it gets mapped to http://127.0.0.1/blog/view/site_media/images/image.jpg. How can I make view_post function map image urls to the proper http://127.0.0.1/site_media/images/image.jpg url.
TITLE: Relative url mapping for images in django imagefield QUESTION: I am using imagefield to render images. These are the urls; (r'^site_media/(?P.*)$', 'django.views.static.serve', {'document_root': site_media}), (r'^$', 'webapp.blog.views.index'), url( r'^blog/view/(?P [^\.]+).html', 'webapp.blog.views.view_post', name='view_blog_post'), These are the views: def index(request): return render_to_response('index.html', { 'categories': Category.objects.all(), 'posts': Blog.objects.all()[:5] }) def view_post(request, slug): return render_to_response('view_post.html', { 'post': get_object_or_404(Blog, slug=slug), }) If I call a image object in the index page with {{ posts.photos.url }} it properly maps to http://127.0.0.1/site_media/images/image.jpg. But if I call the image object on view_post template it gets mapped to http://127.0.0.1/blog/view/site_media/images/image.jpg. How can I make view_post function map image urls to the proper http://127.0.0.1/site_media/images/image.jpg url. ANSWER: This is not a function of your urlconf, but how you are displaying the images in your template. You are probably doing something like this: when you should be doing... note the initial slash. Alternatively, if you're using STATIC_URL or MEDIA_URL, make sure they're defined with the initial slash in your settings.py.
[ "django", "django-templates", "django-urls", "django-models" ]
1
3
2,172
1
0
2011-06-10T17:47:02.160000
2011-06-10T18:06:13.520000
6,310,191
6,310,239
How to Query Mysql based on GPS latitude and longitude columns based on relative distance
In an app I'm building, One of the features i'd like users to be able to discover people around them easily. I'm using the GPS to get the latitude and longitude, then storing that information in the mysql db along with the other user information under a column for latitude and another with the longitude. What's would the best practice be to do a query that looks at the person whos making the query's information...and then have it find the closest possible relatable lat and longitude then start there and limit it to 24 results? And furthermore, how would I remember where it stopped so I could allow another query to start where it left off and return more getting further and further away Basically, to generalize how can I do a mysql query that starts as close as it can to 2 latitude and longitude points that I supply and then have it grab the next 24 sorted by closest to furthest? I feel like its going to be hard to do because its being based on 2 columns. Is there a way I should/could be combining the GPS values into 1 column so it will be easy to find relative distance? Maybe I could somehow get the zip code (but then that might cause non US problems). I'm not sure. I'm stuck.
Just search for "Haversine Formula" here on Stackoverflow and you will find several related questions.
How to Query Mysql based on GPS latitude and longitude columns based on relative distance In an app I'm building, One of the features i'd like users to be able to discover people around them easily. I'm using the GPS to get the latitude and longitude, then storing that information in the mysql db along with the other user information under a column for latitude and another with the longitude. What's would the best practice be to do a query that looks at the person whos making the query's information...and then have it find the closest possible relatable lat and longitude then start there and limit it to 24 results? And furthermore, how would I remember where it stopped so I could allow another query to start where it left off and return more getting further and further away Basically, to generalize how can I do a mysql query that starts as close as it can to 2 latitude and longitude points that I supply and then have it grab the next 24 sorted by closest to furthest? I feel like its going to be hard to do because its being based on 2 columns. Is there a way I should/could be combining the GPS values into 1 column so it will be easy to find relative distance? Maybe I could somehow get the zip code (but then that might cause non US problems). I'm not sure. I'm stuck.
TITLE: How to Query Mysql based on GPS latitude and longitude columns based on relative distance QUESTION: In an app I'm building, One of the features i'd like users to be able to discover people around them easily. I'm using the GPS to get the latitude and longitude, then storing that information in the mysql db along with the other user information under a column for latitude and another with the longitude. What's would the best practice be to do a query that looks at the person whos making the query's information...and then have it find the closest possible relatable lat and longitude then start there and limit it to 24 results? And furthermore, how would I remember where it stopped so I could allow another query to start where it left off and return more getting further and further away Basically, to generalize how can I do a mysql query that starts as close as it can to 2 latitude and longitude points that I supply and then have it grab the next 24 sorted by closest to furthest? I feel like its going to be hard to do because its being based on 2 columns. Is there a way I should/could be combining the GPS values into 1 column so it will be easy to find relative distance? Maybe I could somehow get the zip code (but then that might cause non US problems). I'm not sure. I'm stuck. ANSWER: Just search for "Haversine Formula" here on Stackoverflow and you will find several related questions.
[ "php", "mysql", "database", "gps", "latitude-longitude" ]
2
2
3,296
2
0
2011-06-10T17:48:42.023000
2011-06-10T17:52:46.183000
6,310,200
6,310,219
Difference between class initializers in C#?
Possible Duplicate: Why are C# 3.0 object initializer constructor parentheses optional? What is the difference between instatiating an object by using classInstance = new Class() { prop1 = "", prop2 = "" }; and classInstance = new Class { prop1 = "", prop2 = "" };
Nothing. The second is just a short-cut for the first. The first allows you to include arguments to a constructor. So, you can't use the short-cut if the class doesn't have an empty constructor. You may have an interest in this question: Why are C# 3.0 object initializer constructor parentheses optional? And Eric Lippert´s great blog post: Ambiguous Optional Parentheses, Part One
Difference between class initializers in C#? Possible Duplicate: Why are C# 3.0 object initializer constructor parentheses optional? What is the difference between instatiating an object by using classInstance = new Class() { prop1 = "", prop2 = "" }; and classInstance = new Class { prop1 = "", prop2 = "" };
TITLE: Difference between class initializers in C#? QUESTION: Possible Duplicate: Why are C# 3.0 object initializer constructor parentheses optional? What is the difference between instatiating an object by using classInstance = new Class() { prop1 = "", prop2 = "" }; and classInstance = new Class { prop1 = "", prop2 = "" }; ANSWER: Nothing. The second is just a short-cut for the first. The first allows you to include arguments to a constructor. So, you can't use the short-cut if the class doesn't have an empty constructor. You may have an interest in this question: Why are C# 3.0 object initializer constructor parentheses optional? And Eric Lippert´s great blog post: Ambiguous Optional Parentheses, Part One
[ "c#", ".net", "class", "object", "instantiation" ]
7
4
479
3
0
2011-06-10T17:50:00.987000
2011-06-10T17:51:16.480000
6,310,203
6,310,270
How do I make a control that simulates UpdatePanel but with Jquery AJAX?
The question is how do I create a control that simulates an updatepanel? You're asking me why to hell do I want to that???? It's just pure desire for knowledge:)... How do I want it to work exactly like UpdatePanel but with totaly my control. like that: //my html with server controls and other stuff... some scripts and so on..... Can you suggest how do I begin building some thing like that? Because I really don't want to use ScriptManager and real UpdatePanel. I appreciate any suggestion and thank you in advance.
That's not something you'd ever really want to do, for learning or otherwise. UpdatePanel was a very cheap solution, good for very (very) simple scenarios. If you're wanting to hand-roll some Ajax, then you should take a look at jQuery's Ajax, and com-manipulation APIs. You would essentially use jQuery (or Prototype, DoJo, etc) to make a call to a web service, then provide a callback that uses the service result to update your dom. There are many tutorials online that will get you started.
How do I make a control that simulates UpdatePanel but with Jquery AJAX? The question is how do I create a control that simulates an updatepanel? You're asking me why to hell do I want to that???? It's just pure desire for knowledge:)... How do I want it to work exactly like UpdatePanel but with totaly my control. like that: //my html with server controls and other stuff... some scripts and so on..... Can you suggest how do I begin building some thing like that? Because I really don't want to use ScriptManager and real UpdatePanel. I appreciate any suggestion and thank you in advance.
TITLE: How do I make a control that simulates UpdatePanel but with Jquery AJAX? QUESTION: The question is how do I create a control that simulates an updatepanel? You're asking me why to hell do I want to that???? It's just pure desire for knowledge:)... How do I want it to work exactly like UpdatePanel but with totaly my control. like that: //my html with server controls and other stuff... some scripts and so on..... Can you suggest how do I begin building some thing like that? Because I really don't want to use ScriptManager and real UpdatePanel. I appreciate any suggestion and thank you in advance. ANSWER: That's not something you'd ever really want to do, for learning or otherwise. UpdatePanel was a very cheap solution, good for very (very) simple scenarios. If you're wanting to hand-roll some Ajax, then you should take a look at jQuery's Ajax, and com-manipulation APIs. You would essentially use jQuery (or Prototype, DoJo, etc) to make a call to a web service, then provide a callback that uses the service result to update your dom. There are many tutorials online that will get you started.
[ "jquery", "c#-4.0", "updatepanel", "custom-controls" ]
0
1
168
2
0
2011-06-10T17:50:10.167000
2011-06-10T17:55:32.480000
6,310,206
6,310,254
Iterate a script X times
I have several functions that may or may not need to be repeated a certain number of times. The number of times is set by the user, and is stored in a variable: xTcount. if (xTcount > 0) { for (i=0; xTcount <= i; i++) { $(document).miscfunction(); } } I haven't actually tested the script above, as i'm sure it's incorrect. What makes what i want tricky, is that i don't want to have to code a "check xTcount" clause into every function that is repeatable. if possible, i'd like to create some master checker that simply repeats the next-called function xTcount times...
Repeat some things xTcount times? Maybe I'm misunderstanding, but it looks pretty simple: for(var i = 0; i < xTcount; i++) { doSomething(); doSomethingElse(); } If the trouble is that you don't like the look of the for loop, or that your script requires you to build the same loop multiple times, you could extract it if you reeeaaallllly wanted to: function repeat(fn, times) { for(var i = 0; i < times; i++) fn(); } repeat(doSomething, xTcount); //...later... repeat(doSomethingElse, xTcount);
Iterate a script X times I have several functions that may or may not need to be repeated a certain number of times. The number of times is set by the user, and is stored in a variable: xTcount. if (xTcount > 0) { for (i=0; xTcount <= i; i++) { $(document).miscfunction(); } } I haven't actually tested the script above, as i'm sure it's incorrect. What makes what i want tricky, is that i don't want to have to code a "check xTcount" clause into every function that is repeatable. if possible, i'd like to create some master checker that simply repeats the next-called function xTcount times...
TITLE: Iterate a script X times QUESTION: I have several functions that may or may not need to be repeated a certain number of times. The number of times is set by the user, and is stored in a variable: xTcount. if (xTcount > 0) { for (i=0; xTcount <= i; i++) { $(document).miscfunction(); } } I haven't actually tested the script above, as i'm sure it's incorrect. What makes what i want tricky, is that i don't want to have to code a "check xTcount" clause into every function that is repeatable. if possible, i'd like to create some master checker that simply repeats the next-called function xTcount times... ANSWER: Repeat some things xTcount times? Maybe I'm misunderstanding, but it looks pretty simple: for(var i = 0; i < xTcount; i++) { doSomething(); doSomethingElse(); } If the trouble is that you don't like the look of the for loop, or that your script requires you to build the same loop multiple times, you could extract it if you reeeaaallllly wanted to: function repeat(fn, times) { for(var i = 0; i < times; i++) fn(); } repeat(doSomething, xTcount); //...later... repeat(doSomethingElse, xTcount);
[ "jquery", "function", "loops" ]
4
18
24,135
1
0
2011-06-10T17:50:16.117000
2011-06-10T17:54:01.507000
6,310,207
6,310,235
How to separate css style from common to different statement
I have two elements, I want to apply same background style, but different font style to them, how to write the style statement in the header part without having to write duplicate statement?
It doesn't get simpler than: #element1, #element2 { background: red } #element1 { font: 20px sans-serif } #element2 { font: 24px serif } You should read up on selector grouping.
How to separate css style from common to different statement I have two elements, I want to apply same background style, but different font style to them, how to write the style statement in the header part without having to write duplicate statement?
TITLE: How to separate css style from common to different statement QUESTION: I have two elements, I want to apply same background style, but different font style to them, how to write the style statement in the header part without having to write duplicate statement? ANSWER: It doesn't get simpler than: #element1, #element2 { background: red } #element1 { font: 20px sans-serif } #element2 { font: 24px serif } You should read up on selector grouping.
[ "css" ]
0
3
109
3
0
2011-06-10T17:50:21.957000
2011-06-10T17:52:28.130000
6,310,208
6,310,229
Overriding remote git repository with my repository
The remote repository contains a bad version. I have the copy of a good version locally. I want to replace everything that's on the remote repository with my current repository (the remote repository has a few more commits (including a merge) that should not have happened). If I try to push, it tells me I need to pull first, but I don't want to do that, because that would mess my local version. I want the remote repo to contain what I have locally. How can I do that?
Use the --force, Luke. http://www.kernel.org/pub/software/scm/git/docs/git-push.html
Overriding remote git repository with my repository The remote repository contains a bad version. I have the copy of a good version locally. I want to replace everything that's on the remote repository with my current repository (the remote repository has a few more commits (including a merge) that should not have happened). If I try to push, it tells me I need to pull first, but I don't want to do that, because that would mess my local version. I want the remote repo to contain what I have locally. How can I do that?
TITLE: Overriding remote git repository with my repository QUESTION: The remote repository contains a bad version. I have the copy of a good version locally. I want to replace everything that's on the remote repository with my current repository (the remote repository has a few more commits (including a merge) that should not have happened). If I try to push, it tells me I need to pull first, but I don't want to do that, because that would mess my local version. I want the remote repo to contain what I have locally. How can I do that? ANSWER: Use the --force, Luke. http://www.kernel.org/pub/software/scm/git/docs/git-push.html
[ "git" ]
24
72
22,454
2
0
2011-06-10T17:50:24.027000
2011-06-10T17:51:57.657000
6,310,214
6,310,243
Javascript: Iterate through objects
I'm iterating through this object: var object = { first: { child1: 'test1', child2: 'test2' }, second: { child1: 'test3', child2: 'test4' }, first: { child1: 'test5', child2: 'test6!' } }; with this: for(var attribute in object){ alert(attribute + ": " + object[attribute]); } First it seemed that it works, but it iterates only on child objects with unique name, so the first object with: first is skipped. So what's the proper solution to iterate through an entire object?
JavaScript objects are associative maps, and cannot have multiple values with the same key (name). Your data cannot have that structure. Another option might be an array of key-value pairs. var object = [ ["first", { child1: 'test1', child2: 'test2' }], ["second", { child1: 'test3', child2: 'test4' }], ["first", { child1: 'test5', child2: 'test6!' }] ]; var i, attribute, value; for (i = 0; i < object.length; i++) { attribute = object[i][0]; value = object[i][1]; alert("" + attribute + " = " + value); }
Javascript: Iterate through objects I'm iterating through this object: var object = { first: { child1: 'test1', child2: 'test2' }, second: { child1: 'test3', child2: 'test4' }, first: { child1: 'test5', child2: 'test6!' } }; with this: for(var attribute in object){ alert(attribute + ": " + object[attribute]); } First it seemed that it works, but it iterates only on child objects with unique name, so the first object with: first is skipped. So what's the proper solution to iterate through an entire object?
TITLE: Javascript: Iterate through objects QUESTION: I'm iterating through this object: var object = { first: { child1: 'test1', child2: 'test2' }, second: { child1: 'test3', child2: 'test4' }, first: { child1: 'test5', child2: 'test6!' } }; with this: for(var attribute in object){ alert(attribute + ": " + object[attribute]); } First it seemed that it works, but it iterates only on child objects with unique name, so the first object with: first is skipped. So what's the proper solution to iterate through an entire object? ANSWER: JavaScript objects are associative maps, and cannot have multiple values with the same key (name). Your data cannot have that structure. Another option might be an array of key-value pairs. var object = [ ["first", { child1: 'test1', child2: 'test2' }], ["second", { child1: 'test3', child2: 'test4' }], ["first", { child1: 'test5', child2: 'test6!' }] ]; var i, attribute, value; for (i = 0; i < object.length; i++) { attribute = object[i][0]; value = object[i][1]; alert("" + attribute + " = " + value); }
[ "javascript", "object", "loops" ]
0
4
236
2
0
2011-06-10T17:51:06.927000
2011-06-10T17:52:54.773000
6,310,215
6,310,371
ASP.NET: How to fix FAST blinking cursor in edit control?
I set focus to an edit control and don't do anything else. When I run the web app, this cursor is at the edit control but blinks much faster than normal. It is more like jittering or flickering than blinking. What might be the cause of this behavior and how do I prevent it? I want a blinking cursor, or a non-blinking cursor in the textbox but not a flickering one. Thanks.
The cursor blink rate isn't something you can control by Javascript. It's an accessibility setting set by either the Operating System or the Browser itself. Likely, what you're seeing is something that is either reflective of that setting, or as Brandon Boone suggests, a side effect of other Javascript happening on the page. Here's what I'd do to narrow it down: If it's a browser or OS issue, it can be easily checked by rendering an input on an empty html page (there's nothing special about ASP.NET text box controls--they get translated to input elements when they get served). Put your cursor in that text box. If you see the same behavior, it's an accessibility setting by the browser or OS. If not, then check your code and see if you're doing some particularly nasty JavaScript that may be rather intensive. Also, try it from other browsers and see if perhaps it's just a particular browser issue.
ASP.NET: How to fix FAST blinking cursor in edit control? I set focus to an edit control and don't do anything else. When I run the web app, this cursor is at the edit control but blinks much faster than normal. It is more like jittering or flickering than blinking. What might be the cause of this behavior and how do I prevent it? I want a blinking cursor, or a non-blinking cursor in the textbox but not a flickering one. Thanks.
TITLE: ASP.NET: How to fix FAST blinking cursor in edit control? QUESTION: I set focus to an edit control and don't do anything else. When I run the web app, this cursor is at the edit control but blinks much faster than normal. It is more like jittering or flickering than blinking. What might be the cause of this behavior and how do I prevent it? I want a blinking cursor, or a non-blinking cursor in the textbox but not a flickering one. Thanks. ANSWER: The cursor blink rate isn't something you can control by Javascript. It's an accessibility setting set by either the Operating System or the Browser itself. Likely, what you're seeing is something that is either reflective of that setting, or as Brandon Boone suggests, a side effect of other Javascript happening on the page. Here's what I'd do to narrow it down: If it's a browser or OS issue, it can be easily checked by rendering an input on an empty html page (there's nothing special about ASP.NET text box controls--they get translated to input elements when they get served). Put your cursor in that text box. If you see the same behavior, it's an accessibility setting by the browser or OS. If not, then check your code and see if you're doing some particularly nasty JavaScript that may be rather intensive. Also, try it from other browsers and see if perhaps it's just a particular browser issue.
[ "asp.net", "web-applications" ]
0
1
789
1
0
2011-06-10T17:51:10.713000
2011-06-10T18:07:15.873000
6,310,217
6,310,401
UIWIndow Not Declared iOS 4.3 AppDelegate
I just downloaded the newest iOS SDK (4.3) and noticed that when I start a Window Based Application, the UIWindow is not declared in the header file, it is only mentioned as a property. #import @interface GleekAppDelegate: NSObject { IBOutlet UILabel *label; } @property (nonatomic, retain) IBOutlet UIWindow *window; @end I would expect, and remember from older SDK's, that the above code should be #import @interface GleekAppDelegate: NSObject { IBOutlet UILabel *label; UIWindow *window; } @property (nonatomic, retain) IBOutlet UIWindow *window; @end Is that just a new feature of the SDK? Thanks
The new Objective-C runtime has the ability to synthesize ivars without explicitly declaring them. From Runtime Difference in The Objective-C Programming Language: In general the behavior of properties is identical on both modern and legacy runtimes (see “Runtime Versions and Platforms” in Objective-C Runtime Programming Guide). There is one key difference: the modern runtime supports instance variable synthesis whereas the legacy runtime does not.... With the modern runtime, if you do not provide an instance variable, the compiler adds one for you. From Runtime Versions and Platforms in Objective-C Runtime Programming Guide: Phone applications and 64-bit programs on Mac OS X v10.5 and later use the modern version of the runtime. Other programs (32-bit programs on Mac OS X desktop) use the legacy version of the runtime. Also have a look at this questions: Objective C: Why do we declare ivars in the.h member area if @property seems to do it automatically? What is the underlying mechanism for ivar synthesis in the modern Objective C runtime Automatic iVars with @synthesize
UIWIndow Not Declared iOS 4.3 AppDelegate I just downloaded the newest iOS SDK (4.3) and noticed that when I start a Window Based Application, the UIWindow is not declared in the header file, it is only mentioned as a property. #import @interface GleekAppDelegate: NSObject { IBOutlet UILabel *label; } @property (nonatomic, retain) IBOutlet UIWindow *window; @end I would expect, and remember from older SDK's, that the above code should be #import @interface GleekAppDelegate: NSObject { IBOutlet UILabel *label; UIWindow *window; } @property (nonatomic, retain) IBOutlet UIWindow *window; @end Is that just a new feature of the SDK? Thanks
TITLE: UIWIndow Not Declared iOS 4.3 AppDelegate QUESTION: I just downloaded the newest iOS SDK (4.3) and noticed that when I start a Window Based Application, the UIWindow is not declared in the header file, it is only mentioned as a property. #import @interface GleekAppDelegate: NSObject { IBOutlet UILabel *label; } @property (nonatomic, retain) IBOutlet UIWindow *window; @end I would expect, and remember from older SDK's, that the above code should be #import @interface GleekAppDelegate: NSObject { IBOutlet UILabel *label; UIWindow *window; } @property (nonatomic, retain) IBOutlet UIWindow *window; @end Is that just a new feature of the SDK? Thanks ANSWER: The new Objective-C runtime has the ability to synthesize ivars without explicitly declaring them. From Runtime Difference in The Objective-C Programming Language: In general the behavior of properties is identical on both modern and legacy runtimes (see “Runtime Versions and Platforms” in Objective-C Runtime Programming Guide). There is one key difference: the modern runtime supports instance variable synthesis whereas the legacy runtime does not.... With the modern runtime, if you do not provide an instance variable, the compiler adds one for you. From Runtime Versions and Platforms in Objective-C Runtime Programming Guide: Phone applications and 64-bit programs on Mac OS X v10.5 and later use the modern version of the runtime. Other programs (32-bit programs on Mac OS X desktop) use the legacy version of the runtime. Also have a look at this questions: Objective C: Why do we declare ivars in the.h member area if @property seems to do it automatically? What is the underlying mechanism for ivar synthesis in the modern Objective C runtime Automatic iVars with @synthesize
[ "iphone", "ios", "xcode", "ipad" ]
3
3
511
1
0
2011-06-10T17:51:14.527000
2011-06-10T18:10:47.033000
6,310,226
6,310,297
Business Case for abandoning IE7 as the *developer's* browser?
I'm a software developer. The only browser I have at work is IE7. I don't have freedom to select my browser. I am constantly learning and researching things online and, of course, IE7 is a very poor tool for doing that work. I've been invited to present a business case for replacing the dev team's IE7 browsers w/ a something more modern. I don't want browser recommendations, and this isn't about which browser the users of my software/webapps will use, but...... what behaviors/traits/sideeffects of IE7 should I highlight when making the case that it has a very real negative impact when I'm trying to do my work as a software developer? Do I talk about security vulnerabilities (on my workstation)? Do I talk about the cost of waiting for tabs to open all day? Do I talk about the memory leaks? Do I try to measure how often the browser just flat-out crashes on me? What would resonate best with the corporate decision makers?
Words that important people like to hear: Security (use open security vulnerability charts and such) Standards (talk very briefly about web standards, but then hammer in the point that IE does not follow them throughout the presentation) Productivity (here's where you get to talk about speed, additional features etc) Also make sure to talk about the minimal cost that the switch will have in terms of IT time required.
Business Case for abandoning IE7 as the *developer's* browser? I'm a software developer. The only browser I have at work is IE7. I don't have freedom to select my browser. I am constantly learning and researching things online and, of course, IE7 is a very poor tool for doing that work. I've been invited to present a business case for replacing the dev team's IE7 browsers w/ a something more modern. I don't want browser recommendations, and this isn't about which browser the users of my software/webapps will use, but...... what behaviors/traits/sideeffects of IE7 should I highlight when making the case that it has a very real negative impact when I'm trying to do my work as a software developer? Do I talk about security vulnerabilities (on my workstation)? Do I talk about the cost of waiting for tabs to open all day? Do I talk about the memory leaks? Do I try to measure how often the browser just flat-out crashes on me? What would resonate best with the corporate decision makers?
TITLE: Business Case for abandoning IE7 as the *developer's* browser? QUESTION: I'm a software developer. The only browser I have at work is IE7. I don't have freedom to select my browser. I am constantly learning and researching things online and, of course, IE7 is a very poor tool for doing that work. I've been invited to present a business case for replacing the dev team's IE7 browsers w/ a something more modern. I don't want browser recommendations, and this isn't about which browser the users of my software/webapps will use, but...... what behaviors/traits/sideeffects of IE7 should I highlight when making the case that it has a very real negative impact when I'm trying to do my work as a software developer? Do I talk about security vulnerabilities (on my workstation)? Do I talk about the cost of waiting for tabs to open all day? Do I talk about the memory leaks? Do I try to measure how often the browser just flat-out crashes on me? What would resonate best with the corporate decision makers? ANSWER: Words that important people like to hear: Security (use open security vulnerability charts and such) Standards (talk very briefly about web standards, but then hammer in the point that IE does not follow them throughout the presentation) Productivity (here's where you get to talk about speed, additional features etc) Also make sure to talk about the minimal cost that the switch will have in terms of IT time required.
[ "internet-explorer-7" ]
0
2
219
2
0
2011-06-10T17:51:48.840000
2011-06-10T17:58:22.210000
6,310,241
6,310,278
Pros and Cons of implementing a generic custom exception
What are the pros and cons of implementing a custom exception as follows: Create an enum which represents error messages in its descriptions: public class Enums { public enum Errors { [Description("This is a test exception")] TestError,... } } Create a custom exception class: public class CustomException: ApplicationException { protected Enums.Errors _customError; public CustomException(Enums.Errors customError) { this._customError = customError; } public override string Message { get { return this._customError!= Enums.Errors.Base? this.customError.GetDescription(): base.Message; } } } The GetDescription method is an enum extension method which gets the enum description using reflection. This way, I can throw exception like: throw new customException(enums.Errors.TestError); And show it to the user in catch block like: Console.WriteLn(ex.Message); I've seen this approach recommended by an MVP. What are the benefits of this approach over the followings: Using generic exception: throw new Exception("Error Message");. Using Custom Exception: Define custom exceptions for any situation. e.g. ( WebServiceException class, AuthenticationException class, etc.) Here's the link to the recommendation by the MVP. Thank you.
Personally, i don't think it's a good idea. You should always throw as specific exceptions as possible. The same goes for catching. It's easy to decide if we want to catch a WebServiceException or AuthenticationException, but with your Enum-example, we have to parse a string to decide if we want to catch it or not. What happens if this message changes? I don't think it has any benefits at all. For each error type, you have to create a new Enum member. Why not create a new class instead?
Pros and Cons of implementing a generic custom exception What are the pros and cons of implementing a custom exception as follows: Create an enum which represents error messages in its descriptions: public class Enums { public enum Errors { [Description("This is a test exception")] TestError,... } } Create a custom exception class: public class CustomException: ApplicationException { protected Enums.Errors _customError; public CustomException(Enums.Errors customError) { this._customError = customError; } public override string Message { get { return this._customError!= Enums.Errors.Base? this.customError.GetDescription(): base.Message; } } } The GetDescription method is an enum extension method which gets the enum description using reflection. This way, I can throw exception like: throw new customException(enums.Errors.TestError); And show it to the user in catch block like: Console.WriteLn(ex.Message); I've seen this approach recommended by an MVP. What are the benefits of this approach over the followings: Using generic exception: throw new Exception("Error Message");. Using Custom Exception: Define custom exceptions for any situation. e.g. ( WebServiceException class, AuthenticationException class, etc.) Here's the link to the recommendation by the MVP. Thank you.
TITLE: Pros and Cons of implementing a generic custom exception QUESTION: What are the pros and cons of implementing a custom exception as follows: Create an enum which represents error messages in its descriptions: public class Enums { public enum Errors { [Description("This is a test exception")] TestError,... } } Create a custom exception class: public class CustomException: ApplicationException { protected Enums.Errors _customError; public CustomException(Enums.Errors customError) { this._customError = customError; } public override string Message { get { return this._customError!= Enums.Errors.Base? this.customError.GetDescription(): base.Message; } } } The GetDescription method is an enum extension method which gets the enum description using reflection. This way, I can throw exception like: throw new customException(enums.Errors.TestError); And show it to the user in catch block like: Console.WriteLn(ex.Message); I've seen this approach recommended by an MVP. What are the benefits of this approach over the followings: Using generic exception: throw new Exception("Error Message");. Using Custom Exception: Define custom exceptions for any situation. e.g. ( WebServiceException class, AuthenticationException class, etc.) Here's the link to the recommendation by the MVP. Thank you. ANSWER: Personally, i don't think it's a good idea. You should always throw as specific exceptions as possible. The same goes for catching. It's easy to decide if we want to catch a WebServiceException or AuthenticationException, but with your Enum-example, we have to parse a string to decide if we want to catch it or not. What happens if this message changes? I don't think it has any benefits at all. For each error type, you have to create a new Enum member. Why not create a new class instead?
[ "c#", ".net", "exception", "custom-exceptions" ]
2
5
2,192
6
0
2011-06-10T17:52:48.753000
2011-06-10T17:56:15.690000
6,310,274
6,310,309
Smooth transition from launch image to main view
Is it possible to implement a smooth transition when the app loads, from the launch image to the first view? The default behavior is on/off, with an immediate change: the launch image appears, then it instantaneously disappears to let the main view controller take place. I'd like to implement some fading or zooming in or out. Is this possible? Thank you!
There's no framework support, but you can get that result if you do it yourself, manually. Depending on what your launch image is, and what your UI looks like, you can do it in different ways, but basically: make your first view controller load and display your default.png image in an image view when it loads up. Then animate a fade out of that image to reveal your actual UI.
Smooth transition from launch image to main view Is it possible to implement a smooth transition when the app loads, from the launch image to the first view? The default behavior is on/off, with an immediate change: the launch image appears, then it instantaneously disappears to let the main view controller take place. I'd like to implement some fading or zooming in or out. Is this possible? Thank you!
TITLE: Smooth transition from launch image to main view QUESTION: Is it possible to implement a smooth transition when the app loads, from the launch image to the first view? The default behavior is on/off, with an immediate change: the launch image appears, then it instantaneously disappears to let the main view controller take place. I'd like to implement some fading or zooming in or out. Is this possible? Thank you! ANSWER: There's no framework support, but you can get that result if you do it yourself, manually. Depending on what your launch image is, and what your UI looks like, you can do it in different ways, but basically: make your first view controller load and display your default.png image in an image view when it loads up. Then animate a fade out of that image to reveal your actual UI.
[ "iphone", "transition", "launch" ]
8
15
10,724
4
0
2011-06-10T17:56:02.060000
2011-06-10T17:59:51.540000
6,310,289
6,310,324
Ajax.ActionLink triggering from Javascript?
I am successfully using @Ajax.ActionLink to refresh data on a portion of my page, but I would like to do the same from Javascript. How can I simulate the effects of clicking that ActionLink in js? Thanks! @Ajax.ActionLink("ClickMe", "List", "Organizations", New AjaxOptions With {.UpdateTargetId = "dashboardDetails"})
You need to look at using the $.get() and.$post() jQuery functions. So basically, you can perform a call to a controller action, from Javascript, using either of these functions (depending on whether your getting or posting data). An example can be found here.
Ajax.ActionLink triggering from Javascript? I am successfully using @Ajax.ActionLink to refresh data on a portion of my page, but I would like to do the same from Javascript. How can I simulate the effects of clicking that ActionLink in js? Thanks! @Ajax.ActionLink("ClickMe", "List", "Organizations", New AjaxOptions With {.UpdateTargetId = "dashboardDetails"})
TITLE: Ajax.ActionLink triggering from Javascript? QUESTION: I am successfully using @Ajax.ActionLink to refresh data on a portion of my page, but I would like to do the same from Javascript. How can I simulate the effects of clicking that ActionLink in js? Thanks! @Ajax.ActionLink("ClickMe", "List", "Organizations", New AjaxOptions With {.UpdateTargetId = "dashboardDetails"}) ANSWER: You need to look at using the $.get() and.$post() jQuery functions. So basically, you can perform a call to a controller action, from Javascript, using either of these functions (depending on whether your getting or posting data). An example can be found here.
[ "javascript", "jquery", "ajax", "razor" ]
1
2
5,935
3
0
2011-06-10T17:57:18.913000
2011-06-10T18:01:45.843000
6,310,292
6,310,331
Most efficient way to retrieve/update an object from a collection?
I'm working with a silverlight datagrid that is bound to an observable collection of a business object. We do not support inline editing of the objects within the grid but we do display a corresponding editing panel for the user selected row. When the user submits the edits from this panel, I'm persisting the changes in the DB but I'd like the changes to also reflect in the grid. I know that through the use of the observable collection and notify property changed that if I change the object that the selected row is bound to, the changes will display in the grid. However, since I'm not inline editing, I need to search the observable collection for the object and make the change to the business object's instance in the observable collection. I'd like to avoid having to loop through the collection to find said object but I'm worried this is the only real way. There's no other more efficient, less performance-heavy way that I'm not aware of to retrieve an object from a collection correct? Other than simply to loop through until I hit it?
can you bind your edit grid to the selected item of the display grid? Since they are references this will push/pull changes into the observable collection which can then be persisted.
Most efficient way to retrieve/update an object from a collection? I'm working with a silverlight datagrid that is bound to an observable collection of a business object. We do not support inline editing of the objects within the grid but we do display a corresponding editing panel for the user selected row. When the user submits the edits from this panel, I'm persisting the changes in the DB but I'd like the changes to also reflect in the grid. I know that through the use of the observable collection and notify property changed that if I change the object that the selected row is bound to, the changes will display in the grid. However, since I'm not inline editing, I need to search the observable collection for the object and make the change to the business object's instance in the observable collection. I'd like to avoid having to loop through the collection to find said object but I'm worried this is the only real way. There's no other more efficient, less performance-heavy way that I'm not aware of to retrieve an object from a collection correct? Other than simply to loop through until I hit it?
TITLE: Most efficient way to retrieve/update an object from a collection? QUESTION: I'm working with a silverlight datagrid that is bound to an observable collection of a business object. We do not support inline editing of the objects within the grid but we do display a corresponding editing panel for the user selected row. When the user submits the edits from this panel, I'm persisting the changes in the DB but I'd like the changes to also reflect in the grid. I know that through the use of the observable collection and notify property changed that if I change the object that the selected row is bound to, the changes will display in the grid. However, since I'm not inline editing, I need to search the observable collection for the object and make the change to the business object's instance in the observable collection. I'd like to avoid having to loop through the collection to find said object but I'm worried this is the only real way. There's no other more efficient, less performance-heavy way that I'm not aware of to retrieve an object from a collection correct? Other than simply to loop through until I hit it? ANSWER: can you bind your edit grid to the selected item of the display grid? Since they are references this will push/pull changes into the observable collection which can then be persisted.
[ "c#", ".net", "collections", "iterator" ]
1
2
305
2
0
2011-06-10T17:57:57.483000
2011-06-10T18:02:21.323000
6,310,308
6,310,326
input radio button hover issues in IE 9
I'm having a problem in IE9: Whenever i hover over my top level wrapper div the first radio button acts like it's being hovered over. So even if i have the last radio input pressed, if i click anywhere within the wrapper, the radio will go back to the first one. As soon as i hover my mouse off the wrapper div the light blue color on the first radio input changes back to gray as it should be. My page works as expected in FF, Chrome and IE-Compatability mode. I tried creating a simple page with inputs and can't recreate the problem as it's happening in my large web page. Any input into what can be causing this and/or how to stop it would be greatly appreciated. Edit#1: mycode:...... SOLUTION: Somewhere inside the 'wrapper' div i had a self-closing label IE9 did not support (even though they should)
What you are describing is the behavior of the label tag. Label tags act like a hover and click target for the input with the id specified in the label's for attribute. Either you have inadvertently applied a large label to one specific radio button, or maybe one of them is incorrectly closed, causing it to wrap the whole div. Have you checked all of your label tags to make sure none are incorrectly closed? Now that you've got your problem solved, I thought I'd add a note about self-closing tags in HTML 5 here. XHTML started to tempt the world with XML strictness. Now that we are in an HTML 5 world, it's easy to believe that's still true. However, HTML 5 doesn't know what /> is. Instead, it tries to automatically close some tags for you. So in your case, it sounds like most browsers placed the implicit at the expected place, but one browser placed it way out of context. Either way, it's likely that none of them even cared about the />. Remember our old friend the Why am I not red?? HTML places the before the because block elements are not allowed inside tags. The best thing to do is just get out of the habit of using /> anywhere except elements that always have no content ( link, br, img, etc. — and even then, you probably only want to do that for code readability, since in parsing, it makes absolutely no difference). More info here: http://tiffanybbrown.com/2011/03/23/html5-does-not-allow-self-closing-tags/
input radio button hover issues in IE 9 I'm having a problem in IE9: Whenever i hover over my top level wrapper div the first radio button acts like it's being hovered over. So even if i have the last radio input pressed, if i click anywhere within the wrapper, the radio will go back to the first one. As soon as i hover my mouse off the wrapper div the light blue color on the first radio input changes back to gray as it should be. My page works as expected in FF, Chrome and IE-Compatability mode. I tried creating a simple page with inputs and can't recreate the problem as it's happening in my large web page. Any input into what can be causing this and/or how to stop it would be greatly appreciated. Edit#1: mycode:...... SOLUTION: Somewhere inside the 'wrapper' div i had a self-closing label IE9 did not support (even though they should)
TITLE: input radio button hover issues in IE 9 QUESTION: I'm having a problem in IE9: Whenever i hover over my top level wrapper div the first radio button acts like it's being hovered over. So even if i have the last radio input pressed, if i click anywhere within the wrapper, the radio will go back to the first one. As soon as i hover my mouse off the wrapper div the light blue color on the first radio input changes back to gray as it should be. My page works as expected in FF, Chrome and IE-Compatability mode. I tried creating a simple page with inputs and can't recreate the problem as it's happening in my large web page. Any input into what can be causing this and/or how to stop it would be greatly appreciated. Edit#1: mycode:...... SOLUTION: Somewhere inside the 'wrapper' div i had a self-closing label IE9 did not support (even though they should) ANSWER: What you are describing is the behavior of the label tag. Label tags act like a hover and click target for the input with the id specified in the label's for attribute. Either you have inadvertently applied a large label to one specific radio button, or maybe one of them is incorrectly closed, causing it to wrap the whole div. Have you checked all of your label tags to make sure none are incorrectly closed? Now that you've got your problem solved, I thought I'd add a note about self-closing tags in HTML 5 here. XHTML started to tempt the world with XML strictness. Now that we are in an HTML 5 world, it's easy to believe that's still true. However, HTML 5 doesn't know what /> is. Instead, it tries to automatically close some tags for you. So in your case, it sounds like most browsers placed the implicit at the expected place, but one browser placed it way out of context. Either way, it's likely that none of them even cared about the />. Remember our old friend the Why am I not red?? HTML places the before the because block elements are not allowed inside tags. The best thing to do is just get out of the habit of using /> anywhere except elements that always have no content ( link, br, img, etc. — and even then, you probably only want to do that for code readability, since in parsing, it makes absolutely no difference). More info here: http://tiffanybbrown.com/2011/03/23/html5-does-not-allow-self-closing-tags/
[ "javascript", "html", "css" ]
1
2
1,894
1
0
2011-06-10T17:59:35.160000
2011-06-10T18:01:56.053000
6,310,328
6,310,413
Real world array covariance problem
I'm trying to create an array of the class DataTableColumn, but unfortunately I'm going crazy with that. By now that's what I tried to do without any success public interface IDataTableColumn { string Expression { get; } DataTableFilterType FilterType { get; } TValue Cast(string value); } public class DataTableColumn: IDataTableColumn { public DataTableColumn(string expression, DataTableFilterType filterType = DataTableFilterType.Equal) { Expression = expression; FilterType = filterType; } public string Expression { get; private set; } public DataTableFilterType FilterType { get; private set; } public TValue Cast(string value) { return value.As (); } } My array SHOULD be like private readonly IDataTableColumn [] _columns = { new DataTableColumn ("Id"), // ERROR new DataTableColumn ("Description", DataTableFilterType.StartsWith), // SUCCESS new DataTableColumn ("Date"), // ERROR }; Actually working like that private readonly dynamic[] _columns = { new DataTableColumn ("Id"), new DataTableColumn ("Description", DataTableFilterType.StartsWith), new DataTableColumn ("Date"), }; I think that using dynamic isn't the best way to do that.. someone shed light, please! EDIT damn I forgot the error Cannot implicitly convert type DataTableColumn< int >' to 'IDataTableColumn< object >'. An explicit conversion exists (are you missing a cast?) Cannot implicitly convert type DataTableColumn< System.DateTime? >' to 'IDataTableColumn< object >'. An explicit conversion exists (are you missing a cast?)
I believe it is because int and DateTime are value types which are not covariant with object (they require boxing). I receive the following error when I compile your code: covar.cs(23,13): error CS0266: Cannot implicitly convert type 'DataTableColumn ' to 'IDataTableColumn '. An explicit conversion exists (are you missing a cast?) Per MSDN, "Variance in Generic Interfaces (C# and Visual Basic)": Variance in generic interfaces is supported for reference types only. Value types do not support variance. For example, IEnumerable ( IEnumerable(Of Integer) in Visual Basic) cannot be implicitly converted to IEnumerable ( IEnumerable(Of Object) in Visual Basic), because integers are represented by a value type. DataTableColumn works because it derives directly from object.
Real world array covariance problem I'm trying to create an array of the class DataTableColumn, but unfortunately I'm going crazy with that. By now that's what I tried to do without any success public interface IDataTableColumn { string Expression { get; } DataTableFilterType FilterType { get; } TValue Cast(string value); } public class DataTableColumn: IDataTableColumn { public DataTableColumn(string expression, DataTableFilterType filterType = DataTableFilterType.Equal) { Expression = expression; FilterType = filterType; } public string Expression { get; private set; } public DataTableFilterType FilterType { get; private set; } public TValue Cast(string value) { return value.As (); } } My array SHOULD be like private readonly IDataTableColumn [] _columns = { new DataTableColumn ("Id"), // ERROR new DataTableColumn ("Description", DataTableFilterType.StartsWith), // SUCCESS new DataTableColumn ("Date"), // ERROR }; Actually working like that private readonly dynamic[] _columns = { new DataTableColumn ("Id"), new DataTableColumn ("Description", DataTableFilterType.StartsWith), new DataTableColumn ("Date"), }; I think that using dynamic isn't the best way to do that.. someone shed light, please! EDIT damn I forgot the error Cannot implicitly convert type DataTableColumn< int >' to 'IDataTableColumn< object >'. An explicit conversion exists (are you missing a cast?) Cannot implicitly convert type DataTableColumn< System.DateTime? >' to 'IDataTableColumn< object >'. An explicit conversion exists (are you missing a cast?)
TITLE: Real world array covariance problem QUESTION: I'm trying to create an array of the class DataTableColumn, but unfortunately I'm going crazy with that. By now that's what I tried to do without any success public interface IDataTableColumn { string Expression { get; } DataTableFilterType FilterType { get; } TValue Cast(string value); } public class DataTableColumn: IDataTableColumn { public DataTableColumn(string expression, DataTableFilterType filterType = DataTableFilterType.Equal) { Expression = expression; FilterType = filterType; } public string Expression { get; private set; } public DataTableFilterType FilterType { get; private set; } public TValue Cast(string value) { return value.As (); } } My array SHOULD be like private readonly IDataTableColumn [] _columns = { new DataTableColumn ("Id"), // ERROR new DataTableColumn ("Description", DataTableFilterType.StartsWith), // SUCCESS new DataTableColumn ("Date"), // ERROR }; Actually working like that private readonly dynamic[] _columns = { new DataTableColumn ("Id"), new DataTableColumn ("Description", DataTableFilterType.StartsWith), new DataTableColumn ("Date"), }; I think that using dynamic isn't the best way to do that.. someone shed light, please! EDIT damn I forgot the error Cannot implicitly convert type DataTableColumn< int >' to 'IDataTableColumn< object >'. An explicit conversion exists (are you missing a cast?) Cannot implicitly convert type DataTableColumn< System.DateTime? >' to 'IDataTableColumn< object >'. An explicit conversion exists (are you missing a cast?) ANSWER: I believe it is because int and DateTime are value types which are not covariant with object (they require boxing). I receive the following error when I compile your code: covar.cs(23,13): error CS0266: Cannot implicitly convert type 'DataTableColumn ' to 'IDataTableColumn '. An explicit conversion exists (are you missing a cast?) Per MSDN, "Variance in Generic Interfaces (C# and Visual Basic)": Variance in generic interfaces is supported for reference types only. Value types do not support variance. For example, IEnumerable ( IEnumerable(Of Integer) in Visual Basic) cannot be implicitly converted to IEnumerable ( IEnumerable(Of Object) in Visual Basic), because integers are represented by a value type. DataTableColumn works because it derives directly from object.
[ "c#", "c#-4.0", "covariance", "contravariance" ]
2
4
368
1
0
2011-06-10T18:01:58.997000
2011-06-10T18:11:53.923000
6,310,329
6,310,363
How can I div two columns that are summed in a select statement?
This statement below gets me some data I need. select TankName, COUNT(*) as Tanks, sum(Battles) as Battles, SUM(victories) as Victories from MemberTanks where Tier = 9 and Class = 'Medium' group by TankName order by Tanks desc I would like to show the percentage of the Victories in the resultset but I'm not sure how to do it. I tried... select TankName, COUNT(*) as Tanks, sum(Battles) as Battles, SUM(victories) as Victories, SUM(Victories)/SUM(Battles) as Percentage from MemberTanks where Tier = 9 and Class = 'Medium' group by TankName order by Tanks desc... but percentage came back as "0" for every row. How can I best get this value?
When you are calculating the percentage column since SUM(X) is returning a INT value, the result is getting floored and hence returning 0 as floored result Multiply the SUM(victories) with a decimal value like 1.0 (so as to convert one operand to decimal/numeric) and then you would get correct result. Try this: SELECT TankName, COUNT(*) as Tanks, SUM(Battles) as Battles, SUM(victories) as Victories, SUM(victories) * 1.0/ SUM(Battles) AS Percentage FROM MemberTanks WHERE Tier = 9 AND Class = 'Medium' GROUP BY TankName ORDER BY Tanks desc Also, if you are using SQL Server 2005 or above you can reduce the calculations.computations using a CTE like below: WITH qry AS ( SELECT TankName, COUNT(*) as Tanks, SUM(Battles) as Battles, SUM(victories) as Victories FROM MemberTanks WHERE Tier = 9 AND Class = 'Medium' GROUP BY TankName ) SELECT a.*, Victories * 1.0 / Battles AS Percentage FROM qry a ORDER BY Tanks DESC
How can I div two columns that are summed in a select statement? This statement below gets me some data I need. select TankName, COUNT(*) as Tanks, sum(Battles) as Battles, SUM(victories) as Victories from MemberTanks where Tier = 9 and Class = 'Medium' group by TankName order by Tanks desc I would like to show the percentage of the Victories in the resultset but I'm not sure how to do it. I tried... select TankName, COUNT(*) as Tanks, sum(Battles) as Battles, SUM(victories) as Victories, SUM(Victories)/SUM(Battles) as Percentage from MemberTanks where Tier = 9 and Class = 'Medium' group by TankName order by Tanks desc... but percentage came back as "0" for every row. How can I best get this value?
TITLE: How can I div two columns that are summed in a select statement? QUESTION: This statement below gets me some data I need. select TankName, COUNT(*) as Tanks, sum(Battles) as Battles, SUM(victories) as Victories from MemberTanks where Tier = 9 and Class = 'Medium' group by TankName order by Tanks desc I would like to show the percentage of the Victories in the resultset but I'm not sure how to do it. I tried... select TankName, COUNT(*) as Tanks, sum(Battles) as Battles, SUM(victories) as Victories, SUM(Victories)/SUM(Battles) as Percentage from MemberTanks where Tier = 9 and Class = 'Medium' group by TankName order by Tanks desc... but percentage came back as "0" for every row. How can I best get this value? ANSWER: When you are calculating the percentage column since SUM(X) is returning a INT value, the result is getting floored and hence returning 0 as floored result Multiply the SUM(victories) with a decimal value like 1.0 (so as to convert one operand to decimal/numeric) and then you would get correct result. Try this: SELECT TankName, COUNT(*) as Tanks, SUM(Battles) as Battles, SUM(victories) as Victories, SUM(victories) * 1.0/ SUM(Battles) AS Percentage FROM MemberTanks WHERE Tier = 9 AND Class = 'Medium' GROUP BY TankName ORDER BY Tanks desc Also, if you are using SQL Server 2005 or above you can reduce the calculations.computations using a CTE like below: WITH qry AS ( SELECT TankName, COUNT(*) as Tanks, SUM(Battles) as Battles, SUM(victories) as Victories FROM MemberTanks WHERE Tier = 9 AND Class = 'Medium' GROUP BY TankName ) SELECT a.*, Victories * 1.0 / Battles AS Percentage FROM qry a ORDER BY Tanks DESC
[ "sql" ]
0
4
289
2
0
2011-06-10T18:02:02.947000
2011-06-10T18:06:25.237000
6,310,338
6,310,439
regex for mysql query?
say, I have a varchar(18) field(name:firmware) in a mysql database table. The string format is like: ABC100-DE-3.10-0347, or it might looks like ABC100-DE-3.1-347. Basically, the only thing I can rely on is the "-" delimiter, the last part( 0347,347 ) is called build number. The 3.1/3.10 part is called version number. Is it possible to only select the build number and version number out from this field? I suspect this query might turn help to regex, since string functions won't do the job. Thanks!
Give this a shot: select SUBSTRING_INDEX(theField,'-',-1) as buildNumber, SUBSTRING_INDEX(SUBSTRING_INDEX(theField,'-',-2),'-',1) as versionNumber from theTable
regex for mysql query? say, I have a varchar(18) field(name:firmware) in a mysql database table. The string format is like: ABC100-DE-3.10-0347, or it might looks like ABC100-DE-3.1-347. Basically, the only thing I can rely on is the "-" delimiter, the last part( 0347,347 ) is called build number. The 3.1/3.10 part is called version number. Is it possible to only select the build number and version number out from this field? I suspect this query might turn help to regex, since string functions won't do the job. Thanks!
TITLE: regex for mysql query? QUESTION: say, I have a varchar(18) field(name:firmware) in a mysql database table. The string format is like: ABC100-DE-3.10-0347, or it might looks like ABC100-DE-3.1-347. Basically, the only thing I can rely on is the "-" delimiter, the last part( 0347,347 ) is called build number. The 3.1/3.10 part is called version number. Is it possible to only select the build number and version number out from this field? I suspect this query might turn help to regex, since string functions won't do the job. Thanks! ANSWER: Give this a shot: select SUBSTRING_INDEX(theField,'-',-1) as buildNumber, SUBSTRING_INDEX(SUBSTRING_INDEX(theField,'-',-2),'-',1) as versionNumber from theTable
[ "mysql", "regex", "string" ]
0
2
472
3
0
2011-06-10T18:02:53.597000
2011-06-10T18:14:18.623000
6,310,343
6,310,428
Why is before_save not getting called for my ActiveRecord model?
Nothing prints out to the console when I use IRB to create a new model instance and save, and I get a "ActiveRecord::StatementInvalid: Mysql::Error: Column 'user_id' cannot be null" error, so I assume before_save is not getting called. I can't figure out why. I've even tried using the before_save filter. Here's my code: require 'secure_resource/secure_resource_encryption' class Database < ActiveRecord::Base belongs_to:username_encryption,:class_name => "Encryption",:foreign_key =>:username_encryption_id belongs_to:password_encryption,:class_name => "Encryption",:foreign_key =>:password_encryption_id # Virtual attribute to retrieve the decrypted username. def username if self.username_encryption.nil? return nil end begin return self.username_encryption.encryption rescue SecureResourceError raise SecureResourceError end end # Provides a way to reset the username. def username=(username) if self.username_encryption.nil? self.username_encryption = Encryption.new self.username_encryption.encryption = username end end # Virtual attribute to retrieve the decrypted password. def password if password_encryption.nil? return nil end begin return password_encryption.encryption rescue SecureResourceError raise SecureResourceError end end # Provides a way to reset the password. def password=(password) if self.password_encryption.nil? self.password_encryption = Encryption.new self.password_encryption.encryption = password end end def before_save p 'ZZZZZZZZZZZZZZZ' p self.user_id.to_s + ' ZZZZZZ' p 'ZZZZZZZZZZZZZZZ' self.username_encryption.user_id = self.user_id self.username_encryption.save self.username_encryption_id = self.username_encryption.id self.password_encryption.user_id = self.user_id self.password_encryption.save self.password_encryption_id = self.password_encryption.id end end
As you can see in the documentation, before_save happens after validation. In your case, validation will fail and before_save will never be invoked. Since the goal of your callback is to set your object to a valid state before validation happens, try the before_validation callback.
Why is before_save not getting called for my ActiveRecord model? Nothing prints out to the console when I use IRB to create a new model instance and save, and I get a "ActiveRecord::StatementInvalid: Mysql::Error: Column 'user_id' cannot be null" error, so I assume before_save is not getting called. I can't figure out why. I've even tried using the before_save filter. Here's my code: require 'secure_resource/secure_resource_encryption' class Database < ActiveRecord::Base belongs_to:username_encryption,:class_name => "Encryption",:foreign_key =>:username_encryption_id belongs_to:password_encryption,:class_name => "Encryption",:foreign_key =>:password_encryption_id # Virtual attribute to retrieve the decrypted username. def username if self.username_encryption.nil? return nil end begin return self.username_encryption.encryption rescue SecureResourceError raise SecureResourceError end end # Provides a way to reset the username. def username=(username) if self.username_encryption.nil? self.username_encryption = Encryption.new self.username_encryption.encryption = username end end # Virtual attribute to retrieve the decrypted password. def password if password_encryption.nil? return nil end begin return password_encryption.encryption rescue SecureResourceError raise SecureResourceError end end # Provides a way to reset the password. def password=(password) if self.password_encryption.nil? self.password_encryption = Encryption.new self.password_encryption.encryption = password end end def before_save p 'ZZZZZZZZZZZZZZZ' p self.user_id.to_s + ' ZZZZZZ' p 'ZZZZZZZZZZZZZZZ' self.username_encryption.user_id = self.user_id self.username_encryption.save self.username_encryption_id = self.username_encryption.id self.password_encryption.user_id = self.user_id self.password_encryption.save self.password_encryption_id = self.password_encryption.id end end
TITLE: Why is before_save not getting called for my ActiveRecord model? QUESTION: Nothing prints out to the console when I use IRB to create a new model instance and save, and I get a "ActiveRecord::StatementInvalid: Mysql::Error: Column 'user_id' cannot be null" error, so I assume before_save is not getting called. I can't figure out why. I've even tried using the before_save filter. Here's my code: require 'secure_resource/secure_resource_encryption' class Database < ActiveRecord::Base belongs_to:username_encryption,:class_name => "Encryption",:foreign_key =>:username_encryption_id belongs_to:password_encryption,:class_name => "Encryption",:foreign_key =>:password_encryption_id # Virtual attribute to retrieve the decrypted username. def username if self.username_encryption.nil? return nil end begin return self.username_encryption.encryption rescue SecureResourceError raise SecureResourceError end end # Provides a way to reset the username. def username=(username) if self.username_encryption.nil? self.username_encryption = Encryption.new self.username_encryption.encryption = username end end # Virtual attribute to retrieve the decrypted password. def password if password_encryption.nil? return nil end begin return password_encryption.encryption rescue SecureResourceError raise SecureResourceError end end # Provides a way to reset the password. def password=(password) if self.password_encryption.nil? self.password_encryption = Encryption.new self.password_encryption.encryption = password end end def before_save p 'ZZZZZZZZZZZZZZZ' p self.user_id.to_s + ' ZZZZZZ' p 'ZZZZZZZZZZZZZZZ' self.username_encryption.user_id = self.user_id self.username_encryption.save self.username_encryption_id = self.username_encryption.id self.password_encryption.user_id = self.user_id self.password_encryption.save self.password_encryption_id = self.password_encryption.id end end ANSWER: As you can see in the documentation, before_save happens after validation. In your case, validation will fail and before_save will never be invoked. Since the goal of your callback is to set your object to a valid state before validation happens, try the before_validation callback.
[ "ruby-on-rails", "validation", "activerecord", "callback" ]
11
42
11,028
1
0
2011-06-10T18:03:17.357000
2011-06-10T18:13:33.087000
6,310,344
6,310,356
HttpContext.Current.Server.MapPath alternative in windows application
what is alternative of "HttpContext.Current.Server.MapPath" in Windows application, which is used in web application. What should I use in windows application to access a file. [EDIT] What is alternate of this in window application? reader = XmlReader.Create( @"D:\EnviroTrack\EnviroTracker.Web\TestDevice\Data.xml", settings); Please suggest
You can use the normal Path methods. MapPath helps convert the virtual path to the physical path on the web server. There's no need for this conversion in winforms. You may be looking for Assembly.GetExecutingAssembly().Location which returns the location of the assembly being executed. Edit - Your updated question should work on in a Winform. XmlReader.Create has quite a few overloads, one of them is (string, XmlReaderSettings). This is the overload you're using in your question. You can use the same method, but different directory if you like. reader = XmlReader.Create(@"C:\Data.xml", settings); To get the directory of the executing assembly, you can use AppDomain.CurrentDomain.BaseDirectory. So it could be something like this: reader = XmlReader.Create(AppDomain.CurrentDomain.BaseDirectory + "Data.xml", settings);
HttpContext.Current.Server.MapPath alternative in windows application what is alternative of "HttpContext.Current.Server.MapPath" in Windows application, which is used in web application. What should I use in windows application to access a file. [EDIT] What is alternate of this in window application? reader = XmlReader.Create( @"D:\EnviroTrack\EnviroTracker.Web\TestDevice\Data.xml", settings); Please suggest
TITLE: HttpContext.Current.Server.MapPath alternative in windows application QUESTION: what is alternative of "HttpContext.Current.Server.MapPath" in Windows application, which is used in web application. What should I use in windows application to access a file. [EDIT] What is alternate of this in window application? reader = XmlReader.Create( @"D:\EnviroTrack\EnviroTracker.Web\TestDevice\Data.xml", settings); Please suggest ANSWER: You can use the normal Path methods. MapPath helps convert the virtual path to the physical path on the web server. There's no need for this conversion in winforms. You may be looking for Assembly.GetExecutingAssembly().Location which returns the location of the assembly being executed. Edit - Your updated question should work on in a Winform. XmlReader.Create has quite a few overloads, one of them is (string, XmlReaderSettings). This is the overload you're using in your question. You can use the same method, but different directory if you like. reader = XmlReader.Create(@"C:\Data.xml", settings); To get the directory of the executing assembly, you can use AppDomain.CurrentDomain.BaseDirectory. So it could be something like this: reader = XmlReader.Create(AppDomain.CurrentDomain.BaseDirectory + "Data.xml", settings);
[ "asp.net", "c#-4.0" ]
2
3
9,504
2
0
2011-06-10T18:03:18.257000
2011-06-10T18:05:45.513000
6,310,357
6,310,395
Store multiple sizes of an image or just store the main and resize?
I'm working on a CMS and I'm trying to figure out the common practice for doing a REST style image request. I have three sizes, small, medium, and full. My thought is to store only the full and write a function that will resize on each page request. This has obvious cpu costs. The other end is that I could store all three sizes and only calculate on upload, this seems to waste space. My environment is an intranet, so relatively low requests and a high number of images stored. Thoughts? Note: I realize I don't have to really worry too much since it's intranet and either solution will work, just wondering which would be preferred for knowledge sake.
Another option is to maintain a cache of resized images. Serve up the ones that are available. Create new ones if they are not available. Delete images that have not been requested for a while. This will be a compromise between the CPU and storage issues.
Store multiple sizes of an image or just store the main and resize? I'm working on a CMS and I'm trying to figure out the common practice for doing a REST style image request. I have three sizes, small, medium, and full. My thought is to store only the full and write a function that will resize on each page request. This has obvious cpu costs. The other end is that I could store all three sizes and only calculate on upload, this seems to waste space. My environment is an intranet, so relatively low requests and a high number of images stored. Thoughts? Note: I realize I don't have to really worry too much since it's intranet and either solution will work, just wondering which would be preferred for knowledge sake.
TITLE: Store multiple sizes of an image or just store the main and resize? QUESTION: I'm working on a CMS and I'm trying to figure out the common practice for doing a REST style image request. I have three sizes, small, medium, and full. My thought is to store only the full and write a function that will resize on each page request. This has obvious cpu costs. The other end is that I could store all three sizes and only calculate on upload, this seems to waste space. My environment is an intranet, so relatively low requests and a high number of images stored. Thoughts? Note: I realize I don't have to really worry too much since it's intranet and either solution will work, just wondering which would be preferred for knowledge sake. ANSWER: Another option is to maintain a cache of resized images. Serve up the ones that are available. Create new ones if they are not available. Delete images that have not been requested for a while. This will be a compromise between the CPU and storage issues.
[ "c#", "asp.net-mvc-3", "content-management-system", "storage" ]
3
3
242
6
0
2011-06-10T18:05:46.073000
2011-06-10T18:10:18.010000
6,310,394
6,310,422
Css for Blackberry only?
I doubt this exists, but is there a way to make a css file only be read if it is a blackberry phone (lower then V6 is preferred, but if not that's ok) I am using JQuery mobile so the css is perfect for everything else, I just wanna edit Blackberry
You could check the browser name, in javascript, and make your css file as required. Conditional CSS for Backberry. function getcss(cssfile){ loadcss = document.createElement('link') loadcss.setAttribute("rel", "stylesheet") loadcss.setAttribute("type", "text/css") loadcss.setAttribute("href", cssfile) document.getElementsByTagName("head")[0].appendChild(loadcss) } if(navigator.appName == 'option1')//or navigator.userAgent { getcss('css/common_css_hd.css') } else { getcss('css/common_css.css') }// JavaScript Document
Css for Blackberry only? I doubt this exists, but is there a way to make a css file only be read if it is a blackberry phone (lower then V6 is preferred, but if not that's ok) I am using JQuery mobile so the css is perfect for everything else, I just wanna edit Blackberry
TITLE: Css for Blackberry only? QUESTION: I doubt this exists, but is there a way to make a css file only be read if it is a blackberry phone (lower then V6 is preferred, but if not that's ok) I am using JQuery mobile so the css is perfect for everything else, I just wanna edit Blackberry ANSWER: You could check the browser name, in javascript, and make your css file as required. Conditional CSS for Backberry. function getcss(cssfile){ loadcss = document.createElement('link') loadcss.setAttribute("rel", "stylesheet") loadcss.setAttribute("type", "text/css") loadcss.setAttribute("href", cssfile) document.getElementsByTagName("head")[0].appendChild(loadcss) } if(navigator.appName == 'option1')//or navigator.userAgent { getcss('css/common_css_hd.css') } else { getcss('css/common_css.css') }// JavaScript Document
[ "css", "blackberry" ]
0
3
1,338
1
0
2011-06-10T18:09:59.697000
2011-06-10T18:13:02.273000
6,310,411
6,310,429
using 'global' in php
I'm in learning mode here, very new to PHP, so I'm working with a code sample. Please forgive my use of 'global' here, but I want to understand php variable scoping. Here is myGlobals.php: Here is connectToDb.php: Here is addDbRecords.php: Here is index.php: Here is the problem. When I call doAddDeleteRecord($db_server) inside the file addDbRecords.php above, $db_server is not valid -- it is null -- when I call mysql_query(.., $db_server,...) -- this is the error message: "Warning: mysql_query() expects parameter 2 to be resource, null given in C:\xampp\htdocs\addDbRecords.php on line 29" So I tried using the 'global' declaration inside doAddDeleteRecord() (commented out above) -- no change. The mysql_query(...) still fails with a NULL value for $db_server. I know the mysql_connect(....) works because other code pulls all my records out of my database successfully (using a SELECT) and the existing records get displayed correctly in the browser. So in my opinion, the fact that $db_server is declared with 'global' should mean that the scope of $db_server is such that once mysql_connect(...) is called -- at file scope in all my files, $db_server will be a valid connection to my database. I'm only trying to learn about php scoping, not OOAD or anything else (for now). Why is $db_server() null here?
So, you have: and you include this where needed: require_once 'myGlobals.php'; // other inline code..... doAddDeleteRecord($db_server); The problem is that if you already included 'myGlobals.php' elsewhere, it won't be included here. So you can't guarantee that the global will be brought into scope. Instead, write: require 'myGlobals.php'; // other inline code..... doAddDeleteRecord($db_server); Or take the much better approach of just: // other inline code..... doAddDeleteRecord($GLOBALS['db_server']);
using 'global' in php I'm in learning mode here, very new to PHP, so I'm working with a code sample. Please forgive my use of 'global' here, but I want to understand php variable scoping. Here is myGlobals.php: Here is connectToDb.php: Here is addDbRecords.php: Here is index.php: Here is the problem. When I call doAddDeleteRecord($db_server) inside the file addDbRecords.php above, $db_server is not valid -- it is null -- when I call mysql_query(.., $db_server,...) -- this is the error message: "Warning: mysql_query() expects parameter 2 to be resource, null given in C:\xampp\htdocs\addDbRecords.php on line 29" So I tried using the 'global' declaration inside doAddDeleteRecord() (commented out above) -- no change. The mysql_query(...) still fails with a NULL value for $db_server. I know the mysql_connect(....) works because other code pulls all my records out of my database successfully (using a SELECT) and the existing records get displayed correctly in the browser. So in my opinion, the fact that $db_server is declared with 'global' should mean that the scope of $db_server is such that once mysql_connect(...) is called -- at file scope in all my files, $db_server will be a valid connection to my database. I'm only trying to learn about php scoping, not OOAD or anything else (for now). Why is $db_server() null here?
TITLE: using 'global' in php QUESTION: I'm in learning mode here, very new to PHP, so I'm working with a code sample. Please forgive my use of 'global' here, but I want to understand php variable scoping. Here is myGlobals.php: Here is connectToDb.php: Here is addDbRecords.php: Here is index.php: Here is the problem. When I call doAddDeleteRecord($db_server) inside the file addDbRecords.php above, $db_server is not valid -- it is null -- when I call mysql_query(.., $db_server,...) -- this is the error message: "Warning: mysql_query() expects parameter 2 to be resource, null given in C:\xampp\htdocs\addDbRecords.php on line 29" So I tried using the 'global' declaration inside doAddDeleteRecord() (commented out above) -- no change. The mysql_query(...) still fails with a NULL value for $db_server. I know the mysql_connect(....) works because other code pulls all my records out of my database successfully (using a SELECT) and the existing records get displayed correctly in the browser. So in my opinion, the fact that $db_server is declared with 'global' should mean that the scope of $db_server is such that once mysql_connect(...) is called -- at file scope in all my files, $db_server will be a valid connection to my database. I'm only trying to learn about php scoping, not OOAD or anything else (for now). Why is $db_server() null here? ANSWER: So, you have: and you include this where needed: require_once 'myGlobals.php'; // other inline code..... doAddDeleteRecord($db_server); The problem is that if you already included 'myGlobals.php' elsewhere, it won't be included here. So you can't guarantee that the global will be brought into scope. Instead, write: require 'myGlobals.php'; // other inline code..... doAddDeleteRecord($db_server); Or take the much better approach of just: // other inline code..... doAddDeleteRecord($GLOBALS['db_server']);
[ "php", "global", "scoping" ]
4
5
491
2
0
2011-06-10T18:11:33.313000
2011-06-10T18:13:36.970000
6,310,415
6,310,436
Java: Store variables in file
I know how to write text to a file and store it in Java, but I was wondering if there is a way of storing lots of variables that can be retrieved from the file at a later date, and put back into the Java application as variables. I would be storing numbers and strings, but groups of them. Thanks:)
Java can read properties files like it reads a map. This gives you an easy way of storing information using a key/value system. Check out http://download.oracle.com/javase/6/docs/api/java/util/Properties.html
Java: Store variables in file I know how to write text to a file and store it in Java, but I was wondering if there is a way of storing lots of variables that can be retrieved from the file at a later date, and put back into the Java application as variables. I would be storing numbers and strings, but groups of them. Thanks:)
TITLE: Java: Store variables in file QUESTION: I know how to write text to a file and store it in Java, but I was wondering if there is a way of storing lots of variables that can be retrieved from the file at a later date, and put back into the Java application as variables. I would be storing numbers and strings, but groups of them. Thanks:) ANSWER: Java can read properties files like it reads a map. This gives you an easy way of storing information using a key/value system. Check out http://download.oracle.com/javase/6/docs/api/java/util/Properties.html
[ "java", "file" ]
9
14
17,700
3
0
2011-06-10T18:12:19.570000
2011-06-10T18:14:08.637000