text
stringlengths
8
267k
meta
dict
Q: How to get WPF combobox display text using UIAutomation? I just started using UIAutomation for some testing. I got the most stuff working except this seemly simple one. I want to verify the localized text displayed in a combobox, but I couldn't figure out how to retrieve the (localized) display text (combobox items are enumeration items) using UIAutomation API. UISpy doesn't show me the localized display text either (it shows the enum.ToString() value of the current selected item). Your help is much appreciated. A: From your description, it sounds like the ComboBox is bound to some enum values. How is the string being displayed localized? In any case the ComboBoxAutomationPeer supports the ValuePattern which returns the value for the Text property on the ComboBox. So it should be possible to bind the ComboBoxText property to your localized string and thus make it available via UIAutomation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543336", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Alternatives to caseInsensitiveCompare sortDescriptor An array to be sorted has strings such as: 200burgers 1apple 2burgers 11apples and similar. When sorting ascendingly with caseInsenstive, I get: 11apples 1apple 200burgers 2burgers Which makes sense, but I would prefer a lexicographical sort that put "1" before "10", "10" before "100", &c., such as: 1apple 11apples 2burgers 200burgers Must I construct a custom comparator or is there some other option? A: I think you'll probably need a custom comparator, but it'd be something really simple: NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@"key" ascending:YES comparator:^(id one, id two) { return [one compare:two options:NSCaseInsensitiveSearch | NSNumericSearch]; }]; A: If you can't adjust the string then you would have to write a custom comparator to search the string for the non-digit and sort on the string part then number part. Much easier however would be to have those two elements as separate objects and use - (NSArray *)sortedArrayUsingDescriptors:(NSArray *)sortDescriptors Where you will sort on "string" and then "count". Lexically the numbers will not sort correctly in the concatenated form you have posted.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543340", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Using a Java Library across iPhone and Android app version Good libraries are either written in C or Java a lot of the time. (No offense to Python, javascript, or Erlang). Well this time the best library for what I am doing is in Java. But I want to use it for both the Android and iPhone version of my app. How can this be done. This is a very important question because there will always be times when the best library is in Java even for an iPhone app. I am also open to HTML5 and PhoneGap solution, but essentially I need some way to access a Java Library in both environments. How can this be done? A: It can't be done. You cannot run a Java lib on iOS. You will either need to find an equivalent library that is written in C/Objective-C and use the Java one with Android and the C/Objective-C one with iOS, or you'll need to find one that runs on both (JavaScript). If you use Java/C solutions you'll then need to create a plugin for each to create a JavaScript API for PhoneGap to talk to. You can find information about all of this here. A: You could use something like RoboVM or j2objc to transpile the Java to Objective C.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543344", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JTextPane - how to style selected text I am looking for the most simple way to control JTextPane (its inner text) font color and font size within selected text only. I know I must look at StyledDocument but its snippets show the JMenu action listener tricks but not JButton :( I couldn't find code snippets which could show how to change selected text style by JButton clicked (the actionPerformed(...) method) etc :( I mean something in this direction * *A) I have a text in JTextPane lets say "My home is to turn into borabora and this is..." *B) Text "borabora" is selected in JTextPane *C) JButton("size=16") was clicked *D) Text "borabora" size becomes 16 I couldn't find this kind of snippets so I need your advice. Any useful comment is appreciated A: In your actionPerformed method of the applicable jbutton you could run this. (modify as needed.) String text = jTextPane.getSelectedText(); int cursorPosition = jTextPane.getCaretPosition(); StyleContext context = new StyleContext(); Style style; jTextPane.replaceSelection(""); style = context.addStyle("mystyle", null); style.addAttribute(StyleConstants.FontSize, new Integer(16)); jTextPane.getStyledDocument().insertString(cursorPosition - text.length(), text, style); A: but its snippets show the JMenu action listener tricks but not JButton You can add an Action to a JButton as well as well as a JMenu. For example: Jbutton button = new JButton( new StyledEditorKit.FontSizeAction("16", 16) ); You would use Styles when you want to apply multiple properies at one time to a piece of text. A: Based on @scartag answer and the comment about the API (from @kleopatra), I have found another way to do it. StyleContext context = new StyleContext(); Style style = context.addStyle("mystyle", null); style.addAttribute(StyleConstants.FontSize, new Integer(16));; jTextPane.setCharacterAttributes(style , true); The method setCharacterAttributes(style, replace) changes the style of the selected text so you don't need to remove it and add again with a new style. And more, the boolean replace indicates if the style replaces the old style (true) or if is added to the old style (false).
{ "language": "en", "url": "https://stackoverflow.com/questions/7543346", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Converting an Access database from 03 to 07 programatically with vb.net? I need to convert old .mdb Access files to the new .accdb format. What's the best way to do this in vb.net? A: Use Office InterOp to instantiate Application of Access and try to open .mdb, file then save it using SysCmd method. Honestly, I didn't tried so far yet but here are some undocumented sysCmd code but there is a simple approach to convert .mdb to .acccdb via ConvertAccessProject method. app = new Application() src ="c:\csnet\file.mdb" dst= "c:\csnet\file.accdb" app.ConvertAccessProject(src, dst, AcFileFormat.acFileFormatAccess2007) app.Quit()
{ "language": "en", "url": "https://stackoverflow.com/questions/7543348", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ADO.Net - Having multiple DBDataReaders running at the same time? When I have multiple DBDataReaders reading data at the same time I get the following error: There is already an open DataReader associated with this Connection which must be closed first I have ConnectionPooling enabled in my config so I don't understand why I am getting this error. Doesn't it suppose to create a new connection since my current connection is already in use? I know that setting MultipleActiveResultSets to true would fix the problem, but I'm still trying to understand why the problem exist A: Connection pooling does not do what you think it does. If you do something like this var connection = new SqlConnection(connectionString); connection.Open(); var command = connection.CreateCommand(); command.CommandText = // some query var reader = command.ExecuteReader(); var anotherCommand = connection.CreateCommand(); anotherCommand.CommandText = // another query var anotherReader = anotherCommand.ExecuteReader(); then all of this will happen on one connection, whether or not you have connection pooling. Connection pooling just keeps a cache of connections that you can draw from every time that you create a new connection (new SqlConnection) and open it (SqlConnectinon.Open). When you close a connection, it returns to the pool to be reused. But one open SqlConnection object corresponds to one connection from the pool. Period.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543349", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQL: username and password not recognized correctly ..of which I can't figure out what the exact problem is and/or why the interepreter is complaining about this. I'll post my code: <?php $path = realpath(dirname(__FILE__)); require("../data/userhandler.class.php"); $db = connectViaPdo(); //var_dump($db); $userHandler = new UserHandler($db); $username = $_POST['username']; $password = $_POST['password']; $email = $_POST['email']; $ip = $_SERVER['REMOTE_ADDR']; $query = "select username, password from users where ip = {$ip}"; $stmt = $db->prepare($query); $result = $stmt->fetch(); if(!$result) { $isBanned = $userHandler->checkIfBanned($ip); if (!$isBanned) { $query = "INSERT INTO users(username, password, ip, email) VALUES({$username}, {$password}, {$ip}, {$email})"; $stmt = $db->prepare($query); $result = $stmt->execute(); } else { echo "You are BANNED from this server. Leave now and do not come back."; exit(); } } else { $query = "UPDATE users SET username = {$username}, password = {$password}, email = {$email} WHERE ip = {$ip} "; $stmt = $db->prepare($query); $result = $stmt->execute(); } ?> My output resembles the following: Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.193.239, test@email.com)' at line 1' in /home/someuser/somedomain.com/portfolio/private_html/modules/register_user.script.php:29 Stack trace: #0 /home/someuser/somedomain.com/portfolio/private_html/modules/register_user.script.php(29): PDOStatement->execute() #1 {main} thrown in /home/someuser/somedomain.com/portfolio/private_html/modules/register_user.script.php on line 29 While I did follow the Stacktrace, it didn't really seem to help anything: my PDOstatement is correct. A: I think your string values need to be inside quotes: $query = "INSERT INTO users(username, password, ip, email) VALUES('{$username}', '{$password}', '{$ip}', '{$email}')";
{ "language": "en", "url": "https://stackoverflow.com/questions/7543352", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Algorithm behind typo corrections in Google Search I notice if I make a typo in Google search bar, it is very likely to correct it for me. Like, if I type "incerdible", it will suggest "incredible", or for "stackovflow", it will be "stackoverflow". What is the core idea of such algorithm? A: Here is an explanation, and some more links with further details: http://norvig.com/spell-correct.html A: There are many algorithms to solve that problem. The core algorithm is to calculate the difference between two words. You can take a look at Levenshtein distance, this is a great algorithm to do that. If you want to use something like that, you can use some npm package like this: https://www.npmjs.com/package/typo-correction
{ "language": "en", "url": "https://stackoverflow.com/questions/7543353", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How do OSes keep themselves from crashing when I stack overflow? What methods do operating systems use to prevent crashes or erratic behavior when one of my programs accidentally leaks memory or stack overflow? A: Briefly: Memory management. Typically each process is allocated a limited (but usually adjustable) amount of stack space, so a single process can't use up enough to cause problems for the system as a whole. And if a process attempts to access memory outside what's been allocated for it, that will (at worst) crash the process itself; this frees up the resources allocated for that process without stepping on other processes. A: OSes don´t generally protect from memory leaks in your program; but once your application ends all its memory is reclaimed. If your application never ended, then the OS would eventually get into trouble when it runs out of memory. Regarding stack overflows, they can detect that you have gone through your stack size. A posibility is to flag a few pages after the stack as protected memory, if you try to access it then you will get a segfault and your program will be terminated. A: Very good question, thanks for asking. There are three issues that I can think of off the bat. And, for each issue, there are two cases. Stack overflows: If your program is written in anything but assembly language, the OS can detect stack overflow because all stack operations are software operations. The run-time system manages the software stack and knows when overflow happens. If you have taken the trouble to write your program in assembly language and you pop the hardware stack in error, well, the OS can't save you. Bad things can happen. Out-of-bounds memory accesses: When your C++ program starts, the OS sets memory bounds on your behalf into the CPU. If your program tries to access memory outside those bounds, the CPU raises a hardware interrupt. The OS, as it handles the interrupt, can tell you that your program has misbehaved. This is what happens when you try to dereference a NULL pointer, for example. Your assembly-language program, though, can try to read or write from/into whatever memory it feels like. If your program is polite and was started by the OS in the usual way, then the OS can catch that error. But if your program is evil and somehow started outside the purview of the OS, it can do some real damage. Memory Leaks: Sorry, nobody can help you here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543362", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: PE header entry point RVA I am having an issue with a non .net, x86 machine type, pe32 executable piece of malware I am analyzing on a virtual machine. The entry point field is not NULL so this rules out execution starting at 0x0. When I break with a debugger at the entry point after creating the process in a suspended state, this program is managing to get calls out before the entry point. I am a little confused here, how exactly can this work? A: TLS (thread-local-storage) callbacks are called by the system before the application entry point. Here is a blogpost about that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543365", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: implode a key with a value How do I implode 2 values, 1 as the key and the other as the value. Say I have: $string = 'hello_world'; $arg = explode('_', $string); I now have $arg[0] and $arg[1] (as you know) How can I implode that so it becomes this structure Array ( 'hello' => 'world' ) A: $array = array($arg[0] => $arg[1]); A: Here's a fun way to do it without using intermediate args ;) $string = "hello_world"; $result = call_user_func_array( "array_combine", array_chunk( explode("_", $string ), 1 )); A: I'm not sure if you're looking for something this obvious: $arg = explode('_', 'hello_world'); print_r(array($arg[0] => $arg[1])); I assume it's a bit more complicated than this. Maybe the string contains multiple of these things. ex: 'hello_world,foo_bar,stack_overflow'. In which case you'd need to explode by the comma first: $args = explode(',', 'hello_world,foo_bar,stack_overflow'); $parsed = array(); foreach($args as $arg) { list($key, $value) = explode('_', $arg); $parsed[$key] = $value; } A: $string = 'hello_world'; $arg = explode('_', $string); $array = array($arg[0] => $arg[1]); would be the quickest way
{ "language": "en", "url": "https://stackoverflow.com/questions/7543367", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Wicket pageparameter I am trying to add and fetch with a key as String and value as List<object> in Wicket PageParameters. While am fetching the value with key, I got classcastException:String cant be converted into list. I am using something like this: List<Example> list = (List<Example>)params.get("ExampleList"); Any help is appreciated. A: You can't store objects in PageParameters because PageParameters are an abstraction of HTTP request parameters and the protocol only supports String values. You have to get the list of Strings from the parameters and process it into Example objects. List<StringValue> values = parameters.getValues("examples"); for(StringValue value : values) { Example example = new Example(value.toString()); examples.add(example); } A: // Populate PageParameters final String dynamicValue = textFieldID.getModelObject(); PageParameters pageParameters = new PageParameters(); pageParameters.add("username", usernameValue); pageParameters.add("username", "fixedValue"); // Retrieving PageParameters String newValue = parameters.getValues("username").get(1).toString(); // here newValue will contain "fixedValue" (the second element)
{ "language": "en", "url": "https://stackoverflow.com/questions/7543376", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Loading MKMapKit overlay tiles from server The Apple sample code TileMap is great at showing how to add raster image overlays using gdal2tiles, but it depends on having the tile directory on the device. What is the best way to adapt the code to load the files from the web? I noticed that one of the first thing it does is enumerate through the directory structure of the tiles folder to find out the available tiles. Is there a similar way to do this directory enumeration for a remote server? Thanks for the help A: You could start with the Open Street Map iOS page, which links to some libraries. Route Me is an open-source replacement for a MapView. Not quite what you're looking for, but you might be able to grab the network code and use it. Let's Do It World has some sample code, with instructions here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543378", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: rails / css : variable width text inputs Is this possible? I have an input (just one line, not a text-field) for comments which currently has a set width of 200px. But Could I make this text input scale with the browser width? So if the browser was 500px the input would be small but it it was 2560px the input would be very wide? Thanks A: Use the CSS attribute width with a percentage, like 20%. jsFiddle example.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543380", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I get an existing app to use the new permissions dialog? How do I get an existing app to use the new permissions dialog? I am using oAuth 2.0, which sends the visitor to facebook.com/oauth/authorize. If I try and add extended permissions like "user_actions.music" I get this error: Error Message: invalid permissions: user_actions.music. Am I missing something? Thanks! A: UPDATE: It seems that you need to use the old notation: perms instead of scope!
{ "language": "en", "url": "https://stackoverflow.com/questions/7543386", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to update an Object in play framework? How do I edit an existing object in the database? For example, if I have a model like this: class Topic{title,content,author}, when I edit and save the object I do not want to add the "author" object again. How do I update my existing object rather than adding a new one? A: If you're inheriting from the Model class (as you should), it provides a save() method as well as an ID attribute. When you call save() on an object you got out of the database, it will be updated, and if you call it on a new object it will be saved to the database. It's all automagical! Updating only specific fields Model.save() saves the whole object, so if you want to update only some data fields in your object, you first have to construct the exact object you want to go in your database. So let's say you don't want to update null fields, using your Topic(id, content, author) object: Topic newT = Topic(1L, 'yyy', null); Long id = newT.getID(); Topic oldT = Topic.findByID(id); //Retrieve the old values from the database Author newAuthor = newT.getAuthor(); //null if (newAuthor != null) { //This test will fail oldT.setAuthor(newAuthor); //Update the old object } String newContent = newT.getContent(); //Not null if (newContent != null) { oldT.setContent(newContent); //Update the old object } // Now the object oldT holds all the new, non-null data. Change the update tests as you see fit, of course, and then... oldT.save(); //Update the object in the database. That's how I would do it. Depending on how many fields you have this code is going to get really clunky really fast. Definitely put it in a method. Also, see here about findByID() and other ways to pull objects from the database. A: If you look at the JPA Object Binding part of the documentation, you will see it explains that, if you pass in an object to your controller, containing an ID, the object is first automatically loaded from the database, and then the new fields passed in are added to the object. This means, you can simply call the save() method. So, you controller action could be something like public static void editTopic(Topic topic) { topic.save(); //...any post edit processing }
{ "language": "en", "url": "https://stackoverflow.com/questions/7543391", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Send HTTP POST request to a server and get the response? I'm trying to send a HTTP POST request to a Google server and get the response. I'm trying to send the exact same request that my browser would send. When I search, I checked the request and response from Chrome's developer tools. According to that, this is my request. Request URL:http://www.google.com/hotelfinder/rpc Request Method:POST Status Code:200 OK request headers: POST /hotelfinder/rpc HTTP/1.1 Host: www.google.com Connection: keep-alive Content-Length: 116 Origin: http://www.google.com X-GWT-Module-Base: http://www.google.com/hotelfinder/static/ X-GWT-Permutation: A237247005BD7F571F547C07F4E1BA8D User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.186 Safari/535.1 Content-Type: application/json; charset=UTF-8 Accept: */* Referer: http://www.google.com/hotelfinder/ Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 Cookie: rememberme=true; --my cookie-- payload: [,[[,"hs","[,[,\"Las Vegas, NV\",\"2011-10-02\",1]\n]\n"] ] ,[,[[,"b_ca","101"] ,[,"b_qu","0"] ,[,"b_qc","1"] ] ] ] I used the Apache HTTP client to send the request but am only getting a page with that Google top bar. Please help me to do this. A: Open the page in a normal webbrowser, rightclick and View Source. That's exactly what HttpClient also retrieves. Do you see that bunch of JavaScript? Disable JavaScript in your browser, refresh the page. Do you now see that you get the same result (only the Google top bar)? In other words, JavaScript is required. You've to parse, interpret and execute JavaScript yourself. HttpClient doesn't do that, it just gives you the same as whatever your webbrowser retrieves as you can see in View Source. Your HttpClient code is working perfectly fine. The only difference is that your webbrowser is able to parse, interpret and execute JavaScript. That said, I wonder if you realize that you're actually violating their terms of service this way. I suggest to look for a public hotel finder webservice API. This question has been asked before: Travel/Hotel API's?
{ "language": "en", "url": "https://stackoverflow.com/questions/7543394", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using ActiveRecord serialize with Hash not working? I've been reading up on the use of serialize from ActiveRecord, and I thought I understood how to use it, but my attempts are failing so I'm not sure if what I want is even possible this way? What I want is to store a simple hash linking id's of objects called accruals to a number of days. For example {"1" => "12", "5" => "24"}. I set this up as follows: class User < ActiveRecord::Base serialize :accrual_days, Hash end And for the database def self.up unless column_exists? :users, :accrual_days add_column :users, :accrual_days, :text end end I then went into the rails console, and inputted these commands: User.find(1).accrual_days => nil User.find(1).accrual_days = {"1"=>"12"} => {"1"=>"12"} User.find(1).accrual_days => nil It seems like the accrual_days are being set, but then it doesn't persist. I tried saving the user after setting the accrual day, and storing it as string instead of text in the database, but the problem persists. What am I doing wrong? A: You're not saving the values in the database. Try user = User.find(1) user.accrual_days = {"1"=>"12"} user.save User.find(1).accrual_days
{ "language": "en", "url": "https://stackoverflow.com/questions/7543400", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create a multi-model, multi-page form in Rails? I am a newbie trying to learn Ruby on Rails. I am trying to learn how to work with the has_many association. I have a blog that I want to be able to add comments to. I am able to put an add comments form in a post page but i want to also learn how to add comments by going to a new page with an "add comments form". However, I am not able to pass the necessary information about what post a comment belongs to. I am not sure if it is a problem with my form or the comments_controller. posts_controller class PostsController < ApplicationController def show @post = Post.find(params[:id]) end def new @post = Post.new end def index @posts = Post.all end end comments_controller class CommentsController < ApplicationController def new @comment = Comment.new end def create @post = Post.find(params[:post_id]) @comment = @post.comments.create(params[:comment]) redirect_to post_path(@post) end end comment model class Comment < ActiveRecord::Base belongs_to :post end post model class Post < ActiveRecord::Base validates :name, :presence => true validates :title, :presence => true, :length => { :minimum => 5 } has_many :comments, :dependent => :destroy accepts_nested_attributes_for :comments end comment form <h1>Add a new comment</h1> <%= form_for @comment do |f| %> <div class="field"> <%= f.label :commenter %><br /> <%= f.text_field :commenter %> </div> <div class="field"> <%= f.label :body %><br /> <%= f.text_area :body %> </div> <div class="actions"> <%= f.submit %> </div> <% end %> routes.rb Blog::Application.routes.draw do resources :posts do resources :comments end resources :comments root :to => "home#index" end A: I guess you need to have the post id inside your comments page. Do something like this: When you are redirecting to the comments controller, pass the post id and get it from comments controller class CommentsController < ApplicationController def new @post_id = params[:id] @comment = Comment.new end def create @post = Post.find(params[:post_id]) @comment = @post.comments.create(params[:comment]) redirect_to post_path(@post) end end And in your comments/new.erb view, add the post id as a hidden param <h1>Add a new comment</h1> <%= form_for @comment do |f| %> <div class="field"> <%= f.label :commenter %><br /> <%= f.text_field :commenter %> </div> <div class="field"> <%= f.label :body %><br /> <%= f.text_area :body %> </div> <div class="actions"> <%= f.submit %><%= f.text_field :post_id, @post_id %> </div> <% end %>
{ "language": "en", "url": "https://stackoverflow.com/questions/7543402", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: .NET CLR Stored procedure OUTPUT Parameter I am creating a CLR stored procedure in VB.NET (.NET 3.5,SQLServer 2005). The procedure has 4 BYVal parameter and 4 BYRef parameters. It compiles and deploys correctly into SQL Server and a Stored procedure is created. However when I try to run the SP it insists on passing the OUTPUT parameters in. It gives the following error I am running it from SQL Server as Below DECLARE @return_value int, @outI int, @outS nvarchar(4000), @outD datetime, @outB bit EXEC @return_value = [dbo].[ProofOfConcept] @inI = 23, @inS = N'john', @inD = N'12/12/2009', @inB = 1, @outI = @outI OUTPUT, @outS = @outS OUTPUT, @outD = @outD OUTPUT, @outB = @outB OUTPUT 'TestProc' failed because parameter 5 is not allowed to be null. My VB.NET procedure declaration is below Public Shared Sub TestProc(ByVal inI As Integer, ByVal inS As String, ByVal inD As DateTime, ByVal inB As Boolean, _ ByRef outI As Integer, ByRef outS As String, ByRef outD As DateTime, ByRef outB As Boolean) A: Use Out() attribute before ByRef as in the code below Imports System.Runtime.InteropServices … Public Shared Sub PriceSum ( <Out()> ByRef value As SqlInt32)
{ "language": "en", "url": "https://stackoverflow.com/questions/7543408", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use folders in Codeigniter? I'm just starting with Codeigniter. I created a simple controller called home.php and a view called home_view.php. This is working fine. Now I would eventually like this site I'm building to have a admin section in addition to the public www version. So I reorganized my file structure like so: controllers: www - home.php admin Views: www - home_view.php admin Eventually I will put the admin related controllers and views in their respective directories. But after having moved my files like so, they no longer work. I think I need to changes something in the routes or config file. What do I have to do? A: For the views you just need to add the folder name to the begin of the view like: $this->load->view('www/home_view.php'); You will probably need to redo the routing for the controllers, so that extra folders are accounted for. This can be done with something like the following: $route['admin/(:any)/(:any)'] = 'admin/$1/$2'; $route['admin/(:any)'] = 'admin/$1/index'; This will use the controller($1) and function($2) inside the admin folder if the url is www.example.com/index.php/admin/[controller]/[function] for the controllers in the admin folder; and update the default controller like this: $route['default_controller'] = "www/home";
{ "language": "en", "url": "https://stackoverflow.com/questions/7543409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Pass in only strings and ints in C#? I have a function like the below. I ran into a problem were i accidentally passes in enums when i wanted the value. Same problem would occur if i passed in structs or classes. Is there a way i can pass call the func and only have strings and ints as my arguments? static public string Func(string fmt, params object[] args) A: You can create a paramarray of a specific type. If you want to accept two different types, you can create a class with implicit conversions from int and string and accept a paramarray of that class. A: It seems that the first parameter is used to communicate the format of the data in the second parameter, the array. I would create two public methods to solve this by making use of method overloading. see http://csharp.net-tutorials.com/classes/method-overloading. I believe this will work for array parameters. static public Func(string[] args) ... and static public Func(int[] args) ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7543411", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ios UIImagePickerController Take photo button title I can take the photo by UIImagePickerController and the sourceType = UIImagePickerControllerSourceTypeCamera ; i want to know how to make the button title based on device language. Now the cancel button, it only display "Cancel". how can i make the cancel button base on difference langauge? Thx A: Simple answer is you can't unless you use a custom picker controller. I think it should change automatically based upon the device language but I think I am wrong on that. A: It can be done with the following code, just change the Done title with cancel and provoke a dismissViewController: - (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated { UINavigationItem *ipcNavBarTopItem; // add done button to right side of nav bar UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:@\"Done\" style:UIBarButtonItemStylePlain target:self action:@selector(saveImages:)]; UINavigationBar *bar = navigationController.navigationBar; [bar setHidden:NO]; ipcNavBarTopItem = bar.topItem; ipcNavBarTopItem.title = @\"Pick Images\"; ipcNavBarTopItem.rightBarButtonItem = doneButton; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7543415", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: BSSID vs MAC address? I don't understand the difference between MAC address and BSSID. I understand that MAC is an identifier to local networks, but when I searched BSSID on wiki I got this: In an infrastructure BSS, the BSSID is the MAC address of the wireless access point (WAP). from source: http://en.wikipedia.org/wiki/Service_set_%28802.11_network%29 if BSSID is the mac address of WAP, then how come MAC addresses and BSSIDs are different? I tried this on a simple android app, when I getConnectionInfo I have a different BSSID from a MAC address. Can someone please explain this to me? Thanks A: The MAC address identifies a piece of hardware. The hub has a MAC address, and so does your network card which is connecting to it. The former is also the BSSID. getConnectionInfo will be returning your MAC address as "MAC address", and the hub's MAC address as "BSSID". A: The MAC address is the access point (AP) address. Each AP can support up to 16 SSIDs (Service Set ID). Each of these SSIDs has their own MAC address derived from the AP MAC address. For more information and to see how the BSSID derived from the MAC address please see: https://community.arubanetworks.com/t5/Controller-Based-WLANs/How-is-the-BSSID-derived-from-the-Access-Point-ethernet-MAC/ta-p/176290 I hope this answers the question for the future viewer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543419", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "25" }
Q: How to capture the client's connections and disconnections at the server side? I have written a server/client using WCF (net.tcp). Now I want to capture the client's connections and disconnections at the server side. A: If you have got authentication built within your WCF with slight modification this can be achieved. You create 2 methods on the service (Connect, Disconnect), where Connect is the first thing called by the client on startup (or logon) and Disconnect the last method client executes. On the server you log the connections/disconnections to database or any other storage of your choice. This is simple and does what you need. However, if the client app ends with unexpected exception or there are network issues you will not know that it happened. This is why I would add another method on the server that is called Refresh. The way this would work - every time client calls connect, you start a background thread on a timer and run Refresh every 5 minutes. This way your server side logs activity of the client at least every 5 minutes. Also I would create a Windows service running on the server on a timer every 10 minutes and if there are any not refreshed connection it creates a forced Disconnect. So this is how high level code on server would work: [DataContract] public class Session { public string UserName { get; set; } public byte[] passwordHash { get; set; } public Guid sessionGuid { get; set; } } public bool Connect(Session sessionObject) { if (GetOpenSession(sessionObject.sessionGuid) == null) { if (CreateNewSession(sessionObject)) return true; else return false; } else { CloseSession(GetOpenSession(sessionObject.sessionGuid)); if (CreateNewSession(sessionObject)) return true; else return false; } } public void Disconnect(Guid sessionGuid) { if (GetOpenSession(sessionGuid) != null) { CloseSession(GetOpenSession(sessionGuid)); } } public bool Refresh(Guid sessionGuid) { if (GetOpenSession(sessionGuid) != null) { UpdateSession(sessionGuid); return true; } else { return false; } } On the client if Connect or Refresh return false it would mean that connection has been lost and user needs to reconnect (re-login);
{ "language": "en", "url": "https://stackoverflow.com/questions/7543420", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Leaking Memory In C++ With boost::ptr_vector I been working in a project, but recently I check if my program has some leaking and the results is that it's leaking and a lot. I use _CrtDumpMemoryLeaks(); to receive all the messages of leaking and I check that most of them are related with boost, I know that it must be my problem, but I can't understand why it's leaking. In the debug output shows me these lines: Dumping objects -> {673} normal block at 0x00E075E0, 8 bytes long. Data: <H @e > 48 92 E0 00 40 65 E0 00 {671} normal block at 0x00E065C0, 8 bytes long. Data: <@e > 40 65 E0 00 00 00 00 00 {669} normal block at 0x00E06540, 68 bytes long. Data: < e mountains.pn> C0 65 E0 00 6D 6F 75 6E 74 61 69 6E 73 2E 70 6E {665} normal block at 0x00E063B0, 8 bytes long. Data: <H > 48 92 E0 00 00 00 00 00 {663} normal block at 0x00E09248, 68 bytes long. Data: < c nubes.png > B0 63 E0 00 6E 75 62 65 73 2E 70 6E 67 00 CD CD Which leads me to believe that the problem is where I use those strings, and the first call with those are in these lines: tutorialLevel->addLayerToList("nubes.png", 1600.f, 720.f, 1.0f, 0.0f, 0.1f, true); tutorialLevel->addLayerToList("mountains.png", 1600.f, 720.f, speedXVectorPanda.at(0), 0.0f, 0.5f, false); And the actual function addLayerToList is the next: void Level::addLayerToList(std::string name, GLfloat widthLayer, GLfloat heightLayer, GLfloat velX, GLfloat velY, GLfloat constantX, bool hasRepetition) { layersList.push_back( new Layer(name, widthLayer, heightLayer, velX, velY, constantX, hasRepetition) ); } And layersList is define like this: boost::ptr_vector< Layer > layersList; Maybe, I misunderstood how the ownership of pointers work in Boost, but in the examples I recently check, this is a correct way to pass ownership of the object to the ptr_vector, am I wrong? And my other question is, if it's necessary release the pointers for the vector, or it's better leave the auto_ptr do his work? Thanks for the help. A: Depending on where you placed it but in almost all cases, _CrtDumpMemoryLeaks will not show you the truth when using STL/BOOST smart pointers. It will see the usage of new within the STL as a memory leak. A: I'm sorry, I found out what was the problem and it is really stupid, really doesn't exist another word for that. I forgot that the class that handles dinamically Level it wasn't allocated with new, so until the main function finishes, it wasn't clean all the data, so my solution was create a method for cleanUp the class before go out of scope, so in this way all the pointer we're correctly deallocated. Thanks to everyone for the help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543424", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Configure Emacs for Web Development (PHP) I am trying to use Emacs as a beginner. I want to configure it for web development. I want syntax-highlighting for PHP, Javascript, HTML, CSS, and also I want (project wide)code completion. Can anyone please guide me where to start? What packages must be installed? Any guides on the installation and configuration? I am running GNU Emacs 23.2.1 on Debian Squeeze. Thanks in advance. A: Javascript, HTML, and CSS are all syntax-highlighted out of the box. The problem is that you will be writing PHP files that intermix all of those, which is a real pain even if you do set up one of the multiple-mode modes. You can improve things over the defaults, however. For Javascript I recommend installing js2-mode; it's got better syntax highlighting, indentation, and error reporting than the built-in javascript mode. For HTML I've always used nxml-mode, which has lately become the default. It's been ages since I've done anything with PHP, so I don't have any personal recommendations for that. However, I notice something called nxhtml-mode which looks quite interesting. It looks like nxml-mode upgraded to better support XHTML specifically (as opposed to XML generically), complete with a MuMaMo setup for handling CSS, Javascript, and even PHP. Looks like it'd be a good choice. I've never really set up any code completion in Emacs, I look forward to seeing everyone else's answers. A: As db48x suggested, the nxhtml-mode is the way to go. It will support highlighting different regions of your file using different rules (using MuMaMo). It's not perfect but more than enough for usual HTML+other languages in a single file work. I don't use code completion but I use auto-complete.el and am quite happy with it. It's not language aware but I don't usually use that. Works mostly out of the box. My own (rather messy) config files are on github if you want to take a look.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543428", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Paypal payment_gross is empty I am working with with paypal sandbox. According with that article after IPN verification i need to check payment_gross field but in my case it is empty. Also i have fields mc_gross and mc_gross_1 which is contains paid amount so should i check mc_gross insteard? any thoughts why payment_gross is empty? A: Not sure why payment_gross is empty (or whether or not it should be) but I've always used mc_gross to check the payment amount and I've never had any problems. In fact if memory serves I originally copied that from a PHP code sample from the Paypal developer documents. A: * *payment_gross: Will be empty for non-USDpayments. This is a legacy fieldreplaced by *mc_gross: If this amount is negative, it signifies a refund or reversal, and either of those payment statuses can be for the full or partial amount of the original transaction. Make sense?
{ "language": "en", "url": "https://stackoverflow.com/questions/7543435", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Would WebClient.DownloadString work as if a user is browsing the website? Basically I am downloading string/source of an online forum with threads/topics per page. But as a user, when I use a browser and browse through the site by clicking n number of links, it sometimes tells me that the server is too busy with an empty page with no topics. Would I encounter the same thing if I try to access the same website n number of times by using WebClient.DownloadString()? Would it be able to identify that my program is trying to access the website intensively? Although it's not a high profile website like yahoo, google, etc, so it most likely doesn't have sophisticated algorithms. A: Yes, the same rules and limitations are going to be impacted for a call via WebClient.DownloadString as you would see as a user browsing the site. If the server is too busy, or if the server has some sort of throttling or other system in place, it will still apply to your calls via this method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543436", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to move a SVG using jQuery SVG? I have written the following in a JavaScript method : <html> ... <script type="text/javascript" charset="utf-8"> $(function() { $('#layout').svg({}); var svg = $('#layout').svg('get'); svg.rect(150, 50, 100, 50, 10, 10, {fill: 'grey'}); svg.text(200, 75, "Some Text", {'font-family':"Verdana", 'font-size':20, 'text-anchor':"middle", 'fill':"#00ff00"}); $('#layout').click(function(e) { $(this).slideDown("slow"); }); } ... <body> <div id="layout" style="width: 640px; height: 480px;"></div> </body> </html> Ultimately I am trying to get 'layout' to move across the browser window. However I cannot get the 'layout' to move in anyway using slideDown() or animate(). How to I accomplish the effect? ----- Update (September 25, 2011) ------ I got it work with the following code. Thanks to Jason for tipping me off on the problem: <html lang="en"><head><meta http-equiv="Content-Type" content="application/xhtml+xml; charset=UTF-8"> ... <style type="text/css"> #layout { background: #6699FF; height: 480px; width: 640px; position: relative; } </style> <script type="text/javascript" charset="utf-8"> $(function() { $('#layout').svg({}); var svg = $('#layout').svg('get'); svg.rect(150, 50, 100, 50, 10, 10, {fill: 'grey'}); svg.text(200, 75, "SomeText", {'font-family':"Verdana", 'font-size':20, 'text-anchor':"middle", 'fill':"#00ff00"}); $('#layout').click(function(e) { $("#layout").animate({opacity: "0.1", left: "-=800"}, 500); }); }); </script> </head> <body> <div id="layout"></div> </body> </html> A: If you're trying to get a div to move across the entire window, regardless if it contains SVG or not, make sure its position is absolute in the CSS. You can then animate the left and top properties with jQuery.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543440", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CSS or JS for list item with no children from sibling list item with children I am creating a dropdown menu and want to add rounded borders on all four corners on hover if the main list item has no submenu, but I want only the top corners to be rounded on hover if the menu list item has a submenu. The submenu itself would not have any rounded borders and would blend into the tab of the parent. The HTML that creates the menu is derived from a WordPress function (wp_page_menu) which does not create different CSS classes for li tag without children versus li tag with children. This CSS creates a dark gray rounded rectangle around the menu list item when a list item is moused-over. But I only want this effect if the menu list item is childless. .menu ul li:hover a { background:#111; -moz-border-radius: 15px; -khtml-border-radius: 15px; -webkit-border-radius: 15px; border-radius: 15px; } Okay, so now the main menu list items that don't have children have 4 rounded borders, and the main menu list items that do have children have just the top rounded borders. So that is good. But .... now the children list items are also tabbed (i.e., the submenu is inheriting the style from the tabbed parent). I have fussed with the style sheet for hours and can't get what I want. The children list items should not have any rounded borders. Using the jQuery and/or CSS, how can I prevent the submenu from inheriting? A: If you have jQuery on that site then you can put something like this $(function(){ $('.menu li').has('ul').addClass('has-subitems'); }); this will add has-subitems class to all menu items that have sub menus. After that you can style them appropriately in CSS: .menu li.has-subitems { ... } .menu li:not(.has-subitems) { ... } A: If you only want certain corners to be rounded, you can use border-top-left-radius like this: border-top-left-radius: 15px; -moz-border-radius-topleft: 15px; If you are trying to add this CSS to only <li> elements without children, you will have to use javascript/jQuery because it is not possible in CSS (yet). You can use the solution that @c-smile posted for that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543447", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to launch a pdftk subprocess while in wsgi? I need to launch a pdftk process while serving a web request in Django, and wait for it to finish. My current pdftk code looks like this: proc = subprocess.Popen(["/usr/bin/pdftk", "/tmp/infile1.pdf", "/tmp/infile2.pdf", "cat", "output", "/tmp/outfile.pdf"]) proc.communicate() This works fine, as long as I'm executing under the dev server (running as user www-data). But as soon as I switch to mod_wsgi, changing nothing else, the code hangs at proc.communicate(), and "outfile.pdf" is left as an open file handle of zero length. I've tried a several variants of the subprocess invocation (as well as plain old os.system) -- setting stdin/stdout/stderr to PIPE or to various file handles changes nothing. Using "shell=True" prevents proc.communicate() from hanging, but then pdftk fails to create the output file, both under the devserver or mod_wsgi. This discussion seems to indicate there might be some deeper voodoo going on with OS signals and pdftk that I don't understand. Are there any workarounds to get a subprocess call like this to work properly under wsgi? I'm avoiding using PyPDF to combine pdf files, because I have to combine large enough numbers of files (several hundred) that it runs out of memory (PyPDF needs to keep every source pdf file open in memory while combining them). I'm doing this under recent Ubuntu, pythons 2.6 and 2.7. A: Try with absolute file system paths to input and output files. The current working directory under Apache will not be same directory as run server and could be anything. Second attempt after eliminating the obvious. The pdftk program is a Java program which is relying on being able to generate/receive SIGPWR signal to trigger garbage collection or perform other actions. Problem is that under Apache/mod_wsgi in daemon mode, signals are blocked within the request handler threads to ensure that they are only received by the main thread looking for process shutdown trigger events. When you are forking the process to run pdftk, it is unfortunately inheriting the blocked sigmask from the request handler thread. The consequence of this is that it impedes the operation of the Java garbage collection process and causes pdftk to fail in strange ways. The only solution for this is to use Celery and have the front end submit a job to the Celery queue for celeryd to then fork and execute pdftk. Because this is then done from a process created distinct from Apache, you will not have this issue. For more gory details Google for mod_wsgi and pdftk, in particular in Google Groups. http://groups.google.com/group/modwsgi/search?group=modwsgi&q=pdftk&qt_g=Search+this+group A: Update: Merging Two Pdfs Together Using Pdftk on Python 3: It's been several years since this question was posted. (2011). The original poster said that os.system didn't work for them when they were running older versions of python: * *Python 2.6 and *Python 2.7 On Python 3.4, os.system worked for me: * *import os *os.system("pdftk " + template_file + " fill_form " + data_file + " output " + export_file) Python 3.5 adds subprocess.run * *subprocess.run("pdftk " + template_file + " fill_form " + data_file + " output " + export_file) *I used absolute paths for my files: * *template_file = "/var/www/myproject/static/" I ran this with Django 1.10, with the resulting output being saved to export_file. How to Merge Two PDFs and Display PDF Output: from django.http import HttpResponse, HttpResponseNotFound from django.core.files.storage import FileSystemStorage from fdfgen import forge_fdf import os template_file = = "/var/www/myproject/template.pdf" data_file = "/var/www/myproject/data.fdf" export_file ="/var/www/myproject/pdf_output.pdf" fields = {} fields['organization_name'] = organization_name fields['address_line_1'] = address_line_1 fields['request_date'] = request_date fields['amount'] = amount field_list = [(field, fields[field]) for field in fields] fdf = forge_fdf("",field_list,[],[],[]) fdf_file = open(data_file,"wb") fdf_file.write(fdf) fdf_file.close() os.system("pdftk " + template_file + " fill_form " + data_file + " output " + export_file) time.sleep(1) fs = FileSystemStorage() if fs.exists(export_file): with fs.open(export_file) as pdf: return HttpResponse(pdf, content_type='application/pdf; charset=utf-8') else: return HttpResponseNotFound('The requested pdf was not found in our server.') Libraries: * *pdftk *fdfgen
{ "language": "en", "url": "https://stackoverflow.com/questions/7543452", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: 000webhosting appending script I'm tearing my hair out with these guys. I'm trying to work on my ajax, and they're making it extremely difficult. If I make an ajax request or try to use a page as a javascript tag's source, they automatically append: <!-- www.000webhost.com Analytics Code --> <script type="text/javascript" src="http://analytics.hosting24.com/count.php"></script> <noscript><a href="http://www.hosting24.com/"><img src="http://analytics.hosting24.com/count.php" alt="web hosting" /></a></noscript> <!-- End Of Analytics Code --> Can I do anything about this? A: Append the beginning of an HTML comment at the end of every page: <!-- In the case of an AJAX response try ending with a JS Multiline Comment: /* So if you're using PHP: echo json_encode(array('take that' => 'cheap hosting')); echo '/*'; When you eval() the JSON response in Javascript you may need to append a closing comment tag: eval(response.text+'*/'); With any luck, the user's browser's HTML parsers will complete the comment (and hide the code your host inserts). I'm fairly certain that an eval within javascript will ignore comments so my second solution should work too. I'm not 100% sure though because I don't have a cheap host to test this on! Let me know if it actually works. A: You can disable that by going to: http://members.000webhost.com/analytics.php No need for workarounds or hacks.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543455", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Regex for URI routing I'm following up on a question since the question changed Finding the regex for /<region>/<city>/<category>? The answer that works is /(?:[^/]+)/?([^/]*)/?([^/]*) and it outputs city in $1, category in $2 but I also just want to output $0 so can you help me modify it a little do achieve this? It seems I'll finally be able to do what I want with this regex and it also applies to 2 earlier questions I asked Can I use a python regex for letters, dashes and underscores? How to represent geographical locations My plan is to implement the functionality with multitenancy so that same software can serve large cities like sao paulo and delhi at same time with same code so I must make it very general and for all locations with same expression i.e. // Plus the problem what we mean when we say e.g. "Search New York" - the region or the city? One piece of info for this is the output from google maps that defines "New York" where "region" corresponds to "administrative area": { "name": "New York", "Status": { "code": 200, "request": "geocode" }, "Placemark": [ { "id": "p1", "address": "New York, NY, USA", "AddressDetails": { "Accuracy" : 4, "Country" : { "AdministrativeArea" : { "AdministrativeAreaName" : "NY", "SubAdministrativeArea" : { "Locality" : { "LocalityName" : "New York" }, "SubAdministrativeAreaName" : "New York" } }, "CountryName" : "USA", "CountryNameCode" : "US" } }, "ExtendedData": { "LatLonBox": { "north": 40.8495342, "south": 40.5788964, "east": -73.7498543, "west": -74.2620919 } }, "Point": { "coordinates": [ -74.0059731, 40.7143528, 0 ] } }, { "id": "p2", "address": "Manhattan, New York, NY, USA", "AddressDetails": { "Accuracy" : 4, "Country" : { "AdministrativeArea" : { "AdministrativeAreaName" : "NY", "SubAdministrativeArea" : { "Locality" : { "DependentLocality" : { "DependentLocalityName" : "Manhattan" }, "LocalityName" : "New York" }, "SubAdministrativeAreaName" : "New York" } }, "CountryName" : "USA", "CountryNameCode" : "US" } }, "ExtendedData": { "LatLonBox": { "north": 40.8200450, "south": 40.6980780, "east": -73.9033130, "west": -74.0351490 } }, "Point": { "coordinates": [ -73.9662495, 40.7834345, 0 ] } } ] } : However I don't think all the code has to be in the same file since I can make one file per region or some structure like that since the total number of regions ("states") for the whole world is not very much larger than the total number of countries but the total number of cities of the world is a large number. And it seems to have a file for every country included in the project is an easy and good way to organize. Many thanks Update The regex I found useful is application = webapp.WSGIApplication([('/([^/]+)/?([^/]*)/?([^/]*)',Handler),],debug=True) A: (?:...) A non-capturing version of regular parentheses. Matches whatever regular expression is inside the parentheses, but the substring matched by the group cannot be retrieved after performing a match or referenced later in the pattern. http://docs.python.org/library/re.html ?: is means, match it but doesn't save it in groups, remove it and try again.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543462", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Forcing a trailing slash at the end of the URL I currently have this on my htaccess file to map mydomain.com/contact-us -> mydomain.com/contact-us.php RewriteEngine On RewriteRule ^contact-us(\/?)$ /contact-us.php [NC,QSA,L] My problem is I want it ALWAYS to show a / at the end of the URL even if the users did not typed it, currently both with or without slash it will map to mydomain.com/contact-us.php A: You could redirect requests to the page without a slash to the page with a slash with a permanent redirect: RewriteEngine On RewriteRule ^contact-us$ /contact-us/ [R=301,QSA,L] RewriteRule ^contact-us/$ /contact-us.php [NC,QSA,L]
{ "language": "en", "url": "https://stackoverflow.com/questions/7543466", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Distinct results in db.collection.find() query I have query over a collection db.users.find() which is returning duplication results. For example user._id "1" can repeat multiple times. Is there a way to return distinct results? A: If you want only all the distinct user._id, use db.users.distinct("_id") if you want the whole records with distinct _id you have to think of a strategy to choose between 2 records with the same user._id You can use group or map reduce but you have to think about, what do I want when there are 2 user with the same _id. BTW, _id are usually generated by mongodb and there supposed to be unique. If you have 2 ids which are the same either you have a very very high insertion rate in your collection either you are generating _id yourself. Is there any particular reason you are generating non unique _id ? A: A single find should never return duplicate results, as there's no such thing as a join in Mongo so there's no circumstance in which a single document would be returned twice by a query. So what you're describing sounds like it should never happen - but it's hard to say without more details. However, one possibility is that find returns an open cursor, so if, for example, you were iterating through a large number of documents and updating them as you go, you may end up getting the same document back again later. The reason for this is that your update can increase the size of the document so that it no longer fits in the space it has, so it has to be reallocated space at the end of the collection, where it is later picked up again by the cursor. If that is what you're doing you probably need to think about doing the update in a different way.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543467", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: 406 (Not Acceptable) error on rails and jquery mobile autocomplete I keep getting this 406 (Not Acceptable) error when i type in an autocomplete field. I am using jquery mobile and jquery ui autocomplete and rails here is my jquery $("#request_artist").focus(function(){ $("#request_artist").autocomplete({ source: function(req, add){ $.getJSON(artistRequestUrl, req, function(data) { var suggestions = data.suggestions; add(suggestions); }); }, change: function() { $("#request_song").attr("disabled", false); $("#request_submit").attr("disabled", false); $("#request_like_reason").attr("disabled", false); $('.disable_color').css("color", "black"); }, }); }); here is my html <div data-role="fieldcontain"> <label for="search">Artist</label> <input type="search" name="password" id="request_artist" value="" /> </div> here is my rails action def ajax_artist bands = Band.all artists = bands.map(&:name).uniq.sort filter_input(artists, params[:term]) Rails.logger.info @all_instances_hash.inspect respond_to do |format| format.json { render :json => @all_instances_hash} end end if i look at the logger in the console i get this for @all_instances_hash if i enter the letter c {:query=>"c", :suggestions=>["Casting Crowns", "John Mark McMillan"]} But the autocomplete is not working...any idea A: I'd guess that Rails thinks you're asking for HTML back. Your ajax_artist can only ever respond (sensibly) with JSON so try ignoring the format completely: def ajax_artist bands = Band.all artists = bands.map(&:name).uniq.sort filter_input(artists, params[:term]) Rails.logger.info @all_instances_hash.inspect render :json => @all_instances_hash end
{ "language": "en", "url": "https://stackoverflow.com/questions/7543469", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a high level shape drawing API for C or C++? I am starting a new project (Windows application), which needs a simple graphical interface. The graphics are not the main point of the application, the algorithms behind them are, so I'd like to spend as little time as possible thinking about graphics. I need to draw simple shapes, connect them with lines, and label both the shapes and the edges. My ideal API would look something like n1 = Rectangle(width, height, center1); n1->label("Node1"); n2 = Circle(radius, center2); l = Line(n1->rightEdge()->midpoint()), (n2->center()-Point(n2->radius,0)); l->label("pathway",BELOW); I know I could certainly use a low-level library to build up to this level of abstraction. But I'd rather not, if it has already been done. Does a graphics library with this level of abstraction exist? I'd be equally happy with C/C++. C# would be an option too. A: Due to the general ease of writing that kind of high-level system, given a low-level drawing API, you generally don't see this kind of 2D scene graph library. The kind where there are explicit objects in the scene, and you move the objects around on the level of objects. The closest I can think of is the way WPF handles drawing, where you create graphics objects and attach them to windows. And that's .NET only. Everything else, whether Cairo, AGG, Direct2D, etc are all immediate drawing APIs. There are no "objects" that you manipulate or attach labels to. You simply draw stuff in a location. If you want to move something, you have to draw the stuff in that new location. A: I use SDL for my graphics needs. I only use it for the OpenGL context (which it handles great) but it's quite friendly for getting efficient and portable graphics to work. There are software drawing routines available if you don't want to deal with OpenGL. A: There is the new Direct2D API for Windows by Microsoft, mainly aimed at vector graphics. A: perhaps AGG would work for you. if you step back a few revs, you will also find a license which is better for commercial development. A: You can also try with qt lib qt is a great toolkit and multiplatform
{ "language": "en", "url": "https://stackoverflow.com/questions/7543471", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Swing Applet losing dirty data In reaction to a button being pressed on a toolbar, the user is prompted if he wants to Discard his changes (dirty data). If he selects YES that he wants to Discard his changes the displayed applet is stopped and destroyed. Alternatively, if the user selects NO that he does not want to Discard his changes, I trick the application into saving his changes (dirty data). I force a ToolbarController.SAVE event which ties into a SaveAction Thread to force his changes. I want to allow enough time for the SaveAction thread to do its job, so I wrapped the code in a SwingUtilities.invokeAndWait thread method call. At runtime, the dirty data is lost. Is the SwingUtilities.invokeAndWait the proper method to use in this case? Here is the code snippet: public void shutdown() { if (configurationManager.isModifedConfigurations()) { int selection = 999; // Discard changes ? selection = JOptionPane.showConfirmDialog(null, messages.getString("ConfigPowerbarChangeConfirmMsg"), messages.getString("ConfigPowerbarChangeConfirmMsgTitle"), JOptionPane.YES_NO_OPTION); if (selection == JOptionPane.NO_OPTION) { //Discard Changes configurationManager.setModifedConfigurations(false); super.shutdown(); removeBindings(); stopCurrentApplet(); } else if (selection == JOptionPane.YES_OPTION) { //Force Save changes System.out.println("Catch ApplicationEvent !!! Force Save of Mutable Table fields."); try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { toolbarController = new ToolbarController(ToolbarModelFactory.getSystemwideToolbarModel()); ApplicationEvent evt = new ApplicationEvent(ToolbarController.SAVE, toolbarController); toolbarController.handleApplicationEvent(evt); } }); } catch (InterruptedException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } } Suggestions? A: Problem maybe that SwingWorker is not blocking the shutdown procedure. Imagining that theres nothing to refresh in the GUI that makes use of SwingWorker mandatory in this use case i would just run the code that SwingWorker currenlt run but without using the SwingWorker. This way, thinks that are being done in the SwingWorker will block the shutdown process.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543472", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Use of inode fields for storing encryption key of the file I am working on inherent kernel functionality for file encryption and decryption ; directory name with some predefined prefix will be automatically be encrypted. Now I am stucked to store encryption key for file securely can I use any unused field of inode for that? Will it be efficient or please suggest any other idea. A: Storing the encryption key in the inode of a file which is encrypted is self-defeating - you can read this key using e.g. a disk editor and access the file content, thereby defeating encryption. You need to provide a /proc interface for that, so userspace can decide how this key is supplied (e.g. the user is prompted for a password which is hashed to obtain the encryption key). The kernel should not write the encryption key anywhere, it should only receive it when it is written to a special /proc file. You can use another /proc file to tell the kernel the directory prefix that marks encrypted directories. If you need to store some encryption metadata in the file (not the encryption key!), put it in a header like eCryptfs does.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543475", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Hashcode function My hashcode function for string is as follows hashVal=(127*hashVal+key.charAt(i))%16908799 I am following cs61 b lectures online and I dont quite follow when Prof.Jonathan on what would happen if instead of 1690877 we would use a value that is no relatively prime with 127. I understand the simple case where he uses 127 instead of 16908799 but what if it was a simple multiple of 127 ? How would it "bias" the hashvalue ? How does the bias depend on the common factor "x" ? Can anyone suggest me the reason ? A: Use smaller numbers and think it out. Say you're working in a modulus 10 space (instead of 16908799). Your hashVal can then only contain the numbers 0-9. If you multiply by 7, for instance, you should see that you can get out all numbers 0-9: (7*0)%10 = 0 (7*1)%10 = 7 (7*2)%10 = 4 (7*3)%10 = 1 (7*4)%10 = 8 (7*5)%10 = 5 (7*6)%10 = 2 (7*7)%10 = 9 (7*8)%10 = 6 (7*9)%10 = 3 However if you multiply by 6 (which is not relatively prime with 10 because they have the common factor 2), then you will not get all numbers 0-9 out, thus there is bias: (6*0)%10 = 0 (6*1)%10 = 6 (6*2)%10 = 2 (6*3)%10 = 8 (6*4)%10 = 4 (6*5)%10 = 0 (6*6)%10 = 6 (6*7)%10 = 2 (6*8)%10 = 8 (6*9)%10 = 4
{ "language": "en", "url": "https://stackoverflow.com/questions/7543478", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do you set a variable to an Edit Text Box I'm new to android developing. I have a value in a variable that I need to set = to a edit text box. How do you do this? I keep getting a null exception error. myStockPrice = (EditText)findViewById(R.id.txtStockPrice); ManualPrice = input1.getText().toString().trim(); else if (ManualPrice != null) { myStockPrice.setText(ManualPrice); } Thanks A: Hi try this may be in manualprice has no any value so you get a error : myStockPrice = (EditText)findViewById(R.id.txtStockPrice); ManualPrice = input1.getText().toString().trim(); else if (ManualPrice.length() > 0) { myStockPrice.setText(ManualPrice); } A: myStockPrice could be null because the edittext you are looking for is not in the layout you set with secContentView. is input1 a textview or an edittext? If so check if the belongs to the same layout you set with setContentView.. As others ask you, giving a bit of bt could better help to understand your problem A: Assuming that input1 is not null, this should solve your problem, myStockPrice = (EditText)findViewById(R.id.txtStockPrice); ManualPrice = input1.getText().toString(); if (ManualPrice != null) { myStockPrice.setText(ManualPrice.trim()); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7543480", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery Horizontal Accordion Jitter I know this is a fairly popular topic around here, but I'm hoping someone can help me with my particular implementation. I'm working on a design that uses jQuery animations to create an accordion menu, and it works, but I get a lot of jitter during the animation. From my searching, the solution for this seems to be to animate all of the elements with one animate() object and a step() function to ensure synchronization. The problem is, I can't for the life of me, come up with a step() function that works. Here is my latest attempt: http://www.3strandsmarketing.com/jq-test-v2.html It works if you move your mouse slowly, but the code is kludgy to say the least, and if you move your mouse quickly it totally falls apart (btw, I've tried mitigating this with the hoverIntent plugin, but I didn't like the lag it added). I think the answer maybe in JQuery Accordion Jitter Issue or Jitter in Jquery Accordion Implementation, but I lack the skill to adapt their code to my situation. Also I really want to avoid the extra weight of adding jQuery UI if at all possible. Any help is greatly appreciate. Thanks. A: Well, after several hours of tinkering, it's now 5am and I think I have it. I was eventually able to adapt the solution I referenced in my original question. I updated the jsfiddle that @rwilliams made with the new code, so if you're interested, you can see my adaptation there (http://jsfiddle.net/bKZ4t/2/). It works pretty well. Sadly though, the jitter is not completely gone. It is much less noticeable than it used to be though, and I think I'll just have to settle for that unless someone else can improve my implementation. Thanks to all who contributed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543483", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ASP : How to get the last index of FB friendlist Json.Parse data? I use json2.asp in my app. This is the code to parse friend list json data. Set friendlist = JSON.parse(friendlist_json_data) The result, I can get first friend id with this code friendid = friendlist.data.get(0).id So the friendid = 1234567890 (something like that) The question is, how to get the last index of friendlist array? I try to use lastindex = friendlist.data.get.count and lastindex = ubound(friendlist.data.id) but nothing work. I hope someone will help me because I want to show all user's friends photo profile in my app. A: You need length of the object called data.Like this: lastindex = friendlist.data.length - 1 friendid = friendlist.data.get(lastIndex).id
{ "language": "en", "url": "https://stackoverflow.com/questions/7543489", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: libboost_date_time linker error I just built and installed boost on cygwin and was trying to compile a program but it gave me a linker error because it was looking for libboost_date_time, and I have libboost_date_time-mt instead in usr/local/lib I tried to reinstall boost using the following (the same command I had used initially) ./bootstrap.sh --with-libraries=chrono,date_time,exception,filesystem,graph,graph_parallel,iostreams,math,program_options,random,serialization,signals,system,test,thread,wave link=static link=shared threading=single threading=multi but I get the error: bash: ./bootstrap.sh: no such file or directory any idea why the build wouldn't have worked with the ./boostrap command above the first time, and how I can fix it? A: ./bootstrap.sh means run the shell script bootstrap.sh in the cirrent directory. So you need to be in the sirectory the script is in So cd C:\cygwin\home\ba\boost_1_47_0 and then run the bootstrap script An alternative is to install boost via cygwin itself if you can use 1.43
{ "language": "en", "url": "https://stackoverflow.com/questions/7543491", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to check which specialized template is compiled in I have a templated function, which is also specialized with built-in types (int, float). Is there a way to display which functions are being used and which are being pruned out by the compiler, at compile-time?? Perhaps using #pragma?? template<typename T> int func(T val) { ... } template<> int func<float>(float val) { ... } // etc A: Your best option is to just leave all of the functions undefined, and see what errors the compiler throws at you when it tries to instantiate the template functions. If you need to do this multiple times, perhaps setting up a #ifdef around that code would allow for a "dump out the used functions" build. From there it would be a simple shell script or something to pull out the types of the functions instantiated from the compiler's error log. Alternatively, you could possibly add a compile error based on the template parameter: template<typename T> int func(T val) { T::this_version_is_being_included; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7543493", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: One tap printing on iPhone I want to make an app on the iPhone that would print an image just by tapping a button. I've tried the tutorials about UIPrintInteractionController online, but all of them will take me to a selection page before I can actually print. Can I programmatically skip that page by sending a default print job directly to an available printer that the iOS can connect to? A: No. Using the printing UI is a requirement; otherwise, the user doesn't have a way to change printers or set printer settings. Unlike a desktop computer, printers in iOS are transient, so there's not a notion of a "default printer" or configuration for one-click printing. See the Drawing and Printing guide for more information about the UI expectations for apps which print.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543497", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What's wrong with this MySQL trigger? So what is wrong with this trigger? MySQL is only nice enough to tell me it is a 1064 error. DELIMITER | CREATE TRIGGER new_member BEFORE INSERT on member FOR EACH ROW BEGIN INSERT INTO party(PartyId, PartyTypeCode, DateCreated, DateUpdated)      VALUES(New.PartyId, ’M’,now(), now()); END; | DELIMITER ; A: I'd guess that your problem is the non-ASCII quotes in your VALUES: VALUES(New.PartyId, ’M’,now(), now()); -- -----------------^ Try using plain old single quotes like SQL expects: VALUES(New.PartyId, 'M', now(), now());
{ "language": "en", "url": "https://stackoverflow.com/questions/7543499", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: apply jquery selector to object corresponding to hover For some reason .add on the last line doesn't work as expected, all the :first-child in the document are modified, I want only the :first-child from the hovered object to be modified. I tried everything I could think of, have no idea what the problem is. jQuery.fn.img=function(background,param,repeat) { $(this).css('background-image','url(/static/img/'+background+'.png') .css('background-repeat',repeat) .css('background-position',param+' top');} $('#sliding-door li').hover(function(e) {$(this).img('b1_middle_focus','left','repeat-x'); $(this).add(':first-child span').img('b1_left_focus','left','no-repeat');}, The html: <ul> <li><a href="/href1"><span><span>Something</span></span></a></li> <li><a href="/href2"><span><span>Another thing</span></span></a></li> </ul> A: Update I see what you're trying to do now. If you still need the hover function to apply on all the lis, while testing for the first child for just one subroutine, you can use an if statement: $('#sliding-door li').hover(function(e) { $(this).img('b1_middle_focus','left','repeat-x'); if ($(this).is(':first-child')) { $(this).find('span').img('b1_left_focus','left','no-repeat'); } }, ...); Old answer, ignore If you're looking for the span in the first child of $(this), you meant to use $(this).find() rather than $(this).add(): $(this).find(':first-child span').img('b1_left_focus','left','no-repeat'); .add() adds all the elements matched by the :first-child span selector on a document level to the $(this) object, which isn't quite what you expect it to do. See the jQuery docs: http://api.jquery.com/add
{ "language": "en", "url": "https://stackoverflow.com/questions/7543509", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: inline javascript: can it retrieve reference to the element it was invoked from? On basically any element you can put a onclick='func()' or some such to run JS when interacted with. Is there any way to get a reference to the DOM element itself? When i do the obvious thing: <input type='button' onclick='alert(self);' /> I get [Object DOMWindow], which isn't quite as convenient as I'd hoped. I realize I can easily hack my way through it by using id's or classes. But that means for each new custom-code button i create I must ensure it has a unique self referencing id, which I'd like to do without because that is more difficult to maintain. A: Inline event handlers embedded in the HTML are called with this being the element in question. <input type='button' onclick='alert(this);' />
{ "language": "en", "url": "https://stackoverflow.com/questions/7543514", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: HTML5 wrapper for old browsers, Modernizr I'm new to HTML5. It appears that Modernizr and a massive array of "HTML5 shims" provide bits of HTML5 support for older browsers. But what if I'm lazy and I don't want to even think about older browsers? Which HTML5 features can be perfectly emulated and which cannot? A: If you're new to HTML5, you should read everything on DiveIntoHTML5.ep.io.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543525", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to prevent duplicate entries in SQL Database using Stored procedures in C#.net I'm trying to make a simple user registration form with the following 4 fields, * *userid ( which is unique) *username ( which is unique) *password *email Now i'm able to prevent user from entering duplicate user entries in the Sql Database. But want to fire an event where the message can be successfully displayed to the user that the account 'already exists' when user provides the same userid/username or 'account creation successful' when the userid/username does not pre-exist. Please provide some C# code help (asp.net) to solve this issue. Thanks. A: Can't you just use a stored procedure that will test and insert the user and also return an output parameter with the result? CREATE PROC addUser @UserID decimal, @Username varchar()..., @Result varchar(50) output as if exists(Select UserId from Users where username = @Username) begin set @Result = 'Already there' return end insert Users .... set @Result= 'Success' A: You can handle the check before the insertion. To do this, you can use an event such as an OnItemInserting event with a DetailsView, use the values the user entered to check if the username exists and cancel the insert if it does. You can use the OnItemInserted event to confirm the new account afterward. You should definitely do additional input checks and check values, etc but the below is just pseudo code to get you in the right direction. Take a look at these examples OnItemInserting http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.detailsview.iteminserting.aspx OnItemInserted http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.detailsview.iteminserted.aspx Example (pseudo code) <asp:DetailsView ID="NewAccount" runat="server" DataSourceID="Account" AutoGenerateRows="false" OnItemInserted="NewAccount_ItemInserted" OnItemInserting="NewAccount_ItemInserting"> <Fields> <asp:BoundField DataField="UserName" HeaderText="UserName" /> <asp:TemplateField HeaderText="Password"> <InsertItemTemplate> <%-- Put your password boxes here --%> </InsertItemTemplate> </asp:TemplateField> <asp:BoundField DataField="Email" HeaderText="Email" /> </Fields> </asp:DetailsView> The code behind void NewAccount_ItemInserted(object sender, DetailsViewInsertedEventArgs e) { // Account successfully inserted PanelAccountSuccessful.Visible = true; // Show the successful message } void NewAccount_ItemInserting(object sender, DetailsViewInsertEventArgs e) { // Check for account that exists SqlConnection .... SqlDataSource .... //use e.Values["key"] to compare // select an account that matches e.Values["UserName"] and/or e.Values["Email"] SqlDataReader reader .... while (reader.read()) { // If you returned results then the account exists PanelAccountExists.Visible = true; // Show the error message that the account exists e.Cancel = true; // This cancels the insert } // Otherwise this will fall through and do the insert // Check that the passwords match and any other input sanitation you need if (Password1.Text.Trim() != Password2.Text.Trim()) e.Cancel = true; // Cancel if passwords don't match }
{ "language": "en", "url": "https://stackoverflow.com/questions/7543533", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Restart single activity within a tabactivity As title, I have read some articles. And I wrote this to do so. public class TabManager { private static Context tabAct; private static final String TAG = "TabManager"; public static void setTabActivity(Context t) { Log.i(TAG, "setTabActivity"); tabAct = t; } public static void restart(String tid, Class act) { Log.i(TAG, "restart " + tid); LocalActivityManager manager = ((ActivityGroup) tabAct).getLocalActivityManager(); manager.destroyActivity(tid, true); manager.startActivity(tid, new Intent(tabAct, act)); } } However, when I did TabManager.restart("tid4", MyActivity.class); The activity was destroyed but it didn't start. Could someone give me some advices? Thanks! A: Take a look at the documentation of the LocalActivityManager. It says calling startActivity will restart the activity if it meets some conditions. So the call to destroyActivity is not required.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543534", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Tilestream support in Route-me Has anyone been able to integrate the opensource TileStream server with the route-me framework for iOS? The documentation is pretty scarce. I have been able initialize a dictionary with the data for my map, however I get a sigabrt whenever I try and run the code. Thanks A: I've created a sample project showing how this works: https://github.com/mapbox/tilestream-ios-example
{ "language": "en", "url": "https://stackoverflow.com/questions/7543540", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why is the following negative lookahead is not working import re txt = 'harry potter is awsome so is harry james potter' pat = '\W+(?!potter)' re.findall(pat,txt) according to my understanding the the output should have been all the words that are not followed by potter that is ['potter', 'is', 'awsome', 'so', 'is', 'harry', 'james', 'potter'] but the actual output is ['harry', 'potter', 'is', 'awsome', 'so', 'is', 'harry', 'james', 'potter'] why is the pattern also matching the harry that is followed by potter ? A: because " potte" doesn't match "potter". >>> txt = 'harry potter is awsome so is harry james potter' >>> pat = '(\w+)(?:\W|\Z)(?!potter)' >>> re.findall(pat,txt) ['potter', 'is', 'awsome', 'so', 'is', 'harry', 'potter'] A: according to my understanding the the output should have been all the words that are not followed by potter It does. The thing is, every word is not followed by potter, because every word, by definition, is followed by either whitespace or the end of the string. A: import re txt = txt = 'harry potter is awsome so is harry james potter' pat = r'\w+\b(?![\ ]+potter)' print re.findall(pat,txt) A: I get this result: [' ', ' ', ' ', ' ', ' ', ' '] ...which is exactly what I expect. \W+ (note the uppercase W) matches one or more non-word characters, so \W+(?!potter) matches the whitespace between the words in your input, except when the upcoming word starts with "potter". If I wanted to match each word that's not followed by the word "potter" I would use this regex: pat = r'\b\w+\b(?!\W+potter\b)' \b matches a word boundary; the first two insure that I'm matching a whole word, and the last one makes sure the upcoming word is "potter" and not a longer word that starts with "potter". Notice how I used raw string (r'...'). You should get in the habit of using them for all your regexes in Python. In this case, \b would be interpreted as a backspace character if I had used a normal string.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543541", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Simple regex help using C# (Regex pattern included) I have some website source stream I am trying to parse. My current Regex is this: Regex pattern = new Regex ( @"<a\b # Begin start tag [^>]+? # Lazily consume up to id attribute id\s*=\s*['""]?thread_title_([^>\s'""]+)['""]? # $1: id [^>]+? # Lazily consume up to href attribute href\s*=\s*['""]?([^>\s'""]+)['""]? # $2: href [^>]* # Consume up to end of open tag > # End start tag (.*?) # $3: name </a\s*> # Closing tag", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace ); But it doesn't match the links anymore. I included a sample string here. Basically I am trying to match these: <a href="http://visitingspain.com/forum/f89/how-to-get-a-travel-visa-3046631/" id="thread_title_3046631">How to Get a Travel Visa</a> "http://visitingspain.com/forum/f89/how-to-get-a-travel-visa-3046631/" is the **Link** 304663` is the **TopicId** "How to Get a Travel Visa" is the **Title** In the sample I posted, there are at least 3, I didn't count the other ones. Also I use RegexHero (online and free) to see my matching interactively before adding it to code. A: For completeness, here how it's done with the Html Agility Pack, which is a robust HTML parser for .Net (also available through NuGet, so installing it takes about 20 seconds). Loading the document, parsing it, and finding the 3 links is as simple as: string linkIdPrefix = "thread_title_"; HtmlWeb web = new HtmlWeb(); HtmlDocument doc = web.Load("http://jsbin.com/upixof"); IEnumerable<HtmlNode> threadLinks = doc.DocumentNode.Descendants("a") .Where(link => link.Id.StartsWith(linkIdPrefix)); That's it, really. Now you can easily get the data: foreach (var link in threadLinks) { string href = link.GetAttributeValue("href", null); string id = link.Id.Substring(linkIdPrefix.Length); // remove "thread_title_" string text = link.InnerHtml; // or link.InnerText Console.WriteLine("{0} - {1}", id, href); } A: This is quite simple, the markup changed, and now the href attribute appears before the id: <a\b # Begin start tag [^>]+? # Lazily consume up to href attribute href\s*=\s*['""]?([^>\s'""]+)['""]? # $1: href [^>]+? # Lazily consume up to id attribute id\s*=\s*['""]?thread_title_([^>\s'""]+)['""]? # $2: id [^>]* # Consume up to end of open tag > # End start tag (.*?) # $3: name </a\s*> # Closing tag Note that: * *This is mainly why this is a bad idea. *The group numbers have changed. You can use named groups instead, while you're at it: (?<ID>[^>\s'""]+) instead of ([^>\s'""]+). *The quotes are still escaped (this should be OK in character sets) Example on regex hero. A: Don't do that (well, almost, but it's not for everyone). Parsers are meant for that type of thing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543542", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: PHP output buffer is not empty? I have this peculiar problem. I am making an AJAX call to a PHP page. In case of error I am returning the string "error" to success: function(msg) i.e. msg will have the value "error". But for some reason it is sending back "error" but with a line break preceding it. And this fails the condition when i check if (msg=="error"). I have to put ob_clean() to clear out the output buffer. Then it returns "error" without line break. I checked but my PHP function is not outputting anything before the "error". What can be the issue that the output buffer is not empty? A: That happens because some of your php files has an empty line before <?php or after ?> As PhpMyCoder propsed - you could also not put ?> in the end of the file at all. Php allows doing that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543546", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: c pointer assignment to pointer to pointer what does it mean I have a code snippet am struggling to understand. char *c; // c is uni dimensional table ( single row ) char **p ; // p is a two dimensional table **p = *c; // what does this mean ? When I do the above the assignment, is the c copied as first row of p ? or c is copied as first column of p ? A: **p = *c; // what does this mean ? When I do the above the assignment , Is the c copied as first row of p ? or c is copied as first column of p ? Neither, that code is copying the first element of c to the first element of p. Is equivalent to p[0][0] = c[0]; A: char *c; // c is uni dimensional table ( single row ) No, c is a pointer, not an array. If you initialize it properly, it can point to the first element of an array, but the pointer itself is not an array. char **p ; // p is a two dimensional table No, p is a pointer to a char*; it's not a table. Again, it might point to something that acts like a two-dimensional array. A true two-dimensional array is simply an array of arrays, but there are several other ways to use pointers to simulate more flexible versions of 2-d arrays, with dynamic allocation and varying row sizes. **p = *c; // what does this mean ? If p and c haven't been initialized, it means undefined behavior (which means your program crashes if you're lucky. If they have been initialized properly: p points to a char* object; let's call that object pstar. pstar points to a char object; let's call that object pstarstar. c also points to a char object; let's call it cstar. The assignment copies the value of cstar into pstarstar. What that means depends on what p and c point to. Recommended reading: section 6 of the comp.lang.c FAQ. A: It means that the char that c points to is copied to whatever p points to points to. c->some char is copied to p->*p->some char
{ "language": "en", "url": "https://stackoverflow.com/questions/7543547", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Piping a program that uses WriteConsole I wanted to call _popen to get the results from an executable but it was blanking out. I looked in debugger and found out the program uses Kernel32.WriteConsoleW to write a unicode string to the console, instead of using stdout. How do I capture it? A: Any output generated with WriteConsole will not be written to the redirection pipe. If a handle to a pipe or a file or anything else than a console is given to WriteConsole, it will fail with ERROR_INVALID_HANDLE (6). From High-Level Console Input and Output Functions on MSDN: ReadConsole and WriteConsole can only be used with console handles; ReadFile and WriteFile can be used with other handles (such as files or pipes). ReadConsole and WriteConsole fail if used with a standard handle that has been redirected and is no longer a console handle. A: The overkill solution: intercept calls to WriteConsoleW by hooking into the application on start. Probably not what you're looking for, and I'm sure there's an easier way. But it'll work for sure :) A: You should be able to redirect the Output of a child process. Have a look at Creating a Child Process with Redirected Input and Output Furthermore the application might use STD_ERROR_HANDLE instead of STD_OUTPUT_HANDLE.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543548", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: toPaddedString equivalent in javascript or jquery Anyone know if there is an equivalent method in jquery or javascript that matches the prototype toPaddedString method? A: There's nothing to match this in jQuery, but here, I whipped you up a straight Javascript version of the Prototype method: function toPaddedString(number, length, radix) { var string = number.toString(radix || 10), slength = string.length; for (var i=0; i<(length - slength); i++) string = '0' + string; return string; } toPaddedString(13, 4); // "0013" A: String.prototype.padLeft=function(n, s){ var t= this, L= s.length; while(t.length+L<= n) t= s+t; if(t.length<n) t= s.substring(0, n-t)+t; return t; } String.prototype.padRight=function(n, s){ var t= this, L= s.length; while(t.length+L<= n) t+=s; if(t.length< n) t+= s.substring(0, n-t); return t; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7543551", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: UITableView with Right-Side Index, Sections and Searchbar Causes Right-Side Index to Become Squished I have a UITableView with a section, searchbar and a right-hand side index. Initially, everything works and is drawn properly. However, when I type into my search bar then click cancel the right index is not redrawn properly. Here's how the index looks after I click the Cancel button. Here's normal: [Update] For some reason I needed to use this method to get my table reloadData to work: -(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar { ...} instead of this method: -(void)searchDisplayControllerDidEndSearch:(UISearchDisplayController *)controller { ...} Here is my method: /* Reset Table here */ -(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar { NSLog(@"\n===searchBarTextDidEndEditing"); self.isFiltered = NO; self.tableView = self.myTableView; [self genIndexWithFilter:NO]; [self.tableView reloadData]; } If someone can explain the subtle details, I'll upvote and accept their answer. A: Assuming your self.isFiltered boolean is the variable which controls which set of data is being rendered to screen; either the full list or a refined searched set. When -(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar { ...} is invoked, the self.isFiltered flag is set and you reload the table via. [self.tableView reloadData]; reloads the table checking the if you are rendering the filtered data or not. As well when reloadData is called it checks to see how many section are to be rendered. If done correctly, you can have something like this... - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView { if(self.isFiltered) //If searching return nil; //Return empty section else return sectionSelectionArray; //Return list of headers }
{ "language": "en", "url": "https://stackoverflow.com/questions/7543554", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Questions about Saving/Accessing saved files in Android All right, i'm reading a lot about the saving and accessing implementations in various Android and off-site documentations/help sites, but i still can't understand the implementation and how does it work, so my last resort is to turn to StackOverFlow (i'm working on this on my own) I'm going to sound a bit daft and retarded at times in this question because i'm learning on-the-fly whilst making my application, so bear with me (and i've labelled out parts of the entire document where i have questions): First off, i see that to implement a saved file, one has to write (as taken from android docs): //Declarations String FILENAME = "hello_file"; String string = "hello world!"; //Meaning that FILENAME is to be saved as hello_file, and "hello world!" converts the string to bytes FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE); fos.write(string.getBytes()); fos.close(); inside whichever function that saves the data (example a button) inside, like this: public void testButtonPressToSave() { FileOutputStream testSaveFile = openFileOutput(SavedFile, Context.MODE_PRIVATE); testSaveFile.write(); testSaveFile.close(); } However, when i implement it into the code, Eclipse recommends me to use a try/catch exception in the openFileOutput part, and the entire thing changes to: public void testButtonPressToSave() { FileOutputStream testSaveFile; try { testSaveFile = openFileOutput(SavedFile, Context.MODE_PRIVATE); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { testSaveFile.write(testString.getBytes()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { testSaveFile.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } (QUESTION) Is this normal? How am i able to reuse my saved file if it is on another activity? Do i import the entire main activity into the, say, a widget provider class? Also, I fully understand that: 1) FileOutputStream testSaveFile; and testSaveFile = openFileOutput(SavedFile, Context.MODE_PRIVATE); Declares testSaveFile as a FileOutputStream object and that it saves a file (.txt?) using a Context.MODE_PRIVATE which limits the file to only being able to be accessed by the application itself. and, 2) testSaveFile.close(); Ends the stream, somehow (but this is pretty direct, it just closes the file) The part i don't really get is, how do i save multiple variables inside the SavedFile data package? The Android documentation provides me with the available write() functions under FileOutputStream: public void write (byte[] buffer, int offset, int byteCount) public void write (byte[] buffer) public void write (int oneByte) Which isnt exactly what i want, because i need the stream to save multiple variables such as a String and Integer[]. (QUESTION) How do i go about saving my desired data types into the SavedFile? I've also read about Serialization, but i'm unsure how it would actually work to save a file into my application. Also, i'm not very confident that Serialization would be very efficient on a Dalvik VM (Android) because most of the code i've read and gone through are based on Java systems. There was also a Bundle android resource thingy that i don't understand but seems like the answer to store various multiple variables into one package and then unpackaging them at the next activity, although i don't see how i am able to actually save it into a file or something. Alright, i'm blabbing away with a lot of points but i'd be very grateful if anyone would be able to answer these questions. You don't have to provide an answer, but a clear explanation would be very much appreciated (especially around technical jargons :S) A: Looks like i've found a more effective way to store my data, through SQLiteDatabase in Android. Thanks anyway!
{ "language": "en", "url": "https://stackoverflow.com/questions/7543557", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: NullPointerException using append method on a view in android? I am trying to populate data from database into a TextView using this code: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView view = (TextView) findViewById(R.id.textView); db = (new DatabaseHelper(this)).getWritableDatabase(); cursor = getCursor(); cursor.moveToFirst(); while (cursor.isAfterLast() == false) { String text = cursor.getString(2); view.append(text); cursor.moveToNext(); } However I am getting a NullPointerException on this line: view.append(text); and I am not sure about the reason as the view exists. A: However I am getting a NullPointerException on this line: view.append(text); and I am not sure about the reason as the view exists. If you are sure that view exists and is not null, then text has to be null. You could for instance rewrite it as view.append(text != null ? text : "(null)"); A: You have to give the directions of the database how my example look. I do the same example, but with this difference: **db = SQLiteDatabase.openDatabase("/data/data/cl.kl.muestrausuario/DataBases/BDUsuarios",null,SQLiteDatabase.OPEN_READONLY);** Cursor c = db.query("usuario", new String[]{"regID", "nombre", "apellido"}, null, null, null, null, null); c.moveToFirst(); while (c.isAfterLast() == false) { view.append("\n" + c.getString(1)); view.append("\r" + c.getString(2)); c.moveToNext();
{ "language": "en", "url": "https://stackoverflow.com/questions/7543560", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What's the meaning of "value class space is flat"? I am now reading the book Programming in Scala. In chapter 11, it mentioned: Note that the value class space is flat. But no one explain what it means. Is it important? Why? And how to use and how to check value class space is really flat. It seems that ,it should told that ref class space is not flat, but no, and no other words say it again. So I want to know what the meaning of "space is flat", and why value class space is flat. A: A flat class hierarchy is one with lots of sibling classes and few or no subclasses (none in this particular case).
{ "language": "en", "url": "https://stackoverflow.com/questions/7543561", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: MediaWiki like directory system So if you look at a mediawiki url: http://en.wikipedia.org/wiki/Stack_Overflow You see that the page is a subdirectory of index.php in /wiki. How can I make my script work like http://mysite.com/users/Walter when all I have in the users directory is index.php (and other resources to make index.php work?) A: You will need to do some URL rewrite on your web server, for examples on nginx: server { listen 80; server_name wiki.example.com; root /var/www/mediawiki; location / { index index.php5; error_page 404 = @mediawiki; } location @mediawiki { rewrite ^/wiki([^?]*)(?:\?(.*))? /index.php5?title=$1&$2 last; } location ~ \.php5?$ { include /etc/nginx/fastcgi_params; fastcgi_pass 127.0.0.1:8888; fastcgi_index index.php5; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; } } There's a very good guide over here: https://www.mediawiki.org/wiki/Manual:Short_URL
{ "language": "en", "url": "https://stackoverflow.com/questions/7543562", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Does Wikipedia allow URL fetching via Google App Engine? I am writing a Python web app and in it I plan to leverage Wikipedia. When trying out some URL Fetching code I was able to fetch both Google and Facebook (via Google App Engine services), but when I attempted to fetch wikipedia.org, I received an exception. Can anyone confirm that Wikipedia does not accept these types of page requests? How can Wikipedia distinguish between me and a user? Code snippet (it's Python!): import os import urllib2 from google.appengine.ext.webapp import template class MainHandler(webapp.RequestHandler): def get(self): url = "http://wikipedia.org" try: result = urllib2.urlopen(url) except urllib2.URLError, e: result = 'ahh the sky is falling' template_values= { 'test':result, } path = os.path.join(os.path.dirname(__file__), 'index.html') self.response.out.write(template.render(path, template_values)) A: urllib2 default user-agent is banned from wikipedia and it results in a 403 HTTP response. You should modify your application user-agent with something like this: #Option 1 import urllib2 opener = urllib2.build_opener() opener.addheaders = [('User-agent', 'MyUserAgent')] res= opener.open('http://whatsmyuseragent.com/') page = res.read() #Option 2 import urllib2 req = urllib2.Request('http://whatsmyuseragent.com/') req.add_header('User-agent', 'MyUserAgent') urllib2.urlopen(req) #Option 3 req = urllib2.Request("http://whatsmyuseragent.com/", headers={"User-agent": "MyUserAgent"}) urllib2.urlopen(req) Bonus link: High level Wikipedia Python Clients http://www.mediawiki.org/wiki/API:Client_code#Python A: You can set your user-agent to any string you wish; it will be modified by App Engine to append the string AppEngine-Google; (+http://code.google.com/appengine; appid: yourapp). In urllib2, you can set the user-agent header like this: req = urllib2.Request("http://en.wikipedia.org/", headers={"User-Agent": "Foo"}) response = urllib2.urlopen(req)
{ "language": "en", "url": "https://stackoverflow.com/questions/7543571", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Is there any free unlimited album artwork search API service? Google's custom search API has a limitation up to 100 queries per day. That is far less than what I expected. I want to add that artwork-search function to my app. Thanks a lot. A: Musicbrainz and the Internet Archive offer the Cover Art Archive but you do need to request using the album's MBID. A: Last.FM provides an API for getting art but you can't actually use it in publicly distributed applications. They said that the recording companies own the art and they aren't licensed to distribute it. Huh? Why the API then? I don't get it. A: Last FM's album.getInfo API call offers images in four different sizes and can be searched using names or musicbrainz IDs. Output can be XML/JSON/JSONP. A: Last.fm isn't completely free and unlimited "Last.fm reserves the right to share in revenue generated from your use of Last.fm Data in future on terms to be negotiated in good faith between Last.fm and You." Discovered the FreeCover website API a few minutes ago searching for the same thing: http://www.freecovers.net/api/ For the record, ROVi seems loaded (they source Apple): http://developer.rovicorp.com/ ...but same as every good service on the internet: if you want good (meaning reliable) service, you'll have to pay eventually ;) A: How about Discogs, or Amazon or seeing what Cover Fetcher does? A: Other than the Cover Art Archive the only other approachably "free" and unlimited resource is Wikipedia: http://www.onemusicapi.com/blog/2014/09/10/querying-wikipedia-album-artwork/ You can use DBpedia to search for the album, then use the Wikimedia APIs to actually download the image.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543574", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "25" }
Q: Eclipse ide tasks tag problem I have been puzzled by the problem for several days: the task tags(TODO FIXME XXX and etc.) disappeared in tasks view in my working java project. What strange is this problem did not occur if a create a new project. Perhaps that's because I changed some configuration of my working project, but I can not figure out what it is,-_-! A: The task tags are under: Window > Preferences And then under: Java > Compiler > Task Tags Also you can check up in the top right corner there is a link for: `Configure Project Specific Settings` I think that's where you want to be A: Java Task Tags are only detected when a Build occurs (other than Clean), so leave automatic builds on if you want to get the most out of them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543575", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Does multiprocessing.Queue work with gevent? Anyone know what is wrong with this code? It simply "loads" forever. No output. "Sites" is a list of a few dozen strings. num_worker_threads = 30 def mwRegisterWorker(): while True: try: print q.get() finally: pass q = multiprocessing.JoinableQueue() for i in range(num_worker_threads): gevent.spawn(mwRegisterWorker) for site in sites: q.put(site) q.join() # block until all tasks are done A: Use gevent.queue.JoinableQueue instead. Green threads (gevent internally uses it) are neither threads nor process, but coroutine w/ user-level scheduling. A: gevent.spawn() creates greenlets not processes (even more: all greenlets run in a single OS thread). So multiprocessing.JoinableQueue is not appropriate here. gevent is based on cooperative multitasking i.e, until you call a blocking function that switches to gevent's event loop other greenlets won't run. For example conn below uses patched for gevent socket methods that allow other greenlets to run while they wait for a reply from the site. And without pool.join() that gives up control to the greenlet that runs the event loop no connections will be made. To limit concurrency while making requests to several sites you could use gevent.pool.Pool: #!/usr/bin/env python from gevent.pool import Pool from gevent import monkey; monkey.patch_socket() import httplib # now it can be used from multiple greenlets import logging info = logging.getLogger().info def process(site): """Make HEAD request to the `site`.""" conn = httplib.HTTPConnection(site) try: conn.request("HEAD", "/") res = conn.getresponse() except IOError, e: info("error %s reason: %s" % (site, e)) else: info("%s %s %s" % (site, res.status, res.reason)) finally: conn.close() def main(): logging.basicConfig(level=logging.INFO, format="%(asctime)s %(msg)s") num_worker_threads = 2 pool = Pool(num_worker_threads) sites = ["google.com", "bing.com", "duckduckgo.com", "stackoverflow.com"]*3 for site in sites: pool.apply_async(process, args=(site,)) pool.join() if __name__=="__main__": main()
{ "language": "en", "url": "https://stackoverflow.com/questions/7543579", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Integrating Dwolla with PHP with their API Foreword: Okay I've used APIs in the past such as TwitterAPI but I always used a library and some documentation to assist me with connections, and retrieving tokens. I have a basic understanding of how API's work. Okay so I've tried multiple ways of requesting the dwolla API with PHP I've tried making a <form action="https://www.dwolla.com/payment/pay" method="post"> <input type="hidden" name="key" value="soMeVerYLongAcsiiKey"/> <input type="hidden" name="secret" value="soMeVerYLongAcsiiseCret"/> </form> I actually got a json reponse from the above code but i could never get it to accept my credentials. I also tried doing something like string queries such as https://www.dwolla.com/payment/pay?key=someverylongAcssikey&secret=someverylonAcessisecret I've attempted at signing up at the Dwolla.org/d website for their official forums by they are taking for ever to accept me. I also tried the "Developer Forums" link which took me here http://getsatisfaction.com/dwolla and I posted my dilemma on there too no response. I just need some quick and dirty php pseudo code to make a request so customers can quickly just pay for their merchandise. I would like to use the oAuth2.0 method If you are a Bitcoiner, please post your Bitcoin address and I will accommodate you for your help. Thanks everyone! A: Finally got a respone from the Dwolla Developers and they are saying this way of doing it is deprecated as the SOAP API for Dwolla is deprecated and the recommended way for using the API is the REST API. A: You use the SOAP protocol to communicate with their API. Here is a link to a discussion on the API: http://www.dwolla.org/d/showthread.php?3-SOAP-API Here is a link to the php.net database on SOAP, and how to implement it: http://www.php.net/manual/en/class.soapclient.php This is the address that you use to communicate with the API: https://www.dwolla.com/api/API.svc?wsdl You authenticate with an API key, generated in your dwolla API settings, I believe. Then you can use the other functions of the API. Sorry can't be more specific right now, it's pretty late here right now. But it's pretty easy to do, just read through the documentation on both of those links, and you should figure it out. A: Have you defined all your parameters properly? Also, you can call the methods directly. For a full method list, uncomment the three lines after SoapClient is instanciated. $client = new SoapClient("https://www.dwolla.com/api/TestAPI.svc?wsdl"); # header('content-type: text/plain'); # var_dump($client->__getFunctions()); # exit; $params = array( 'ApiKey' => $apiKey, 'ApiCode' => $apiCode, 'Amount' => 1.00, 'Description' => $description, 'CustomerID' => $customerId ); var_dump($client->RequestPaymentKey($params)); //RequestPaymentKey returns a boolean: true if the request was successfully processed, False or exception otherwise http://payb.tc/nuri
{ "language": "en", "url": "https://stackoverflow.com/questions/7543582", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How can I get the user ID in the Facebook PHP sdk? I'm having the toughest time figuring this out... how can I get the user ID? While I relize the question sounds a bit retarded, I can't find this anywhere! This is my following top part of my code: require '../fb_fc/facebook-php-sdk-9147097/src/facebook.php'; $appId = 'APP_ID'; $appSecret = 'APP_SECERT'; $userId = 'USER_ID?????'; $userAccessToken = 'ACCESS_TOKEN'; How can I get the user ID? I get the access token by using $GET_['access_token']; and this is the URL : http://friendsconnect.org/example.php?access_token=ACCESS_TOKEN_HERE#access_token=ACCESS_TOKEN_HERE&expires_in=0 (This is not a working link). How can I do this? I'm also new to this and am open to suggestions. A: From: https://github.com/facebook/php-sdk The minimum code to get the user ID (assuming a cookie has been set or the access token already passed in) is: require 'php-sdk/src/facebook.php'; $facebook = new Facebook(array( 'appId' => 'YOUR_APP_ID', 'secret' => 'YOUR_APP_SECRET', )); // Get User ID $user = $facebook->getUser();
{ "language": "en", "url": "https://stackoverflow.com/questions/7543585", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to ping a database from NSIS? Putting together a NSIS installer. (first time) Currently, a manual step in our install is to make a URL connection to a database, and save a basic connection properties file to a folder under Tomcat. To aid this, we currently use a small JAR application that helps the user build this connection property file. It has built in functionality to try and ping the DB. It aids users by having a drop down to choose different db vendors/versions, and thus helping with building the URL. In my mockup, ideally, I wanted something that did away with the JAR app and have this component built into the installer. Something like this: I already know that I will need to create a custom page for this, (will use something like NSISDialogDesigner to assist with this). The bit that I am unsure about, is the best approach for pinging the database from NSIS to ensure a correct URL/credentials has been supplied, and to return the errors back to the custom page. What would be the best approach for implementing this functionality within a NSIS installer? For background, once I have achieved this, a later step will be to create a database by running some SQL scripts I have. Just thinking ahead, I guess which database vendor/version they have, will depend on which sql script to run. Im thinking that if the user chooses e.g. SQL Server 2005 on this page, this could be writen to a variable to use later when choosing the right sql script. A: The best way of pulling this off is to write a helper commandline application which you should run invisibly in the background and then check the exit code for success or failure. This helper app can be Java, C++, C#, or anything, whatever you're comfortable with. I've worked on several very large NSIS deployments and we had maybe 10 - 20 such tools launched during different phases of setup. For single WIN32 API calls, NSIS provides a P/Invoke-like wrapper, but for anything even remotely complicated, helper apps are the way to go.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543586", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Paypal IPN processing after payment I have IPN controller which is validating IPN and then validating some fields according with that article After user clicking pay on paypal website the ipn sending to my ipn controller and at the same time user getting redirected back to my web site(after paypal controller) from paypal web site. But the problem is, there is not enough time for my IPN controller to finish all the logic and user landed to my website on after paypal controller before IPN processing finished. So i cant say to user is there was any error or is it was successful. My be some one may share their experience with that? What I can do? I would redirect user from paypal back to my website only after ipn processing finished, so i could be able to say to user is it was successful or not, etc. On my after paypal controller i want to check if the ipn processing was successful and than display related message. Any thoughts? A: IPN is separate from the end users experience. You need 3 pages/actions: one for if paypal said "payment confirmed" another for if paypal said "payment failed" - these 2 pages mean nothing, the user could hack the site to see these pages, they are just there to let the user know what's going on. Third page/action is for IPN, it's just a listener that waits for paypal's response. Once you get the response then you check against it to make sure everything is ok: * *Make sure your email was paid *Make sure the price is right *Updates your db with "Paid!" marker, yada yada You could then have a simple binding to ("Paid!") that updates when the user 'postsback' or you could have ajax do it async. -- As a final point, I'm genuinely trying to find out here how to process/test the IPN and your obviously unresearched question has wasted my time. Do some research man.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543590", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Verilog Barrel Shifter I want to create a 64-bit barrel shifter in verilog (rotate right for now). I want to know if there is a way to do it without writing a 65 part case statement? Is there a way to write some simple code such as: Y = {S[i - 1:0], S[63:i]}; I tried the code above in Xilinx and get an error: i is not a constant. Main Question: Is there a way to do this without a huge case statment? A: I've simplified some of the rules for clarity, but here are the details. In the statement Y = {S[i - 1:0], S[63:i]}; you have a concatenation of two signals, each with a constant part select. A constant part select is of the form identifier [ constant_expression : constant_expression ] but your code uses a variable for the first expression. As you saw this isn't allowed, but you are correct in that there are ways to avoid typing a large case statement. What you can use instead is an indexed part select. These are of the form identifier [ expression +: constant_expression ] identifier [ expression -: constant_expression ] These constructs enforce that the width of the resulting signal is constant, regardless of the variable on the left side. wire [HIGH_BIT:LOW_BIT] signalAdd,signaSub; signalAdd[some_expression +: some_range]; signalSub[some_expression -: some_range]; //Resolves to signalAdd[some_expression + (some_range - 1) : some_expression]; signalSub[some_expression : some_expression - (some_range - 1)]; //The location of the high value depends on how the signal was declared: wire [15: 0] a_vect; wire [0 :15] b_vect; a_vect[0 +: 8] // a_vect[7 : 0] b_vect[0 +: 8] // b_vect[0 : 7] Rather than trying to build one signal out of two part selects, you can simply extend the input signal to 128 bits, and use a variable part select from that. wire [63:0] data_in,data_out; wire [127:0] data_in_double; wire [5:0] select; //Concatenate the input signal assign data_in_double = {data_in,data_in}; //The same as signal[select + 63 : select] assign data_out = data_in_double[select+63-:64]; Another approach you could use is generate loops. This is a more general approach to replicating code based on a variable. It is much less efficient since it creates 4096 signals. wire [63:0] data_in,data_out; wire [127:0] data_in_double; wire [5:0] select; wire [63:0] array [0:63]; genver i; //Concatenate the input signal assign data_in_double = {data_in,data_in}; for(i=0;i<64;i=i+1) begin : generate_loop //Allowed since i is constant when the loop is unrolled assign array[i] = data_in_double[63+i:i]; /* Unrolls to assign array[0] = data_in_double[63:0]; assign array[1] = data_in_double[64:1]; assign array[2] = data_in_double[65:2]; ... assign array[63] = data_in_double[127:64]; */ end //Select the shifted value assign data_out = array[select]; A: The best way I found to do this is finding a pattern. When you want to rotate left an 8 bit signal 1 position (8'b00001111 << 1) the result is = 8'b00011110) also when you want to rotate left 9 positions (8'b00001111 << 9) the result is the same = 8'b00011110, and also rotating 17 positions, this reduce your possibilities to next table: so if you look, the tree first bits of all numbers on table equivalent to rotate 1 position (1,9,17,25...249) are equal to 001 (1) the tree first bits of all numbers on table equivalent to rotate 6 positions (6,14,22,30...254) are equal to 110 (6) so you can apply a mask (8'b00000111) to determine the correct shifting number by making zero all other bits: reg_out_temp <= reg_in_1 << (reg_in_2 & 8'h07); reg_out_temp shall be the double of reg_in_1, in this case reg_out_temp shall be 16 bit and reg_in_1 8 bit, so you can get the carried bits to the other byte when you shift the data so you can combine them using an OR expression: reg_out <= reg_out_temp[15:8] | reg_out_temp[7:0]; so by two clock cycles you have the result. For a 16 bit rotation, your mask shall be 8'b00011111 (8'h1F) because your shifts goes from 0 to 16, and your temporary register shall be of 32 bits.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543592", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Help extracting data from JSON result I am having an issue retrieving the key from this JSON result returned from the last.fm api this is what is being returned: {"session":{"name":"mcbeav","key":"***************","subscriber":"1"}} and i just need the key, but if i try to print_r or var_dump , nothing is displayed how would i go about doing so? for example if i print_r($json['key']); or if i print_r['session']['key']; what is printed is "{"; A: just use the php function $myJsonData = json_decode($myJsonString,true) it will give you an assocative array like you have in your code (what the second arguement true is for) Hope that is what you are looking for A: $json = json_decode('{"session":{"name":"mcbeav","key":"eab5a0axxxxxxx0c3","subscriber":"1"}}'); echo $json->session->key; Or if you want an array: $json = json_decode('{"session":{"name":"mcbeav","key":"eab5a0axxxxxxx0c3","subscriber":"1"}}', true); echo $json['session']['key'];
{ "language": "en", "url": "https://stackoverflow.com/questions/7543593", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C#: Simplest way to dump a custom collection to csv file I have a class public class DevicePatchInfo { public string HostName { get; set; } public string PatchName { get; set; } public bool IsPresent { get; set; } } I have a List<DevicePatchInfo> which is loaded with the data and is bound to a datagrid. I want to press a button and serialize this to a csv file. The obvious way to do is to: * *Create a StreamWriter with the csv path in the constructor. *Read all property names of the DevicePatchInfo class via reflection and write that as the first line in the csv file. *Enumerate over the List with a foreach. *Read each item in the list and create a string.format with comma separating all item values. *stream.write the new string *Dispose streamwriter when all done. Huf ! Is there any simpler solution to this ? or I should've just typed the code instead of this. A: Use the open-source FileHelpers library, which does this for you. A: Your proposed solution is almost as close to the metal as you can get. I would suggest you hard-code the headers instead of using reflection, since the class you are writing, DevicePatchInfo, is well-defined.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543597", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery Get values of number fields depending on Button Click I have 20 fields that are created (numbered 1-20) with corresponding submit buttons. I need to retrieve the values of those fields for an AJAX post depending on which button number was clicked. For example: $(function(){ $("#addCommentButton1").click(function(event) { var trackid = $("#trackidField1").val(); var comment = $("#addcommentfield1").val(); $(function(){ $("#addCommentButton2").click(function(event) { var trackid = $("#trackidField2").val(); var comment = $("#addcommentfield2").val(); I'm hoping there is an easier way to do this than writing the function 20 times. Thanks! $(function(){ $(".addCommentsExpBtn").click(function(event) { var container = $(this).closest(".songPost"); container.find('.addCommentsExp').slideToggle(); }); }); A: you can do like this, <div> <input type="button" class="addCommentBtn" value="Add Comment"> <input type="text" class='trackId'> </div> <div> <input type="button" class="addCommentBtn" value="Add Comment"> <input type="text" class='trackId'> </div> and jquery, $(function(){ $(".addCommentBtn").click(function(event) { var parent=$(this).parent(); var trackid = $(".trackId",parent).val(); //others }); }); A: Give each of your elements a class name. You can then write $(function(){ $(".addCommentButton1").click(function(event) { var container = $(this).closest(".commentBoxContainer"); var trackid = container.find(".trackidField").val(); var comment = container.find(".addcommentfield").val();
{ "language": "en", "url": "https://stackoverflow.com/questions/7543598", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: multithread boost C++ program design for low-latency large-data exchange I am trying to solve a network flow problem by C++ multithreading. Given a network (all nodes are connected by arcs, each arc is connected to 2 and only 2 ending nodes, one is input node and another is output node, each node can have multiple input arcs and output arcs), each node needs to do some computing and then exchange computing result data to its connected input and output nodes. Multiple nodes can be grouped into one task, which is run by one thread. In this way, the whole network computing workload can be partitioned into multiple tasks. All these tasks are pushed into a boost thread pool such that all threads can run the tasks at the same time. But, if a node (in a thread task) needs to do data exchange with another node (in another thread task), there is a synchronization problem. Data receiver needs to wait for data available in the data buffer of the data sender. My proram needs to partition the network such that each thread's task workload is assigned as evenly as possible. If all threads share the one-large data buffer structure, the program parallelism is not good because the critical section is too large. Some threads have to wait the the one-large data buffer structure unlocked even though the part of the data structure (which is useful to them ) has been available for read or write. For example, the one-large data buffer structure has the following buffer cells: cell1 , cell2, cell3 , cell4. When thread 1 is trying to write cell 1, it must lock the whole data buffer structure so that thread 2 cannot read or write cell 2 and so on. So, I want to break the one-large data buffer structure into multiple distinct data cells according to the thread number so that each cell holds the data only needed by one thread task. For example, if we have 2 threads, we create 2 data cells that hold data needed by the 4 thread separately. If we have 4 threads, we create 4 data cells that hold data needed by the 4 thread separately. and so on. My questions are: (1) How to design the data cell ? You can see that its size is based on the number of threads. (2) How to reduce synchronization overhead ? The critical section is small but the overhead of geting and releasing mutex may be very high if the inter-node data exchange frequency is high. (3) When a node's computing is done and data is written to its cell how to notify the data receiver node such that the notification messgae is only received by the waiting thread that run the receiver node computing task. All other unrelated nodes and threads are not impacted. The program is very time-sensitive and the latency of message exchange should be controlled very toughly and reduced as much as possible. Any help is really appreciated. Thanks A: The usual way of dealing with this, I think, is to set up a message-passing infrastructure between threads. Each thread has a message queue. In your example, say node N1 is assigned to thread 1, node N2 is assigned to thread 2, and there is an edge between N1 and N2. Then, when thread 1 finishes the N1 calculation, it sends a message to thread 2: "Send input to node N2" To send a message to a thread, you just lock that thread's message queue and append your message. You use one mutex and two condition variables (queue_not_empty_condition and queue_not_full_condition) to implement a bounded queue. When a thread wants to wait for new work, it just goes to sleep on its message queue. To reduce the synchronization overhead, you might want a way to put multiple messages into a queue ("batch send") while locking the mutex just once. Then then loop within one thread would look something like this: if (I can do work without communicating with other threads) do that work else send all pending messages (in batches to each destination thread) wait on my input queue and pop the messages off in a batch "Batching" of messages might interact in complicated ways with bounded queues, though. No free lunch.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: exception in camera application in android I am getting an exception using a custom front camera. On button click I am calling camera.takepicture. Can anybody tell me what the problem is and how to fix it? 09-23 11:24:35.062: ERROR/AndroidRuntime(949): FATAL EXCEPTION: main 09-23 11:24:35.062: ERROR/AndroidRuntime(949): java.lang.RuntimeException: Method called after release() 09-23 11:24:35.062: ERROR/AndroidRuntime(949): at android.hardware.Camera.native_takePicture(Native Method) 09-23 11:24:35.062: ERROR/AndroidRuntime(949): at android.hardware.Camera.takePicture(Camera.java:746) 09-23 11:24:35.062: ERROR/AndroidRuntime(949): at com.camera.test.CameraActivity.onClick(CameraActivity.java:42) 09-23 11:24:35.062: ERROR/AndroidRuntime(949): at android.view.View.performClick(View.java:2485) 09-23 11:24:35.062: ERROR/AndroidRuntime(949): at android.view.View$PerformClick.run(View.java:9080) 09-23 11:24:35.062: ERROR/AndroidRuntime(949): at android.os.Handler.handleCallback(Handler.java:587) 09-23 11:24:35.062: ERROR/AndroidRuntime(949): at android.os.Handler.dispatchMessage(Handler.java:92) 09-23 11:24:35.062: ERROR/AndroidRuntime(949): at android.os.Looper.loop(Looper.java:123) 09-23 11:24:35.062: ERROR/AndroidRuntime(949): at android.app.ActivityThread.main(ActivityThread.java:3683) 09-23 11:24:35.062: ERROR/AndroidRuntime(949): at java.lang.reflect.Method.invokeNative(Native Method) 09-23 11:24:35.062: ERROR/AndroidRuntime(949): at java.lang.reflect.Method.invoke(Method.java:507) 09-23 11:24:35.062: ERROR/AndroidRuntime(949): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) 09-23 11:24:35.062: ERROR/AndroidRuntime(949): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 09-23 11:24:35.062: ERROR/AndroidRuntime(949): at dalvik.system.NativeStart.main(Native Method) 09-23 11:24:35.082: WARN/ActivityManager(107): Force finishing activity com.camera.test/.CameraActivity my xml <?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/main" android:layout_width="fill_parent" android:layout_height="fill_parent" android:configChanges="orientation"> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <Button android:layout_height="wrap_content" android:layout_width="match_parent" android:text="Button" android:id="@+id/button1"> </Button> <com.camera.test.Preview android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/preview" android:layout_marginTop="100px"/> </LinearLayout> </FrameLayout> my code import java.io.DataOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.NoSuchElementException; import android.app.Activity; import android.content.Context; import android.hardware.Camera; import android.os.Bundle; import android.os.Environment; import android.util.AttributeSet; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class CameraActivity extends Activity implements OnClickListener { Preview p=null; private Button button1=null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Hide the window title. requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); p=(Preview)findViewById(R.id.preview); button1 = (Button) findViewById(R.id.button1); button1.setOnClickListener(this); //p.setOnClickListener(this); } @Override public void onClick(View v) { p.mCamera.takePicture(shutterCallback, null, jpegCallback); /* p.mCamera.(new Camera.AutoFocusCallback() { Camera.ShutterCallback shutterCallback = new Camera.ShutterCallback() { public void onShutter() { // Play your sound here. } }; public void onAutoFocus(boolean success, Camera camera) { p.mCamera.takePicture(shutterCallback, null, jpegCallback); } });*/ } /*p.mCamera.startPreview(); p.mCamera.takePicture(shutterCallback, null, jpegCallback); */ // TODO Auto-generated method stub /*p.mCamera.autoFocus(new Camera.AutoFocusCallback() { Camera.ShutterCallback shutterCallback = new Camera.ShutterCallback() { public void onShutter() { // Play your sound here. } }; public void onAutoFocus(boolean success, Camera camera) { } }); */ Camera.ShutterCallback shutterCallback = new Camera.ShutterCallback() { // <6> public void onShutter() { //Log.d(TAG, "onShutter'd"); } }; //Handles data for raw picture Camera.PictureCallback rawCallback = new Camera.PictureCallback() { // <7> public void onPictureTaken(byte[] data, Camera camera) { // Log.d(TAG, "onPictureTaken - raw"); } }; // Handles data for jpeg picture Camera.PictureCallback jpegCallback = new Camera.PictureCallback() { // <8> public void onPictureTaken(byte[] data, Camera camera) { //YuvImage image = new YuvImage(data, parameters.getPreviewFormat(), size.width, size.height, null); //decodeYUV(argb8888, data, camSize.width, camSize.height); //Bitmap bitmap = Bitmap.createBitmap(argb8888, camSize.width, //camSize.height, Config.ARGB_8888); // p.mCamera.startPreview(); Toast.makeText(CameraActivity.this, "Writing a file", Toast.LENGTH_LONG).show(); File sdCard = Environment.getExternalStorageDirectory(); File dir = new File(sdCard.getAbsolutePath()+"/Vijay"); dir.mkdir(); Toast.makeText(CameraActivity.this, dir.getAbsolutePath(), Toast.LENGTH_LONG).show(); //dir.mkdirs(); //Toast.makeText(CameraActivity.this,"%d.jpg"System.currentTimeMillis()+"", Toast.LENGTH_LONG).show(); File out = new File(dir,String.format("%d.jpg", System.currentTimeMillis())); try { out.createNewFile(); Toast.makeText(CameraActivity.this, "created new file", Toast.LENGTH_LONG).show(); Toast.makeText(CameraActivity.this, out.getAbsolutePath(), Toast.LENGTH_LONG).show(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } DataOutputStream fo = null; try { fo = new DataOutputStream( new FileOutputStream(out)); //write what you want to fo fo.write(data); fo.close(); } catch (Exception e) { // TODO Auto-generated catch block Toast.makeText(CameraActivity.this, "entering exception",Toast.LENGTH_LONG).show(); PrintWriter pw; try { File sdCard1 = Environment.getExternalStorageDirectory(); File dir1 = new File(sdCard1.getAbsolutePath()+"/Log"); dir1.mkdir(); File out1 = new File(dir1,String.format("%d.txt", System.currentTimeMillis())); try { out1.createNewFile(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } pw = new PrintWriter(out1); e.printStackTrace(pw); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); // } // TODO: handle exception //e.printStackTrace(); } Toast.makeText(getBaseContext(), "Preview", Toast.LENGTH_SHORT).show(); //camera.release(); } }; } this is my preview package com.camera.test; import java.io.IOException; import java.util.NoSuchElementException; import android.content.Context; import android.hardware.Camera; import android.util.AttributeSet; import android.view.SurfaceHolder; import android.view.SurfaceView; class Preview extends SurfaceView implements SurfaceHolder.Callback { Camera mCamera; private final SurfaceHolder mHolder; final static int SUPPORTED_WIDTH = 640; final static int SUPPORTED_HEIGHT = 480; public Preview(Context context, AttributeSet attributes) { super(context, attributes); // Install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed. mHolder = getHolder(); mHolder.addCallback(this); mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } /** * Works in API level >= 10. * * @return Front camera handle. */ Camera getFrontFacingCamera() throws NoSuchElementException { final Camera.CameraInfo cameraInfo = new Camera.CameraInfo(); for (int cameraIndex = 0; cameraIndex < Camera.getNumberOfCameras(); cameraIndex++) { Camera.getCameraInfo(cameraIndex, cameraInfo); if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { try { return Camera.open(cameraIndex); } catch (final RuntimeException e) { e.printStackTrace(); } } } throw new NoSuchElementException("Can't find front camera."); } /** * Works in API level >= 7 at Samsung Galaxy S. * * @param Camera handle. */ void setFrontCamera(Camera camera) { final Camera.Parameters parameters = camera.getParameters(); parameters.set("camera-id", 2); try { camera.setParameters(parameters); } catch (final RuntimeException e) { // If we can't set front camera it means that device hasn't got "camera-id". Maybe it's not Galaxy S. e.printStackTrace(); } } /** * @see android.view.SurfaceHolder.Callback#surfaceChanged(android.view.SurfaceHolder, int, int, int) */ public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { // Now that the size is known, set up the camera parameters and begin the preview. final Camera.Parameters parameters = mCamera.getParameters(); parameters.setPreviewSize(SUPPORTED_WIDTH, SUPPORTED_HEIGHT); mCamera.setParameters(parameters); mCamera.startPreview(); } /** * The Surface has been created, acquire the camera and tell it where to draw. * * @see android.view.SurfaceHolder.Callback#surfaceCreated(android.view.SurfaceHolder) */ public void surfaceCreated(SurfaceHolder holder) { if (android.os.Build.VERSION.SDK_INT >= 10) { mCamera = getFrontFacingCamera(); mCamera.setDisplayOrientation(90); } else { mCamera = Camera.open(); setFrontCamera(mCamera); } try { mCamera.setPreviewDisplay(holder); } catch (final IOException e) { //mCamera.setPreviewCallback(null); mCamera.release(); mCamera = null; e.printStackTrace(); } } /** * @see android.view.SurfaceHolder.Callback#surfaceDestroyed(android.view.SurfaceHolder) */ public void surfaceDestroyed(SurfaceHolder holder) { // Surface will be destroyed when we return, so stop the preview. // Because the CameraDevice object is not a shared resource, it's very // important to release it when the activity is paused. mCamera.stopPreview(); //mCamera.setPreviewCallback(null); mCamera.release(); mCamera = null; } } Thanks A: Uncomment the line mCamera.setPreviewCallback(null); in public void surfaceDestroyed(SurfaceHolder holder) callback.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543614", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting values from dictionary I have a Dictionary<int, int> in my class. How can I access both values without knowing the key? For instance, I want to be able to do something like this: If the dictionary contains Dictionary<int, int> and the values are <5, 4> I want to be able to get the value of <(this),(this)> like Pseudo code: foreach(Dictionary item or row) { my first int = Dictionary<(this), (not this)> my second int = Dictionary<(not this), (this)> } How can I do this using a dictionary? If this is not doable: Is there another way? A: foreach (KeyValuePair<int, int> kvp in myDictionary) { var first = kvp.Key; var second = kvp.Value; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7543615", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CSS not modifying link properties Whatever I try to do, I can't modify the color of my links ( want to create a color rollover effect). They always stay the same default blue color with the underline effects. I know its something very minor that I did wrong, but can anyone tell me? <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <style type="text/css"> body, html { margin:0; padding:0; color:#101010; font-family: helvetica; } p { margin:10px 0 0 20px; font-size: 13px; line-height: 1.3em; padding-bottom: 10px; } #wrapper { width:960px; margin:0 auto; padding: 0px; background:#fff; } #header { padding:5px 10px; background:#fff; height:518px; } #nav { padding:5px 10px; background:#fff; width: 960px; height: 35px; position: absolute; top: 370px; font-size: 18px; color: #000; } #nav ul { margin:0; padding:0; list-style:none; position: absolute; bottom: 5px; } #nav li { display:inline; margin:0; padding:0; width:160px; float:left; #nav li:hover { background-color: #faffd8; border-color: #004f7b; } #nav a { color: #000; text-decoration: none; } #nav a:link { color: #333333; text-indent: -9999px; text-decoration: none; } #nav a:hover { color: #000000; text-decoration: none; } #nav a:visited{ color: #999999; text-decoration: none; } #nav a:active { color: #000000; text-decoration: none; } #topcontent p { color: #444444; } } #leftcontent { float:left; width:480px; height: 1%; background:#fff; } h2 { margin:10px 0 0 20px; color: #24389b; font-size: 19px; padding-bottom: 8px; } #rightcontent { float:right; width:480px; background:#fff; height: 1%; } #footer { clear:both; padding:5px 10px; background:#fff; } #footer p { margin:0; } * html #footer { height:1px; } </style> </head> <body> <div id="wrapper"> <div id="header"><img src="pold.png" alt="Pold Logo" /></div> <div id="nav"> <ul> <li><a href="Research">Research</a></li> <li><a href="Research">Publications</a></li> <li><a href="Research">Software</a></li> <li><a href="Research">People</a></li> <li><a href="Research">Volunteer</a></li> <li><a href="Research">Resources</a></li> </ul> </div> <div id="topcontent"> <p>The interests of our lab are generally centered around....</p> </div> <div id="leftcontent"> <h2>Funded Projects</h2> <p><a href="url">The Cognitive Atlas</a><br />(funded by NIMH )<br />The Cognitive Atlas project aims to develop an ontology for cognitive processes through social collaborative knowledge building.</p> </div> <div id="rightcontent"> <h2>Center Grants</h2> <p><a href="url">Consortium for Neuropsychiatric Phenomics</a><br />(funded by NIH)<br />This Roadmap Interdisciplinary Research Consortium is leveraging the new discipline of phonemics to understand neuropsychiatric disorders at multiple levels, from genes to neural systems to </p> </div> <div id="footer"> </div> </div> </body> </html> New Edit 09/27: All. I apologize for posting twice -- I'm brand new here and didn't think to continue on this thread. As indicated on my post (see Sparky672's link), I'm having problems with my columns and my navigation looking how I want it. Please see this link for a demo http://rich2233.host22.com/pold.html .. I guess you can grab the code from your browser. Thanks for your help A: **#nav li { display:inline; margin:0; padding:0; width:160px; float:left;** #nav li:hover { background-color: #faffd8; border-color: #004f7b; } #nav a { color: #000; text-decoration: none; } #nav a:link { color: #333333; text-indent: -9999px; text-decoration: none; } #nav a:hover { color: #000000; text-decoration: none; } #nav a:visited{ color: #999999; text-decoration: none; } #nav a:active { color: #000000; text-decoration: none; } **#topcontent p { color: #444444; } }** ** check starred CSS Styles there no closing for first CSS style also extra closing for last one A: You're missing a curly brace in this block: #nav li { display:inline; margin:0; padding:0; width:160px; float:left; A: Because your CSS only specifies the color of the links contained within the #nav <div>. All other links on page will be default color/style. EDIT: Not sure exactly which links you're talking about though. If you're talking about your navigation links, then see the others' answers pointing out the fact that you have a misplaced bracket } in your CSS. If you're talking about the other links on the page, see my original answer above. You have no CSS for those links. A: I think it has to do with the fact that you are not referencing your ul correctly, could be wrong though. Anyway take a look at this. <style> ul#navlist li{ list-style:none; } ul#navlist li a:link {text-decoration: none} ul#navlist li a:visited {text-decoration: none} ul#navlist li a:active {text-decoration: none} ul#navlist li a:hover { color: #cccccc; background-color: #003366; border: 1px #ffffff inset; } </style> <div id="navcontainer"> <ul id="navlist"> <li><a href="#">Item one</a></li> </ul> </div> I kind of mix and mashed from my reference and your example and I think this is what you are looking for. Oh and if you didn't know by this point, your braces are messed up. A: You missed some close-braces } that I fixed them by editing your question. Another Issue in your code is that should create css for A in this order: a {} a:link {} a:visited {} a:hover {} a:focus {} a:active {} to take effect. just change your A styles ordering and it'll work correctly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543616", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Is it faster to use XML or Serialize() saving data to a DB in PHP? I have a project that has a ridiculous amount of customization required. As such, I am looking for a way that will be the fastest (or near fastest) at runtime and also be rock solid stable to save a variable number of customized fields. For instance: The two locations save the same 2 data fields. At location #1, the two fields must be returned in number_format($num, 3) format while at location #2 those same two fields are text fields with no formatting required. I am trying to find the best (as defined above) way to save/retrieve the format of these fields. As of right now I am leaning towards saving in XML and serialize(), but during run-time, to optimize for speed, I would only be polling the serialize() data. This approach would alleviate my concerns about data corruption in the serialize() data as I can manually parse the data in the XML doc if necessary. NOTE: I am just concerned with the formatting/style/etc of how to manipulate the fields for viewing, NOT the actual storing of the data in those fields. I personally would rather not have to save this customization data as raw files on the server, since that is what a database is for and each location's customization data would be rather small (at most 40-50 fields). A: Serialized values are not that easy to read (and edit) by humans compared to XML. However tools exist to parse serialized data, like the Serialized PHP library. On the other hand, serialized values can be easily read back into variables, much easier than with XML. For XML You would need to create a "serializer" that is able to convert variables to XML and back. There is one in PEAR (XML_Serializer), another XML Serializer is available in Symfony2 as well. Normally it's wise to not create a database inside a dabase. If you need to, ensure you can easily change that later on w/o changing your application design too much.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543617", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Android GPS Fix & getFromLocation I have two issues, the first is that I have a String Builder that obtains an address and prints it to a edittext: Geocoder mGC = new Geocoder(context,Locale.getDefault()); address = mGC.getFromLocation(lat, lng, 1); if (address !=null){ Address currentAddr = address.get(0); mSB = new StringBuilder(); for (int i=0; i<currentAddr.getMaxAddressLineIndex(); i++){ mSB.append(currentAddr.getAddressLine(i)).append(", "); } outputText.setText(mSB.toString()); } The problem is randomly the address = mGC.getFromLocation(lat, lng, 1); line returns a null pointer exception. Sometimes it works for days...then suddenly it has a null pointer exception; anyone know why? Also my second issue is my GPS fix takes some time, I am using the GPS Satellite for it; is there a way I can use Network provided info first and then the GPS Satellite for a faster fix? A: About your second issue: You need to have two location listeners, one for network and the other one for GPS. Then you should use onLocationChanged on each listener to do your logic, in this case first use the network location, and once you get an update for the GPS one you use that one instead. A: For the first problem, it is possible that for the given, lat,lon there maybe no address. Also this Geocoder service needs internet to be active. GPS will always take time to get a fix. For a cold start it is about 20 minutes. For a warm start it can be 20 seconds to 1 minute. You see, it scans throughout the spectrum for signs of satellite visibility, and then calculates the doppler shift among other things. If you have internet on your phone it will shorten this time due to AGPS servers assisting your phone. The NetworkProvider is highly inaccurate. This is the best way of juggling them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543619", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: sum with join in active records Hi pleas bear with me I'm very new to mysql/active records (all previous projects have only been basic CRUD) I am trying to join two tables so I can generate a table of my invoices with a subtotal (database structure based on bamboo invoice) currently trying with no luck (syntax error) $this->db->select('invoice_number, dateIssued '); $this->db->select('(SELECT SUM(amount * qty) FROM manage_invoice_items DISTINCT invoice_id) AS subtotal' , FALSE); $this->db->from('manage_invoices'); $this->db->join('manage_invoice_items', 'manage_invoices.id = manage_invoice_items.invoice_id'); $this->db->where('client_id', $client_id); $query = $this->db->get(); return $query->result(); with $this->db->select('invoice_number, dateIssued'); $this->db->from('manage_invoices'); $this->db->join('manage_invoice_items', 'manage_invoices.id = manage_invoice_items.invoice_id'); $this->db->where('client_id', $client_id); $query = $this->db->get(); return $query->result(); I get results for each invoice item (I want one result per invoice with a subtotal of the invoice items for that invoice number) Hope that all makes send like I said I don't know much about mysql (even reference to a good tutorial on combining functions would be handy. A: I'm not personally familiar with CodeIgniter/ActiveRecord but it seems like what you want is to group the records using a GROUP BY function. I found this link that may be helpful. You probably want to use: $this->db->select_sum("amount * qty"); and $this->db->group_by("invoice_number"); A: $this->db->select('invoice_number, dateIssued'); $this->db->select('ROUND((SUM(amount * qty)), 2) AS subtotal', FALSE); $this->db->from('manage_invoices'); $this->db->join('manage_invoice_items', 'manage_invoices.id = manage_invoice_items.invoice_id'); $this->db->where('client_id', $client_id); $this->db->group_by('invoice_number'); $query = $this->db->get(); return $query->result(); thanks to Narthring (i didn't know about group_by)
{ "language": "en", "url": "https://stackoverflow.com/questions/7543622", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Does a template type waste space in C++? I was going through EASTL's list class to look at how the author has implemented the nodes. My expectation was a simplistic class/structure. Instead, I see a base and a node that is inheriting from this base (still simplistic, but why two classes?). His comments explain why: We define a ListNodeBase separately from ListNode (below), because it allows us to have non-templated operations such as insert, remove (below), and it makes it so that the list anchor node doesn't carry a T with it, which would waste space and possibly lead to surprising the user due to extra Ts existing that the user didn't explicitly create. The downside to all of this is that it makes debug viewing of a list harder, given that the node pointers are of type ListNodeBase and not ListNode. However, see ListNodeBaseProxy below. I don't understand a couple of things here. I do understand the part about why it will make debug viewing a bit harder, but what does he mean by list anchor node doesn't carry a T with it and would waste space and possibly lead to surprising the user due to extra Ts existing that the user didn't explicitly create? A: Without the helper class, the list root node would contain an instance of T that is never used. The second sentence is saying that you might not expect an empty list to create a T. For example, creating a T might have side effects. A: It seems to me that the idea is to separate the abstraction of the list, from the data it carries. You only need the ListNode when you actually want to access the data, all the rest can be done on the abstract ListNodeBase. That's how I understand the list anchor node doesn't carry a T with it. There's something there about space. Template classes are created per type, so if you have several different types used for T, without the ListNodeBase you would be creating templated copies of all the operations per type, with it - you don't, and the LinkNode inherits them, and only requires the memory for the actual data. Seems that the space saved refers to the actual size of the code in this case. A: You really want to support empty lists. If the head node itself always contains one T, and every list contains a head node, then it follows that every list contains at least one T, and therefore never can be empty.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543623", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: How to send automatic email via Gmail client from Android I searched a lot from internet for this thing. But everywhere very complex code. Can anybody provide me simple code to send an automatic email without user interaction from my device? may be very simple steps like * *Create an email client object. *Set To,From,subject and body. *Send the mail with Success or fail status. Is it possible? A: No, you can not send automatic emails without user interaction via Gmail or other in-built emails apps. If you could this would be an apparent security risk, wouldn't it? What you can do is send an Intent that invokes the in-built email app. The user then decides to send/cancel it. A: I found the code with JAR files and I am using it with that. Thanks for all your efforts.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543624", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Why does the keylistener stop working? In my Java program, whenever I select some text from a JTextField, the keyListener stops detecting key presses. I noticed the same thing happens when a JButton is pressed. Do I need to remove the keyListener from the objects after using them? If so, how to I do this? Here is a copy of the program I'm having problems with: import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ColourDropper extends JPanel implements KeyListener, ActionListener { private Color background = Color.WHITE; private int mouseX, mouseY; private Timer t; private JTextField rgb, hsb, hex, alp; private JLabel tRgb, tHsb, tHex, tHold, tAlp; private String hexString; private boolean hold = false; public ColourDropper() { this.setFocusable(true); t = new Timer(100, this); t.start(); rgb = new JTextField(7); hsb = new JTextField(9); hex = new JTextField(6); alp = new JTextField(3); tRgb = new JLabel("RGB"); tHsb = new JLabel("HSB"); tHex = new JLabel("Hex"); tAlp = new JLabel("Alpha"); rgb.setEditable(false); hsb.setEditable(false); hex.setEditable(false); alp.setEditable(false); add(tRgb); add(rgb); add(tHex); add(hex); add(tHsb); add(hsb); add(tAlp); add(alp); addKeyListener(this); } public void actionPerformed(ActionEvent e) { if(!hold) { mouseX = MouseInfo.getPointerInfo().getLocation().x; mouseY = MouseInfo.getPointerInfo().getLocation().y; try { Robot robot = new Robot(); background = robot.getPixelColor(mouseX, mouseY); hexString = "#" + Integer.toHexString(background.getRGB()).toUpperCase().substring(2); } catch(AWTException a) { System.out.println(a.getMessage()); } catch(Exception x) { System.out.println(x.getMessage()); } try { rgb.setText(background.getRed() + " " + background.getGreen() + " " + background.getBlue()); float[] cHsb = Color.RGBtoHSB(background.getRed(), background.getGreen(), background.getBlue(), null); int hue = (int)(cHsb[0] * 360); int sat = (int)(cHsb[1] * 100); int bri = (int)(cHsb[2] * 100); hsb.setText(hue + "� " + sat + "% " + bri + "%"); hex.setText(hexString); alp.setText("" + background.getAlpha()); } catch(NullPointerException n) { System.out.println(n.getMessage()); } repaint(); } } public void keyPressed(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_SPACE) hold = !hold; if(hold) { rgb.setForeground(Color.RED); hex.setForeground(Color.RED); hsb.setForeground(Color.RED); alp.setForeground(Color.RED); } else { rgb.setForeground(Color.BLACK); hex.setForeground(Color.BLACK); hsb.setForeground(Color.BLACK); alp.setForeground(Color.BLACK); } } public void paintComponent(Graphics g) { g.setColor(new Color(238, 238, 238)); g.fillRect(0, 0, 246, 120); g.setColor(background); g.fillRect(5, 57, 230, 30); } public void keyTyped(KeyEvent e) {} public void keyReleased(KeyEvent e) {} public static void main(String[] args) { JFrame frame = new JFrame("Colour Dropper"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setPreferredSize(new Dimension(246, 120)); frame.pack(); frame.setVisible(true); ColourDropper frameContent = new ColourDropper(); frame.add(frameContent); frame.setResizable(false); frame.setLocation(100, 100); frame.setAlwaysOnTop(true); frame.setIconImage(Toolkit.getDefaultToolkit().getImage("dropper.png")); } } A: For a KeyListener to work, the component that is being listened to must have the focus. As soon as the focus is directed elsewhere, the KeyListener fails. Often you're better off using key bindings instead. A: Howevercrafts advice to use Key Bindings is generally the best solution when listening for individual KeyStrokes. Key Bindings should be preferred over a KeyListener in this case as well. However, the main problem in this case is that you made the frame visible before adding the components to the frame. The setVisible(true) method should always be executed after all components have been added to the GUI. Adding components after making the frame visible caused a problem with the panel not getting focus. At least that is the problem using JDK6_7 on XP. In the future post code in the forum so we can see the code without downloading it. If I didn't take the time to download it we would just be making wild guesses. A: You just have to add these following lines: frame.setFocusable(true); in the void main and requestFocus(); at the end of void actionPerformed I hoped, that this will fix your problems ;)
{ "language": "en", "url": "https://stackoverflow.com/questions/7543628", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Good practice to free malloc's at program conclusion? I have a simple program which reads a bunch of ini file settings in memory allocated dynamically (malloc), then does stuff in loops for a long time, then ends. When I run valgrind I see that the memory I malloc'ed for my ini strings is not freed. On the one hand, I think that it shouldn't matter since the program is shutting down (and no memory is leaked in the loops). On the other hand, I like when valgrind gives me a big pat on the back for cleaning up my own mess. Aside from the pat on the back...is it good practice to release every malloc'ed space upon termination (or just let the OS cleanup)? If it is, how can I track which of my pointers point to malloc'ed memory (versus pointing to string constants which are the defaults) to ensure I'm releasing the right stuff? A: I would say the biggest advantage is this: Code always lives longer than you expect, so doing things right usually pays in the long run, even if it means "troubling yourself" today. Today, your program is simple. But tomorrow, somebody (who may be you) will want to re-use the code for reading and parsing that .ini file. And their program might well need to run for hours, days, or months. By designing your .ini parser to have a clean interface and to manage its memory properly, somebody (who may be you) will thank you someday. Plus you will probably find it makes your own code easier to write, read, and review today. (Oh yeah, also the valgrind thing.) Manual resource management is just part of the language. Every experienced C programmer I know designs it in to every program, even the trivial ones, as a matter of habit. If you want to stick with C, my advice is to learn the same habit. A: The main advantage to freeing mallocs at shutdown is to help valgrind track down your memory leaks - you can't find true memory leaks when you have pages full of false positives, after all. Apart from that, though, there's no harm in letting the OS clean up. As for keeping track of string constants vs heap allocated values, one simple policy would be to always use heap values - fill in the defaults with strdup()d strings at startup. A: The main advantage is to demonstrate that your code has no leaks, or anyway no leaks of a certain kind. As Nemo says, this makes it easier to reuse the code in future. Beware though that even if you demonstrably free everything at shutdown, that doesn't prove that your app doesn't have creeping memory usage and hence behaves for all practical purposes exactly as though it has leaks. For example, if your app has some kind of cache with no size limit, that might grow indefinitely during typical use of the app, but all get neatly freed by your shutdown code. That's as bad as a "genuine" leak. The main disadvantage applies to large apps: the process of churning through all your memory, perhaps pulling a few 10s or 100s of MB out of the page file and into RAM, can be quite slow. It will also slow down whatever other apps got pushed out of RAM to make space for your dying app. For this reason, if your app ever gets annoyingly slow at shutdown time you could consider doing all that stuff in debug builds only, and/or using a pool allocator so that you can drop big data structures consisting of many small nodes, without having to visit each node. In this particular case: unless your configuration has thousands of separate items, the parsed contents of your .ini file is probably a small structure of a few small allocations, so on its own it's unlikely to be slow, ever.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543630", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to display messagebox only one time in a loop I am New In C sharp, I am using messagebox to display the line. but it is in a loop so the messagebox display more times i want to display it only one time and message box should not be display for the next time. try{ using (var sr = File.OpenText("test.txt")){ string newone = 20110501;//date string line; while ((line = sr.ReadLine()) != null){ if (three => one){ MessageBox.Show("Buy : " + line); //Its Displaying more than 50 times i want to displayit only //onetime and should dispose for the next Time } } } } catch { } Thanks In Advance. A: use this: try { using (var sr = File.OpenText("test.txt")) { bool flag = true; string newone = 20110501;//date string line; while ((line = sr.ReadLine()) != null) { if (flag) { MessageBox.Show("Buy : " + line); //Its Displaying more than 50 times i want to displayit only //onetime and should dispose for the next Time } flag = false; } } } catch { } A: Simple have a boolean flag saying whether the message box has already been shown or not, and use it to guard that action. Update: bool shown = false; ... if( !shown ) { MessageBox.Show("Buy : " + line); shown = true; } A: You're trying to break; from the loop.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543633", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Reading text fields from file with custom separator I am working on a problem for a class I'm taking in which we need to read in text from a file to a 2d table of strings (called 'string table[][]'). The text file I'm reading in is formatted as follows: Ain el Beida # - # - # OEB # Algeria # Africa # F # 42578 # 61997 # 90560 # # Segbana # - # - # ALI # Benin # Africa # F # -1 # 10219 # -1 # # Skelmersdale # - # - # LAN # England # Europe # F # 42611 # 42104 # 39279 # # # As you can see, each field is separated by a '#', the end of a line is denoted by 2 #'s, and the end of the file with 3 #'s. I've been looking at a few different ways of isolating each field so that I can save it to the array, but so far have not found anything that works well for my purpose. I've been banging my head against this for a few hours now and I would really appreciate any advice on how to go about getting this to work. A: Consider using std::getline, since it allows you to specify a delimiter (in your case, the delimiter is #). std::ifstream file("somefile.txt"); std::string field1; std::getline(file, field1, '#'); // Ain el Beida Note though that each field is actually separated by a space and a #, so you will have leading / trailing whitespace in some cases. Since this is for a class, I'll let you figure out the rest!
{ "language": "en", "url": "https://stackoverflow.com/questions/7543637", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Socket Server for PHP Chat System? I was told that a simple PHP (with Ajax) chat system wont be able to support more than a hundred users before it's too much for the system unless I use a socket server. Is this true? And if so, where can I learn about creating a socket server or w/e?
{ "language": "en", "url": "https://stackoverflow.com/questions/7543639", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ruby, RVM version messup and not picking up right versions Here is my terminal output. Anand@luckydev:~ $ which ruby /usr/local/bin/ruby Anand@luckydev:~ $ rvm list rvm rubies jruby-1.6.2 [ darwin-x86_64-java ] ruby-1.8.7-p334 [ x86_64 ] => ruby-1.9.2-p180 [ x86_64 ] Anand@luckydev:~ $ ruby -v ruby 1.8.7 (2009-06-12 patchlevel 174) [i686-darwin10.3.2] This is the problem I have. I'm running MacOSX Lion. And when I run system ruby, it gives me this. Anand@luckydev:~ $ which ruby /usr/local/bin/ruby Anand@luckydev:~ $ ruby -e "puts 'hello'" hello But when I run using rvm ruby, Anand@luckydev:~ $ rvm use 1.9.2-p180 Using /Users/Anand/.rvm/gems/ruby-1.9.2-p180 dyld: Library not loaded: /Users/lakshman/.rvm/rubies/ruby-1.9.2-p180/lib/libruby.1.9.1.dylib Referenced from: /Users/Anand/.rvm/rubies/ruby-1.9.2-p180/bin/ruby Reason: image not found ruby-1.9.2-p180 Anand@luckydev:~ $ ruby -e "puts 'hello'" dyld: Library not loaded: /Users/lakshman/.rvm/rubies/ruby-1.9.2-p180/lib/libruby.1.9.1.dylib Referenced from: /Users/Anand/.rvm/rubies/ruby-1.9.2-p180/bin/ruby Reason: image not found Trace/BPT trap: 5 dyld: Library not loaded: /Users/lakshman/.rvm/rubies/ruby-1.9.2-p180/lib/libruby.1.9.1.dylib Referenced from: /Users/Anand/.rvm/rubies/ruby-1.9.2-p180/bin/ruby Reason: image not found My home directory used to be /Users/lakshman. I changed it to /Users/Anand. I updated ~/.rvmrc to reflect the new rvm_path also. Anand@luckydev:~ $ cat .rvmrc export rvm_path="/Users/Anand/.rvm" When I use system ruby, things are fine. But when I start using rvm, it throws me error that it cannot pickup that library file pointed by DYLD_LIBRARY_PATH (I assume from error message). How do i update it to take it from /Users/Anand. I tried setting it manually by exporting DYLD_LIBRARY_PATH to take the new path. But this didn't help. Also, I don't think this is gonna be manually set. rvm must be setting this automatically as I switch between different rubies. Please help..... A: I think you have to remove the .rvm folder and rebuild your rvm installation/rubies. The binary ruby is linked against an absolute path that is no longer existent. I'd just do that and take the opportunity to install ruby 1.9.2 290 which has some performance increases.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543645", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: git:// urls with gitolite I am running a gitolite system and I currently clone like this: git clone gitolite@debainserver.local:my-project and it works fine, but I want to clone into an application that needs (no work arounds, tried them all) a git:// address. so how can I set this up. To clarify a little more look at github's addresses yourself. git clone git://github.com/git/git.git how does this work, and how can I set it up? I want to be able to go git clone git://debainserver.local:my-project and have it clone. A: You will have to setup git daemon appropriately to do that: http://computercamp-cdwilson-us.tumblr.com/post/48589656281/git-gitolite-git-daemon-gitweb-setup-on-ubunt
{ "language": "en", "url": "https://stackoverflow.com/questions/7543651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to parse HTML to DOM in chrome extension I am building a Chrome Extension, that I will scan many pages of different domains in background and examine whether there are some text patterns in the pages. I can use regex to search the plain HTML text, but I prefer to parse the HTML text into DOM and then traverse the DOM. My question is, how can I get the DOM in a Chrome Extension ? Thanks! A: You can get it with jquery: var html = "<html>...</html>"; var el = $(html).find(".class");
{ "language": "en", "url": "https://stackoverflow.com/questions/7543656", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP mysql_num_rows WHERE this equals this Is it possible to do something like the WHERE clause in a mysql_num_rows statement in PHP? For example, say I have the column "number" in my database. I want to use mysql_num_rows($number) to display how many rows have the number 1. I know the other ways to do this, but it would be much much easier for what I'm doing to be able to use mysql_num_rows with a WHERE clause. A: SELECT COUNT(*) cnt FROM tablename WHERE rowname = 1 With this query you don't need mysql_num_rows which is overhead for cases when you don't need the data itself but the number of rows.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543657", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Weird "EXC_BAD_ACCESS" error I'm trying to make a simple binary-adding app. Here's the two main methods that I use. You can assume that anything I don't declare in the code has been declared in the header file: -(IBAction)valuesChanged { if ((![input1.text isEqualToString:@""]) && (![input2.text isEqualToString:@""])) { if (bitRange.selectedSegmentIndex == 0) {flowLimit = 8;} else if (bitRange.selectedSegmentIndex == 1) {flowLimit = 16;} else {flowLimit = 32;} NSMutableArray* bin1 = [[NSMutableArray alloc] initWithCapacity:32]; NSMutableArray* bin2 = [[NSMutableArray alloc] initWithCapacity:32]; NSMutableArray* resBin = [[NSMutableArray alloc] initWithCapacity:32]; input1Decimal = [input1.text intValue]; input2Decimal = [input2.text intValue]; int decimalDummy = input1Decimal; while (decimalDummy > 0) { if (decimalDummy == 1) { [bin1 addObject:[NSNumber numberWithInt:1]]; decimalDummy--; } else { [bin1 addObject:[NSNumber numberWithInt:(decimalDummy % 2)]]; decimalDummy = decimalDummy/2; } } decimalDummy = input2Decimal; while (decimalDummy > 0) { if (decimalDummy == 1) { [bin2 addObject:[NSNumber numberWithInt:1]]; decimalDummy--; } else { [bin2 addObject:[NSNumber numberWithInt:(decimalDummy % 2)]]; decimalDummy = decimalDummy/2; } } while ([bin1 count] < flowLimit) {[bin1 addObject:[NSNumber numberWithInt:0]];} while ([bin2 count] < flowLimit) {[bin2 addObject:[NSNumber numberWithInt:0]];} resBin = [self addBinary:bin1 toBinary:bin2]; NSString* string1 = @""; NSString* string2 = @""; NSString* string3 = @""; for (int i = 0; i < flowLimit; i++) { string1 = [[NSString stringWithFormat:@"%@",[bin1 objectAtIndex:i]] stringByAppendingString:string1]; string2 = [[NSString stringWithFormat:@"%@",[bin2 objectAtIndex:i]] stringByAppendingString:string2]; string3 = [[NSString stringWithFormat:@"%@",[resBin objectAtIndex:i]] stringByAppendingString:string3]; } [output1 setText:string1]; [output2 setText:string2]; [binResult setText:string3]; [bin1 release]; [bin2 release]; [resBin release]; } } -(NSMutableArray*)addBinary:(NSMutableArray*)binary1 toBinary:(NSMutableArray*)binary2 { BOOL carry = NO; NSMutableArray* result = [NSMutableArray arrayWithCapacity:32]; for (int i = 0; i < flowLimit; i++) { if (([[binary1 objectAtIndex:i] intValue] == 0) && ([[binary2 objectAtIndex:i] intValue] == 0)) { if (carry) { [result addObject:[NSNumber numberWithInt:1]]; } else {[result addObject:[NSNumber numberWithInt:0]];} } else if (([[binary1 objectAtIndex:i] intValue] == 1) && ([[binary2 objectAtIndex:i] intValue] == 0)) { if (carry) { [result addObject:[NSNumber numberWithInt:0]]; carry = YES; } else {[result addObject:[NSNumber numberWithInt:1]];} } else if (([[binary1 objectAtIndex:i] intValue] == 0) && ([[binary2 objectAtIndex:i] intValue] == 1)) { if (carry) { [result addObject:[NSNumber numberWithInt:0]]; carry = YES; } else {[result addObject:[NSNumber numberWithInt:1]];} } else { if (carry) { [result addObject:[NSNumber numberWithInt:1]]; carry = YES; } else { [result addObject:[NSNumber numberWithInt:0]]; carry = YES; } } carry = NO; } return result; } The code runs fine in the debugger, but somewhere after these methods are run, I get an "EXC_BAD_ACCESS" error. Anyone know why this is happening? A: Instead of removing all the [X release] messages, try changing this: NSMutableArray* bin1 = [[NSMutableArray alloc] initWithCapacity:32]; NSMutableArray* bin2 = [[NSMutableArray alloc] initWithCapacity:32]; NSMutableArray* resBin = [[NSMutableArray alloc] initWithCapacity:32]; To this: NSMutableArray* bin1 = [NSMutableArray array]; NSMutableArray* bin2 = [NSMutableArray array]; NSMutableArray* resBin = [NSMutableArray array]; Named initializers are autoreleased by default, but when you explicitely call alloc and initialize the return value of alloc, you must release it or it will leak. Another good debugging tip: Set NSZombieEnabled, malloc stack logging, and guard malloc in the debugger. Then, when your App crashes, type this in the gdb comsole: (gdb) info malloc-history 0x543216 Replace 0x543216 with the address of the object that the stack trace says caused the crash,and it will give you a much more useful stack trace and it should highlight the exact line that is causing the problem. Check out this article for more info on NSZombieEnabled. This one for MallocStackLogging info More info on guard malloc here After rereading the code, the only problem I can see is here: resBin = [self addBinary:bin1 toBinary:bin2]; [resBin release]; Your releasing something without increasing the retain count first and since it has already been autoreleased by the second method, you get the EXC_BAD_ACCESS. Either remove the [resBin release]; or do this: NSMutableArray *resBin = [[NSMutableArray alloc] initWithArray:[self addBinary:bin1 toBinary:bin2]]; Then you can safely call [resBin release];. A: Try removing all [something release] of those mutable arrays. Then see if that fixes the problem. If you know the cause you can come up with the solution. If that is your cause, check the code for any other usage of any data from those arrays. Update: you can also try to add the following code [something autorelease]; for each of those arrays. A: I think your problem is mos likely in the second method -(NSMutableArray*)addBinary:(NSMutableArray*)binary1 toBinary:(NSMutableArray*)binary2 You are creating the result array NSMutableArray* result = [NSMutableArray arrayWithCapacity:32]; Wich creates an autoreleased instance of a NSArray wich then you return and I assume you make use of it somewhere else in your code, but since its autoreleased when you try to access it is most likely to had already been released by the system. I would recommend that you retain the result when you call the method. For example binary1_plus_binary2 = [[binaryObject addBinary:binary1 toBinary:binary2] retain]; And when your done using binary1_plus_binary2 you release it. ================== EDIT resBin is being released but that variable is already released since its the result from addBinary method, don't release that one, only relese the other two, the ones you initiated with alloc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543658", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Unit Testing of actions If I need to Unit Test my actions, how do I do it? Do I need to use /test/bootsrap/ for that? A: Functional tests is what you need to write. They do exactly what you need: It calls your action with different parameters and test your response.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543663", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jquery get children of children of children Okay, this may be a bit basic. The HTML is : <div class="parents-of-all"> <p> <a> <span class="thechild">Something</span> </a> </p> The jquery is $('.parents-of-all').click(function(){ alert($(this).find('span').attr('class')); }); But somehow it doesn't work. Test it here : http://jsfiddle.net/3zn7e/1/ My question is how can I traverse to the span? My usual way is $(this).children().children().children().attr('class'); I'm sure there are shorter ways than this and using find() is one of them, but I can't seem to make it work. Many thanks! EDIT : DUH! Apparently I forgot the . for the parents-of-all DOM selector. Sometimes the simplest error is right there in your face. But again, is there any difference between using find() and multiple children() ? I find using multiple children() ensures more accurate traversing since we can add elements selector if we want, but any other major difference? A: You were missing the dot in your class selector: $('.parents-of-all').click(function(){ alert($(this).find('span').attr('class')); }); http://jsfiddle.net/BoltClock/3zn7e/2 A: If you are looking to change an attribute on the children-with-ancestor or children-with-parent, you should use the respective selector: * *decendant selector *child selector For example: $('.parents-of-all span').addClass('hello'); Would apply the class "hello" to all <span> elements that are descendants of an element of class parents-of-all.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543665", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Max width in css header So basically, my css and html works like this. I have a top and bottom to the header, as well as a userbox if the user is logged in. My html and css are formed like this: <div id=header> <div id=leftheader> <div id=topheader> [top header] </div> <div id=bottomheader> [bottom header] </div> </div> <div id=rightheader> [userbox] </div> In a sense, I want the userbox to appear to the right of the top and bottom nav menus when the user is logged in. However, if they're not logged in, I want to make the headers expand the full width of the screen. I have the PHP which does the back end. The previous was accomplished easy by doing width: 100px; on the top and bottom divs. However, when I log in, the userbox appears below the two nav menus. One way I thought to get around this is to make the widths not always 100%. Is there any way to do this to still have my userbox on the right? I tried using max-width, and I take it that it is not defined. For reference I have the top and bottom headers floated left and the right header floated right. Thanks A: This is possible with a <table> layout pretty easily. But since your question involves <div> elements and I presume you want a CSS solution, the following should work: <style type="text/css"> #header { display: table; width: 100%; } #leftheader, #rightheader { display: table-cell; } </style> <div id="header"> <div id="leftheader"> <div id="topheader">[top header]</div> <div id="bottomheader">[bottom header]</div> </div> <div id="rightheader"> [userbox] </div> </div> jsFiddle: http://jsfiddle.net/fausak/ju3su/ Here's a link to quirksmode.org talking about display: table: http://www.quirksmode.org/css/display.html#table display: table tells the element to display as a table. Nested elements should be displayed as table-row and table-cell, mimicking the good old TR's and TD's.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543670", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to convert pointer to c array to python array I have a C++ callback function that calls into Python using ctypes. This function's parameters are a pointer to an array of double and the number of elements. There are a lot of elements, approximately 2,000,000. I need to send this into scipy functions. The C++ prototype is : bool (*ptsetDataSource)(double*, long long); which is the following python code: CPF_setDataSource = CFUNCTYPE(c_bool, POINTER(c_double),c_longlong) CPF_setSelection= CFUNCTYPE(c_bool,c_char_p, c_longlong,c_longlong) CPF_ResetSequence = CFUNCTYPE(c_bool) def setDataSource(Data, DataLength): Datalist=[0.0]*100 for i in range(0,100): Datalist[i]=Data[i] print Datalist return True The problem is that print datalist returns: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] which is not correct(data is filled with a lot of other numbers when checked on the c++ side. Also, if I use this code to convert the data to a python list, it locks up the computer at the allocate step. Is there anyway to load the data from the C++ array and then convert it to an array fit for scipy? A: If Data were (c_double*DataLength.value) array then you could: a = np.frombuffer(Data) # no copy. Changes in `a` are reflected in `Data` If Data is a POINTER(c_double) you could get numpy array using numpy.fromiter(). It is the same loop as in your question but faster: a = np.fromiter(Data, dtype=np.float, count=DataLength.value) # copy To create a numpy array from POINTER(c_double) instance without copying you could use .from_address() method: ArrayType = ctypes.c_double*DataLength.value addr = ctypes.addressof(Data.contents) a = np.frombuffer(ArrayType.from_address(addr)) Or array_pointer = ctypes.cast(Data, ctypes.POINTER(ArrayType)) a = np.frombuffer(array_pointer.contents) Both methods convert POINTER(c_double) instance to (c_double*DataLength) before passing it to numpy.frombuffer(). Cython-based solution Is there anyway to load the data from the C++ array and then convert it to an array fit for scipy? Here's C extension module for Python (written in Cython) that provide as C API the conversion function: cimport numpy as np np.import_array() # initialize C API to call PyArray_SimpleNewFromData cdef public api tonumpyarray(double* data, long long size) with gil: if not (data and size >= 0): raise ValueError cdef np.npy_intp dims = size #NOTE: it doesn't take ownership of `data`. You must free `data` yourself return np.PyArray_SimpleNewFromData(1, &dims, np.NPY_DOUBLE, <void*>data) It could be used with ctypes as follows: from ctypes import (PYFUNCTYPE, py_object, POINTER, c_double, c_longlong, pydll, CFUNCTYPE, c_bool, cdll) import pointer2ndarray tonumpyarray = PYFUNCTYPE(py_object, POINTER(c_double), c_longlong)( ("tonumpyarray", pydll.LoadLibrary(pointer2ndarray.__file__))) @CFUNCTYPE(c_bool, POINTER(c_double), c_longlong) def callback(data, size): a = tonumpyarray(data, size) # call scipy functions on the `a` array here return True cpplib = cdll.LoadLibrary("call_callback.so") # your C++ lib goes here cpplib.call_callback(callback) Where call_callback is: void call_callback(bool (*)(double *, long long)).
{ "language": "en", "url": "https://stackoverflow.com/questions/7543675", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }