text
stringlengths
8
267k
meta
dict
Q: Boost.Assign: using objects with map_list_of? Using C++ with boost. In Boost.Assign can I use the new operator with map_list_of? For example: std::map<int, MyObject*> objects = boost::assign::map_list_of (1, new MyObject())(2, new MyObject())(3, new MyObject()) If not, is there another way to do it? A: It does work, yes; calling new just returns a pointer to MyObject, and it can be used anywhere that type is valid. HOWEVER the call to new might throw an exception, or MyObject's constructor might throw an exception, meaning your whole map of heap-allocated MyObjects will be leaked. If you want exception safety as well as not having to bother deleting those objects, you should use a smart pointer instead: std::map<int, boost::shared_ptr<MyObject> > objects = boost::assign::map_list_of<int, boost::shared_ptr<MyObject> > (1, new MyObject()) (2, new MyObject()) (3, new MyObject()); A: Seems yes. This compiles fine with VS2010 & boost 1.47. #include <boost\assign.hpp> class MyObject{ public: MyObject(int i):m_i(i){} private: int m_i; }; int main (void) { std::map<int, MyObject*> objects = boost::assign::map_list_of(1, new MyObject(1))(2, new MyObject(2))(3, new MyObject(3)); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7531878", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Sorting and manipulating a hash in Ruby In my rails 3.1 project I have a Book model that has a ID, NAME, and BOOK_ORDER. I am using the ranked-model gem, which for its sorting process creates large numbers in the sorting(:book_order) column. Im looking for some help to create a method to sort all of the Books by the :book_order column, then simplify the :book_order numbers. So, I have this: controller @books = Books.all view <% @books.each do |book| %> <%= book.book_order %> <% end %> # book1.book_order => 1231654 # book2.book_order => 9255654 # book3.book_order => 1654 But want this: view <% @books.each do |book| %> <%= book.clean_book_order %> <% end %> # book1.clean_book_order => 2 # book2.clean_book_order => 3 # book3.clean_book_order => 1 Additionally, i don’t want to change the database entry, just use its current values to make simpler ones. Thanks! UPDATE: Thanks to nash’s response I was able to find a solution: In my Book Model I added the clean_book_order method: class Book < ActiveRecord::Base include RankedModel ranks :book_order def clean_book_order self.class.where("book_order < ?", book_order).count + 1 end end A: <% @books.each do |book| %> <%= book.book_order_position %> <% end %> EDIT: Oh, I see. https://github.com/harvesthq/ranked-model/issues/10
{ "language": "en", "url": "https://stackoverflow.com/questions/7531880", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: No gcc 4.2 compiler option in Xcode 4? In my Xcode 4 installation, I only have 2 compiler options: * *Apple LLVM compiler 3.0 *GCC LLVM 4.2 In many Xcode examples I have seen that GCC 4.2 is shown as a third option, but this simply isn't there. I intentionally did a clean installation of XCode 4. Is there a standard method for adding GCC 4.2 if it's not already there? One of my projects requires that I use GCC (and not GCC LLVM), the other projects I am happy with GCC LLVM, so it's only an issue for that one. A: Here is a way to enable compiling with gcc 4.2 in xcode 4.2. This is mostly done via command line so when you see lines starting with: [ 15:30 jon@MacBookPro / ]$, you need to open up Terminal.app and run the command that starts after the $. No files or directories are removed or deleted in this process, so it is easy to undo if you need to compile with LLVM in the future. * *Download - but do not install yet - xcode_4.1_for_lion.dmg or xcode_4.1_for_snow_leopard.dmg *Now, follow these steps to install Xcode 4.1 into /Developer-4.1: * *Backup the working /Developer directory (where Xcode 4.2 is installed) [ 15:30 jon@MacBookPro / ]$ sudo mv -v /Developer /Developer-4.2 *Run the Xcode 4.1 installer using the default install location (/Developer) *Move the new Xcode 4.1 installation to /Developer-4.1: [ 15:30 jon@MacBookPro / ]$ sudo mv -v /Developer /Developer-4.1 *Move the Xcode 4.2 developer directory back to /Developer: [ 15:30 jon@MacBookPro / ]$ sudo mv -v /Developer-4.2 /Developer *Edit the Xcode 4.2 GCC 4.2.xcspec file to get gcc 4.2 to show in the list of compiler options [1]: [ 15:30 jon@MacBookPro / ]$ sudo vi "/Developer/Library/Xcode/PrivatePlugIns/Xcode3Core.ideplugin/Contents/SharedSupport/Developer/Library/Xcode/Plug-ins/GCC 4.2 (Plausible Blocks).xcplugin/Contents/Resources/GCC 4.2.xcspec" * *Change lines 41 and 42 from this: ShowInCompilerSelectionPopup = NO; IsNoLongerSupported = YES; *To This: ShowInCompilerSelectionPopup = YES; IsNoLongerSupported = NO; *Backup the Xcode 4.2 iOS/Simulator Framework usr directories: [ 15:30 jon@MacBookPro / ]$ sudo mv -v /Developer/Platforms/iPhoneOS.platform/Developer/usr /Developer/Platforms/iPhoneOS.platform/Developer/usr.backup [ 15:30 jon@MacBookPro / ]$ sudo mv -v /Developer/Platforms/iPhoneSimulator.platform/Developer/usr /Developer/Platforms/iPhoneSimulator.platform/Developer/usr.backup *Copy Xcode 4.1 iOS/Simulator Framework usr directories to Xcode 4.2: [ 15:30 jon@MacBookPro / ]$ sudo cp -rv /Developer-4.1/Platforms/iPhoneOS.platform/Developer/usr /Developer/Platforms/iPhoneOS.platform/Developer/usr [ 15:30 jon@MacBookPro / ]$ sudo cp -rv /Developer-4.1/usr /Developer/Platforms/iPhoneSimulator.platform/Developer/usr *Copy the gcc and info iOS SDK library directories from Xcode 4.1 to Xcode 4.2 [2]: [ 15:30 jon@MacBookPro / ]$ sudo cp -rv /Developer-4.1/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.3.sdk/usr/lib/gcc /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.0.sdk/usr/lib/gcc [ 15:30 jon@MacBookPro / ]$ sudo cp -rv /Developer-4.1/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.3.sdk/usr/lib/info /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.0.sdk/usr/lib/info *Compile using gcc-4.2! This is a blog post I've written with a little more info about this process. Feel free to leave a comment on the blog if you run into any issues or have any questions. [1] If opening from a command line (using something like vi, emacs, nano, etc) make sure to either enclose the path in quotes "/long path/with spaces/in it/file.xcspec" or escape the spaces /some/long\ path/with\ spaces/in\ it/file.xcspec [2] This is necessary because the iPhoneOS.platform SDK has its own seperate /usr/lib directories but the iPhoneSimulator.platform SDK does not A: Xcode 4.3 has a specific folder /Applications/Xcode.app/Contents/Developer/Toolchains. Is there a way to add other tool-chains as AVR-gcc and PIC32-gcc?
{ "language": "en", "url": "https://stackoverflow.com/questions/7531881", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: What is the fastest way to find a file in a directory tree I have a directory tree similar to the one below. It contains around 30,000 files in total. rootDir rootDir\subDir1 rootDir\subDir1\subSubDir1 rootDir\subDir1\subSubDir2 rootDir\subDir2 rootDir\subDir2\subSubDir1 rootDir\subDir3 ... rootDir\subDirN What is the fastest way to find a file from a directory structure such as the one above based on it's name using C++ on Windows? A: If you do have Windows Desktop Search or Windows Search operating (or the target computer might have it, anyway), you can use ISearchFolderItemFactory (or ISearchDesktop, for WDS) to have it do a search for you. If there's no pre-existing index, nearly the only way to do this is with FirstFirstFile, FindnextFile and FindClose. I generally recommend against the obvious recursive method of doing the search though -- a breadth-first search is usually at least as fast, and depending on the situation, can easily be twice as fast. To do a breadth-first search, you maintain a collection (I usually use a priority queue, but a normal queue, stack, etc., will also work) of sub-directories you haven't searched yet. You start a search by entering the starting directory into the collection, and then having your search function do it's thing. Your search runs in a loop, continuing searching until the collection is empty. When it encounters a directory, it adds it to the collection. A: Perhaps not the answer you're looking for, but having an index of available files in the file system optimized for the search patterns you support would be fastest. If you're using some API to do it, it simply depends on how well you write code, profile and improve it. :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7531882", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: User interface is not visible when the app runs (only in interface builder) I'm stuck on a very stupid issue. I've built my mac osx app user interface with Interface Builder (and xcode3). Now when I run my app I can't see the app window (but only the menu on top). The MyDocument.xib file is correctly loaded (from xCode navigation sidebar) and I can see my user interface in interface builder. In my code I haven't changed this method: - (NSString *)windowNibName { // Override returning the nib file name of the document // If you need to use a subclass of NSWindowController or if your document supports multiple NSWindowControllers, you should remove this method and override -makeWindowControllers instead. return @"MyDocument"; } What am I doing wrong ? thanks A: Check out the following methods in the NSApplicationDelegate documentation: * *(BOOL)applicationShouldOpenUntitledFile:(NSApplication *)sender *(BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)flag A: Each window has an option (checkbox) called visible at start (or something like that; can't check ATM). Doublecheck if that's activated. A: It was a bad configured ArrayController! No error messages.. just the interface not showing up
{ "language": "en", "url": "https://stackoverflow.com/questions/7531888", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: function of searching a string from a file This is some code I wrote to check a string's presence in a file: bool aviasm::in1(string s) { ifstream in("optab1.txt",ios::in);//opening the optab //cout<<"entered in1 func"<<endl; char c; string x,y; while((c=in.get())!=EOF) { in.putback(c); in>>x; in>>y; if(x==s) return true; } return false; } it is sure that the string being searched lies in the first column of the optab1.txt and in total there are two columns in the optab1.txt for every row. Now the problem is that no matter what string is being passed as the parameter s to the function always returns false. Can you tell me why this happens? A: What a hack! Why not use standard C++ string and file reading functions: bool find_in_file(const std::string & needle) { std::ifstream in("optab1.txt"); std::string line; while (std::getline(in, line)) // remember this idiom!! { // if (line.substr(0, needle.length()) == needle) // not so efficient if (line.length() >= needle.length() && std::equal(needle.begin(), needle.end(), line.begin())) // better // if (std::search(line.begin(), line.end(), needle.begin(), needle.end()) != line.end()) // for arbitrary position { return true; } } return false; } You can replace substr by more advanced string searching functions if the search string isn't required to be at the beginning of a line. The substr version is the most readable, but it makes a copy of the substring. The equal version compares the two strings in-place (but requires the additional size check). The search version finds the substring anywhere, not just at the beginning of the line (but at a price). A: It's not too clear what you're trying to do, but the condition in the while will never be met if plain char is unsigned. (It usually isn't, so you might get away with it.) Also, you're not extracting the end of line in the loop, so you'll probably see it instead of EOF, and pass once too often in the loop. I'd write this more along the lines of: bool in1( std::string const& target ) { std::ifstream in( "optab1.txt" ); if ( ! in.is_open() ) // Some sort of error handling, maybe an exception. std::string line; while ( std::getline( in, line ) && ( line.size() < target.size() || ! std::equal( target.begin(), target.end(), line.begin() ) ) ) ; return in; } Note the check that the open succeeded. One possible reason you're always returning false is that you're not successfully opening the file. (But we can't know unless you check the status after the open.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7531890", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: wchar_t NUL in managed/unmanaged C++ I need to use this (unmanaged) C++ library. One of the methods has a wchar_t* as a parameter. Tried using it in C#, but all my attempts resulted in an error code 'invalid argument'. I wrote a managed C++ wrapper for it - same problem. Now I compared the values of arguments from my C++ wrapper and native C++ example that came with the library. The only significant difference I see is that NUL in my managed C++ is "0 L''" (Visual Studio watch) and NUL in unmanaged example is simply "0". They both have the same value... 0. Can this really be the issue? (I tried manually setting that character to '0' but got the same results) If yes, how do I solve it? EDIT: Image: http://img6.imageshack.us/img6/5977/comparisonofvalues.png Ok, on the left side is my code (managed C++), on the right side is the example (unmanaged C++). As it is, right one is working, left one isn't (the function rejects the arguments). I think the issue is in the 17th character - NUL. Any further thoughts? A: The difference in your debugger is just appearances. You'll note that the debugger generally shows two values: the binary value, and the matching Unicode character. But you can't show a Unicode character for binary value 0. The two debuggers deal with it in slightly different ways (showing L'' versus showing nothing) , but the bits in memory are the same. On the other hand, your ip string is garbage. A: You might check your project properties. There is a compiler option that controls whether wchar_t is treated as a built-in type or not. Setting this to NO will use the old header definition of wchar_t and may fix your problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531900", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Wordpress - MooTools sub-menu not working correctly I have installed the Akiraka theme from RocketTheme and am trying to get my sub-menu's working. Currently when I hover over the main menu item a white box displays where the sub-menu items should be. The site is: http://testing.bfcmv.org/ I have compared everything to their site and can't see any difference between my configuration and their configuration. A: Which browser/OS are you using? It looks to be working OK for me. Tested on Linux Firefox/Chrome A: I was trying to use the most recent version of WordPress 3.2.x and found that I should have been using a 2.x version.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531906", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How does one create a SugarCRM View that combines 2 Detail Views I would like to extend the Contact Detail View so that a Detail View of the associated account appears on the same view. MY instinct is to override the display function for the Contacts Detail View and from there create an instance of the Accounts Detail and attach it's display output. But I don't know if there is a standard way of pulling this of. A: I learned that in the up coming version (6.3), there will be a way of generating computed fields that have access to the fields of a related module. If this is the case, then one option will be to create computed fields that reference the Account fields and then add a panel to Contact DetailView with the referenced Account fields. Though, my original hunch proved to be doable as well and not as hacky as I had assumed at first: <?php require_once('include/MVC/View/views/view.detail.php'); class ContactsViewDetail extends ViewDetail { function ContactsViewDetail() { parent::ViewDetail(); } function preDisplay(){ parent::preDisplay(); // Configuration to display All account info $this->dv2 = new DetailView2(); $this->dv2->ss =& $this->dv->ss; $this->bean2 = new Account(); $this->bean2->retrieve($this->bean->account_id); $accountMetadataFile = 'custom/modules/Accounts/metadata/detailviewdefs.php'; $accountTemplate = 'custom/modules/Accounts/tpls/AccountsDetailView.tpl'; $this->dv2->setup('Accounts', $this->bean2, $accountMetadataFile, $accountTemplate); } function display(){ parent::display(); // Display Accounts information. $this->dv2->process(); echo $this->dv2->display(); } } ?> In summary * *Override the detail view. *Add a new display to the current View. *Add a new bean (module) to the View. *Process the display with the new bean. *Echo the display. A: Another easier option may be just add an iframe field, which loads the detailview on the account inside of it. Not as pretty, but lots less hacking as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531907", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Remove .php from URL and force a trailing slash / I want to use .htaccess mod_rewrite to remove .php from all my files and force a trailing slash /. However, it is only resulting in me getting server errors. A: You want to map : http://sampledomain.ext/index/ -> http://sampledomain.ext/index.html Use the following .htaccess RewriteEngine On RewriteCond %{REQUEST_URI} ! \.php$ #Avoid real php page, do what you want with them RewriteCond %{REQUEST_URI} /$ #Ensure a final slash RewriteRule ^(.*)$ $1.php #Add your extension Tx to David Wolever who write quitely the same stuff 1 If I can give my opinion, it's a little bit strange to force the / at the end for a file no?
{ "language": "en", "url": "https://stackoverflow.com/questions/7531909", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: CURL and ZLIB Compilation When compiled correctly, how are these two associated together? I'm attempting to use the ZLIB library in my CURL install and want to confirm that I've compiled CURL and ZLIB correctly. Should the libcurl.lib now have all of ZLIB after a successful compile or is the zlib.lib library still required? A: No. It is not like that. When you compiled CURL with ZLIB SUPPORT, those header files were included in CURL source which were needed for compiling the function/API's present in the ZLIB library. You would never be able to compile CURL with ZLIB support with ZLIB library in your sustem. Consider, CURL with ZLIB is just a program which you would write to call functions provided by ZLIB. A: The .lib archives are just a collection of compiled source files, nothing more. By convention and practicality, they only include the objects compiled for their respective library. So, to link against the libcurl you have created, you must also link against the zlib. Professional configuration systems (e.g. pkg-config) will automate this step away from you, but you'll always need the zlib.lib if you didn't do any linker magic.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531912", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Carrierwave + Fog (S3) + Heroku: TypeError (can't convert Hash into String) I have an application on Heroku that uses Carrierwave to upload images to S3. The app is running perfectly on local machine but on Heroku throws the following error and fails the uploading to S3: TypeError (can't convert Hash into String): 2011-09-23T15:12:07+00:00 app[web.1]: app/controllers/admin/albums_controller.rb:49:in `create' 2011-09-23T15:12:07+00:00 app[web.1]: app/controllers/admin/albums_controller.rb:48:in `create' That line corresponds to the "if @album.save" instruction. My Albums controller create action is: def create @album = Album.new(params[:album]) respond_to do |format| if @album.save format.html { redirect_to(admin_album_path(@album), :notice => 'Àlbum creat correctament.') } format.xml { render :xml => [:admin, @album], :status => :created, :location => @album } else format.html { render :action => "new" } format.xml { render :xml => @album.errors, :status => :unprocessable_entity } end end end My Carrierwave initializer: CarrierWave.configure do |config| config.fog_credentials = { :provider => 'AWS', :aws_access_key_id => APP_CONFIG['storage']['s3_access'], :aws_secret_access_key => APP_CONFIG['storage']['s3_secret'], } config.fog_directory = 'romeu' config.fog_host = 'http://xxxxx.s3.amazonaws.com' config.fog_public = true config.root = Rails.root.join('tmp') config.cache_dir = 'carrierwave' end My image_uploader.rb: class ImageUploader < CarrierWave::Uploader::Base include CarrierWave::MiniMagick storage :fog def store_dir "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}" end # Album Cover version version :cover do process :square_resize => [150,150] end # Thumb version version :thumb do process :square_crop => [80,80] end def square_crop(width, height) manipulate! do |img| side = [img['width'], img['height']].min x = (img['width'] - side) / 2 y = (img['height'] - side) / 2 img.crop("#{side}x#{side}+#{x}+#{y}") img.resize("#{width}x#{height}") img end end def square_resize(width, height) manipulate! do |img| img.resize("#{width}x#{height}") img end end # Valid list def extension_white_list %w(jpg jpeg gif png) end end My config.ru: # This file is used by Rack-based servers to start the application. require ::File.expand_path('../config/environment', __FILE__) use Rack::Static, :urls => ['/carrierwave'], :root => 'tmp' run Encen::Application I have inspected the @album object and everything seems okay: _mounters: :image: !ruby/object:CarrierWave::Mount::Mounter _memoized_option: ? - :mount_on : column: :image integrity_error: options: {} processing_error: record: *id001 uploader: !ruby/object:ImageUploader cache_id: 20110923-0810-1-0644 file: !ruby/object:CarrierWave::SanitizedFile content_type: image/jpeg file: /app/tmp/carrierwave/20110923-0810-1-0644/image.jpg original_filename: filename: image.jpg model: *id001 mounted_as: :image original_filename: image.jpg versions: :thumb: !ruby/object: file: !ruby/object:CarrierWave::SanitizedFile cache_id: 20110923-0810-1-0644 content_type: image/jpeg file: /app/tmp/carrierwave/20110923-0810-1-0644/image.jpg original_filename: filename: image.jpg model: *id001 mounted_as: :image original_filename: image.jpg parent_cache_id: 20110923-0810-1-0644 versions: {} :cover: !ruby/object: cache_id: 20110923-0810-1-0644 file: !ruby/object:CarrierWave::SanitizedFile content_type: image/jpeg file: /app/tmp/carrierwave/20110923-0810-1-0644/image.jpg original_filename: filename: image.jpg model: *id001 mounted_as: :image attributes: title: body: model: *id001 previously_changed: {} readonly: false I have spent a bunch of days intending to resolve that error but unsuccessful, what I am missing? Thanks in advance. A: After long days of frustation I have solved the problem. It was such as an stupid thing like the environment vars of S3 access keys on Heroku were incorrectly defined. I don't understand why Fog gem don't gives you more accurate debugging information about that kind of errors.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531915", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I find strings and string patterns in a set of many files? I have a collection of about two million text files, that total about 10GB uncompressed. I would like to find documents containing phrases in this collection, which look like "every time" or "bill clinton" (simple case-insensitive string matching). I would also like to find phrases with fuzzy contents; e.g. "for * weeks". I've tried indexing with Lucene but it is no good at finding phrases containing stopwords, as these are removed at index time by default. xargs and grep are a slow solution. What's fast and appropriate for this amount of data? A: You may want to check out the ugrep utility for fuzzy search, which is much faster than agrep: ugrep -i -Z PATTERN ... This runs multiple threads (typically 8 or more) to search files concurrently. Option -i is for case-insensitive search and -Z specifies fuzzy search. You can increase the fuzziness from 1 to 3 with -Z3 to allow up to 3 errors (max edit distance 3) or only allow up to 3 insertions (extra characters) with -Z+3 for example. Unicode regex matching is supported by default. For example for fuzzy-matches für (i.e. one substitution). A: you could use a postgreSQL datbase. There is full text search implementation and by using dictionaries you can define your own stop words. I don't know if it helps much, but I would give it a try.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531919", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Converting an UploadedFile to PIL image in Django I'm trying to check an image's dimension, before saving it. I don't need to change it, just make sure it fits my limits. Right now, I can read the file, and save it to AWS without a problem. output['pic file'] = request.POST['picture_file'] conn = myproject.S3.AWSAuthConnection(aws_key_id, aws_key) filedata = request.FILES['picture'].read() content_type = 'image/png' conn.put( bucket_name, request.POST['picture_file'], myproject.S3.S3Object(filedata), {'x-amz-acl': 'public-read', 'Content-Type': content_type}, ) I need to put a step in the middle, that makes sure the file has the right size / width dimensions. My file isn't coming from a form that uses ImageField, and all the solutions I've seen use that. Is there a way to do something like img = Image.open(filedata) A: image = Image.open(file) #To get the image size, in pixels. (width,height) = image.size() #check for dimensions width and height and resize image = image.resize((width_new,height_new)) A: I've done this before but I can't find my old snippet... so here we go off the top of my head picture = request.FILES.get['picture'] img = Image.open(picture) #check sizes .... probably using img.size and then resize #resave if necessary imgstr = StringIO() img.save(imgstr, 'PNG') imgstr.reset() filedata = imgstr.read() A: The code bellow creates the image from the request, as you want: from PIL import ImageFile def image_upload(request): for f in request.FILES.values(): p = ImageFile.Parser() while 1: s = f.read(1024) if not s: break p.feed(s) im = p.close() im.save("/tmp/" + f.name)
{ "language": "en", "url": "https://stackoverflow.com/questions/7531921", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Unexpected results after joining another table I use three tables to get to the final result. They are called project_board_members, users and project_team. This is the query: SELECT `project_board_members`.`member_id`, `users`.`name`, `users`.`surname`, `users`.`country`, `project_team`.`tasks_completed` FROM `project_board_members` JOIN `users` ON (`users`.`id` = `project_board_members`.`member_id`) JOIN `project_team` ON (`project_team`.`user_id` = `project_board_members`.`member_id`) WHERE `project_board_members`.`project_id` = '5' You can ignore last line because it just points to the project I'm using. Table project_board_members holds three entries and have structure like: * *id, *member_id, *project_id, *created_at; I need to get member_id from that table. Then I join to users table to get name, surname and country. No problems. All works! :) After that, I needed to get tasks_completed for each user. That is stored in project_team table. The big unexpected thing is that I got four entries returned and the big what-the-f*ck is that in the project_board_members table are only three entries. Why is that so? Thanks in advice! A: A SQL join creates a result set that contains one row for each combination of the left and right tables that matches the join conditions. Without seeing the data or a little more information it's hard to say what exactly is wrong from what you expect, but I'm guessing it's one of the following: 1) You have two entries in project_team with the same user_id. 2) Your entries in project_team store both user_id and project_id and you need to be joining on both of them rather than just user_id. A: The table project_board_members represent what is called in the Entity-Relationship modelling world an "associative entity". It exists to implement a many-to-many relationship (in this case, between the project and user entities. As such it is a dependent entity, which is to say that the existence of an instance of it is predicated on the existence of an instance of each of the entities to which it refers (a user and a project). As a result, the columnns comprising the foreign keys relating to those entities (member_id and project_id) must be form part or all of the primary key. Normally, instances of an associative entity are unique WRT the entities to which it relates. In your case the relationship definitions would be: * *Each user is seated on the board of 0-to-many projects; *Each project's board is comprise of 0-to-many users which is to say that a particular user may not be on the board of a particular project more than once. The only reason for adding other columns (such as your id column) to the primary key would be if the user:project relationship is non-unique. To enforce this rule -- a user may sit on the board a particular project just once -- the table schema should look like this: create table project_board_member ( member_id int not null foreign key references user ( user_id ) , project_Id int not null foreign key references project ( project_id ) , created_at ... ... primary key ( member_id , project_id ) , ) } The id column is superfluous. A: For debugging purposes do SELECT GROUP_CONCAT(pbm.member_id) AS member_ids, GROUP_CONCAT(u.name) as names, GROUP_CONCAT(u.surname) as surnames, GROUP_CONCAT(u.country) as countries, GROUP_CONCAT(pt.tasks_completed) as tasks FROM project_board_members pbm JOIN users u ON (u.id = pbm.member_id) JOIN project_team pt ON (pt.user_id = pbm.member_id) WHERE pbm.project_id = '5' GROUP BY pbm.member_id All the fields that list multiple entries in the result are messing up the rowcount in your resultset. To Fix that you can do: SELECT pbm.member_id u.name, u.surname, u.country, pt.tasks_completed FROM (SELECT p.project_id, p.member_id FROM project_board_members p WHERE p.project_id = '5' LIMIT 1 ) AS pbm JOIN users u ON (u.id = pbm.member_id) JOIN project_team pt ON (pt.user_id = pbm.member_id)
{ "language": "en", "url": "https://stackoverflow.com/questions/7531924", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why isn't this working for recursively reading from hash? @hash is a global hash that looks something like: @hash = { "xmlns:xsi" =>"http://www.w3.org/2001/XMLSchema-instance", "xsi:noNamespaceSchemaLocation"=>"merchandiser.xsd", "header" =>[{"merchantId"=>["35701"], "merchantName" =>["Lingerie.com"], "createdOn" =>["2011-09-23/00:33:35"]}], "trailer" =>[{"numberOfProducts"=>["0"]}] } And I would expect this to work if I call the method below like: def amethod hash_value("header", "merchantName") // returns "Lingerie.com" end def hash_value *attributes, hash = nil hash = @hash unless hash att = attributes.delete_at.first attributes.empty? ? hash[att].first : hash_value(attributes, hash[att].first) end A: You can't have a default argument after a splat arg. Instead, require that the attribute list be passed as an array, like so: def hash_value(attributes, hash = @hash) return hash if attributes.empty? hash_value(attributes[1..-1], hash[attributes.first].first) end p hash_value(["header", "merchantName"]) # => "Lingerie.com" p hash_value(["trailer", "numberOfProducts"]) # => "0" A: Try this: def hash_value(*attributes, hash) hash = @hash unless hash att = attributes.delete_at.first attributes.empty? ? hash[att].first : hash_value(attributes, hash[att].first) end
{ "language": "en", "url": "https://stackoverflow.com/questions/7531925", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Django foreign keys - one class has the same relationship to multiple other classes I have a model with three classes: PendingAuthorisation, Director, and Member. Director and Member instances are considered inactive if they have a corresponding PendingAuthorisation. My problem is quite how to model this. I would ideally like PendingAuthorisation to have just one field, defers, which can refer to either a Director or a Member. If I create a foreign key in both Director and Member then I need to have two differently-named relations, and when using a PendingAuthorisation I would need to check both to find the object it is deferring. In no case should a PendingAuthorisation be deferring one object of each type. Any suggestions on how to model this? A: I'd recommend having two foreign keys (with a sanity check in your save method to make sure that they're not both set), and then a property to return back the object that's set. Think about something like: from django.db import models class PendingAuthorization(models.Model): director = models.ForeignKey(Director, null=True, blank=True) member = models.ForeignKey(Member, null=True, blank=True) def save(self, *args, **kwargs): if self.director and self.member: raise ValueError, 'Both a director and member are set; this is not allowed.' return super(PendingAuthorization, self).save(*args, **kwargs) @property def defers(self): if self.director: return self.director if self.member: return self.member return None
{ "language": "en", "url": "https://stackoverflow.com/questions/7531929", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Implementing Seam Carving Method in C# I would like to Scale an Image from 640x480 to 64x48. There are different approaches used by the picture manipulating programs like Gimp and Photoshop. For eg.Gimp uses liquid rescale algorithm and photoshop uses path match algorithm for better scaling. Both uses Seam Carving approach. But I am unable to compare and implement them in C#. I downloaded some example code , but it is in Matlab. Is there an efficient algorithm in C# to implement this in better way. Please provide, if any existing code for the Seam carving Implementation in C#. A: I've found following implementations of seam carving on C#: * *magicarver *My library: Seam-Carving-Advanced. GPU processing under developing. This lib is porting of C++ lib: seam-carving-gui A: I would just use ImageMagic since your doing C#, it will give you all kind of conversion possibilities.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531932", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: CreateFileMapping for Directory I have this function which gives the full file name(path) from the file handle. The only problem is CreateFileMapping fails for directory handles. Is there a workaround for it? I get the handle using NtCreateFile() ULONG status = NtCreatefile(&f, GENERIC_ALL, &oa, iosb, NULL, FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ | FILE_SHARE_WRITE, FILE_OPEN, FILE_OPEN_BY_FILE_ID , NULL, 0); printf("status: %X, handle: %x\n", status, f); AND BOOL CHouseKeeper::GetFileNameFromHandle(HANDLE hFile) { BOOL bSuccess = FALSE; TCHAR pszFilename[MAX_PATH+1]; HANDLE hFileMap; // Get the file size. DWORD dwFileSizeHi = 0; DWORD dwFileSizeLo = GetFileSize(hFile, &dwFileSizeHi); if( dwFileSizeLo == 0 && dwFileSizeHi == 0 ) { _tprintf(TEXT("Cannot map a file with a length of zero.\n")); return FALSE; } // Create a file mapping object. //It fails here if a directory handle is passed, it returns 0 hFileMap = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 1, NULL); if (hFileMap) { // Create a file mapping to get the file name. void* pMem = MapViewOfFile(hFileMap, FILE_MAP_READ, 0, 0, 1); if (pMem) { if (GetMappedFileName (GetCurrentProcess(), pMem, pszFilename, MAX_PATH)) { // Translate path with device name to drive letters. TCHAR szTemp[BUFSIZE]; szTemp[0] = '\0'; if (GetLogicalDriveStrings(BUFSIZE-1, szTemp)) { TCHAR szName[MAX_PATH]; TCHAR szDrive[3] = TEXT(" :"); BOOL bFound = FALSE; TCHAR* p = szTemp; do { // Copy the drive letter to the template string *szDrive = *p; // Look up each device name if (QueryDosDevice(szDrive, szName, MAX_PATH)) { size_t uNameLen = _tcslen(szName); if (uNameLen < MAX_PATH) { bFound = _tcsnicmp(pszFilename, szName, uNameLen) == 0 && *(pszFilename + uNameLen) == _T('\\'); if (bFound) { // Reconstruct pszFilename using szTempFile // Replace device path with DOS path TCHAR szTempFile[MAX_PATH]; StringCchPrintf(szTempFile, MAX_PATH, TEXT("%s%s"), szDrive, pszFilename+uNameLen); StringCchCopyN(pszFilename, MAX_PATH+1, szTempFile, _tcslen(szTempFile)); } } } // Go to the next NULL character. while (*p++); } while (!bFound && *p); // end of string } } bSuccess = TRUE; UnmapViewOfFile(pMem); } CloseHandle(hFileMap); }else { wcout<<GetLastError()<<endl; } _tprintf(TEXT("File name is %s\n"), pszFilename); return(bSuccess); } A: You can use NtQueryInformationFile with FileNameInformation to retrieve the name associated with a file handle.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531933", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Qt “forgets” to link one of my “moc_MyClass.o” objects The source file is clearly in the project, among the rest of my classes. I have Q_OBJECT defined for the class, like the rest of my Qt Classes. My class compiles with the rest of the classes. Yet, the linker fails on the vtable for the constructor/destructor for my class. Checking the linker command: It seems like the moc_Myclass.cpp is never generated or built. so nothing to link against. How can that be? why is it left out? A: Troubling resolution: When I removed the cpp/h file from the projcet, and then added them back in the moc for my class began being generated correctly so link passed. That's clearly a Qt "project cancer" bug, but at least now I know how to "cure" it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531934", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why not change color when pressed? when you click the color should change to another but it doesnt work! My code: # public class CreateActivity extends Activity { TableLayout table; Integer i; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); table = (TableLayout)findViewById(R.id.myTable); Button left = (Button) findViewById(R.id.buttonLeft); Button right = (Button) findViewById(R.id.buttonRight); TextView color = (TextView) findViewById(R.id.text); i=0; right.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub i++; //+1 } }); //COLOR switch(i){ case 1: table.setBackgroundColor(Color.RED); break; case 2: table.setBackgroundColor(Color.rgb (255, 127, 0) ); break; case 3: table.setBackgroundColor(Color.YELLOW); break; case 4: table.setBackgroundColor(Color.GREEN) ; break; case 5: table.setBackgroundColor(Color.rgb (0,191,255) ); break; case 6: table.setBackgroundColor(Color.BLUE ); break; case 7: table.setBackgroundColor(Color.rgb (160,32,240) ); break; } } } A: When the button is clicked, you're incrementing i - but you won't be running the switch/case statement again. If you look in the debugger you'll find that the variable value is changing, but you haven't instructed any part of the display to change. You should put that common logic in a separate method which is called both from the onCreate method and the OnClickListener. For example: public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); table = (TableLayout)findViewById(R.id.myTable); Button left = (Button) findViewById(R.id.buttonLeft); Button right = (Button) findViewById(R.id.buttonRight); TextView color = (TextView) findViewById(R.id.text); i=0; right.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { i++; // Cycle round if (i == 8) { i = 1; } applyBackgroundColor(); } }); applyBackgroundColor(); } private void applyBackgroundColor() { switch(i) { // TODO: Consider what you want to do when i is 0... case 1: table.setBackgroundColor(Color.RED); break; case 2: table.setBackgroundColor(Color.rgb(255, 127, 0)); break; case 3: table.setBackgroundColor(Color.YELLOW); break; case 4: table.setBackgroundColor(Color.GREEN); break; case 5: table.setBackgroundColor(Color.rgb(0,191,255)); break; case 6: table.setBackgroundColor(Color.BLUE); break; case 7: table.setBackgroundColor(Color.rgb(160,32,240)); break; } } There are various other things I'd change about this code, but that should at least get you over this hump.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531942", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Adding a wireless AccessPoint through the Smart Device Framework I have a couple questions: In general, what is the general difference between the OpenNETCF.Net namespace and the OpenNETCF.Net.NetworkInformation namespace in the Smart Device Framework? There seems to be a lot of functionality overlap between the two. Is the OpenNETCF.Net namespace now deprecated in favor of the NetworkInformation namespace? More specifically, I have a device with a wireless adapter. My goal is to be able to query nearby access points and then connect to them through my own user interface. OpenNETCF.Net.Networking.GetAdapters()[1] gives me my adapter object representing the wireless adapter. Even though this is a wireless adapter, IsWireless and IsWirelessZeroConfigCompatible both return false. However, NearbyAccessPoints DOES return a list of nearby access points as you would expect a wireless adapter to do. I need a way to add one of the discovered access points to the PreferredAccessPoints collection. I have not found a method to accomplish this within the OpenNETCF.Net namespace. The only way I've found to add an AccessPoint is through the AddPreferredNetwork() method of the OpenNETCF.Net.NetworkInformation.WirelessZeroConfigNetworkInterface class. The problem I'm having is that I've been unable to find a way to obtain a WirelessZeroConfigNetworkInterface object. The object returned by the NetworkInterface.GetAllNetworkInterfaces() method is just a plain old NetWorkInterface object, not a WirelessZeroConfigNetworkInterface object as I hoped. I'm sure this is probably related to the issue with IsWireless returning false in the NetworkAdapter object. Is there a way to construct the WirelessZeroConfigNetworkInterface object even though the framework seems to think it is not wireless? It looks like the functionality is there as demostrated by the Wireless related methods of the NetworkAdapter object. A: The history is a bit confusing, yes. Basically SDF 2.2 (or earlier, I don't recall any more) had everything in the OpenNETCF.Net namespace. When I was adding features in 2.3, I added a boatload of stuff in the OpenNETCF.Net.NetworkInformation namespace that paralleled the full framework. Some of that had functional overlap with things we had done in the wireless stuff, so I made the decision to move everything over to the OpenNETCF.Net.NetworkInformation namespace. I left the originals and marked them as deprecated to try to be friendly to existing deployments. The items you should use are the ones in the OpenNETCF.Net.NetworkInformation namespace. Now on to how the stuff functions. First we query NDIS for all network interfaces. This gives us wired, RNDIS, wireless, etc - basically everything that the network stack knows about. NDIS, however, doesn't know much about "wireless" stuff - it does know some though. Once we have our list of known adapters, we then ask NDIS if it's a wireless device - it can at least tell us that becasue the driver tells NDIS at registration. Once we have a list of wireless adapters, we then walk them and ask the WZC subsystem if it knows about the adapter. WZC is an interface that knows everything about the wireless devices, allowing us to intereact with it through a common, published interface. If WZC does know about it (meaning the driver reported itself at initialization to WZC) then we create a WirelessZeroConfigNetworkInterface for it. If it isn't known by WZC, then we know it's wireless (NDIS told us it was), but we only have the NDIS methods for interacting with it. NDIS doesn't give us a way to associate. It does give us a way to ask for nearby SSIDs. The Adapter interface you have, then, exposes the capabilities we know of. In some cases the driver has a proprietary API to manipulate the WiFi settings (e.g. old Cisco cards). What version of the OS is this you're running on? What WiFi chipset/adapter are you using?
{ "language": "en", "url": "https://stackoverflow.com/questions/7531943", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python range function Say I want to loop from 0 to 100 but with a step of 1/2. If you try for i in range(0, 100, 0.5): whatever Error: the step must not be 0 Question: Is there any built-in way in Python 2.x to do something like this? A: You have to use integer steps for range() and xrange(). That's why your 0.5 step gets internally converted to 0 and you get that error. Try for i in [j / 2.0 for j in xrange(100 * 2)]: A: You'll have to either create the loop manually, or define your own custom range function. The built-in requires an integer step value. A: Python2.x: for idx in range(0, int(100 / 0.5)): print 0.5 * idx outputs: 0.0 0.5 1.0 1.5 .. 99.0 99.5 Numpy: numpy.arange would also do the trick. numpy.arange(0, 100, 0.5) A: If you have numpy, here are two ways to do it: numpy.arange(0, 100, 0.5) numpy.linspace(0, 100, 200, endpoint=False) A: for x in map(lambda i: i * 0.5, range(0,200)): #Do something with x A: For large ranges it is better to use an generator expression than building a list explicitly: for k in ( i*0.5 for i in range(200) ): print k This consumes not much extra memory, is fast und easy to read. See http://docs.python.org/tutorial/classes.html#generator-expressions
{ "language": "en", "url": "https://stackoverflow.com/questions/7531945", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: Why won't my Admob Ads show up in my android application? I have made an application for the Android Market and I tried to include an Ad in it using Admob. I have everything set up correctly, but the ad doesn't show up no matter what I do. If I check the Admob Marketplace I can see that there were a lot of requests sent and I got a good fillrate, too, but my ads simply do not show up in my program, as if they were invisible. The AdView appears if I am in the graphical XML designer, but just won't show up when I run the program, although as I said, it sends a request. I would really appreciate it if you could help me out! :) By the way, here is the main code of the AdView(I tried to add it using Java too, but it didn't show up either): <com.google.ads.AdView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/ad" ads:loadAdOnCreate="true" ads:adSize="BANNER" ads:adUnitId="MyIdHere"> </com.google.ads.AdView> A: I found out that the padding of my layout prevented the Adview from appearing. Removing the padding fixes the problem! -- answer by Calin
{ "language": "en", "url": "https://stackoverflow.com/questions/7531947", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I execute query using job and convert result grid to text? I need to execute query and convert result to text. I know how to do it within Management Studio. But I need to do it within stored procedure and saved output result to text column A: The query itself has no idea what a grid or text pane is - these are presentation niceties coded into Management Studio. If you want to combine the values in a row and concatenate them into a single string, then insert those rows into your text column (I hope you mean VARCHAR(MAX) or NVARCHAR(MAX), since TEXT is deprecated and shouldn't be used), you can say something like this, keeping in mind that you'll need to manually convert any non-string types (int, date, etc.) to varchar or nvarchar. INSERT dbo.OtherTable(NVARCHAR_MAX_COLUMN) SELECT varchar_column + CONVERT(VARCHAR(12), int_column) + ... FROM dbo.table; If you need to combine rows as well and insert one big value that represents a text dump of the whole table, then you can do it slightly differently: DECLARE @v NVARCHAR(MAX) = N''; SELECT @v += CHAR(13) + CHAR(10) + varchar_column + CONVERT(VARCHAR(12), int_column) + ... FROM dbo.table; INSERT dbo.OtherTable(NVARCHAR_MAX_COLUMN) SELECT @v;
{ "language": "en", "url": "https://stackoverflow.com/questions/7531949", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android: Accessing resources without an Activity or Context refeerence I am posting this question in the hope that I can get some kind of definitive answer. Is it really impossible to access resources without an activity or context reference. Passing around such references when all that is required is to access some values or assets or strings which have nothing to do with the UI makes for overly complicated code. Plus all those potential hanging references. Also this completely ruins various Design Patterns such as singletons, having to supply parameters when getting the instance. Putting a static reference So is there a way or does the whole community just live with this problem. A: Your resources are bundled to a context, it's a fact and you can't change that. Here's what you can do: Extend Application, get the application context and use that as a static helper. public class App extends Application { private static Context mContext; public static Resources getResources() { return mContext.getResources(); } public void onCreate() { super.onCreate(); mContext = getApplicationContext(); } } Your manifest: <application android:icon="@drawable/icon" android:label="@string/app_name" android:name="your.package.path.to.App"> A: Make your Application class a singleton and use that. It is a Context. All resources are tied to your app, so you need a Context reference. You can pre-load strings, etc. in a singleton class if you don't want to load them dynamically. A: I guess you could use context from some UI element like textView.getContext() if the other responses don't work for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531959", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: UPLOADIFY loader hangs on 0% when trying to use scriptData I found a bug while using uploadify. When I user the scriptData attribute to pass post information to the script the loader does not work. The script is actually called and the items are uploaded but the loader hangs on 0 %. When you user multiple files it will hang on the first one sometimes on 95% and mostly on 0%. It looks as tho the files arent uploaded but they are. This is very anoying though, seeing that the user will think their files arent uploaded and wait on the screen. I tried to work around this by just using GET information and putting my extra variables into the actual url in the script: attribute. This also results in the same problem. A simple note is that I am using CodeIgniter for this project so this could be a problem. It would really be helpful if this was fixed but dont know if its gonna happen any time soon. I checked this problem on multiple browsers and have the same issue. Has anyone here dealt with this. I used to like uploadify but Im begging to start looking for something else A: I had this problem, too, and it drove me crazy. It turns out that the script that you're using to handle the upload has to output something - anything - before uploadify will continue. So in your 'script', like upload.php below, make the last line of the script output something at the bottom of the script - even something simple like echo "done";. This will let uploadify know that the script is finished so it can continue. $('#file_upload').uploadify({ 'uploader' : '/js/jquery/uploadify/uploadify.swf', 'script' : '/distributed/ajax/upload.php', 'cancelImg' : '/js/jquery/uploadify/cancel.png', 'folder' : '/distributed/files', 'auto' : true, 'scriptData': { 'request_no':req_no }, 'onComplete': function(evt, ID, fileObj, response, data) { alert("Finished!"); } } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7531960", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: VS 11 does not pay attention to install location I've download VS 11 Developer preview. I do not have sufficient disk space in my C drive, so I entered "E:\Program Files\Visual Studio 11\" as the install location and the installer continues, but after a while, my C: drive goes out of disk space and I get the following error in the log file: (vs_professionalcore) failed: Error: 1601 ErrorMessage: Out of disk space -- Volume: 'C:'; required space: 606,561 KB; available space: 178,516 KB. Free some disk space and retry. Note that no files gets copied to my E: drive during the installation process. What's the solution? A: This isn't unique to VS 2011. All versions of Visual Studio (at least all the .NET flavors I have used since 2002) have strong dependencies that can only installed onto the C: drive. These dependencies can be stuff like the .NET 4.5 and various runtime components. The IDE itself is all that can be placed on another drive. You usually see this in the installer where it will show that after changing the drive letter still large parts of the C: drive will be used. I decided to fire up a VM and see what the difference was between C drive install and E drive install on VS 2010 Ultimate. As you can see the difference was only ~2GB with the bulk being on the C drive still as I stated above. Visual Studio 2010 Ultimate C Drive Full Install Visual Studio 2010 Ultimate E Drive Full Install A: Unfortunately I don't believe there is a solution here. This sounds like a simple bug in the installer. The only real option is to file a bug on Visual Studio Connect to ensure it's fixed for RTM * *http://connect.microsoft.com/visualstudio Note: This is a preview release so quality is not that of RTM. It's certainly a case I would expect to be fixed for RTM though. When I worked in Visual Studio QA in particular often installed to non-default locations.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531961", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to add custom Haml helper to Rails project? I've created Haml helper and put it as file in path app/helpers/haml_helper.rb module Haml::Helpers def build_segment(files) files.each do |f| if f[:dir] == nil haml_tag :li do haml_tag :a, :class=>"file", :href=>f[:name] do f[:name] end end else haml_tag :li do haml_tag :a, :class=>"folder", :href=>f[:name] do f[:name] end end haml_tag :ul do build_segment(f[:dir]) end end end end end But then I've got an error: LoadError in SourceFilesController#index Expected /home/megas/Work/read_the_code/app/helpers/haml_helper.rb to define HamlHelper SourceFilesController#index is an action which going to use this custom helper. How to add custom haml helper to the project? A: So, when you have haml_helper.rb, it expects it to define HamlHelper .... but you wanted Haml::Helper. So: /helpers/haml/helpers This is the same when you have namespaced controllers. Admin::CustomersController is at app/controllers/admin/customers_controller.rb
{ "language": "en", "url": "https://stackoverflow.com/questions/7531963", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Json encode an entire mysql result set I want to get json with php encode function like the following <?php require "../classes/database.php"; $database = new database(); header("content-type: application/json"); $result = $database->get_by_name($_POST['q']); //$_POST['searchValue'] echo '{"results":['; if($result) { $i = 1; while($row = mysql_fetch_array($result)) { if(count($row) > 1) { echo json_encode(array('id'=>$i, 'name' => $row['name'])); echo ","; } else { echo json_encode(array('id'=>$i, 'name' => $row['name'])); } $i++; } } else { $value = "FALSE"; echo json_encode(array('id'=>1, 'name' => "")); // output the json code } echo "]}"; i want the output json to be something like that {"results":[{"id":1,"name":"name1"},{"id":2,"name":"name2"}]} but the output json is look like the following {"results":[{"id":1,"name":"name1"},{"id":2,"name":"name2"},]} As you realize that there is comma at the end, i want to remove it so it can be right json syntax, if i removed the echo ","; when there's more than one result the json will generate like this {"results":[{"id":1,"name":"name1"}{"id":2,"name":"name2"}]} and that syntax is wrong too Hope that everybody got what i mean here, any ideas would be appreciated A: Do the json_encoding as the LAST step. Build your data structure purely in PHP, then encode that structure at the end. Doing intermediate encodings means you're basically building your own json string, which is always going to be tricky and most likely "broken". $data = array(); while ($row = mysql_fetch_array($result)) { $data[] = array('id'=>$i, 'name' => $row['name']); } echo json_encode($data); A: build it all into an array first, then encode the whole thing in one go: $outputdata = array(); while($row = mysql_fetch_array($result)) { $outputdata[] = $row; } echo json_encode($outputdata); A: If I were you, I would not json_encode each individual array, but merge the arrays together and then json_encode the merged array at the end. Below is an example using 5.4's short array syntax: $out = []; while(...) { $out[] = [ 'id' => $i, 'name' => $row['name'] ]; } echo json_encode($out);
{ "language": "en", "url": "https://stackoverflow.com/questions/7531965", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Maven GWT Plugin copies multiple versions of the same snapshot jars I have this issue where I build my project (mvn clean install), some of the transitive dependencies are snapshot versions and are downloaded and copied into the target webapp directory e.g XXXUtil-1.0-20110922.172721-52.jar. Then when I run mvn gwt:run, it finds uses XXXUtil-1.0-SNAPSHOT.jar and copies it to the target webapp directory. I can't figure out why this is happening. In doesn't matter whether I run as exploded or inplace. <plugins> <!-- GWT Maven Plugin --> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>gwt-maven-plugin</artifactId> <version>2.3.0-1</version> <executions> <execution> <goals> <goal>compile</goal> <goal>i18n</goal> <goal>generateAsync</goal> </goals> </execution> </executions> <configuration> <runTarget>Shell.html</runTarget> <hostedWebapp>${webappDirectory}</hostedWebapp> <i18nMessagesBundle>com.myapp.client.Messages</i18nMessagesBundle> </configuration> <dependencies> <dependency> <groupId>com.google.gwt</groupId> <artifactId>gwt-user</artifactId> <version>${gwt.version}</version> </dependency> <dependency> <groupId>com.google.gwt</groupId> <artifactId>gwt-dev</artifactId> <version>${gwt.version}</version> </dependency> </dependencies> </plugin> <!-- Copy static web files before executing gwt:run --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.1.1</version> <executions> <execution> <phase>compile</phase> <goals> <goal>exploded</goal> </goals> </execution> </executions> <configuration> <!-- <outputFileNameMapping>@{artifactId}@-@{version}@.@{extension}@</outputFileNameMapping> --> <webappDirectory>${webappDirectory}</webappDirectory> </configuration> </plugin> </plugins> None of the suggestions described here help: http://www.tikalk.com/alm/forums/maven-war-plugin-picking-multiple-version-same-snapshot-jars. If i build local snapshots of XXXUtil-1.0-SNAPSHOT.jar it works buts not when downloading snapshots from a nexus repository. Another way to look at it is like this Project A generates a WAR, and depends on B.jar, which depends on C.jar. When i build my war using mvn install, it generates the correct jars in WEB-INF/lib so we have C-1.0-20110922.172721-52.jar. Which is correct and it works if i deploy my war. If i run in hosted mode using eclipse, its fine. But when i run mvn:gwt-run, C-1.0-SNAPSHOT.jar is copied into WEB-INF/lib so i have 2 jars C-1.0-SNAPSHOT.jar and C-1.0-20110922.172721-52.jar. A: The only thing I can suggest you is to try to debug maven-gwt-plugin. Checkout it from git repository https://github.com/gwt-maven-plugin/gwt-maven-plugin.git A: I had exactly the same problem. After debugging, I removed the use of maven-war-plugin and added maven-resources-plugin (compile phase, copy-resources goal). I tried gwt:run and install after that, worked without any problems. This way, we avoid the dependencies getting copied twice.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531971", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Constructing Strings using Regular Expressions Assuming you have a a set E = {a,b}, and you have a superset E* consisting of all possible combinations of a, and b in E. How do you construct an expression for a String that has number of a's divisible by 3? A: Try /^(b*ab*ab*ab*)+$/ Examples: abbb => N bbb => N aaab => Y ababbbba => Y aaabba => N bbbaaaabbbabbbba => Y => N
{ "language": "en", "url": "https://stackoverflow.com/questions/7531972", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Change colour of TLabel in FireMonkey iOS app, and add items to TStringGrid? I managed to get Xcode (running as a VM under Windows) pushing an XE2 build FireMonkey iOS HD app to my (jailbroken) iPhone after XE-script-prep (creating the Xcode folder), with a valid company certificate. Anyway, faking the native cocoa controls seems a little seedy, but sticking a TToolbar (panel with standard iPhone gradient), a couple of TSpeedButtons (which have this curious V slope thing going on), and a TStringGrid and you're almost in the realms of basic iPhone app design. Drop a TLabel on the TToolbar for a caption and straight away you'll want to change the colour, which there doesnt appear to be a property for. Yeah but it's all style (TLayout) driven now I hear you say, which is what I thought, but the style editor doesnt have a colour (color!?) property within TLayout or TText aspects of the Style Designer. Shoe-horning a second question which is just as quick, I dropped a TStringGrid on there and thought I'd dynamically set the rows, so I created a string column, set the RowCount to 6, then set the Cells[1, n] := 'Row ' + IntToStr(iLoop); ...with no effect (I also tried Cells[0, n], in case it was a zero-based list). Am I going mad? Still stumped on connectivity (how do you talk to anything outside the iPhone!?), and the performance of spinning a 48x48 image with a TFloatAnimation on an iPhone 4 was quite frankly appalling. But I'm optimistic, we've got this far! A: This works fine for me. procedure TForm3.Button1Click(Sender: TObject); var i: Integer; begin for i:= 0 to 6 do begin StringGrid1.Cells[0,i] := 'Row:' + IntToStr(i); end; end; I noticed you had both nand iLoop wich one was the loop variable? As to the color setting Roberts answer works designtime, if you want to set it in code you can do Label1.FontFill.Color := TAlphaColorRec.Beige; better way. Label1.ApplyStyleLookup; Label1.FontFill.Color := TAlphaColorRec.White; But I think the correct approach would be to give FontFill a setter function like: function GetFontFill: TBrush; begin if FNeedStyleLookup then ApplyStyleLookup; Result := FFontFill; end; A: To change the color of a Label you need to use the Style. Right Click on the Component and select Edit|Custom Style... Then expand the Tlayout to find and select the TText Then adjust the Fill Property to change the color.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531973", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Large sample database for HSQLDB? I'm taking a database class and I'd like to have a large sample database to experiment with. My definition of large here is that there's enough data in the database so that if I try a query that's very inefficient, I'll be able to tell by the amount of time it takes to execute. I've googled for this and not found anything that's HSQLDB specific, but maybe I'm using the wrong keywords. Basically I'm hoping to find something that's already set up, with the tables, primary keys, etc. and normalized and all that, so I can try things out on a somewhat realistic database. For HSQLDB I guess that would just be the .script file. Anyway if anybody knows of any resources for this I'd really appreciate it. A: You can use the MySQL Sakila database schema and data (open source, on MySQL web site), but you need to modify the schema definition. You can delete the view and trigger definitions, which are not necessary for your experiment. For example: CREATE TABLE country ( country_id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT, country VARCHAR(50) NOT NULL, last_update TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (country_id) )ENGINE=InnoDB DEFAULT CHARSET=utf8; modified: CREATE TABLE country ( country_id SMALLINT GENERATED BY DEFAULT AS IDENTITY, country VARCHAR(50) NOT NULL, last_update TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (country_id) ) Some MySQL DDL syntax is supported in the MYS syntax mode of HSQLDB, for example AUTO_INCREMENT is translated to IDENTITY, but others need manual editing. The data is mostly compatible, apart from some binary strings. You need to access the database with a tool that reports the query time. The HSQLDB DatabaseManager does this when the query output is in Text mode.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531974", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Inserting irregular data into SQL Server I have a file of data which I want to regularly insert into a table in SQL Server 2008. The file contains several fixed width text fields and one field which is free text and very long. When I try to insert the data via SSIS I get error messages telling me that data has been truncated and if I choose to ignore truncation then the free text field is simply not imported and I get an empty field. If I try to use a bulk insert I get a message saying that I am exceeding the maximum row size of 8060. The free text field which is causing the problem contains a lot of white space so one option would be to trim it before I insert it but I am not sure how to do this. I'm afraid I cannot post any sample data as it is of a sensitive, medical nature. Could anyone suggest a possible solution to this problem?
{ "language": "en", "url": "https://stackoverflow.com/questions/7531976", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using Regex to replace a specific string occurrence but ignore others based on neighboring characters I have a string "sub section 15(1) of main section, this might be a <link href="15(1)">15(1)</link>". I want to use the Regex.Replace method to replace "15(1)" with a new string value of "15" but only where it occurs individually. I am using the following pattern but it's not working. temp = "sub section 15(1) of main section, this might be a <link href="15(1)">15(1)</link>"; temp = Regex.Replace(temp, @"15(1)", @"15"); The output string should be: "sub section 15 of main section, this might be a <link href="15(1)">15(1)</link>" Any help will be appreciated. Thanks A: Try this (note you need to escape the brackets around 1): \W15\(1\)\W where \W is a non-word character; or \s15\(1\)\s where \s is a whitespace character. A: In your post you said you want to replace "15(1)" when it is "used individually." Does that mean when it is surrounded by whitespace? This approach matches your desired output: string pattern = @"(?<=^|\s)15\(1\)(?=\s|$)"; string result = Regex.Replace(input, pattern, "15"); Console.WriteLine(result); This pattern will match only if the value occurs at the start of the line or is preceded by a whitespace character, and if it is followed by a whitespace character or the end of the line. A: This works (?<!\S)15\(1\)(?!\S)
{ "language": "en", "url": "https://stackoverflow.com/questions/7531977", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how to fetch all the links starting with http://plus I have a pregmatch with the following search : $regexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>"; now how can I reformat this to look for something like : href="http://plus I dont want the entire thing to be changed , just that part for the href. Thanks A: $regexp = "<a\s[^>]*href=(\"??)(http:\/\/plus[^\" >]*?)\\1[^>]*>(.*)<\/a>";
{ "language": "en", "url": "https://stackoverflow.com/questions/7531978", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to instantiate a static vector of object? I have a class A, which has a static vector of objects. The objects are of class B class A { public: static void InstantiateVector(); private: static vector<B> vector_of_B; } In function InstantiateVector() for (i=0; i < 5; i++) { B b = B(); vector<B>.push_back(b); } But I have compilation error using visual studio 2008: unresolved external symbol... Is it possible to instantiate static vector using above method? For object b to be created, some data has to be read from input file, and stored as member variables of b Or it is not possible, and only simple static vector is possible? I read somewhere that to instantiate static vector, you must first define a const int a[] = {1,2,3}, and then copy a[] into vector A: Add the definition of the static member object to your class implementation file: #include "A.h" std::vector<B> A::vector_of_B; Or rather, absorbing and obviating the initialization routine: std::vector<B> A::vector_of_B(5, B()); // same effect as `A::InstantiateVector()` Note: In C++98/03, vector_of_B(5) and vector_of_B(5, B()) are identical. In C++11 they're not. A: You have to provide the definition of vector_of_b as follows: // A.h class A { public: static void InstantiateVector(); private: static vector<B> vector_of_B; }; // A.cpp // defining it fixes the unresolved external: vector<B> A::vector_of_B; As a side note, your InstantiateVector() makes a lot of unnecessary copies that may (or may not) be optimized away. vector_of_B.reserve(5); // will prevent the need to reallocate the underlying // buffer if you plan on storing 5 (and only 5) objects for (i=0; i < 5; i++) { vector_of_B.push_back(B()); } In fact, for this simple example where you are just default constructing B objects, the most concise way of doing this is simply to replace the loop all together with: // default constructs 5 B objects into the vector vector_of_B.resize(5); A: You can either use a static helper or use boost::assign 1>using a small helper: #include <boost\assign.hpp> class B{}; class A { public: static bool m_helper; static bool InstantiateVector() { for (int i=0; i < 5; ++i) { B b; vector_of_B.push_back(b); } return true; } private: static vector<B> vector_of_B; }; bool A::m_helper = InstantiateVector();//helper help initialize static vector here 2> Use boost::assign which is eaiser, one line is enough: vector<B> A::vector_of_B = boost::assign::list_of(B())(B())(B())(B())(B());
{ "language": "en", "url": "https://stackoverflow.com/questions/7531981", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Android setImageUri not working with asset Uri I am using the following code to set an image from the assets folder. Uri numBgUri = Uri.parse("file:///android_asset/background_numbers.png"); numBgImage.setImageURI(numBgUri); The background_numbers.png file definitely exists in the assets root directory. I am getting a FileNotFoundException in the log: - 09-23 17:05:23.803: WARN/ImageView(23713): Unable to open content: file:///android_asset/background_numbers.png Any ideas what I could be doing wrong? Thanks! A: I managed to get a viable workaround for this using my own custom ContentProvider (It's easier than you think!). Thanks to skink on Google Groups for the tip This code should work, you just need to set a provider URL and register it as a provider in the manifest file package sirocco.widgets; import java.io.FileNotFoundException; import java.io.IOException; import android.content.ContentProvider; import android.content.ContentValues; import android.content.res.AssetFileDescriptor; import android.content.res.AssetManager; import android.database.Cursor; import android.net.Uri; public class AssetContentProvider extends ContentProvider { private AssetManager mAssetManager; public static final Uri CONTENT_URI = Uri.parse("content://your.provider.name"); @Override public int delete(Uri arg0, String arg1, String[] arg2) { return 0; } @Override public String getType(Uri uri) { return null; } @Override public Uri insert(Uri uri, ContentValues values) { return null; } @Override public boolean onCreate() { mAssetManager = getContext().getAssets(); return true; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { return null; } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { return 0; } @Override public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException { String path = uri.getPath().substring(1); try { AssetFileDescriptor afd = mAssetManager.openFd(path); return afd; } catch (IOException e) { throw new FileNotFoundException("No asset found: " + uri); } } } I hope this helps any googlers out there with the same problem! A: You need to place all images in you resources directory. For example : /root/res/drawable/background_numbers.png And you can access it via: numBgImage.setImageResource(R.drawable.background_numbers); A: I advice you to double check that: * *ImageView activity that appears in your logcat belongs to the same apk that your code. asset files are only readable from within your application. *The assets folder is in the project directory root. EDIT It seems that it is not possible to feed an ImageView directly from an asset ressource. See this question for illustration. As a workaround you should try to create a drawable from your asset file, then associate it with your Image view using ImageView.setImageDrawable: Drawable d = Drawable.createFromStream(getAssets().open("background_numbers.png"), null); if (null != d) numBgImage.setImageDrawable(d); The first line of this code is an adaptation of this answer from @IgorKhomenko .
{ "language": "en", "url": "https://stackoverflow.com/questions/7531989", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What does a single splat/asterisk in a Ruby argument list mean? I was poking through the Rails 3 ActiveRecord source code today and found a method where the entire parameter list was a single asterisk. def save(*) I couldn't find a good description of what this does (though I have some ideas based on what I know about splat arguments). What does it do, and why would you use it? A: It means it can have any number of arguments (including zero) and it discards all those arguments.
{ "language": "en", "url": "https://stackoverflow.com/questions/7531990", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How to scale down blocks without causing pixel overlapping I have a bunch of blocks that needs to be drawn into a grid. Now displaying them unscaled everything is fine but when I try to scale them down to fit withing a window I get "scale-artifacts" because I use a normal scale-ratio formula and floats. Is there a way to avoid these problems ? Common example data: Original length: 200000 Scaled down to a 25x25 pixel grid (it's this small for development and debugging) The scaled down max length: 625 (25 * 25) Scale-ratio: (625 / 200000) = 0,003125 Example data 1 - overlapping, scaled blocks overwrite each other Start of block => end of block: [start, end) 1: 2100 => 2800 2: 2800 => 3600 3: 3600 => 4500 4: 4500 => 5500 Jumping over showing the output of this example because I think example 2 and 3 will get the point across. Left it in for completeness. Example data 2 - incorrect space between 2 and 3 Start of block => end of block: [start, end) 1: 960 => 1440 2: 1440 => 1920 3: 1920 => 2400 1: 960 => 1440, length: 480, scaled length: 1.5: 2: 1440 => 1920, length: 480, scaled length: 1.5: 3: 1920 => 2400, length: 480, scaled length: 1.5: pixel start, end, length 1: 3, 0, 1 2: 4, 0, 1 3: 6, 0, 1 Displayed grid: [ 0, 0, 0, 1, 2, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] ... Example data 3 - 1 moved a step back incorrectly Start of block => end of block: [start, end) 1: 896 => 1344 2: 1344 => 1792 3: 1792 => 2240 1: 896 => 1344, length: 448, scaled length: 1.4: 2: 1344 => 1792, length: 448, scaled length: 1.4: 3: 1792 => 2240, length: 448, scaled length: 1.4: pixel start, end, length 1: 2, 0, 1 2: 4, 0, 1 3: 5, 0, 1 Displayed grid: [ 0, 0, 1, 0, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] ... What example data 2 and 3 should have looked like: [ 0, 0, 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] ... Remember the block values are [start, end) Preemptive strike (down-voters / trollers) Remember: I'm not psychic or a mind-reader. If you want to give negative do it in a constrictive way or it is useless (i will not learn anything) and will just pollute the thread. Update #include <iostream> #include <math.h> #include <limits.h> #include <assert.h> #include <vector> #include <array> #include <utility> // pair #include <algorithm> // for_each using namespace std; const size_t width_size = 25; // 25 pixels const size_t height_size = 25; // 25 pixels const size_t grid_length = width_size * height_size; // width * height array<size_t, grid_length> grid; const size_t original_length = 200000; typedef pair<unsigned long, unsigned long> block; vector<block> test_values; void show_grid() { for (size_t y = 0; y < height_size; ++y) { const size_t start_pos_for_current_heigth = y * width_size; const size_t end_pos_for_current_heigth = start_pos_for_current_heigth + width_size; cout << "[ "; for (size_t i = start_pos_for_current_heigth; i < end_pos_for_current_heigth; ++i) { if (i + 1 < end_pos_for_current_heigth) cout << grid[i] << ", "; else cout << grid[i]; }; cout << " ]" << endl; } } void scale_and_add(const float scale) { size_t test_value_id = 1; for_each(test_values.cbegin(), test_values.cend(), [&](const block &p) { const float s_f = p.first * scale; const unsigned long s = round(s_f); const float e_f = p.second * scale; const unsigned long e = round(e_f); const unsigned long block_length = p.second - p.first; const float block_length_scaled = block_length * scale; assert(s <= grid_length); assert(e <= grid_length); cout << test_value_id << ":" << endl; cout << " " << p.first << " => " << p.second << " length: " << block_length << endl; cout << " " << s << " (" << s_f << ") => " << e << " (" << e_f << ") length: " << (e - s) << " (" << block_length_scaled << ")" << " (scaled)" << endl; for (size_t i = s; i < e; ++i) { if (grid[i] != 0) { cout << "overlapp detected !" << endl; } grid[i] = test_value_id; } ++test_value_id; }); } void reset_common() { grid.fill(0); test_values.clear(); } int main() { const float scale = ((float)grid_length / (float)original_length); cout << "scale: " << scale << " length per pixel: " << ((float)original_length / (float)grid_length) << endl; // Example data 1 /* cout << "Example data 1" << endl; test_values.push_back(make_pair(2100, 2800)); test_values.push_back(make_pair(2800, 3600)); test_values.push_back(make_pair(3600, 4500)); test_values.push_back(make_pair(4500, 5500)); scale_and_add(scale); show_grid(); reset_common(); // Example data 2 cout << "Example data 2" << endl; test_values.push_back(make_pair(960, 1440)); test_values.push_back(make_pair(1440, 1920)); test_values.push_back(make_pair(1920, 2400)); scale_and_add(scale); show_grid(); reset_common(); // Example data 3 cout << endl << "Example data 3" << endl; test_values.push_back(make_pair(896, 1344)); test_values.push_back(make_pair(1344, 1792)); test_values.push_back(make_pair(1792, 2240)); scale_and_add(scale); show_grid(); reset_common();*/ // Generated data - to quickly find the problem cout << "Generated data" << endl; auto to_op = [&](const size_t v) { return v * (original_length / grid_length) * 1.3; // 1.4 and 1.5 are also good values to show the problem }; size_t pos = 0; size_t psize = 1; // Note this value (length) and check it with the displayed one, you'll be surprised ! for (size_t g = 0; g < 10; ++g) { test_values.push_back(make_pair(to_op(pos), to_op(pos + psize))); pos += psize; } scale_and_add(scale); show_grid(); return 0; } Output: scale: 0.003125 length per pixel: 320 Generated data 1: 0 => 416 length: 416 0 (0) => 1 (1.3) length: 1 (1.3) (scaled) 2: 416 => 832 length: 416 1 (1.3) => 3 (2.6) length: 2 (1.3) (scaled) 3: 832 => 1248 length: 416 3 (2.6) => 4 (3.9) length: 1 (1.3) (scaled) 4: 1248 => 1664 length: 416 4 (3.9) => 5 (5.2) length: 1 (1.3) (scaled) 5: 1664 => 2080 length: 416 5 (5.2) => 7 (6.5) length: 2 (1.3) (scaled) 6: 2080 => 2496 length: 416 7 (6.5) => 8 (7.8) length: 1 (1.3) (scaled) 7: 2496 => 2912 length: 416 8 (7.8) => 9 (9.1) length: 1 (1.3) (scaled) 8: 2912 => 3328 length: 416 9 (9.1) => 10 (10.4) length: 1 (1.3) (scaled) 9: 3328 => 3744 length: 416 10 (10.4) => 12 (11.7) length: 2 (1.3) (scaled) 10: 3744 => 4160 length: 416 12 (11.7) => 13 (13) length: 1 (1.3) (scaled) [ 1, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] This code example demonstrates my problem more clearly. Interesting fact: mingw-g++, which i used to write this example, shows slightly different values. I usually use visual studio 2010 but couldn't this time because I'm not at home. A: Yeah +1 to get you back up, the question is OK. I don't know why people thing it is so fun to downvote without even leaving a comment. Well, to the question :-) Usually when drawing you have this overlapping issues and in 3D computer graphics with scanline renderers (DirectX & OpenGL for ex) they usually Skip exactly one pixel (say all on the right and down side). Maybe this can help you out. It is possible too that when the division is perfect, you don't have the artefacts so you must maybe deal with that (ie. if the value is a 'perfect integer', for example 185.000000 then don't remove the last pixel). HTH A: I am not sure if I am getting the problem statement but I will take a stab at it. You have ranges of information that you are displaying contigously a range is usually [a,b). Everything is fine when a and b directly represent the pixels that you are trying to draw, but you are having problems when you want to scale the whole thing. Not dealing with multiple rows of pixels, if you have two ranges R1=[a,b) and R2=[b,c) unscaled you just draw from a to b-1 and from b to c-1 and your ranges are drawn so what is the problem in the scaled case drawing from (int)(a*scale) to ((int)(b*scale)-1) and then from (int)(b*scale) to ((int)(c*scale)-1), you can use any float to int conversion, rounding, floor or ceiling and you should be ok. The next problem area would be if your scale ranges amount to less than 1 pixel, in this case you might need to detect if the size of the scaled range is 0 and carry a correction factor (in pixels) that is added at the end of the calculation. Pseudocode DrawRanges(List<Range> ranges, float scale) int carry = 0; foreach(Range range in ranges) { int newStart = ceiling(range.start*scale); int newEnd = ceiling(range.end*scale)-1; if (newStart <= newEnd) { newEnd = newStart; ++carry; } DrawRange(newStart+carry,newEnd+carry); } This will eventually fail if you have more Ranges than blocks in your scaled down grid, you would have to figure out how to drop ranges completely. In draw rang you map your index to an actual block coordinate. Does this solve your problem ?
{ "language": "en", "url": "https://stackoverflow.com/questions/7531996", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to use an ArrayList java object passed into the Rhino javascript engine? The following data: sku=[111222] is being passed in as an argument to a javascript function being invoked in the Rhino javascript engine. On the java side (where the data originates) this means that a String key of "sku" is mapped to an ArrayList with one String "111222" inside it. Once this goes over to the Rhino side, I have no idea how to make use of this as a javascript object. For example: How do I even do something as simple as fetching the 111222 value on the JS side? I decided to spit out what a key/value dump of this object looked like on the JS side and this is what I got: sku= empty: false indexOf: function indexOf() {/* int indexOf(java.lang.Object) */} notifyAll: function notifyAll() {/* void notifyAll() */} removeAll: function removeAll() {/* boolean removeAll(java.util.Collection) */} trimToSize: function trimToSize() {/* void trimToSize() */} containsAll: function containsAll() {/* boolean containsAll(java.util.Collection) */} contains: function contains() {/* boolean contains(java.lang.Object) */} equals: function equals() {/* boolean equals(java.lang.Object) */} notify: function notify() {/* void notify() */} subList: function subList() {/* java.util.List subList(int,int) */} class: class java.util.ArrayList set: function set() {/* java.lang.Object set(int,java.lang.Object) */} isEmpty: function isEmpty() {/* boolean isEmpty() */} add: function add() {/* void add(int,java.lang.Object) boolean add(java.lang.Object) */} ensureCapacity: function ensureCapacity() {/* void ensureCapacity(int) */} size: function size() {/* int size() */} iterator: function iterator() {/* java.util.Iterator iterator() */} clear: function clear() {/* void clear() */} wait: function wait() {/* void wait() void wait(long) void wait(long,int) */} listIterator: function listIterator() {/* java.util.ListIterator listIterator(int) java.util.ListIterator listIterator() */} retainAll: function retainAll() {/* boolean retainAll(java.util.Collection) */} toString: function toString() {/* java.lang.String toString() */} hashCode: function hashCode() {/* int hashCode() */} toArray: function toArray() {/* java.lang.Object[] toArray(java.lang.Object[]) java.lang.Object[] toArray() */} lastIndexOf: function lastIndexOf() {/* int lastIndexOf(java.lang.Object) */} addAll: function addAll() {/* boolean addAll(java.util.Collection) boolean addAll(int,java.util.Collection) */} clone: function clone() {/* java.lang.Object clone() */} get: function get() {/* java.lang.Object get(int) */} getClass: function getClass() {/* java.lang.Class getClass() */} remove: function remove() {/* java.lang.Object remove(int) boolean remove(java.lang.Object) */} Can anyone tell me how to work with such objects in rhino javascript engine? A: The JavaScript program is receiving a Java ArrayList; this is why the above dump matches the API of java.util.ArrayList. (See the Java API documentation.) You can call the Java methods of that Java object relatively transparently from your JavaScript code. So, for example, to loop through the elements of the array you are receiving: var sku = [however you are getting it]; for (var i=0; i<sku.size(); i++) { var nextElement = sku.get(i); // do something } Caveat: Assuming the ArrayList is created on the Java side and is creating Java objects, the algorithm above will put a Java java.lang.String into the nextElement variable. This object may behave strangely if your application is JavaScript-centric (for example, typeof(nextElement) == "object" /* not "string" */). If you want a JavaScript string, you'll need to convert it; the easiest way is String(nextElement).
{ "language": "en", "url": "https://stackoverflow.com/questions/7532005", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Drupal Site Slow, Drupal Tweaks my site is very slow and i disabled the bulk of modules, so I think it was my hosting, first I upped the memory limit from 90M to 256M which helped with "500 errors" but the site is still very slow. I am thinking it may be the database settings, I am changing them with the module "drupal tweaks" for convenience. A: Define "slow". Is your page slow to appear? If so, is it taking a while to load the page's HTML, or is much of the time spent trying to load CSS, JS, images, etc.? The "Net" panel in Firebug can help here, as can wget. If the page itself is slow, is the slowness encountered at the network, Web server, PHP, or database level? Network slowness is easy to diagnose; try a ping. Either the network or the web server can show faults through the simple test of just throwing a big, static file somewhere on the server and then downloading it. PHP or DB slowness will show up when you look at the page with the devel module, but DB slowness can generally also be seen as long-running (as opposed to long-sleeping!) processes in the output of SHOW PROCESSLIST. Alternately, give NewRelic a try. It will automate several of these steps, and give you fancy graphs, to boot. Lastly: Consider getting a better hosting provider, ideally one with a great deal of Drupal experience (like BlackMesh or Acquia). At a great host, fixing this issue (if it arose in the first place) would be a collaborative effort between the hosting provider and the customer, rather than something you have to figure out on your own. It doesn't take many (billable) hours spent debugging hosting before you've paid for better hosting than you're getting now. A: If you have a staging or development copy of the site, try installing the Devel module, which has an option for logging and appending stats about each query to the bottom of each Drupal page. That should help you track down the offending query or queries. A: Here are some optimisation tips you might try. * *First it is possible that your cache table should be messed up. Try to log in your phpmyadmin and try to flush all your cache tables (don't delete the tables just empty them). *Check inside the MySql installation folders config file alternative like: my-large.ini, my-huge.ini and try to rename them and copy them as bin/my.ini they are out of the box optimisations for your mySQL database. *You never mentioned the Drupal version you use. Drupal 7 has a brand new database API build on top of PHP PDO objects. Here is a link that will help you a lot: http://drupal.org/node/310075 Rather than writing a SQL query in raw text and calling a helper function to execute the query, you can create a "query" object, call methods on it to add fields, filters, sorts, and other query elements, then call the query object's "execute" method. Others On my website PHP memory limit is 512Mb, 215Mb however should be ok for a production website. Also why don't you enable APC logging? Sometimes masive scripts could slow down your pages. in Performance, check your option: agregate CSS and JS file. you might consider Drupal Pressflow over Drupal. Boost up your website by installing Boost module: http://drupal.org/project/boost Cache your Views Other advanced techniques could include: Cacherouter ( a module that replace the default Drupal cache). Using Elysia Cron to reduce cron impact Eventually switch to a superior hosting package or change your hosting provider Regards... A: Drupal site performance is obvious slow, but if its slow to a extreme level then you can go with other options that improved its performance. 1) You can install the memcache module on server,that is very fast in terms of site caching. Refer: How to install memcache 2) Change the PHP ini settings or mysql conf. 3) Check the custom modules if have, because execution of frequent queries create deadlock. 4) Check the mysql table storage engine & I will recommend the InnoDB which will provide row level locking.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532007", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Defining POJO id in Spring form for single object this is what controller sends to me: model.addAttribute("weather", weatherService.getWeatherByCity(id)); this is my JSP: <form:form commandName="newWeather" method="post" action="edit"> <c:forEach items="${cities}" var="city"> <form:input path="temperature"></form:input> <input type="submit" value="Submit"> </c:forEach> </form:form> Problem: I get one object from database named weather. I want to edit that by changing temperature. So I must send back atleast id and field temperature. I know how to send back temperature as shown, but how can I send back my id. I think I can get it from model by ${weather.id}, but how can I place it in form? A: <input type="hidden" name="id" value="${weather.id}">
{ "language": "en", "url": "https://stackoverflow.com/questions/7532011", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: DosBox on Windows Phone 7 and Android? Is there any port of DosBox on Windows Phone 7 and Android? If not is it any good VM of any old hardware (QNX, DOS (DJGPP, Watcom), Amiga) for both Windows Phone 7 and Android? Basically I am trying to emulate my own game written in Allegro 4.2.3 on both Windows Phone 7 and Android. A: Your problem is that DOS was written for the x86 CPU, and few mobile devices use an x86 CPU. Most Android phones use ARM CPUs, and I imagine that Windows Phone is the same. You would either need to rewrite DOS and whatever "Allegro 4.2.3" is and your app to run on ARM, or run an x86 emulator on ARM and try to get all that code to run in the emulator. I am not aware of any x86 emulators that will run on Android or Windows Phone devices. A: I don't know about WinPhone7, but I do know that android does have a DOSBox port in progress. I've never used it personally (as it requires a hardware keyboard, and my current phone lacks one), but I've heard from others that it works pretty well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532014", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: FreeBSD: Questions about NIC ring buffers, mbufs, and bpf buffers I've been going through many technical documents on packet capture/processing and host stacks trying to understand it all, there's a few areas where I'm troubled, hopefully someone can help. Assuming you're running tcpdump: After a packet gets copied from a NIC's ring buffer (physical NIC memory right?) does it immediately get stored into an mbuf? and then BPF gets a copy of the packet from the mbuf , which is then stored in the BPF buffer, so there are two copies in memory at the same time? I'm trying to understand the exact process. Or is it more like: the packet gets copied from the NIC to both the mbuf (for host stack processing) and to the BPF pseudo-simultaneously? Once a packet goes through host stack processing by ip/tcp input functions taking the mbuf as the location(pointing to an mbuf) i.e. packets are stored in mbufs, if the packet is not addressed for the system, say received by monitoring traffic via hub or SPAN/Monitor port, the packet is discarded and never makes its way up the host stack. I seem to have come across diagrams which show the NIC ring buffer(RX/TX) in a kernel "box"/separating it from userspace, which makes me second guess whether a ring buffer is actually allocated system memory different from the physical memory on a NIC. Assuming that a ring buffer refers to the NIC's physical memory, is it correct that the device driver determines the size of the NIC ring buffer, setting physical limitations aside? e.g. can I shrink the buffer by modifying the driver? Thanks! A: ETHER_BPF_MTAP macro calls bpf_mtap(), which excepts packet in mbuf format, and bpf copies data from this mbuf to internal buffer. But mbufs can use external storage, so there can be or not be copying from NIC ring buffer to mbuf. Mbufs can actually contain packet data or serve just as a header with reference to receiving buffer. Also, current NICs use their little (128/96/... Kb) onboard memory for FIFO only and immediately transfer all data to ring buffers in main memory. So you really can adjust buffer size in device driver.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532017", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to open 3 different PDF reports in a single window? I am generating 3 different PDF reports with a servlet. There are 3 checkboxes in the JSP. If I click on all the 3 checkboxes, the PDF report will open in 3 windows by JavaScript. But I want them to be opened in a single window. How can I do this? Here is the JavaScript: for (i = 0; i < document.myform.FORMTYPE.length; i++) { if (document.myform.FORMTYPE[i].checked) { window.open('PDF_CNTRL_SERVLETS?FORMTYPE=' + document.myform.FORMTYPE[i].value + '&UNIQUEID1=' + CCNID + '&UNIQUEID2=' + arrestID); } } A: You need to collect the checked values in a single query string and then open only one window. var formtypes = []; for (i = 0; i < document.myform.FORMTYPE.length; i++) { if (document.myform.FORMTYPE[i].checked) { formtypes.push(document.myform.FORMTYPE[i].value); // Consider encodeURIComponent() the value whenever it is not guaranteed to contain only ASCII chars. } } if (formtypes.length) { window.open('PDF_CNTRL_SERVLETS?FORMTYPE=' + formtypes.join('&FORMTYPE=') + '&UNIQUEID1=' + CCNID + '&UNIQUEID2=' + arrestID); } In the servlet you can get all checked values by String[] formtypes = request.getParameterValues("FORMTYPE"); // ... Then you can let iText merge and output those 3 reports into a single response. A: Here is some code I wrote to merge PDFs using Apache PDFBox. Just loads the PDFs on the server into Streams or byte[] and call the correct method below. The code runs on the server, all you need to do is load it into a new Window or Frame. import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import org.apache.pdfbox.exceptions.COSVisitorException; import org.apache.pdfbox.util.PDFMergerUtility; public class PDFMerger { /** * Given a List of byte[] which contain the PDFs will return a new PDF * with the input PDFs appended one after the other * @param inputData * @return * @throws IOException */ public static byte[] mergePDFData(List<byte[]> inputData) throws IOException { byte[] retData = new byte[0]; if(inputData != null && !inputData.isEmpty()) { List<InputStream> inputs = new ArrayList<InputStream>(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { for(byte[] tmp : inputData) { if(tmp != null && tmp.length > 0) { ByteArrayInputStream bis = new ByteArrayInputStream(tmp); inputs.add(bis); } } mergePDFStreams(bos,inputs); retData = bos.toByteArray(); } finally { // close the streams if(bos != null) bos.close(); if(inputs != null && inputs.size() > 0) { for(InputStream is : inputs) { if(is != null) is.close(); } } } } return retData; } /** * Given a List of InputStreams containing PDFs will concatenate the PDFs to * the output stream * @param oStream * @param inputStreams * @throws IOException */ public static void mergePDFStreams(OutputStream oStream, List<InputStream> inputStreams ) throws IOException { if(oStream != null && inputStreams != null && !inputStreams.isEmpty()) { PDFMergerUtility mergerUtility = new PDFMergerUtility(); mergerUtility.addSources(inputStreams); mergerUtility.setDestinationStream(oStream); try { mergerUtility.mergeDocuments(); } catch(COSVisitorException cosve) { throw new IOException(cosve); } } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7532021", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: pygtk OSError: [Errno 2] No such file or directory. subprocess.Popen PIPE command I'm new to python and I'm trying to make a search bar that searches only 2 directories using two find commands and output the results into an ordered list []. def search_entry(self, widget,): s1 = subprocess.Popen(['find /home/bludiescript/tv-shows', '-type f'], shell=False, stdout=subprocess.PIPE) s2 = subprocess.Popen(['find /media/FreeAgent\ GoFlex\ Drive/tobins-media', '-type f'], stdin=s1.stdout, shell=False, stdout=subprocess.PIPE) s1.stdout.close() self.contents = "\n".join(self.list) s2.communicate(self.contents) My search bar: self.search = gtk.Entry() self.search.connect("activate", self.search_entry,) self.box1.pack_start(self.search, True, True, 0) self.search.show() errormsg: File "/usr/lib/python2.7/subprocess.py", line 679, in __init__ errread, errwrite) File "/usr/lib/python2.7/subprocess.py", line 1228, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory A: Separate all the arguments in the args list: s1 = subprocess.Popen(['find','/home/bludiescript/tv-shows', '-type','f'], shell=False, stdout=subprocess.PIPE) s2 = subprocess.Popen(['find','/media/FreeAgent\ GoFlex\ Drive/tobins-media', '-type', 'f'], stdin=s1.stdout, shell=False, stdout=subprocess.PIPE) OUTPUT on MINE >>> import subprocess >>> s1 = subprocess.Popen(['find /home/bludiescript/tv-shows', '-type f'], shell=False, stdout=subprocess.PIPE) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/subprocess.py", line 672, in __init__ errread, errwrite) File "/usr/lib/python2.7/subprocess.py", line 1201, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory >>> s1 = subprocess.Popen(['find','/home/bludiescript/tv-shows', '-type','f'], shell=False, stdout=subprocess.PIPE) >>> find: `/home/bludiescript/tv-shows': No such file or directory The first is your original code and it raises the python exception. The second runs correctly but "find" complains because I do not have a "bludiescript/tv-shows" directory on my system. A: Did you mean find on line 2? it looks like it is erroring on finding the file "fine"
{ "language": "en", "url": "https://stackoverflow.com/questions/7532023", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add attribute '_meta' to an object? I'm trying to add the django-voting app to my project. I don't know how to use it in my templates, so I'm adding a new template tags for voting up or down when an user click in buttons. I don't know if there's a well form to do it. My problem is with these kind of line in the template tag: obj = Place.objects.filter(id=object_id) Vote.objects.record_vote(obj, self.user, +1) django print: Caught AttributeError while rendering: 'Place' object has no attribute '_meta' How I can add the attribute _meta my object 'Place'? A: The problem is that obj here is not actually an object, but a queryset with one element. You should use get instead of filter, as get actually returns a model instance. obj = Place.objects.get(id=object_id)
{ "language": "en", "url": "https://stackoverflow.com/questions/7532025", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: I don't understand the error on eclipse Please somebody can help me with my error, there is nothing on console, but I can't run the project. This is creenshot: thanks for help A: Click on the Problems tab at the bottom, see what the error is. A: Clean your projects by going Eclipse>Project>clean A: Try cleaning the project (menu/Project/Clean). The project tree looks as if there's a compilation error in one of the files - there's a red "x" on the project; typically, the similar "x" would be on the problematic file. Which can be a source, or a resource, or the manifest. Open up the tree and try to find one. A: I think it is the build path, maybe you forgot to add a library or move it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532029", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: what is wrong with toDateString Following is a script+HTML that tells the user his last visit to page. <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Cookie</title> <script type="text/javascript"> window.onload = initLastVisit; function initLastVisit() { var now = new Date(); var last = new Date(); now.setMonth(now.getMonth()+6); document.cookie = "lastVisit=" + last.toDateString() + ";path=/;expires=" + now.toGMTString(); document.getElementById("lastVisitedOn").innerHTML = document.cookie.split("=")[1]; } </script> </head> <body> <form> <label>Enter your name&nbsp;&nbsp;<input type="text" id="name_field" /></label> <br/> </form> <h1 id="lastVisitedOn"></h1> </body> </html> The statement that sets the cookie in the above script is : document.cookie = "lastVisit=" + last.toDateString() + ";path=/;expires=" + now.toGMTString(); . If in this i replace now.toGMTString() with now.toDateString() the expire time in the browser is "Expires when i close my browser" . Why is that ? It is ok with toGMTString . The expire date is in march 2012 as expected. A: If you try them both in the console, you will see that they don't give the same resulting string at all: (new Date()).toGMTString(); "Fri, 23 Sep 2011 16:33:01 GMT" (new Date()).toDateString(); "Fri Sep 23 2011" When you set a cookie you have to specify the time using GMT format, if you don't your browser fail to recognize the expiry time and consider that none was specified. When no expiry date is specified, cookie are created as "session cookie", which expires once the session end (eg you close your browser). So when you use toDateString(), it is an invalid expiry format, your browser discards it and use its default value of creating a session cookie. A: This is due to the format that is output from toDateString() which is not valid for specifying the expiry date for a cookie. * toDateString() - Fri Sep 23 2011 * toGMTString() - Fri, 23 Sep 2011 16:31:24 GMT Due to the date string not being recognised the cookie will use default behaviour and expire at the end of the session. A: toDateString does not produce a valid date- there is no time zone, and no time data included. toGMT string returns an unambiguous time. I always wished for an integer time stamp, but a javascript timestamp is milliseconds-a thousand times bigger than the 'unix' seconds format. There is always max-age.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532031", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Getting a shell error code from curl in Jenkins while still displaying output in console I am using a shell script in Jenkins that, at a certain point, uploads a file to a server using curl. I would like to see whatever output curl produces but also check whether it is the output I expect. If it isn't, then I want to set the shell error code to > 0 so that Jenkins knows the script failed. I first tried using curl -f, but this causes the pipe to be cut as soon as the upload fails and the error output never gets to the client. Then I tried something like this: curl ...params... | tee /dev/tty | \ xargs -I{} test "Expected output string" = '{}' This works from a normal SSH shell but in the Jenkins console output I see: tee: /dev/tty: No such device or address I'm not sure why this is since I thought Jenkins was communicating with the slave using a normal SSH shell. In any case, the whole xargs + test thing strikes me as a bit of a hack. Is there a way to accomplish this in Jenkins so that I can see the output and also test whether it matches a specific string? A: When Jenkins communicates with slave via SSH, there is no terminal allocated, and so there is no /dev/tty device for that process. Maybe you can send it to /dev/stderr instead? It will be a terminal in an interactive session and some log file in non-interactive session. A: Have you thought about using the Publish over SSH Plugin instead of using curl? Might save you some headache. If you just copy the file from master to slave there is also a plugin for that, copy to slave Plugin. Cannot write any comments yet, so I had to post it as an answer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532036", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Difference between "(NSSet *)touches" and "event.allTouches" in "touchesBegan:withEvent:" I need to move, rotate and zoom an UIImageView object. In the method... touchesBegan(NSSet *)touches withEvent:(UIEvent *)event which touches do I have to use? (NSSet *)touches or event.allTouches In other words, where are my touches? A: touches passed as the parameter are the touches in your view. event.allTouches contains all the touches of the event, even the one that didn't start in your view. Don't hesitate to read the Event Handling Guide for iOS in Apple's doc, it is explained with some pictures it will probably help you understand better. Especially the difference between the touches in the parameters and event.allTouches is described here ;)
{ "language": "en", "url": "https://stackoverflow.com/questions/7532039", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Replacing multiple substrings in Java when replacement text overlaps search text Say you have the following string: cat dog fish dog fish cat You want to replace all cats with dogs, all dogs with fish, and all fish with cats. Intuitively, the expected result: dog fish cat fish cat dog If you try the obvious solution, looping through with replaceAll(), you get: * *(original) cat dog fish dog fish cat *(cat -> dog) dog dog fish dog fish dog *(dog -> fish) fish fish fish fish fish fish *(fish -> cat) cat cat cat cat cat cat Clearly, this is not the intended result. So what's the simplest way to do this? I can cobble something together with Pattern and Matcher (and a lot of Pattern.quote() and Matcher.quoteReplacement()), but I refuse to believe I'm the first person to have this problem and there's no library function to solve it. (FWIW, the actual case is a bit more complicated and doesn't involve straight swaps.) A: It seems StringUtils.replaceEach in apache commons does what you want: StringUtils.replaceEach("abcdeab", new String[]{"ab", "cd"}, new String[]{"cd", "ab"}); // returns "cdabecd" Note that the documenent at the above links seems to be in error. See comments below for details. A: String rep = str.replace("cat","§1§").replace("dog","§2§") .replace("fish","§3§").replace("§1§","dog") .replace("§2§","fish").replace("§3§","cat"); Ugly and inefficient as hell, but works. OK, here's a more elaborate and generic version. I prefer using a regular expression rather than a scanner. That way I can replace arbitrary Strings, not just words (which can be better or worse). Anyway, here goes: public static String replace( final String input, final Map<String, String> replacements) { if (input == null || "".equals(input) || replacements == null || replacements.isEmpty()) { return input; } StringBuilder regexBuilder = new StringBuilder(); Iterator<String> it = replacements.keySet().iterator(); regexBuilder.append(Pattern.quote(it.next())); while (it.hasNext()) { regexBuilder.append('|').append(Pattern.quote(it.next())); } Matcher matcher = Pattern.compile(regexBuilder.toString()).matcher(input); StringBuffer out = new StringBuffer(input.length() + (input.length() / 10)); while (matcher.find()) { matcher.appendReplacement(out, replacements.get(matcher.group())); } matcher.appendTail(out); return out.toString(); } Test Code: System.out.println(replace("cat dog fish dog fish cat", ImmutableMap.of("cat", "dog", "dog", "fish", "fish", "cat"))); Output: dog fish cat fish cat dog Obviously this solution only makes sense for many replacements, otherwise it's a huge overkill. A: I would create a StringBuilder and then parse the text once, one word at a time, transferring over unchanged words or changed words as I go. I wouldn't parse it for each swap as you're suggesting. So rather than doing something like: // pseudocode text is new text swapping cat with dog text is new text swapping dog with fish text is new text swapping fish with cat I'd do for each word in text if word is cat, swap with dog if word is dog, swap with fish if word is fish, swap with cat transfer new word (or unchanged word) into StringBuilder. I'd probably make a swap(...) method for this and use a HashMap for the swap. For example import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class SwapWords { private static Map<String, String> myMap = new HashMap<String, String>(); public static void main(String[] args) { // this would really be loaded using a file such as a text file or xml // or even a database: myMap.put("cat", "dog"); myMap.put("dog", "fish"); myMap.put("fish", "dog"); String testString = "cat dog fish dog fish cat"; StringBuilder sb = new StringBuilder(); Scanner testScanner = new Scanner(testString); while (testScanner.hasNext()) { String text = testScanner.next(); text = myMap.get(text) == null ? text : myMap.get(text); sb.append(text + " "); } System.out.println(sb.toString().trim()); } } A: public class myreplase { public Map<String, String> replase; public myreplase() { replase = new HashMap<String, String>(); replase.put("a", "Apple"); replase.put("b", "Banana"); replase.put("c", "Cantalope"); replase.put("d", "Date"); String word = "a b c d a b c d"; String ss = ""; Iterator<String> i = replase.keySet().iterator(); while (i.hasNext()) { ss += i.next(); if (i.hasNext()) { ss += "|"; } } Pattern pattern = Pattern.compile(ss); StringBuilder buffer = new StringBuilder(); for (int j = 0, k = 1; j < word.length(); j++,k++) { String s = word.substring(j, k); Matcher matcher = pattern.matcher(s); if (matcher.find()) { buffer.append(replase.get(s)); } else { buffer.append(s); } } System.out.println(buffer.toString()); } public static void main(String[] args) { new myreplase(); } } Output :- Apple Banana Cantalope Date Apple Banana Cantalope Date A: Here's a method to do it without regex. I noticed that every time a part of the string a gets replaced with b, b will always be part of the final string. So, you can ignore b from the string from then on. Not only that, after replacing a with b, there will be a "space" left there. No replacement can take place across where b is supposed to be. These actions add up to look a lot like split. split up the values (making the "space" in between strings), do further replacements for each string in the array, then joins them back. For example: // Original "cat dog fish dog fish cat" // Replace cat with dog {"", "dog fish dog fish", ""}.join("dog") // Replace dog with fish { "", {"", " fish ", " fish"}.join("fish") "" }.join("dog") // Replace fish with cat { "", { "", {" ", " "}.join("cat"), {" ", ""}.join("cat") }.join("fish") "" }.join("dog") So far the most intuitive way (to me) is to do this is recursively: public static String replaceWithJointMap(String s, Map<String, String> map) { // Base case if (map.size() == 0) { return s; } // Get some value in the map to replace Map.Entry pair = map.entrySet().iterator().next(); String replaceFrom = (String) pair.getKey(); String replaceTo = (String) pair.getValue(); // Split the current string with the replaceFrom string // Use split with -1 so that trailing empty strings are included String[] splitString = s.split(Pattern.quote(replaceFrom), -1); // Apply replacements for each of the strings in the splitString HashMap<String, String> replacementsLeft = new HashMap<>(map); replacementsLeft.remove(replaceFrom); for (int i=0; i<splitString.length; i++) { splitString[i] = replaceWithJointMap(splitString[i], replacementsLeft); } // Join back with the current replacements return String.join(replaceTo, splitString); } I don't think this is very efficient though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Why is my CSS not working and Div's collapsing? I think I must be having a Friday moment, but why are my DIV's all collapsing and the styles not taking effect on the following link http://s374335087.websitehome.co.uk/help.html A: I don't think a CSS class name can start with a number.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532043", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Finding a grid in an image Having a match-3 game screenshot (for example http://www.gameplay3.com/images/games/jewel-quest-ii-01S.jpg), what would be the correct way to find the bound box for the grid (table with tiles)? The board doesn't have to be a perfect rectangle (as can be seen in the screenshot), but each cell is completely square. I've tried several games, and found that there are some per-game image transformations that can be done to enhance the tiles inside the grid (for example in this game it's enough to take the V channel out of HSV color space). Then I can enlarge the tiles so that they overlap, find the largest contour of the image and get the bound box from it. The problem with above approach is that every game (or even level inside the same game) may need a different transformation to get hold of the tiles. So the question is - is there a standard way to enhance either tiles inside the grid or grid's lines (I've tried finding lines with Hough transform, but, although the grid seems pretty visible to the eye, Hough doesn't find it)? Also, what if the screenshot is obtained using the phone camera instead of taking a screenshot of a desktop? From my experience, captured images have less defined colors (which depends on lighting), and also can be distorted a little, as there is no way to hold the phone exactly in front of the screen. A: I would go with the following approach for a screenshot: * *Find corners in the image using for example a canny like edge detector. *Perform a hough line transform. This should work quite nicely on the edge image. *If you have some information about size of the tiles you could eliminate false positive lines using some sort of spatial model of the grid (eg. lines only having a small angle to x/y axis of the image and/or distance/angle of tile borders. *Identifiy tile borders under the found hough lines by looking for edges found by canny under/next to the lines. Which implementation of the hough transform did you use? How did you preprocess the image? Another approach would be to use some sort of machine learning approach. As you are working in OpenCV you could use either a Haar like feature detector. An example for face detection using Haar like features can be found here: OpenCV Haar Face Detector example Another machine learning approach would be to follow a Histogram of Oriented Gradients (Hog) approach in combination with a Support Vector Machine (SVM). An example is located here: HOG example You can find general information about HoG detection at: Hog detection
{ "language": "en", "url": "https://stackoverflow.com/questions/7532045", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Strategy for dealing with floating point inaccuracy Is there a general best practice strategy for dealing with floating point inaccuracy? The project that I'm working on tried to solve them by wrapping everything in a Unit class which holds the floating point value and overloads the operators. Numbers are considered equal if they "close enough," comparisons like > or < are done by comparing with a slightly lower or higher value. I understand the desire to encapsulate the logic of handling such floating point errors. But given that this project has had two different implementations (one based on the ratio of the numbers being compared and one based on the absolute difference) and I've been asked to look at the code because its not doing the right, the strategy seems to be a bad one. So what is best the strategy for try to make sure you handle all of the floating point inaccuracy in a program? A: Check comparing floating point numbers and this post on deniweb and this on SO. A: You want to keep data as dumb as possible, generally. Behavior and the data are two concerns that should be kept separate. The best way is to not have unit classes at all, in my opinion. If you have to have them, then avoid overloading operators unless it has to work one way all the time. Usually it doesn't, even if you think it does. As mentioned in the comments, it breaks strict weak ordering for instance. I believe the sane way to handle it is to create some concrete comparators that aren't tied to anything else. struct RatioCompare { bool operator()(float lhs, float rhs) const; }; struct EpsilonCompare { bool operator()(float lhs, float rhs) const; }; People writing algorithms can then use these in their containers or algorithms. This allows code reuse without demanding that anyone uses a specific strategy. std::sort(prices.begin(), prices.end(), EpsilonCompare()); std::sort(prices.begin(), prices.end(), RatioCompare()); Usually people trying to overload operators to avoid these things will offer complaints about "good defaults", etc. If the compiler tells you immediately that there isn't a default, it's easy to fix. If a customer tells you that something isn't right somewhere in your million lines of price calculations, that is a little harder to track down. This can be especially dangerous if someone changed the default behavior at some point. A: Both techniques are not good. See this article. Google Test is a framework for writing C++ tests on a variety of platforms. gtest.h contains the AlmostEquals function. // Returns true iff this number is at most kMaxUlps ULP's away from // rhs. In particular, this function: // // - returns false if either number is (or both are) NAN. // - treats really large numbers as almost equal to infinity. // - thinks +0.0 and -0.0 are 0 DLP's apart. bool AlmostEquals(const FloatingPoint& rhs) const { // The IEEE standard says that any comparison operation involving // a NAN must return false. if (is_nan() || rhs.is_nan()) return false; return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_) <= kMaxUlps; } Google implementation is good, fast and platform-independent. A small documentation is here. A: To me floating point errors are essentially those which on an x86 would lead to a floating point exception (assuming the coprocessor has that interrupt enabled). A special case is the "inexact" exception i e when the result was not exactly representable in the floating point format (such as when dividing 1 by 3). Newbies not yet at home in the floating-point world will expect exact results and will consider this case an error. As I see it there are several strategies available. * *Early data checking such that bad values are identified and handled when they enter the software. This lessens the need for testing during the floating operations themselves which should improve performance. *Late data checking such that bad values are identified immediately before they are used in actual floating point operations. Should lead to lower performance. *Debugging with floating point exception interrupts enabled. This is probably the fastest way to gain a deeper understanding of floating point issues during the development process. to name just a few. When I wrote a proprietary database engine over twenty years ago using an 80286 with an 80287 coprocessor I chose a form of late data checking and using x87 primitive operations. Since floating point operations were relatively slow I wanted to avoid doing floating point comparisons every time I loaded a value (some of which would cause exceptions). To achieve this my floating point (double precision) values were unions with unsigned integers such that I would test the floating point values using x86 operations before the x87 operations would be called upon. This was cumbersome but the integer operations were fast and when the floating point operations came into action the floating point value in question would be ready in the cache. A typical C sequence (floating point division of two matrices) looked something like this: // calculate source and destination pointers type1=npx_load(src1pointer); if (type1!=UNKNOWN) /* x87 stack contains negative, zero or positive value */ { type2=npx_load(src2pointer); if (!(type2==POSITIVE_NOT_0 || type2==NEGATIVE)) { if (type2==ZERO) npx_pop(); npx_pop(); /* remove src1 value from stack since there won't be a division */ type1=UNKNOWN; } else npx_divide(); } if (type1==UNKNOWN) npx_load_0(); /* x86 stack is empty so load zero */ npx_store(dstpointer); /* store either zero (from prev statement) or quotient as result */ npx_load would load value onto the top of the x87 stack providing it was valid. Otherwise the top of the stack would be empty. npx_pop simply removes the value currently at the top of the x87. BTW "npx" is an abbreviation for "Numeric Processor eXtenstion" as it was sometimes called. The method chosen was my way of handling floating-point issues stemming from my own frustrating experiences at trying to get the coprocessor solution to behave in a predictable manner in an application. For sure this solution led to overhead but a pure *dstpointer = *src1pointer / *src2pointer; was out of the question since it didn't contain any error handling. The extra cost of this error handling was more than made up for by how the pointers to the values were prepared. Also, the 99% case (both values valid) is quite fast so if the extra handling for the other cases is slower, so what?
{ "language": "en", "url": "https://stackoverflow.com/questions/7532049", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: writing xml data to sql server using sqlbulkcopy in C# asp.net I have two xml files on m system called customers.xml and customerdetails.xml. I am attempting to write this data directly to an sql database I created in asp.net. All of my coding is in C#. The sql database contains a table called CustomerDetails which has the fields CustomerID, CustomerN, CustomerLN, CustomerAdd, CustomerTelNo, and Comments. In asp.net I have created a page called update which contains a upload control which I am attempting to get the xml file and write the data to the database. The code for the control is as follows: using System; using System.Collections.Generic; using System.Data; using System.Data.Sql; using System.Data.SqlClient; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebApplication9 { public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { if (FileUpload1.HasFile) { string fileExt = System.IO.Path.GetExtension(FileUpload1.FileName); if (fileExt == ".xml") { try { DataSet reportData = new DataSet(); SqlConnection connection = new SqlConnection(@"Data Source=.\SQLEXPRESS; AttachDbFilename=|DataDirectory|\CustomerDetails.mdf;Integrated Security=True;User Instance=True"); SqlBulkCopy sbc = new SqlBulkCopy(connection); sbc.DestinationTableName = "CustomerInfo"; connection.Open(); sbc.WriteToServer(reportData.Tables[0]); } catch (Exception ex) { Label1.Text = "ERROR: " + ex.Message.ToString(); } } else { Label1.Text = "Only .xml files allowed!"; } } else { Label1.Text = "You have not specified a file."; } } } } However when I attempt to get the file I am getting an error which says cannot find table [0]; Can anyone help me identify what the problem is here!! A: All you have done here so far is to create a dataset. In order to user table[0] a datatable needs to be added to the dataset. Here's some basics to added a datatable to a dataset: http://msdn.microsoft.com/en-us/library/aeskbwf7(v=vs.80).aspx A: You need some way to get your XML data into the DataSet before you can call .Tables[0]. Try using the .ReadXml() function of the DataSet class to load the data into your dataset: FROM: http://msdn.microsoft.com/en-us/library/fx29c3yd(v=VS.100).aspx DataSet dataSet = new DataSet(); DataTable dataTable = new DataTable("table1"); dataTable.Columns.Add("col1", typeof(string)); dataSet.Tables.Add(dataTable); string xmlData = "<XmlDS><table1><col1>Value1</col1></table1><table1><col1>Value2</col1></table1></XmlDS>"; System.IO.StringReader xmlSR = new System.IO.StringReader(xmlData); dataSet.ReadXml(xmlSR, XmlReadMode.IgnoreSchema); Then you should be able to call sbc.WriteToServer(reportData.Tables[0]); no problem. A: First, you need to save the file to the server. Once you save the file you can populate your DataTable using the DataTable.ReadXml() method. string physicalFilename = Server.MapPath("~/") + filename; FileUploadControl1.SaveAs(physicalFilename); DataTable dt = new DataTable(); dt.ReadXml(physicalFileName); // use SlkBulkCopy to import the dt You may need to add ColumnMappings to the SqlBulkCopy.ColumnMappings collection if your DataTable column names do not match exactly what is in your database.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532052", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Download grid view and some text into a excel in asp.net website I am binding data to a grid view. string MysqlStatement = "SELECT TimeReceived,TimeRead, Concat(FirstName,', ',LastName) as Name FROM tbl_usermessage INNER JOIN tbl_user on tbl_usermessage.UserID = tbl_user.UserID WHERE MsgID = @Value1"; using (DataServer server = new DataServer()) { MySqlParameter[] param = new MySqlParameter[1]; param[0] = new MySqlParameter("@value1", MySqlDbType.Int32); param[0].Value = MessageID; command.Parameters.AddWithValue("@Value1", MessageID); ds = server.ExecuteQuery(CommandType.Text, MysqlStatement, param); } Grid_UserTable.DataSource = ds; Grid_UserTable.DataBind(); I am binding data to a repeater list, string MysqlStatement = "SELECT Title, RespondBy, ExpiresBy, OwnerName, Concat(LowTarget,' - ',TopTarget) as Threshold FROM tbl_message WHERE MsgID = @Value1"; using (DataServer server = new DataServer()) { MySqlParameter[] param = new MySqlParameter[1]; param[0] = new MySqlParameter("@value1", MySqlDbType.Int32); param[0].Value = MessageID; command.Parameters.AddWithValue("@Value1", MessageID); ds = server.ExecuteQuery(CommandType.Text, MysqlStatement, param); } rptList.DataSource = ds; rptList.DataBind(); I have a button to download the report protected void btn_ExcelDownload_Click(object sender, EventArgs e) { string path = Server.MapPath(""); path = path + @"\Resources\MessageStatus.xlsx"; string filename = Path.GetFileName(path); Response.AppendHeader("content-disposition", "attachment; filename=" + filename); Response.ContentType = "Application/msexcel"; Response.WriteFile(path); Response.End(); } I tried few things and managed to download the excel sheet from the button click, but How can I fill all the data from the repeater list and grid view. I haven't done this before pls help. A: Sample aspx: <asp:Repeater ID="Repeater1" runat="server"> <HeaderTemplate> <table> <thead> <tr> <th>Foo</th> <th>Bar</th> </tr> </thead> </HeaderTemplate> <ItemTemplate> <tr> <td>Whatever <%# Container.DataItem %></td> <td>Stuff <%# Container.DataItem %></td> </tr> </ItemTemplate> <FooterTemplate> </table> </FooterTemplate> </asp:Repeater> Sample code behind protected void Button1_Click(object sender, EventArgs e) { Repeater1.DataSource = Enumerable.Range(1, 10); Repeater1.DataBind(); StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); HtmlTextWriter writer = new HtmlTextWriter(sw); Repeater1.RenderControl(writer); Response.Clear(); Response.AppendHeader("content-disposition", "attachment; filename=foo.xlsx"); Response.ContentType = "Application/msexcel"; Response.Write(sb.ToString()); Response.End(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7532053", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get All Strings between tags and echo them? Possible Duplicate: Get content between two strings PHP Ok, here is my delima: here is an example of my $content : <!--nextpage-->First Title Here<!--nexttitle--> some more text here and here and here and here a little more here! <!--nextpage-->Second Title Here<!--nexttitle--> some more text here and here and here and here a little more here! <!--nextpage-->Third Title Here<!--nexttitle--> some more text here and here and here and here a little more here! How could I run a function that finds all "get_all_strings_between()" and echo them at the top of the $content: **First Title Here** / **Second Title Here** / **Third Title Here** and then my content HERE! THanks!! A: If I understood your question correctly this regexp will do it: function get_all_strings_between($content) { preg_match_all('/<!--nextpage-->([^<]*)<!--nexttitle-->/', $content, $m); return implode(' / ', $m[1]); } // then you echo get_all_strings_between($content) where you need it If I'm incorrect, please provide more info what are these nextpage and nexttitle tags? Are they appear like this literally?
{ "language": "en", "url": "https://stackoverflow.com/questions/7532056", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Why isn't RAM as fast as registers/cache memory? Why do we need to cache in Cache Memory? Why cant RAM Memory be made as fast as register or Cache Memory or Cache be as large as RAM Memory (4GB) so that everything can be in cache? Any good article/books to understand these concepts? A: Faster stuff costs more per bit. So you have a descending chain of storage, from a few registers at one end, through several levels of cache, down to RAM. Each level is bigger and slower than the one before. And all the way at the bottom you have disk. A: Registers and cache are on the cpu chip itself, or tied to it very closely. Normal RAM is accessed through an address bus, and it often subject to a level of indirection by memory mapping.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532057", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Modal view not displaying properly I am writing an iPad app and want to put an option on the home screen (root view controller) to allow users to e-mail feedback. I would like the mail to appear with the style "UIModalPresentationFormSheet". However, when I run the code, it appears full screen. What am I doing wrong? Here is the code I am using: MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init]; picker.mailComposeDelegate = self; NSArray *toAddresses = [[NSArray alloc] initWithObjects:@"user@domain.com", nil]; [picker setToRecipients:toAddresses]; [toAddresses release]; [picker setSubject:@"App Feedback"]; self.modalPresentationStyle = UIModalPresentationFormSheet; [self presentModalViewController:picker animated:YES]; [picker release]; A: You must set the style of the viewController being presented, not on the one presenting it.. So set the property of the MFMailComposeViewController and you should be ok. A: You need to set modalPresentationStyle on your new view controller, not self.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532063", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Assign names from one list to another I got a bunch dynamically created regressions stored in some list called regressions. Now I´d like to rename their coefficients efficiently. What I have so far is this loop that works: for (i in 1:length(params[,1])){ names(regressions[[i]]$coefficients)[pos] <- paste(params[i,1],".lag",params[i,2],sep="") } I've been trying for quite a while to get this done a little more generally with the help of a function, cause this not the only list of regressions I have. However I could not get anything else to work. Here a few other tries basically based on lapply: correctNames <- function(reglist,namevec,pos){ names(reglist[[i]]$coefficients)[pos] <- as.character(namevec) } lapply(regressions,correctNames(reglist,namevec,pos), reglist=regressions,namevec=params[,1],pos=2) Another try was to write a function with a for loop which also works internally as print shows but does not assign the names globally (where the regressions list is stored). correctNames <- function(reglist,pos,namevec){ for (i in 1:length(params[,1])){ names(reglist[[i]]$coefficients)[pos] <- paste(namevec,".lag",namevec,sep="") } #this test proves it's work inside the function... print(reglist[[10]] } Ah, gimme a break. A: There's no "i" inside that first version of "correctNames" function; and you probably don't realize that you are not assigning it to "regressions", only to a copy of the regression object. Try instead: correctNames <- function(reglist,namevec,pos){ names(reglist$coefficients)[pos] <- as.character(namevec) return(reglist) } newregs <- mapply(correctNames, reglist=regressions, namevec=as.character(params[,1]), MoreArgs= list( pos=2)) After seeing the note from Ramnath and noticing that the code did work but was giving flaky names for the "params" I looked at params and saw that it was a factor, and so changed the argument in the mapply call to as.character(params[,1]). > newregs[1,1] [[1]] (Intercept) log(M1) -5.753758 2.178137 A: If this is a follow up to your earlier question, then here is what I would do coefs = plyr::ldply(regressions, coef) coefs = transform(coefs, reg_name = paste(x, '.lag', l, sep = ""))[,-c(1, 2)] names(coefs) = c('intercept', 'reg_coef', 'reg_name') This gives you intercept reg_coef reg_name 1 -5.753758 2.178137 log(M1).lag0 2 7.356434 7.532603 rs.lag0 3 7.198149 8.993312 rl.lag0 4 -5.840754 2.193382 log(M1).lag1 5 7.366914 7.419599 rs.lag1 6 7.211223 8.879969 rl.lag1 7 -5.988306 2.220994 log(M1).lag4 8 7.395494 7.127231 rs.lag4 9 7.246161 8.582998 rl.lag4
{ "language": "en", "url": "https://stackoverflow.com/questions/7532064", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Parallelize while loop with OpenMP I have a very large data file, and each record in this data file has 4 lines. I have written a very simple C program to analyze files of this type and print out some useful information. The basic idea of the program is this. int main() { char buffer[BUFFER_SIZE]; while(fgets(buffer, BUFFER_SIZE, stdin)) { fgets(buffer, BUFFER_SIZE, stdin); do_some_simple_processing_on_the_second_line_of_the_record(buffer); fgets(buffer, BUFFER_SIZE, stdin); fgets(buffer, BUFFER_SIZE, stdin); } print_out_result(); } This of course leaves out some details (sanity/error checking, etc), but that is not relevant to the question. The program works fine, but the data files I'm working with are huge. I figured I would try to speed up the program by parallelizing the loop with OpenMP. After a bit of searching, though, it appears that OpenMP can only handle for loops where the number of iterations is know beforehand. Since I don't know the size of the files beforehand, and even simple commands like wc -l take a long time to run, how can I parallelize this program? A: As thiton mentioned, this code could be I/O bounded. However, these days many computers may have SSDs and high-throughput RAID disks. In such case, you can get speedup from parallelization. Moreover, if the computation is not trivial, then parallelize wins. Even if the I/O is effectively serialized due to saturated bandwidth, you can still get speedup by distributing the computation to multicore. Back to the question itself, you can parallelize this loop by OpenMP. With stdin, I have no idea to parallelize because it needs to read sequentially and no prior information of the end. However, if you're working a typical file, you can do it. Here is my code with omp parallel. I used some Win32 API and MSVC CRT: void test_io2() { const static int BUFFER_SIZE = 1024; const static int CONCURRENCY = 4; uint64_t local_checksums[CONCURRENCY]; uint64_t local_reads[CONCURRENCY]; DWORD start = GetTickCount(); omp_set_num_threads(CONCURRENCY); #pragma omp parallel { int tid = omp_get_thread_num(); FILE* file = fopen("huge_file.dat", "rb"); _fseeki64(file, 0, SEEK_END); uint64_t total_size = _ftelli64(file); uint64_t my_start_pos = total_size/CONCURRENCY * tid; uint64_t my_end_pos = min((total_size/CONCURRENCY * (tid + 1)), total_size); uint64_t my_read_size = my_end_pos - my_start_pos; _fseeki64(file, my_start_pos, SEEK_SET); char* buffer = new char[BUFFER_SIZE]; uint64_t local_checksum = 0; uint64_t local_read = 0; size_t read_bytes; while ((read_bytes = fread(buffer, 1, min(my_read_size, BUFFER_SIZE), file)) != 0 && my_read_size != 0) { local_read += read_bytes; my_read_size -= read_bytes; for (int i = 0; i < read_bytes; ++i) local_checksum += (buffer[i]); } local_checksums[tid] = local_checksum; local_reads[tid] = local_read; fclose(file); } uint64_t checksum = 0; uint64_t total_read = 0; for (int i = 0; i < CONCURRENCY; ++i) checksum += local_checksums[i], total_read += local_reads[i]; std::cout << checksum << std::endl << total_read << std::endl << double(GetTickCount() - start)/1000. << std::endl; } This code looks a bit dirty because I needed to precisely distribute the amount of the file to be read. However, the code is fairly straightforward. One thing keep in mind is that you need to have a per-thread file pointer. You can't simply share a file pointer because the internal data structure may not be thread-safe. Also, this code can be parallelized by parallel for. But, I think this approach is more natural. Simple experimental results I have tested this code to read a 10GB file on either a HDD (WD Green 2TB) and a SSD (Intel 120GB). With a HDD, yes, no speedups were obtained. Even slowdown was observed. This clearly shows that this code is I/O bounded. This code virtually has no computation. Just I/O. However, with a SSD, I had a speedup of 1.2 with 4 cores. Yes, the speedup is small. But, you still can get it with SSD. And, if the computation becomes a bit more (I just put a very short busy-waiting loop), speedups would be significant. I was able to get speedup of 2.5. In sum, I'd like to recommend that you try to parallelize this code. Also, if the computation is not trivial, I would recommend pipelining. The above code simply divides into several big chunks, resulting in poor cache efficiency. However, pipeline parallelization may yield better cache utilization. Try to use TBB for pipeline parallelization. They provide a simple pipeline construct. A: Have you checked that your process is actually CPU-bound and not I/O-bound? Your code looks very much like I/O-bound code, which would gain nothing from parallelization. A: In response to "minding", I don't think your code actually optimize anything here. There are a lot of common misunderstanding about this statement "#pragma omp parallel", this one would actually just spawn the threads, without the "for" key word, all the threads will just execute whatever codes that are following. So your code would actually be duplicating the computation on each thread. In response to Daniel, you were right, OpenMP can't optimize while loop, the only way to optimize it is by restructuring the code so that iteration is known in advance (such as while loop it once with a counter). Sorry about posting another answer, as I can't comment yet, but hopefully, this clears out the common misunderstandings.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532067", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Java: Exception in constructors: Problematic or not? I am recently thinking about if throwing constructor from Java is good or not. Currently this is what I gathered: * *Can constructors throw exceptions in Java? Here, Mr. StackOverflow (aka Jon Skeet) does not seem to hold anything against it, but he did hint about having subclass throwing exceptions. What will happen (anything bad?) when subclass throws exceptions? *http://futuretask.blogspot.com/2006/05/java-tip-10-constructor-exceptions-are.html This blog post "Constructor Exceptions are Evil" tells me a way to show that constructor exceptions could be dangerous. However, the example seem to be really esoteric. Is there any real danger here? *I am thinking that if static factory methods (Effective Java 2nd ed., Item 1) are used instead of public constructors, we could safely remove the exceptions from constructors to the static factory method. Is this a valid way to avoid constructor exceptions and is this useful or used in anywhere? Any inputs are helpful & appreciated. Thanks! A: My point about a subclass throwing an exception is a situation like this: public class Parent { private final InputStream stream; public Parent() { stream = new FileInputStream(...); } public void close() throws IOException { stream.close(); } } public class Child extends Parent { public Child() { // Implicit call to super() if (someCondition) { throw new RuntimeException(); } } } Now the Child class really should call close() if it's going to throw an exception. Of course, if close() is overridden by yet another layer of inheritance, that could also cause problems. Just another example of how inheritance gets messy. I still think it's basically fine for constructors to throw exceptions. Even your second link was more about an evil way of capturing the not-successfully-constructed object rather than really about constructor exceptions being evil - it certainly doesn't give any reasons for not throwing exceptions from constructors. It doesn't even give the messy situation I mentioned. Factory methods could potentially help, but as far as the caller is concerned the result is the same: they don't get to see the partially-constructed object. Unless you really need to do something like clean-up on an object which was constructed but then failed some element of validation, I don't think that should be a reason to use factory methods instead of constructors. (There are other reasons to do so, but that's a different matter.) A: There is nothing wrong with exceptions in constructors (or factory methods, either way is fine). sometimes, doing too much work in a constructor can be a poor design, and may make sense to move to a factory method. the only thing that point 2 proves is that exceptions in constructors are not an adequate security mechanism for protecting a class from evil usage. however, there are any number of ways to subvert such a design, which is why the only way to truly run secure code in java is running with a SecurityManager. so point 2 is just a straw man argument. A: I believe throwing exceptions from constructors is fine, more so the one's which checks for the preconditions to a successful object creation, example IllegalArgumentException. However, I do not believe that constructors are the right place to handle business logic or throw business exception/ custom exceptions. As for the reasons cited to not throw an exception, IMHO they are quite contrived; bottom line is if a careless developer wishes to do something evil he can find numerous ways to do it and there's no stopping till the developer does a self review of the code/ follows best practices.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532078", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: How to properly add an Android library to a previously made Android project? I'm trying to add a 2.2 sdk to my project and can't seem to figure out how. I tried adding it as an external JAR in the Android sdk folder but ive encountered some errors. How could I add another Android sdk to a previously made Android project? A: What you're trying to do is change the SDK version that you're project is targeting. You do not do this by including another jar in your project, you do it by changing the target SDK and minimum SDK for you project. Take a look here on how to do that and for more information: http://developer.android.com/guide/topics/manifest/uses-sdk-element.html A: You can't add an SDK to a project, but you can set your project to use a different SDK. To do this, you need to edit the properties of the project (Right-click on the project head in eclipse, and select "Properties"). You can change the SDK to any that you have downloaded through the eclipse plugin. Note that if you want to support different levels of SDKs, you need to have your project targeted for the lowest of the two platforms. For instance, if you want your project to be compatible with both 1.6 and 2.2, you need to set your project target SDK to 1.6. An alternative to this would be to create 2 different versions of your application and release them to market. A: its simple right on properties of a project select android on left side menu change the sdk version thats it......
{ "language": "en", "url": "https://stackoverflow.com/questions/7532080", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Form submit values not recognized in jQuery code I have this form: <form name="form" method="post"> <div> <p> Problem Name: <input type="text" size="20" name="problem_name"></input> </p> <p> Explain the problem </p> <p> <textarea name="problem_blurb" cols=60 rows=6 ></textarea> </p> </div> <div> <span class="error" style="display:none"> Please Enter Valid Data</span> <span class="success" style="display:none"> Registration Successfully</span> <input type="submit" class="button" value="Add Problem"></input> </div> <form> and here is my JS: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script> <script type="text/javascript" > $(function() { $("input[type=submit]").click(function() { var name = $("#problem_name").val(); var problem_blurb = $("#problem_blurb").val(); alert ("name: " + name); alert ("problem_blurb: " + problem_blurb); var dataString = 'name='+ name + '&username=' + username + '&password=' + password + '&gender=' + gender; if(name=='' || username=='' || password=='' || gender=='') { $('.success').fadeOut(200).hide(); $('.error').fadeOut(200).show(); } else { $.ajax({ type: "POST", url: "join.php", data: dataString, success: function(){ $('.success').fadeIn(200).show(); $('.error').fadeOut(200).hide(); } }); } return false; }); }); </script> I went through the basic jQuery tutorials, but still confused with their syntax. For some reason, these variables show up as undefined: var name = $("#problem_name").val(); var problem_blurb = $("#problem_blurb").val(); alert ("name: " + name); alert ("problem_blurb: " + problem_blurb); Any idea what I am doing wrong? A: # refers to id attributes, rather than names. Use $('input[name="problem_name"]') to refer to the elements. A: Add id="problem_name" and id="problem_blurb" respectively. The jQuery '#' selector looks for id attributes. You can have both id and name attributes. id is the DOM identifier while name is the form input identifier. A: The hash-tag selector tells it to look for that ID. In your HTML you only have those tags with a name attribute. Put the same value in the id attribute and you will be all set. <input id="problem_name" type="text" size="20" name="problem_name"></input> <textarea id="problem_blurb" name="problem_blurb" cols=60 rows=6 ></textarea> A: You would also try ID in your elements, which is the identifier for # in jQuery. <input type="text" size="20" id="problem_name"> Which also go for your Button. If you have <input type="button" ... id="bn"> you can replace "input[type=submit]" (which in your case will activate ALL submit buttons on the page) with $("#bn").click(function() { .. });.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532082", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Facebook fan page going immediately to wall after like, used to go back to the app I use fan gates on a lot of different fan pages. The idea has always been you land on the page and see a like us to gain something after clicking like the page reloads and now the user sees the content behind the fan gate. I noticed today that after liking a page it immediately goes to the wall, is this a bug? Is this feature deprecated? I don't have much wall activity on my pages, I'd rather users see our portfolio or special deals. A: I've been having this problem for the past few days, but today I found the solution. It seems the problem lies with the new recommend dialog box on pages. This box only appears on pages for places and prevents the page from reloading. If you have a address assigned to your page then remove it and your fangate will reload in the window when liked and not redirect to the wall page. I know this isn't a preferred fix, but until Facebook fixes the new dialog box it'll have to do. A: This is a bug on facebook right now, described here - https://developers.facebook.com/bugs/110015112440103 It'd be great to have an interim fix but since the code for the Like button is outside of what's accessible to the page tab, I'm having trouble imaging what a solution might look like, short of removing the address from your page to make it not a "place", which seem to be the only pages affected.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Powershell assign multiple ip addresses to adapter I want to write a powershell script to create a loopback adapter and assign multiple ip addresses to it. You can see where I am getting the adapter and then have an if statement that works based on whether or not it already exists. In the if statement I'll want to create and name the adapter. Following that I want to assign multiple IP addresses to it. I manually created the adapter. My code is trying to assign ip addresses. However, the ip addresses don't seem to be getting assigned. Also, if you know how to create the loopback adapter in the first place let me know. cls # Get-wmiobject win32_NetworkAdapter $networkAdapter = Get-WMIObject win32_NetworkAdapter | where{$_.ServiceName -eq 'msloop'} if(!$networkAdapter) { #"null" } "The following IP Addresses are already assigned:" #Get-WMIObject win32_NetworkAdapterConfiguration -filter "IPEnabled = $true" | Foreach-Object { $_.IPAddress } $adapterIndex = $networkAdapter.Index; $adapterConfig = (Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter "Index = $adapterIndex AND ipenabled = 'true'"); $adapterConfig.IPAddress $ip = @("192.168.200.1", "192.168.200.2", "192.168.200.3", "192.168.200.4", "192.168.200.5", "192.168.200.6") $dns = "255.255.255.0" $adapterConfig.EnableStatic($ip, $dns) $adapterConfig.IPAddress
{ "language": "en", "url": "https://stackoverflow.com/questions/7532085", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: error "The connection to adb is down" when run an android app I'm new with android development, and I have problems installing all the recent platform. I'm a java developer that I would like learning android. I've installed all programs succesfully in windows xp sp3 (JDK 1.6 with environment vars created, eclipse 3.5, 3.6 & 3.7 well configured, Android SDK with all the features, devices, platform-tools, APi's, etc, and ADT Plugin 12 for eclipse with an emulator to API 8 -Target 2.2-), but, when I'm running an android project into eclipse (Run -> Android Application), the eclipse console show me: "The connection to adb is down, and a severe error has ocurred... You must restart adb and eclipse... Ensure that adb is in this path 'D:\Android\android-sdk-windows\platform-tools\adb.exe'" (or something similiar). I'm very sure that the path is right, adb is correctly running on command-line, and the commands 'adb kill-server' and 'adb start-server' works fine, but doesn't solve my problem (like I've read in other answers). The emulator, via Eclipse, not working, but if I start the emulator via Eclipse ADV Manager, emulator starts fine, but when I runs the android app, I take the same error. I suppose that Eclipse can't start adb,but I don't know why. Other issue, when I executed 'adb devices', console show me an empty list, no 'no devices' message, but when I plugged my HTC, adb is running fine in console, but Eclipse doesn't. In addition, I also try restarting adb with Eclipse - Devices tab, but the list of devices are empty too. Anyone can help me, please? I've read so much that my eyes are pixelated. xD Best regards!! PD: sorry, but my english is a bit poor ;) A: in the DDMS perspective (if it doesn't show, add it by click window>open perspective>other...>DDMS) then click the triangle of the devices tab > reset adb. this works for me. A: I finally resolved the problem, please see my blog you can do this steps to solve the problem: * *task manager-> process *right click on adb.exe and left click on "properties" *check the path of the process: -if the path is like "Programs\android-sdk\platform-tools", which means it is the android sdk that is running this process. -if not, that means there is another process this is running adb.exe, you have to kill the process or service which runs adb.exe.(you can identify the process by the path) A: I've had this problem too. The solution I've found is to kill eclipse, open up task manager and kill the adb.exe process. Then when you start eclipse again, that should also kick start adb and it should work from there. A: Try the following steps : - Close Eclipse IDE - Go to the Android SDK platform-tools directory in Command Prompt - run adb kill-server - run adb start-server - Now start Eclipse again. Hope this may help you :) A: In my case, in Windows7 * *Close all opened emulators *Go to task manager > processes and then click on adb.exe and press the button 'end process'. *Then go to command prompt go to plate-form tools and type adb start-server *Then run your application through eclipse. It worked fine for me. A: you try Open Task Manager > Processes > eclipse.exe > End Process > restart eclipse A: In my case the problem was the FIREWALL!.Turn off your windows firewall , Then restart adb and eclipse from task-manager
{ "language": "en", "url": "https://stackoverflow.com/questions/7532087", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to install pymorph on windows? I am very new to python so sorry if this is a trivial question. I am developing on windows and I want to install the following library pymorph I know it can be installed on linux but how to install it on windows enviroment ? Thanks A: Download the package. Extract the package, cd to the folder (make sure setup.py is in the folder) and run python setup.py install from your cmd while in said folder. A: There are 2 main ways to install a python dependency. First method You can install pymorph (and almost all python dependencies) with the easy_install software. You can retrieve it here. Example : Run the setuptools-0.6c11.win32-py2.7.exe if you are using python version 2.7. After that, you have the easy_install executable. To install pymorph (in a shell, using cmd.exe) : easy_install-2.7 pymorph Don't forget to adapt the name of the easy_install executable with the good python version. The advantage of this method is that it uses the Python Package Index : According to Wikipedia : The Python Package Index or PyPI is the official third-party software repository for the Python programming language. Python developers intend of it to be a comprehensive catalog of all open source Python packages.1 It is analogous to CPAN, the repository for Perl. Package managers such as EasyInstall, pip and PyPM use PyPI as the default source for packages and their dependencies. Second method In a shell, using the cmd.exe, go to the pymorph folder. After that, always in your shell : python setup.py install In a same way, python executable name can depend of the version of python. Example : python2.7 for python version 2.7
{ "language": "en", "url": "https://stackoverflow.com/questions/7532091", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ComponentOne wijmo data-binding I wasn't able to find the answer to this question in the C1 documentation. Is it possible to bind the ComponentOne wijmo grid to the DefaultView of a System.Data.DataTable? The examples I've seen show the grid being told where to find a MS-Access MDB file and the grid's datasource is being set to a sql select statement. But I'd like to know if it's possible to do something like this, in server-side (e.g. C#) code: // myFunc has a command that executes a SP on the server // and it returns a DataTable System.Data.DataTable T = myFunc(... ); myWijmoGrid.DataSource = T.DefaultView; A: Yes it is possible. The Wijmo GridView implements CompositeDataBoundControl so it can be bound to any DataSource in ASP.NET. For instance it can be bound to DataTables, SqlDataSource, LinqDataSource, etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532092", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to use JQuery .live() without any human interaction, i.e click etc? Here is my code that auto refreshes a div containing tweets pulled from twitter: var twittercacheData; var twitterdata = $('#bottom-bar').html(); var twitterauto_refresh = setInterval( function () { $.ajax({ url: 'twitter.php', type: 'POST', data: twitterdata, dataType: 'html', success: function(twitterdata) { if (twitterdata !== twittercacheData){ //data has changed (or it's the first call), save new cache data and update div twittercacheData = twitterdata; $('#bottom-bar').fadeOut("slow").html(twitterdata).fadeIn("slow"); } } }) }, 60000); // check every minute - reasonable considering time it takes 5 tweets to scroll across The only thing is that in the twitter.php I do this: // initialise the marquee plugin so that we get a nice smooth scrolling effect $('div.twitter marquee').marquee(); So in effect I am pulling tweets and shoving them into a marquee and initialising Remy Shap rp's marquee plug-in and because the div is being refreshed I am thinking the marquee plugin isn't being initialised after the inital refresh because after the first refresh which works perfectly, firebug reports that: marqueeState is undefined I looked into using .live() but don't know what event type to use because I can't think of one that doesn't require user interaction. Any thoughts? A: try using window.onload = functionName A: I would use the livequery plugin and do something like this: $('div.twitter marquee').livequery(function() { $(this).marquee(); }); Or you can use custom events with .live(). A: If you want custom events that can be triggered programatically, jQuery delivers: http://fuelyourcoding.com/jquery-custom-events-they-will-rock-your-world/
{ "language": "en", "url": "https://stackoverflow.com/questions/7532096", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Facebook integration Adobe AIR iOS and Android I was wondering if anyone has had experience using AS3 Facebook integration on mobile devices with Adobe AIR for iOS packager or Android? Ive used the Facebook API for AS3 before for websites but not sure it its feasible using it inside an iOS packager application? All my client is wanting to do is post a highscore to a users wall.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532097", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: DDMS : java.lang.nullPointerException at com.android.ddmlib.Client.sendAndConsume i has create android_2.1 emulator , when ever i rum any application , after some seconds CONSOLE will generate error like that [2011-09-23 21:53:43 - ddms]null java.lang.NullPointerException at com.android.ddmlib.Client.sendAndConsume(Client.java:572) at com.android.ddmlib.HandleHello.sendHELO(HandleHello.java:142) at com.android.ddmlib.HandleHello.sendHelloCommands(HandleHello.java:65) at com.android.ddmlib.Client.getJdwpPacket(Client.java:671) at com.android.ddmlib.MonitorThread.processClientActivity(MonitorThread.java:317) at com.android.ddmlib.MonitorThread.run(MonitorThread.java:263) is any type of error and can have any solution of this error ? A: .. errors generally mean that there's a problem in the communication between ddms and the emulator you have fired up. Have a look at this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532100", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Questions on string.xml and size of the icon In string.xml, <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">nameofmyapp</string> </resources> I wanna change the text size how do I do that..also I want to increase the size of my icon which appears on my phone.. I tried google's http://android-ui-utils.googlecode.com/hg/asset-studio/dist/icons-notification.html#source.type=text&source.space.trim=1&source.space.pad=0.2&source.text.text=Correct!&source.text.font=Helvetica&shape=square&name=example Didn't work! any suggestions? #newbie #thanks A: If you want to change the size of the name string and size of icon on the home screen, such that it will appear bigger relative to other apps, you can not do this. The launcher that is installed on the user's device determines how to display the icon + title, you have no control over this. A: Strings in string.xml only contain values. How it should be displayed must be specified at the time it is used in UI context. For example, if you use app_name in TextView: <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:text="@string/app_name" android:textSize="20sp"/>
{ "language": "en", "url": "https://stackoverflow.com/questions/7532101", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How does #import work in iOS' UI Automation? I'm making a small test framework that uses the JavaScript module pattern for UI Automation testing on iOS. However, I seem to be getting odd results based on #import and extending modules. I have the base test module called Tester-Module.js: (function() { var Tester = this.Tester = {}; Tester.setUp = function() { UIALogger.logMessage('Regular SetUp()'); } }).call(this); If I import this module in my test case, it works fine. Here's the test file tester.js (tester.js is the file I import in Instruments): #import "./Tester-Module.js" // Prints 'Regular SetUp()' Tester.setUp(); However, if I try to extend the Tester-Module.js module in another module file, I cannot reference the Tester object. Tester-Extension.js extends the Tester module defined in Tester-Module.js: #import "./Tester-Module.js" // Outputs: // Exception raised while running script: // ReferenceError: Can't find variable: Tester\n Tester.setUp = function() { UIALogger.logMessage('Overwritten SetUp()'); } And the updated test case file tester.js: #import "./Tester-Extension.js" // Exception is thrown before this Tester.setUp(); My hopefully related questions are: * *Why can I not reference the Tester object inside Tester-Extension.js, but can in tester.js? *What is the #import macro doing? A: After some more searching and testing, it looks like using #import in each module file — similar to require in Node.js — is not supported with the UI Automation framework. The work around is to include a header file that imports every module and then just import that in the test case. Using the example above, the header file would look like: // Tester-Header.js #import "./Tester-Module.js" #import "./Tester-Extension.js" And the test file would simply import the header file like so: #import "./Tester-Header.js" // Prints "Overwritten SetUp()" Tester.setUp(); The Mother May UI BDD framework has a more extensive example of a header file and importing the header file into a test file. Disclosure: I wrote the framework and originally asked this question in order to make the framework more modular.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532108", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Vertex Buffer Objects with SDL When using SDL 1.2, what do I need to include to be able to use OpenGL Vertex Buffer Objects (VBOs)? Currently, I only include SDL.h, SDL_opengl.h, SDL_image.h And get the errors: glGenBuffersARB, glBindBufferARB, glBufferDataARB not declared in this scope A: If you want to use SDL_opengl.h define GL_GLEXT_PROTOTYPES before including it. #define GL_GLEXT_PROTOTYPES #include "SDL.h" #include "SDL_opengl.h" I may or might not work. If you want to do it the "proper" way, use something like glew. A: You should include <GL/gl.h> and <GL/glext.h>. Sometimes OpenGl extension functions are not directly available and must be loaded using SDL_GL_GetProcAddress (this returns the function pointer or 0 if extension is not available). You may be interested to have a look to libglew which loads the extension functions. Here is how you may do it (if not using glew): extern PFNGLGENBUFFERSARBPROC glGenBuffers; // Function pointer declaration, in a header file. // Function pointer initialization glGenBuffers = 0; // Get the function (you should have checked that extension is available) glGenBuffers = (PFNGLGENBUFFERSARBPROC)SDL_GL_GetProcAddress("glGenBuffersARB"); A: It is possible to get the underdevelopment 1.3 version of SDL to open a OpenGL 3.2 context with a bit of work. It's also worth checking out SFML, it's similar to SDL but is hardware accelerated for the 2D stuff, object orientated C++ and is much easier to use. OpenGL is particularly simple to use with it. Once again it's the development 2.0 version that supports OpenGL 3.2 contexts (although it's close to being released.) You will probably need to use the non-ARB versions with the above. A: I find the SDL_opengl.h file to be fairly useless. Personally, I recommend using GLEW or GLee. GLee is easier to add to your project but stops at OpenGL 3.0 (usually fine in SDL apps since SDL only enables an OpenGL 2.1 context). GLEW requires just a bit more work but enables stuff up through OpenGL 4. I ran into this same problem regarding VBOs in SDL.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532110", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: isGUIInitialized() is false, now what? I been looking at some code and I find people doing public static void main(String[] args) { new ExampleCode(); } ExampleCode () { EventQueue.invokeLater(this); } public void run() { if (EventQueueMonitor.isGUIInitialized()) { guiInitialized(); } else { EventQueueMonitor.addGUIInitializedListener(this); } } Which makes sense, but now my question is how they keep the code running. To my understanding the code goes to main--->ExampleCode--->Run and then it stops because GUI was not initialized. Does any of the calls start the GUI else where? I use the same steps on my program, but my GUI is not initialized. Two of my example codes: http://java.sun.com/javase/technologies/accessibility/docs/jaccess-1.1/examples/Explorer/Explorer.java http://www.java2s.com/Code/Java/Swing-JFC/AGUItoshowaccessibleinformationcomingfromthecomponentsinan.htm A: Here is a simple example based on examples from the Swing tutorial: import java.awt.*; import javax.swing.*; public class SSCCE extends JPanel { public SSCCE() { add( new JLabel("Label") ); } private static void createAndShowUI() { JFrame frame = new JFrame("SSCCE"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add( new SSCCE() ); frame.pack(); frame.setLocationRelativeTo( null ); frame.setVisible( true ); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { createAndShowUI(); } }); } } A: The example you posted is using accessibility related features, hence it is possible that the initialization may take more time. The practice that we follow while using Swing is to avoid heavy initialization on event queue. What the original author's logic does is that he waits for swing jframe etc. to initialize completely, then he initialized his own components. // Check to see if the GUI subsystem is initialized correctly. (This is needed in JDK 1.2 and higher). If it isn't ready, then we have to wait. if (EventQueueMonitor.isGUIInitialized()) { createGUI(); } else { EventQueueMonitor.addGUIInitializedListener(this); } } public void guiInitialized() { createGUI(); } The actual initialization logic is written in createGUI method, which will either be called by Swing or by your own logic. You program will not terminate, since Swing uses its own non-daemon thread (i.e. unless you call System.exit, your swing program will not terminate).
{ "language": "en", "url": "https://stackoverflow.com/questions/7532111", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is there a simpler way to calculate this MD5 hash? I'm working on implementing a hosted checkout, and the hosted checkout is supposed to redirect the user back to my website so that I can show a custom receipt page. This is a sample querystring that I'd get back: trnApproved=0&trnId=10000000&messageId=71&messageText=Declined&authCode=000000&responseType=T&trnAmount=20.00&trnDate=9%2f23%2f2011+9%3a30%3a56+AM&trnOrderNumber=1000000&trnLanguage=eng&trnCustomerName=FirstName+LastName&trnEmailAddress=something_something%40gmail.com&trnPhoneNumber=1235550123&avsProcessed=0&avsId=0&avsResult=0&avsAddrMatch=0&avsPostalMatch=0&avsMessage=Address+Verification+not+performed+for+this+transaction.&cvdId=3&cardType=VI&trnType=P&paymentMethod=CC&ref1=9dae6af7-7c22-4697-b23a-413d8a129a75&ref2=&ref3=&ref4=&ref5=&hashValue=33dacf84682470f267b2cc6d528b1594 To validate the request, I'm supposed to remove &hashValue=f3cf58ef0fd363e0c2241938b04f1068 from the end of the querystring, and then append a key. I then perform an MD5 hash of the entire string, and the result should be 33dacf84682470f267b2cc6d528b1594, same as the original. This is easy, except that a few of the fields are causing a problem for me. This is the code I use (taken from a dummy application, so you can ignore some of the bad coding): // Split up the query string parameters string[] parameters = GetQueryString().Split(new[] { "&" }, StringSplitOptions.None); var querySet = new List<string>(); // Rebuild the query string, encoding the values. foreach (string s in parameters) { // Every field that contains a "." will need to be encoded except for trnAmount querySet.Add(param.Contains("trnAmount") ? param : UrlEncodeToUpper(param)); } // Create the querystring without the hashValue, we need to calculate our hash without it. string qs = string.Join("&", querySet.ToArray()); qs = qs.Substring(0, qs.IndexOf("&hashValue")); qs = qs + "fb76124fea73488fa11995dfa4cbe89b"; var encoding = new UTF8Encoding(); var md5 = new MD5CryptoServiceProvider(); var hash = md5.ComputeHash(encoding.GetBytes(qs)); var calculatedHash = BitConverter.ToString(hash).Replace("-", String.Empty).ToLower(); This is the UrlEncode method I use. private static string UrlEncodeToUpper(string value) { // Convert their encoding into uppercase so we can do our hash value = Regex.Replace(value, "(%[0-9af][0-9a-f])", c => c.Value.ToUpper()); // Encode the characters that they missed value = value.Replace("-", "%2D").Replace(".", "%2E").Replace("_", "%5F"); return value; } This all works (until someone enters a character I haven't accounted for), except this seems more complicated than it should be. I know I'm not the only one who has to implement this HCO into an ASP.NET application, so I don't think the simple validation should be so complicated. Am I missing an easier way to do this? Having to loop through the fields, encoding some of them while skipping others, converting their encoding to uppercase and then selectively replacing characters seems a little... odd. A: Here's a better way to work with query strings: var queryString = "trnApproved=0&trnId=10000000&messageId=71&messageText=Declined&authCode=000000&responseType=T&trnAmount=20.00&trnDate=9%2f23%2f2011+9%3a30%3a56+AM&trnOrderNumber=1000000&trnLanguage=eng&trnCustomerName=FirstName+LastName&trnEmailAddress=something_something%40gmail.com&trnPhoneNumber=1235550123&avsProcessed=0&avsId=0&avsResult=0&avsAddrMatch=0&avsPostalMatch=0&avsMessage=Address+Verification+not+performed+for+this+transaction.&cvdId=3&cardType=VI&trnType=P&paymentMethod=CC&ref1=9dae6af7-7c22-4697-b23a-413d8a129a75&ref2=&ref3=&ref4=&ref5=&hashValue=33dacf84682470f267b2cc6d528b1594"; var values = HttpUtility.ParseQueryString(queryString); // remove the hashValue parameter values.Remove("hashValue"); var result = values.ToString(); // At this stage result = trnApproved=0&trnId=10000000&messageId=71&messageText=Declined&authCode=000000&responseType=T&trnAmount=20.00&trnDate=9%2f23%2f2011+9%3a30%3a56+AM&trnOrderNumber=1000000&trnLanguage=eng&trnCustomerName=FirstName+LastName&trnEmailAddress=something_something%40gmail.com&trnPhoneNumber=1235550123&avsProcessed=0&avsId=0&avsResult=0&avsAddrMatch=0&avsPostalMatch=0&avsMessage=Address+Verification+not+performed+for+this+transaction.&cvdId=3&cardType=VI&trnType=P&paymentMethod=CC&ref1=9dae6af7-7c22-4697-b23a-413d8a129a75&ref2=&ref3=&ref4=&ref5= // now add some other query string value values["foo"] = "bar"; // you can stuff whatever you want it will be properly url encoded Then I didn't quite understand what you wanted to do. You want to calculate an MD5 on the result? You could do that and then append to the query string.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532113", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: redirect to same site, but different link (javascript) I want that people in "example.com/index.htm" get redirected to "example.com". but the code is being tricky. It always takes me to a loop. <script type="text/javascript"> function check() { if (window.top!="example.com") { window.location="http://example.com"; }else {} }</script> A: <script type="text/javascript"> function check() { if (window.top.location.href!="http://mysite.com") { window.top.location.href="http://mysite.com"; }else {} }</script> You need to use the location object and it needs to actually match. A: Give this a go (untested): $(function() { var reg = /index.htm/g, top = window.location.href, loc = ''; if(reg.test(top)) { top = top.replace('http://',''); top = top.split('/'); for(i=0;i<top.length-1;i++) { loc = loc + top[i]; } window.location.href = 'http://' + loc; } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7532116", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make Label's text centered vertically? I tried one by one each of these methods : setting the BgAlign property to CENTER in the Resource Editor , myLabel.getStyle().setBackgroundAlignment(Style.BACKGROUND_IMAGE_ALIGN_CENTER); but the text of the Label is not centered vertically. So how to make Label's text centered vertically ? The following image shows the actual alignement of the Label's text : A: Label vertical alignment is unsupported only its positioning in relation to an icon. As far as I recall you are using FlowLayout for every entry which does support vertical alignment see FlowLayout.setValign(Component.CENTER).
{ "language": "en", "url": "https://stackoverflow.com/questions/7532117", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add a custom parameter to a default action in routing Can you please help me? I got stuck! I implemented a single table inheritance for a model "Customer". "Person" and "Company" are "Customers". So I added two new routes to forward all requests to the CustomersController: resources :customers # added by generator resources :people, :controller => 'customers' <== NEW resources :companies, :controller => 'customers' <== NEW What I want to do is * *add a parameter "type" to the action "new" of resource :customers *add a default value "Person" and "Company" to the "type" parameter in both other resources (if the parameter gets inherited!?) My goal is to be able to call new_customer_path(:type => 'Person') and new_person_path I tried the following before, but it stopped other actions (like show) from working resources :people, :controller => 'customers' do get 'new', :on => :member, :type => 'Person' end Can anyone out there tell me about my mistake? A: Try adding the parameter to the resources arguments resources :people, :controller => 'customers', :type => "Person" resources :companies, :controller => 'customers', :type => "Company" A: As for new_person_path you could do: map.new_person "new_person", :controller => "customers", :action => "new", :type => "person" Keep in mind that having: new_customer_path(:type => "person") Will pass "?type=person" in the URL so your visitors will be able to change it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532118", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jquery/prototype conflicts in Magento This is a Magento store based on the Acumen theme from Themeforest. Seemingly out of the blue, jquery stuff is now not working. Acumen has jquery loading through a magento static block and none of that has been touched. Yesterday I was working on adding the jquery.clearfield.js plugin to add that functionality to our forms. I wasn't modifying core files. I loaded the clearfield plugin through another static block and added that static block to our contact CMS page. I was logged in at the time and was getting the logged in values for name/email populating automatically, and at some point I logged out as a customer to test the field values when not logged in. I was unable to login because of the jquery conflicts. I've gone through the code, I can't seem to find anything that's changed that would be causing this, and I hadn't modified any core or theme files. If you view source/inspect element on any of the pages, you'll see the prototype and jquery error messages. Any thoughts/insight would be helpful. Thanks. A: Update: Don't use this anymore, refer to the answer by @MagePsycho above. This isn't a matter of jQuery and Prototype conflicting, but rather of jQuery actually not having loaded yet when you call jQuery.noConflict(). In your source, the "jQuery.noConflict()" call is right in the head, but jQuery itself gets loaded at the very end of the page (below the footer) via the google api. My suggestion would be to abandon the google api, load jQuery locally via XML by <action method="addItem"><type>skin_js</type><name>js/jquery-1.x.x.min.js</name></action> and embed a jQuery.noConflict() call right before the end of jquery-1.x.x.min.js itself. A: If you want to include the jquery and no conflict code in your local.xml then use: <default>     <reference name="head">         <block type="core/text" name="google.cdn.jquery">             <action method="setText">                 <text><![CDATA[<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script><script type="text/javascript">jQuery.noConflict();</script>]]>                 </text>             </action>         </block>     </reference> </default> Cheers!! Revision 2: You will probably want to edit the page.xml and insert the jquery.js and noConflict in there, as page.xml is loaded before local.xml. Or, you can use local.xml to remove all of the previous Prototype js calls, then re-add them. I found editing page.xml to be easier. Also, I had trouble getting Action setText to work for the "var jQuery = jQuery.noConflict();", so I created a separate js file with that line by itself. Not great, but it is loaded right after the main jQuery js file is loaded (and before Prototype) A: When running jQuery and Prototype together you need to run "no conflict" mode. This re-maps jQuery's hook from "$" to "jQuery", allowing Prototype to continue to use "$". If the plug-in us using "$", it's going to be using Prototype's function and will likely crash. You may need to manually edit the plugin and replace "$" with "jQuery".
{ "language": "en", "url": "https://stackoverflow.com/questions/7532124", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: parsing code into components I need to parse some code and convert it to components because I want to make some stats about the code like number of code lines , position of condition statements and so on . Is there any tool that I can use to fulfill that ? A: Antlr is a nice tool that works with many languages, has good documentation and many sample grammars for languages included. You can also go old-school and use Yacc and Lex (or the GNU versions Bison and Flex), which has pretty good book on generating parsers, as well as the classic dragon book. It might be overkill, however, and you might just want to use Ruby or even Javascript. A: You mention two distinct tasks: * *refactor code into modular components *Run static code analysis to get code metrics. I recommend: * *Resharper, as the top code refactoring tool out there (assuming you're a .NET guy) *NCover and NDepend for static code analysis. You get #line of code, cyclomatic complexity, abstractness vs instability diagrams.. all of the cool stuff.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532127", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to keep an image inside the screen limits while using pinch zoom and drag gestures? I'm building an app that uses the pinch zoom and drag. The problem is that for now I can drag the picture out of it bounds. I wanted to know how can I use drag and make sure the image stays on the screen at the same time. Here is my code : public boolean onTouch(View v, MotionEvent event) { ImageView view = (ImageView)v; //handle touch events here. switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: savedMatrix.set(matrix); start.set(event.getX(), event.getY()); Log.d(TAG, "mode=DRAG" ); mode = DRAG; break; case MotionEvent.ACTION_POINTER_DOWN: oldDist = spacing(event); Log.d(TAG, "oldDist=" + oldDist); if (oldDist > 10f) { savedMatrix.set(matrix); midPoint(mid, event); mode = ZOOM; Log.d(TAG, "mode=ZOOM" ); } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: mode = NONE; Log.d(TAG, "mode=NONE" ); break; case MotionEvent.ACTION_MOVE: if (mode == DRAG) { matrix.set(savedMatrix); matrix.postTranslate(event.getX() - start.x, event.getY() - start.y); } else if (mode == ZOOM) { Float newDist = spacing(event); Log.d(TAG, "newDist=" + newDist); if (newDist > 10f) { matrix.set(savedMatrix); Float scale = newDist / oldDist; Matrix temp = new Matrix(); temp.set(matrix); temp.postScale(scale, scale, mid.x, mid.y); float[] f = new float[9]; temp.getValues(f); Float xScale = f[0]; if(xScale >= 1 && xScale <= 10){ matrix.postScale(scale, scale, mid.x, mid.y); savedMatrixZoom.set(matrix); }else{ matrix.set(savedMatrixZoom); } } break; } } //perform the transformation. view.setImageMatrix(matrix); return true; // indicate event was handled } A: Why not grab the dimensions of the screen and check the MotionEvent coordinates are within these before updating your matrix? Something like.. DisplayMetrics displaymetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); int screenHight = displaymetrics.heightPixels; int screenWidth = displaymetrics.widthPixels; ... case MotionEvent.ACTION_MOVE: if (mode == DRAG) { int newX = event.getX() - start.x; int newY = event.getY() - start.y; if ( (newX <= 0 || newX >= screenWidth) || (newY <= 0 || newY >= screenHeight) ) break; matrix.set(savedMatrix); matrix.postTranslate(newX, newY); } ... A: public boolean onTouch(View v, MotionEvent event) { int action = event.getAction(); DisplayMetrics displaymetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); int sH = displaymetrics.heightPixels; int sW = displaymetrics.widthPixels; float dx, dy, newX, newY; switch (action) { case MotionEvent.ACTION_DOWN: dx = event.getRawX() - v.getX(); dy = event.getRawY() - v.getY(); break; case MotionEvent.ACTION_MOVE: newX = event.getRawX() - dx; newY = event.getRawY() - dy; if ((newX <= 0 || newX >= sW-v.getWidth()) || (newY <= 0 || newY >= sH-v.getHeight())) break; v.setX(newX); v.setY(newY); break; default: break; } return true; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7532128", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: PHP Warning: stream_socket_client(): Failed to enable crypto? I'm using swiftMailer to send email using SMTP directly. I get this strange error: 2011/09/23 17:59:01 [error] 489#0: *1032 FastCGI sent in stderr: "PHP Warning: stream_socket_client(): SSL operation failed with code 1. OpenSSL Error messages: error:140770FC:SSL routines:func(119):reason(252) in /home/nginx/websites/example.com/www/inc/lib/swift-mailer/lib/classes/Swift/Transport/StreamBuffer.php on line 271 PHP Warning: stream_socket_client(): Failed to enable crypto in /home/nginx/websites/example.com/www/inc/lib/swift-mailer/lib/classes/Swift/Transport/StreamBuffer.php on line 271 PHP Warning: stream_socket_client(): unable to connect to ssl://mail.xxxxx.net:587 (Unknown error) in /home/nginx/websites/example.com/www/inc/lib/swift-mailer/lib/classes/Swift/Transport/StreamBuffer.php on line 271 PHP Fatal error: Uncaught exception 'Swift_TransportException' with message 'Connection could not be established with host mail.xxxxxxxx.net [ #0]' in /home/nginx/websites/example.com/www/inc/lib/swift-mailer/lib/classes/Swift/Transport/StreamBuffer.php:273 Stack trace: #0 /home/nginx/websites/example.com/www/inc/lib/swift-mailer/lib/classes/Swift/Transport/StreamBuffer.php(66): Swift_Transport_StreamBuffer->_establishSocketConnection() #1 /home/nginx/websites/example.com/www/inc/lib/swift-mailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php(116): Swift_Transport_StreamBuffer->initialize(Array) #2 /home/nginx/websites/example.com/www/inc/lib/swift-mailer/lib/classes/Swift/Mailer.php(79): Swift_Transport_AbstractSmtpTransport->start() #3 /home/nginx/websites/example.com/www/email.php(23): Swift_Mailer->send(Object(Swift_Message)) #4 {main} thrown in /home/nginx/websites/example.com/www/inc/lib/swift-mailer/lib/classes/Swift/Transport/StreamBuffer.php on line 273" while reading response header from upstream, client: xx.xx.xx.xxx, server: example.com, request: "GET /email.php HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "www.example.com" What does it mean? Thanks A: The "failure to enable crypto" means that it was unable to secure the connection - check to be sure that you are successfully passing a certificate, and that your passphrase is set correctly. A: In my case, the issue was with my mac (OSX Sierra). I uploaded php and cert to my server, ran it, and the notification was delivered. Duplicate: APNS + PHP "stream_socket_client(): Failed to enable crypto" A: This error is quite typically that you have tried to contact an invalid port in my experience. Try telnet mail.xxxxx.net 587, and if you do not get anything about an escape character then it is not the right port. If you have access, examine the server config to see if you are trying to access a port which is not exposed for ssl streams. Try the telnet command again to probe other possible candidate ports
{ "language": "en", "url": "https://stackoverflow.com/questions/7532129", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Create folders from folder id and parent id in java I need to make a class that get the list of folders stored in a database and creates them on the local machine in the correct hierarchy. The folders are arranged on the database like so: id name parent_id 1 documents 0 2 movies 0 3 videos 0 4 my files 1 5 desktop 0 6 other 4 So documents, movies, videos and desktop are in the root. 'my files' goes in the folder with the id of 1(documents) and 'other' goes in the folder with the id of 4(my files) I have been trying to do it by using a whyle loop but dont know how to get them to go into the correct folders. try { con = DriverManager.getConnection(url, user, password); } catch (SQLException e) { e.printStackTrace(); } while( i < 50 ) { try { Statement st = con.createStatement(); ResultSet result = st.executeQuery("SELECT name, id, parent_id FROM categories WHERE parent_id = '"+PID+"' AND repository_id = '"+RepoID+"'"); while (result.next ()) { String FolderName = result.getString ("name"); String FolderId = result.getString ("id"); String FolderId = result.getString ("parent_id"); make the folder name here System.out.println( FolderName+" "+FolderId ); } System.out.println( " "); i++ ; PID++; } catch (SQLException ex) { System.out.println(ex.getMessage()); } } A: Create a Folder object to store the data, then build these objects as you read from the database. Once you have built all the Folder objects, do a final loop to bind each Folder to its parent class. Perhaps something like this: class Folder { private String name; private int id; private int parentId; private List<Folder> children = new ArrayList<Folder>(); public Folder(String name, int id, int parentId) { this.name = name; this.id = id; this.parentId = parentId; } public void addChildFolder(Folder folder) { this.children.add(folder); } public List<Folder> getChildren() { return Collections.unmodifiableList(children); } public int getParentFolderId() { parentId; } public String getName() { return name; } public int getId() { return id; } } Now as you read the data from the database, you create these Folder objects (with no children) and add them to the map with: Map<Integer, Folder> data = new HashMap<Integer, Folder>(); ... loop through your result set getting folder data... Folder newFolder = new Folder(nameString, id, parentId); data.put(newFolder.getId(), newFolder); Use Integer.valueOf(String) to convert String to int. Once you have the created all the Folders, you can make one final loop to connect the parent folders to the children, like this: for(Folder folder : data.values()) { int parentId = folder.getParentFolderId(); Folder parentFolder = data.get(parentId); if(parentFolder != null) parentFolder.addChildFolder(folder); } Finally, just grab the folder with id 0 and start building your Files on the disk, using folder.getChildren() as a convenient way to move down the tree. Check out the javadoc on the File object, you will particularly want to use the mkdirs() method. Hope that helps. A: once you get all the values out of the database, i would suggest creating a Map<Integer,Folder> which maps each folder id to its Folder information (where Folder holds the id, name, and parent id). then, you can loop through this map, and for each folder, build up the full path by recursing up the parent ids until you reach the root and (e.g. "foo/bar/baz") and then call File.mkdirs() with this path. A: I see your comment on Sep 29 asking about printing folders. Your code there seems ok, except that you are only printing out the name of the parent folder. If you want to print them all you need to dig into the children and print them too, perhaps something like this: ... for (Folder folder : data.values()) { int parentId = folder.getParentFolderId(); Folder parentFolder = data.get(parentId); if (parentFolder != null) parentFolder.addChildFolder(folder); } printFolderRecursively(data.get(1)); and then write a method that prints a folder name along with it's children: public void printFolderRecursively(Folder folder) { System.out.print("/" + rootFolderName); for(Folder child : folder.getChildren()) printFolderRecursively(child); } hope that helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532130", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Anyone know how to open a fb fan page in iphone app from web page? I'm trying to open my facebook fan page in the fbook app from a web page in safari. I found What are all the custom URL schemes supported by the Facebook iPhone app? and I've tried setting the link to * *fb://pages/[pageid] *fb://pages/?id=[pageid] *fb://page/[pageid] *fb://page/?id=[pageid] *fb://profile/[pageid] They all open the app( of course ) but not at my page, I feel like i'm close but I've been poking round at it for a while now, any help much appreciated. A: To open facebook page in facebook app you should: 1)Find uid of your page (it can be done for example by looking at source code of your facebook page) I got the following fragment from the source code of the page: http://www.facebook.com/Innova.et.Bella {"text":"Innova et Bella","type":"ent:page","uid":73728918115} N.B.: To check if uid is correct substitute uid for pagename: http://www.facebook.com/73728918115 This url should open your page. 2) When the uid is found end is correct use this code: NSURL *urlApp = [NSURL URLWithString:@"fb://profile/73728918115"]; [[UIApplication sharedApplication] openURL:urlApp]; This code will open you page within facebook app. N.B.: Do not forget to check if the facebook app exists( or more precisely that the url can be opened) using: if ([[UIApplication sharedApplication] canOpenURL:urlApp]) otherwise open it in Safari. A: Facebook tab pages do not displayed in the mobile or app version of facebook. Not possible.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532136", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: I am trying to Post Data to an Iframe in asp.net. The post is performed using HTTPRequest and HTTPResponse I am trying to implement Single Sign On allowing the users to sign on to multiple vendors. Each vendor has token that need to be send as a form post. I am posting this token as HTTPRequest and getting the Response back like in the code below private static string PostDataToServerAndGetResponse() { Uri uri = new Uri("http://www.amazon.com/exec/obidos/search-handle-form/102-5194535-6807312"); string data = "field-keywords=ASP.NET 2.0"; if (uri.Scheme == Uri.UriSchemeHttp) { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri); request.Method = WebRequestMethods.Http.Post; request.ContentLength = data.Length; request.ContentType = "application/x-www-form-urlencoded"; StreamWriter writer = new StreamWriter(request.GetRequestStream()); writer.Write(data); writer.Close(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream()); string tmp = reader.ReadToEnd(); response.Close(); //return response.ResponseUri.AbsoluteUri; return tmp; } return null; } The returned value - tmp is a HTML string which I want to display into an Iframe. I can do this by adding a Literal control in the iframe and setting the text property to the value returned by the above function <iframe id="myIFrame" runat="server" height="700" width="950" frameborder="0" /> <asp:Literal ID="litFrame" runat="server" Mode="PassThrough" /> </iframe> litFrame.Text = SAML.PostDataToServerAndGetResponse(); The above code dispaly the page fine, but when i click on any of the links it opens a new page. There is no apparent framebusting java script, because if I set the 'src' attribute of the iframe to response.ResponseUri.AbsoluteUri, all the clicks and page refreshes stay in the frame. What I want to achieve Display the Result of the post into Iframe and all the user to perform any clicks. Condition: Clicks in the frame should refresh the frame and not jump out to a new page. A: Iframes do not work they way you think. The content inside an <iframe> tag is meant to be shown only if the tag is not supported by the browser, not as default content of the iframe. I'm surprised you see any of your literal's content at all on the page -- is there actually an <iframe> output in your html source, or did ASP.NET get 'smart' and output something different? Really, your options are: * *Set the url of the iframe to a page/handler/etc that will generate the content you want inside the iframe (ie, THAT page calls your PostDataToServerAndGetResponse method) *Use javascript to write the content into the iframe *You could set the target of a <form> to the iframe, and post the data to it I'd say option 1 would be the easiest/cleanest.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532137", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PDF to Jasper XML I have a PDF file (softcopy) which was created using iText. Now my company decided to use JasperReports for new release. I need to use that PDF file (softcopy) and need to design JasperReports template and need to populate data. Do we have any plugin in JasperReports that can convert from PDF to JasperReports JRXML or what do I need to do? Any suggestions? A: A PDF is a description of how to render a document on a page. Things like "draw a vertical line here", "write 'foo bar baz' here in Courier". It does not contain any information about the format or organisation of the stuff it is rendering. You won't be able to tell that you're looking at a table, or a list of bullet points, or a paragraph, or anything like that. The PDF format does contain information on a page-by-page basis. Therefore, page breaks are the one piece of format/organisation information that you can find. If you want anything more than a raw stream of completely unformatted, disorganised text, one per page, you are out of luck. It's virtually impossible. from javaranch A: You can use http://xmlprinter.com/ and then use a xslt to transform the resulted xml to the desired jrxml. I'm working in it. If I finish it, i will post the result on github or any other public and open place. Good Luck
{ "language": "en", "url": "https://stackoverflow.com/questions/7532144", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: TFS Merging keeps merging some files without any changes For some unknown reason, TFS seems to keep queuing certain files for merges, even though there are no changes. In the Pending Changes windows, the Change column only states Merge, and not the usual Merge, edit or Merge, branch. Nobody touches these files and yet they keep reappearing under the pending changes merge queue. I've seen this happen before with a folder that was deleted, but kept reappearing in the merges between branches. In that case, I used tf destroy in all branches for that folder's path and it solved the problem. However, in this environment, it's with files that the team wants to keep. Has anyone else experienced and/or resolved this issue? A: Try TFS 2010 SP1 and CU1. It fixed some merge bugs. Like the following: Merge or discard in both directions cause unnecessary "empty" merges in future merge attempts. A: If you have the Team Foundation Power Tools installed you can use tfpt uu to undo changes to any unchanged files (yes, it's well annoying when files are flagged as changed and you get told they are identical!).
{ "language": "en", "url": "https://stackoverflow.com/questions/7532146", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: git over ssh: Repository read access denied I have a git server set up on Linux, and it's working great: [git@HOST ~]$ git clone -v git://HOST.com/repositories/Extras Cloning into Extras... remote: Counting objects: 12, done. remote: Compressing objects: 100% (12/12), done. remote: Total 12 (delta 3), reused 0 (delta 0) Receiving objects: 100% (12/12), 23.54 MiB | 16.63 MiB/s, done. Resolving deltas: 100% (3/3), done. Note that HOST.com is not real. :) I would now like to get the same thing working over SSH, so I can add privacy and authentication. At the moment, it is not working: [git@HOST ~]$ git clone -v ssh://HOST.com/repositories/Extras Cloning into Extras... Enter passphrase for key '/home/git/.ssh/id_rsa': ERROR:gitosis.serve.main:Repository read access denied fatal: The remote end hung up unexpectedly It looks like the SSH connecting is working, but git is having some permissions problems. SELinux is not enabled. In /var/log/messages, I see the following: Sep 23 16:26:18 HOST sshd[32115]: Accepted publickey for git from X.X.X.X port 51023 ssh2 Sep 23 16:26:18 HOST sshd[32116]: fatal: mm_request_receive: read: Connection reset by peer Sep 23 16:26:18 HOST sshd[32115]: pam_unix(sshd:session): session opened for user git by (uid=0) Sep 23 16:26:19 HOST sshd[32121]: Received disconnect from X.X.X.X: 11: disconnected by user Sep 23 16:26:19 HOST sshd[32115]: pam_unix(sshd:session): session closed for user git Anyone have some advice on where I might start looking? Thanks! Mike A: It looks like you're using Gitosis. Have you configured your {{gitosis.conf}} to permit access to the repository you're tryng to use? Have you installed your public key? Start by turning on debug logging in your gitosis configuration: [gitosis] loglevel = DEBUG This will result in verbose logging when you connect with ssh. The most common causes of this problem are: emphasized text - A typo in the repository or user name. - The wrong key installed, or key filename not matching the username in the configuration. The debug output will highlight these problems effectively. For example, connecting to our local gitosis repository with debug logging on includes the following: Access check for 'lars@obliquity.example.com' as 'writable' on 'gitosis-admin.git'... (This shows who gitosis thinks I am.) found 'lars@obliquity.example.com' in 'admins' (This shows what group I'm associated with.) Access ok for 'lars@obliquity.example.com' as 'writable' on 'gitosis-admin' (And this shows my access.) A: If you're going to spend significant time on this, it's better to switch to gitolite. There will be no impact to the users as you can commit the same keys to the gitolite admin repo. For your current problem, try accessing via SSH with the -vvvv option to see a detailed debug output of what key is being used etc. Hope this helps. A: Thanks everyone... In the end I went with gitolite, but that was not the source of the problem. It was a key mismatch between the client and the SSH server... A simple thing that I thought I'd checked. Once I matched up the user's .pub key that I had registered with git, and their ~/.ssh/id_rsa.pub, everything started working as expected. Thanks! Mike
{ "language": "en", "url": "https://stackoverflow.com/questions/7532147", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: I/O performance of multiple JVM (Windows 7 affected, Linux works) I have a program that creates a file of about 50MB size. During the process the program frequently rewrites sections of the file and forces the changes to disk (in the order of 100 times). It uses a FileChannel and direct ByteBuffers via fc.read(...), fc.write(...) and fc.force(...). New text: I have a better view on the problem now. The problem appears to be that I use three different JVMs to modify a file (one creates it, two others (launched from the first) write to it). Every JVM closes the file properly before the next JVM is started. The problem is that the cost of fc.write() to that file occasionally goes through the roof for the third JVM (in the order of 100 times the normal cost). That is, all write operations are equally slow, it is not just one that hang very long. Interestingly, one way to help this is to insert delays (2 seconds) between the launching of JVMs. Without delay, writing is always slow, with delay, the writing is slow aboutr every second time or so. I also found this Stackoverflow: How to unmap a file from memory mapped using FileChannel in java? which describes a problem for mapped files, which I'm not using. What I suspect might be going on: Java does not completely release the file handle when I call close(). When the next JVM is started, Java (or Windows) recognizes concurrent access to that file and installes some expensive concurrency handler for that file, which makes writing expensive. Would that make sense? The problem occurs on Windows 7 (Java 6 and 7, tested on two machines), but not under Linux (SuSE 11.3 64). Old text: The problem: Starting the program from as a JUnit test harness from eclipse or from console works fine, it takes around 3 seconds. Starting the program through an ant task (or through JUnit by kicking of a separate JVM using a ProcessBuilder) slows the program down to 70-80 seconds for the same task (factor 20-30). Using -Xprof reveals that the usage of 'force0' and 'pwrite' goes through the roof from 34.1% (76+20 tics) to 97.3% (3587+2913+751 tics): Fast run: 27.0% 0 + 76 sun.nio.ch.FileChannelImpl.force0 7.1% 0 + 20 sun.nio.ch.FileDispatcher.pwrite0 [..] Slow run: Interpreted + native Method 48.1% 0 + 3587 sun.nio.ch.FileDispatcher.pwrite0 39.1% 0 + 2913 sun.nio.ch.FileChannelImpl.force0 [..] Stub + native Method 10.1% 0 + 751 sun.nio.ch.FileDispatcher.pwrite0 [..] GC and compilation are negligible. More facts: No other methods show a significant change in the -Xprof output. * *It's either fast or very slow, never something in-between. *Memory is not a problem, all test machines have at least 8GB, the process uses <200MB *rebooting the machine does not help *switching of virus-scanners and similar stuff has no affect *When the process is slow, there is virtually no CPU usage *It is never slow when running it from a normal JVM *It is pretty consistently slow when running it in a JVM that was started from the first JVM (via ProcessBuilder or as ant-task) *All JVMs are exactly the same. I output System.getProperty("java.home") and the JVM options via RuntimeMXBean RuntimemxBean = ManagementFactory.getRuntimeMXBean(); List arguments = RuntimemxBean.getInputArguments(); *I tested it on two machines with Windows7 64bit, Java 7u2, Java 6u26 and JRockit, the hardware of the machines differs, though, but the results are very similar. *I tested it also from outside Eclipse (command-line ant) but no difference there. *The whole program is written by myself, all it does is reading and writing to/from this file, no other libraries are used, especially no native libraries. - And some scary facts that I just refuse to believe to make any sense: * *Removing all class files and rebuilding the project sometimes (rarely) helps. The program (nested version) runs fast one or two times before becoming extremely slow again. *Installing a new JVM always helps (every single time!) such that the (nested) program runs fast at least once! Installing a JDK counts as two because both the JDK-jre and the JRE-jre work fine at least once. Overinstalling a JVM does not help. Neither does rebooting. I haven't tried deleting/rebooting/reinstalling yet ... *These are the only two ways I ever managed to get fast program runtimes for the nested program. Questions: * *What may cause this performance drop for nested JVMs? *What exactly do these methods do (pwrite0/force0)? - A: Are you using local disks for all testing (as opposed to any network share) ? Can you setup Windows with a ram drive to store the data ? When a JVM terminates, by default its file handles will have been closed but what you might be seeing is the flushing of the data to the disk. When you overwrite lots of data the previous version of data is discarded and may not cause disk IO. The act of closing the file might make windows kernel implicitly flush data to disk. So using a ram drive would allow you to confirm that their since disk IO time is removed from your stats. Find a tool for windows that allows you to force the kernel to flush all buffers to disk, use this in between JVM runs, see how long that takes at the time. But I would guess you are hitten some iteraction with the demands of the process and the demands of the kernel in attempting to manage disk block buffer cache. In linux there is a tool like "/sbin/blockdev --flushbufs" that can do this. FWIW "pwrite" is a Linux/Unix API for allowing concurrent writing to a file descriptor (which would be the best kernel syscall API to use for the JVM, I think Win32 API already has provision for the same kinds of usage to share a file handle between threads in a process, but since Sun have Unix heritige things get named after the Unix way). Google "pwrite(2)" for more info on this API. "force" I would guess that is a file system sync, meaning the process is requesting the kernel to flush unwritten data (that is currently in disk block buffer cache) into the file on the disk (such as would be needed before you turned your computer off). This action will happen automatically over time, but transactional systems require to know when the data previously written (with pwrite) has actually hit the physical disk and is stored. Because some other disk IO is dependant on knowing that, such as with transactional checkpointing. A: One thing that could help is making sure you explicitly set the FileChannel to null. Then call System.runFinalization() and maybe System.gc() at the end of the program. You may need more than 1 call. System.runFinalizersOnExit(true) may also help, but it's deprecated so you will have to deal with the compiler warnings.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532165", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Disable fast delete on UITextField So, I have the delegate method - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { running to check if a textfield has a minimum of 1 character in it. Well, if the number of characters exceeds 20 or so, when the user holds down the delete button for a second or two it deletes the entire word, jumping over the delegate check and deleting all the way down to 0 characters. Does anyone know how to turn this 'fast delete' off? Can it even be done, or is there a decent work-around I am not seeing? I should also point out this is a single word that will be put in this textfield by the user. A: No way. What will you do if user will mark several letters as block and delete it as whole or change it with one letter? That's the reason why this method operates with ranges but not separate characters. A: Code in -(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string or -(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{ if (![text length]&&range.length&&range.length!=1){ return NO; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7532170", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how do I split string equation into its own array of strings? Possible Duplicate: How would I Evaluate a certain formula? How would I split this formula into an array of characters each having their own number in the array: a1+a2+a5*((a1+a6)*a3) one I have added the spaces I am going to get column 1 because a1 will indicate column one and it will contain a number than I will add that to column 2. I am not allowed to use a tree or any of those other things just stacks and I have been asking that. But people keep telling me to use libraries and trees I am only in a 200 level course ! A: You need a grammar and a parser to do this in a general way. Something like this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532177", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: In emacs, query-replace-regexp keyboard shortcut doesn't work in the terminal (e.g., emacs -nw) Is it expected that C-M-% and ESC C-% do not run the command query-replace-regexp when running emacs in a terminal window (for example, emacs -nw)? According to describe-function the binding exists, but emacs runs query-replace instead (which has the binding M-%). This has happened on several machines I've tried it on, and does not happen when I run emacs in a window. A: The problem is that C-% simply can't be typed in a terminal. The only control sequences available are those that corresponds to ascii-code 0-31, mainly C-letter. A: I have created a new shortcut in my .emacs file. (global-set-key "\M-q" 'query-replace-regexp) A: Control-Alt-Shift-% all together works on Windows and Fedora Linux. Does your keyboard have all those keys?
{ "language": "en", "url": "https://stackoverflow.com/questions/7532180", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Script forgets search keyword When I go to the next page(from index.php to index.php?page=2), the script forgets search keyword "for example country=US" and shows in the next page default option (country=). Then I also tried to add(WHERE country='".mysql_real_escape_string($_GET['country'])."') ,but in this way I think this line doesn't work: foreach($_POST as $key => $value) { $clean[$key] = mysql_real_escape_string(trim($value)); } $name=$clean['name']; $country=$clean['country']; $ip=$clean['ip']; $map=$clean['map']; $o="AND"; Sorry for the mess in the script, because I have collected it from the parts what I have found in the web and etc. So I still don't have enough skills to find out whats wrong. Thanks for any suggestion. <? include("conf.php"); foreach($_POST as $key => $value) { $clean[$key] = mysql_real_escape_string(trim($value)); } $name=$clean['name']; $country=$clean['country']; $ip=$clean['ip']; $map=$clean['map']; $o="AND"; $rest=""; $text="Keywords : "; if($name!="") { if($rest=="") { $rest.=" where name like '%$name%'"; $text.="Name like $name "; } else { $rest.="$o where fname like '%$name%' or mname like '%$name%' or lname like '%$name%' "; $text.="Name like $name "; } } if($country!="") { if($rest=="") { $rest.="where country='$country' "; $text.="Country = $country"; } else { $rest.=" $o country='$country' "; $text.=", Country = $country"; } } if($ip!="") { if($rest=="") { $rest.="where ip = '$ip' "; $text.="Ip Address = $ip "; } else { $rest.=" $o ip = '$ip' "; $text.=", Ip Address = $ip "; } } if($port!="") { if($rest=="") { $rest.="where port = '$port' "; $text.="Port = $port "; } else { $rest.=" $o port = '$port' "; $text.=", Port = $port "; } } if($map!="") { if($rest=="") { $rest.="where map = '$map' "; $text.="Map = $map"; } else { $rest.=" $o map = '$map' "; $text.=", Map = $map"; } } if($rest!="") { $rest=$rest; } else { //die("Enter Search Parameter<br><br><br><br><br><br><br><br><br><br><br>"); } $sql="select $search.* from $search $rest order by id"; $result=mysql_query($sql,$connection) or die(mysql_error()); $num=mysql_num_rows($result); $adjacents = 3; $limit = 10; $query = "SELECT COUNT(*) as num FROM $search"; $total_pages = mysql_fetch_array(mysql_query($query)); $total_pages = $num; /* Setup vars for query. */ $targetpage = "index.php"; //your file name (the name of this file) //how many items to show per page $page = $_GET['page']; if($page) $start = ($page - 1) * $limit; //first item to display on this page else $start = 0; //if no page var is given, set start to 0 /* Get data. */ $sql = "select $search.* from $search $rest order by id LIMIT $start, $limit"; $result = mysql_query($sql); /* Setup page vars for display. */ if ($page == 0) $page = 1; //if no page var is given, default to 1. $prev = $page - 1; //previous page is page - 1 $next = $page + 1; //next page is page + 1 $lastpage = ceil($total_pages/$limit); //lastpage is = total pages / items per page, rounded up. $lpm1 = $lastpage - 1; /* Now we apply our rules and draw the pagination object. We're actually saving the code to a variable in case we want to draw it more than once. */ $pagination = ""; if($lastpage > 1) { $pagination .= "<div class=\"pagination\">"; //previous button if ($page > 1) $pagination.= "<a href=\"$targetpage?page=$prev\">« previous</a>"; else $pagination.= "<span class=\"disabled\">« previous</span>"; //pages if ($lastpage < 7 + ($adjacents * 2)) //not enough pages to bother breaking it up { for ($counter = 1; $counter <= $lastpage; $counter++) { if ($counter == $page) $pagination.= "<span class=\"current\">$counter</span>"; else $pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>"; } } elseif($lastpage > 5 + ($adjacents * 2)) //enough pages to hide some { //close to beginning; only hide later pages if($page < 1 + ($adjacents * 2)) { for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++) { if ($counter == $page) $pagination.= "<span class=\"current\">$counter</span>"; else $pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>"; } $pagination.= "..."; $pagination.= "<a href=\"$targetpage?page=$lpm1\">$lpm1</a>"; $pagination.= "<a href=\"$targetpage?page=$lastpage\">$lastpage</a>"; } //in middle; hide some front and some back elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2)) { $pagination.= "<a href=\"$targetpage?page=1\">1</a>"; $pagination.= "<a href=\"$targetpage?page=2\">2</a>"; $pagination.= "..."; for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++) { if ($counter == $page) $pagination.= "<span class=\"current\">$counter</span>"; else $pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>"; } $pagination.= "..."; $pagination.= "<a href=\"$targetpage?page=$lpm1\">$lpm1</a>"; $pagination.= "<a href=\"$targetpage?page=$lastpage\">$lastpage</a>"; } //close to end; only hide early pages else { $pagination.= "<a href=\"$targetpage?page=1\">1</a>"; $pagination.= "<a href=\"$targetpage?page=2\">2</a>"; $pagination.= "..."; for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++) { if ($counter == $page) $pagination.= "<span class=\"current\">$counter</span>"; else $pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>"; } } } //next button if ($page < $counter - 1) $pagination.= "<a href=\"$targetpage?page=$next\">next »</a>"; else $pagination.= "<span class=\"disabled\">next »</span>"; $pagination.= "</div>\n"; } echo "<div align=left>$text</div>"; echo "<table align=center> <div align=left><tr>\n <td>Records Found: $num &nbsp; \n <td> &nbsp;\n </tr>\n <tr> \n</div>"; $counter=0; while($row=mysql_fetch_array($result)) { A: If you want to carry over POST and GET variables you actually should have some hidden input fields for them. So when you render the new page you assign all values from $_REQUEST to their respective inputs. Thus you will have them later on. e.g. <input type="hidden" name="country" value="<?php echo empty($_REQUEST['country'] ? '':$_REQUEST['country']; ?>"/> As an alternative you can store them to a session variable if you have a session. A: If you want the current search values to be available in $_POST, then you have to POST them. You are making a GET request to index.php?page=2, so the search terms will not be there (in either GET or POST). You could include them in GET and read them from $_GET instead in your loop at the top. Then all of your links would have to include all the search parameters, something like this: "<a href=\"$targetpage?page=$counter&name=$name&country=$country&ip=$ip&map=$map...
{ "language": "en", "url": "https://stackoverflow.com/questions/7532186", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I mysqldump the contents of a few tables or just the schema? Can you help me with the following: * *dump from the database just the contents of a few tables? *dump just the schema? A: mysqldump -u username -p database [table] > file.sql Use the --no-data option to dump just the schema. mysqldump --no-data ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7532192", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: View Database Columns via Checkbox WebFrom and Cookies I am using the telerik MVC template and have a database that has a huge number of columns and the telerik grid does not have a horizontal scroll bar, so I created checkboxes for the user to select exactly what columns they want to view. It works well enough in that when I first go to the page it shows the checkboxes at top with the Apply button and the grid view underneath. Because nothing has been submitted from the WebForm, the grid view shows all the columns. Before adding the cookies, the user only had to press apply once for only those columns to appear. However, if the user then tried to sort or filter one of these columns, it would revert back to showing all of the columns. So, I created a cookie to store the selected information. Unfortunately, this only helped with the selection of the first filter. If a second filter is used, it would, again, show all of the columns instead of just the ones selected. Furthermore, the user now has to press apply twice for their selections to show properly on the grid view. Here is a brief explanation of how I have everything coded: Index View <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <% using (Html.BeginForm("Index", "Order")) { %> <p> <%= Html.CheckBox("osurr", true, "Ad Number")%>Ad Number //I set this and a few other columns to default to true <%= Html.CheckBox("csurr", false, "Customer Number")%>Customer Number <%= Html.CheckBox("rhosurr", false, "RHO Number")%>RHO Number <%= Html.CheckBox("lockid", false, "Lock ID")%>Lock ID //And several more </p> <input type="submit" value="Apply" /> <% } %> <% Html.Telerik().Grid(Model) .Name("Grid") .Columns(columns => { columns.Template(o => { %> <%=Html.ActionLink("Detail", "Edit", new { id = o.osurr })%> <% }).Width(25); if (Request.Cookies["DBCols"]["csurr"] != null) { if (Request.Cookies["DBCols"].Values["csurr"].Equals("True")) { columns.Bound(o => o.csurr).Title("Cust. No."); } } if (Request.Cookies["DBCols"]["rhosurr"] != null) { if (Request.Cookies["DBCols"].Values["rhosurr"].Equals("True")) { columns.Bound(o => o.rhosurr).Title("RHO No."); } } if (Request.Cookies["DBCols"]["lockid"] != null) { if (Request.Cookies["DBCols"].Values["lockid"].Equals("True")) { columns.Bound(o => o.lockid).Title("Lock ID"); } } //And again, several more. }) .Groupable(grouping => grouping.Enabled(true)) .Resizable(resizing => resizing.Columns(true)) .Filterable(filter => filter.Enabled(true)) .Sortable(sorting => sorting.Enabled(true)) .Pageable(paging => paging.Enabled(true).PageSize(25)) .Render(); %> </asp:Content> Controller public ActionResult Index(bool? csurr, bool? rhosurr, bool? lockid /* And Several More */) { ViewData["csurr"] = csurr ?? true; ViewData["rhosurr"] = rhosurr ?? true; ViewData["lockid"] = lockid ?? true; if ((bool)ViewData["csurr"]) { DBCols.Values["csurr"] = (ViewData["csurr"].ToString()); } else { DBCols.Values["csurr"] = "False"; } if ((bool)ViewData["rhosurr"]) { DBCols.Values["rhosurr"] = (ViewData["rhosurr"].ToString()); } else { DBCols.Values["rhosurr"] = "False"; } if ((bool)ViewData["lockid"]) { DBCols.Values["lockid"] = (ViewData["lockid"].ToString()); } else { DBCols.Values["lockid"] = "False"; } //And Several more var db = new MillieOrderDB(); var listView = from m in db.vw_cadords orderby m.createstamp descending select m; return View(listView); } I am working just in the Index ActionResult for now to keep things in one place while I figure out how to get this all to work. Anyone have any ideas why I am having to press apply twice, why I can not use more than one filter, and how to avoid this? A: It turns out that the reason I had to hit apply twice and why when applying more than one filter caused issues was because I had everything in the Index ActionResult. Once I moved all the form data to its own ActionResult and then did RedirecttoAction("Index"), everything worked fine!
{ "language": "en", "url": "https://stackoverflow.com/questions/7532196", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }