text
stringlengths
8
267k
meta
dict
Q: Subtraction of 2 negative integer (two's complement) never overflowing I came across this in a computer architecture textbook: Subtracting a strictly negative integer from another strictly negative integer (in two's complement) will never overflow. The textbook doesn't go on to explain this assertion. It piqued my curiosity. Why is this statement true? A: Here's how it works for 32 bit integers. It works the same for any other bit length. The largest negative number is -1. The smallest negative number is -2^31. Overflow occurs if a result is greater than or equal to 2^31, or smaller than -2^31. You get the largest result of a subtraction by subtracting the smallest number from the largest one. -1 - (-2^31) = 2^31 - 1. This is small enough. You get the smallest result of a subtraction by subtracting the largest number from the smallest one. -2^31 - (-1) = -(2^31 - 1). This is greater than -2^31. A: the range of numbers that can be obtained by such a substraction is [MIN_INT+1,MAX_INT], and thus will never overflow. why? let there be MIN_INT <= x,y < 0 so: MIN_INT = MIN_INT-0 < x-y < 0-MIN_INT = MAX_INT+1 And thus MIN_INT < x-y < MAX_INT + 1 note that 'strong' < prevent overflow. A: Since the range of negative signed integers is -1 to -(MAX_INT+1), the range of possible differences between two such numbers is -MAX_INT to MAX_INT. Since this range is easily representable (remember that the full signed integer range is -(MAX_INT+1) to MAX_INT), then evidently there can never be an overflow.
{ "language": "en", "url": "https://stackoverflow.com/questions/7546753", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Keymando 'Reload' Command I have never gotten this 'reload' command to work ... regardless of the mapping ... currently using ... map "<Ctrl-Cmd-r>" { reload } # not reloading either Could you provide another example? A: This is what I'm using, using a mnemonic with the growl plugin: def reload_configuration lambda{ growl("Configuration reloaded successfully") if reload} end map "<Cmd-y>" do input("rel" => reload_configuration) end
{ "language": "en", "url": "https://stackoverflow.com/questions/7546755", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: File decompression memory footprint I want to process audio offline on iOS, but have a query regarding memory usage. If I use AVAssetReader to decompress an MP3 to raw PCM data, the memory footprint would be huge. So how would I go about processing (offline FFT) an mp3 file if decompression would lead to the app using too much memory? I assume I have to stream it somehow, but I don't know how to do this in iOS. A: AVAssetReader can write to a file using AVAssetWriter. To get PCM, you can write a WAV file format, and then skip the RIFF header(s) on read. Then you only need to pull in as much data from the WAV file into memory at any one time as your FFT length requires. This should only cause a memory footprint problem if each FFT is well over 1 million samples long. You can use C/unix posix calls (fgetc, etc.) to read a file stream under iOS. Or read from an NSInputStream into NSData.
{ "language": "en", "url": "https://stackoverflow.com/questions/7546756", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Best practice when creating reusable corporate namespace Alright, this has been on my mind for a while now. I'm in the process of creating a reusable corporate namespace(class library) for all common middle-tier objects. This assembly can then be referenced by any of our developers during the development phase of their project. Here's my question. Is it more acceptable to create a single assembly which consists of all our middle-tier logic or to break this functionality up into smaller assemblies? Example: Single Assembly(namespace examples) System System.IO System.IO.RegEx System.Net System.Net.Mail System.Security System.Web - AssemblyFull.dll Example: Multiple Assemblies System.IO System.IO.Reg - Compiles to AssemblyIO.dll System.Net System.Net - Compiles to AssemblyNet.dll In the past I've done this using both methods but I'm wondering what everyone else does and why? I'm not looking for any code examples, I just want to know what other developers have doing? Thanks in advance. A: As a general rule, I use to separate assemblies if they are not explicit coupled. For example if you have a low level Networking API, and other API for FTP related operations, probably the later depends upon the former; but for the API user, your developers; there is no need to have both in a single assembly; maybe one project does not require the FTP API, so they only need to include the core "Net" assembly. You can separate APIs in order to be the more atomic as possible and avoid developers to include a big assembly when their will use only a small part of it. The down side of this approach is that if the developer needs the FTP assembly they also need to include the Net one; so you have to find a way to manage those dependencies that reduces the complexity for developers. I use Maven (from Apache) when doing Java applications but by this date I do not know a good maven-like alternative for .NET. But if your are building a few APIs for your company, with a Wiki site or other light weigh documentation tool you can address this problem. A: I dont think their is a right answer for this but I tend to use a common naming approach for all of our libraries. I have a library that handles a lot of the middle-tier functionality, sort of like common tasks that most apps would use. Web.CreditCard Web.CreditCard.Authorization Web.CreditCard.Charge Web.CreditCard.Batch Web.Store.Order Web.Store.Entities Web.Store.Cart Web.Store.Auth Web.User.Auth.OpenID Web.User.Auth.OAuth Web.User.Account Web.User.Preferences So it don't matter which type of project your building you can reuse them and identify them really quick. Some of them have their own interfaces and can be inherited and overloaded to add more functionality depending on the project requirements. A: Thanks to everyone who replied to this question. Since each project is different and it's nearly impossible to come up with a correct answer I'll describe how I'm going to approach this. First: I need to identify which business/middle-tier objects are going to be used in all projects moving forward. Once these have been identified I will create an assembly [company].common or [company].common.util. These will be referenced for each of our current and up-coming projects. Second: Identify the objects that are more project specific. These assemblies may or may not be referenced. An example would be [company].security.cryptography. Third: Make sure that each object is well documented so that future developers will have the knowledge needed to properly maintain and reference the correct assemblies. I wanted to thank everyone for getting back to me so quickly. This was my first post on SO but I can assure you that you'll see me here again very soon. Thanks again. A: I used a different approach for reusable files. I create a separate solution that includes all reusable components, test etc. Each reusable "thing" (class, function, UserControl, icon, etc) is in a separate file. The projects that need some functionality from the reusable part just link directly to the source file. ("Add existing item", "Add as link"). For convenience I place all reused parts in a "utilities" folder in VS (the real utilities folder is empty since the files are linked) This setup allows me to: * *just add the common functionality I need *no extra dependencies *Bug fixes in utilities are automatically included in next build The only drawback is that if you manually need to add any dependencies the added functionality got (e.g. another reusable component or an assembly) Since I don't use different assemblies, the namespace just follows the function: * *Company.Utilites *Company.Utilites.WPF *Company.Utilites.IO
{ "language": "en", "url": "https://stackoverflow.com/questions/7546757", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Trying to display output of Stored Procedure in console Hello I'm having trouble displaying the output of a SP in a console window using C#. Here is the SP code first then the C# after that. (SP code (Updated with SP code)) - GetDepartmentName stored procedure. IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetDepartmentName]') AND type in (N'P', N'PC')) BEGIN EXEC dbo.sp_executesql @statement = N' CREATE PROCEDURE [dbo].[GetDepartmentName] @ID int, @Name nvarchar(50) OUTPUT AS SELECT @Name = Name FROM Department WHERE DepartmentID = @ID ' END GO (c# code) public void RunStoredProcParams() { SqlConnection conn = null; SqlDataReader rdr = null; int ID = 1; //string Name = ""; Tried testing with this try { conn = new SqlConnection("Server=(local);DataBase=School;Integrated Security=SSPI"); conn.Open(); SqlCommand cmd = new SqlCommand("GetDepartmentName", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@ID", ID)); //cmd.Parameters.Add(new SqlParameter("@Name", Name)); Tried testing //with this. Don't get output when added, get error message when commented out. rdr = cmd.ExecuteReader(); while (rdr.Read()) { Console.WriteLine("Department: {0}", rdr["Name"]); } } finally { if (conn != null) { conn.Close(); } if (rdr != null) { rdr.Close(); } } } } //cmd.Parameters.Add(new SqlParameter("@Name", Name)); I added this line above because I keep getting error message ""Procedure or function 'GetDepartmentName' expects parameter '@Name', which was not supplied." Without an input, I get an error message even though this is suppose to output the results.. A: You have to add that parameter to the command like you did with id cmd.Parameters.Add(new SqlParameter("@Name"){Direction = Output}); After you execute the command, you can get the value from cmd.Parameters["@Name"] Ok try this then SqlConnection con = new SqlConnection("ConnectionString"); SqlCommand cmd = new SqlCommand("GetDepartmentName", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@ID", SqlDbType.Int) { Value = _ID }); cmd.Parameters.Add(new SqlParameter("@Name", SqlDbType.VarChar) { Size = 50, Direction = ParameterDirection.Output }); con.Open(); cmd.ExecuteNonQuery(); _Name = cmd.Parameters["@Nume"].Value.ToString();
{ "language": "en", "url": "https://stackoverflow.com/questions/7546762", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to download data asynchrnouslly Please see my code package com.morris.eventHandling; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.StringReader; import java.net.URI; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import android.app.Activity; import android.app.ProgressDialog; import android.os.Bundle; import android.util.Base64; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class EventHandling extends Activity implements OnClickListener { /** Called when the activity is first created. */ ProgressDialog dialog ; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button btn=(Button)findViewById(R.id.button1); btn.setOnClickListener(this); } @Override public void onClick(View v) { // TODO Auto-generated method stub try { executeHttpGet(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); Toast.makeText(this, e+"", Toast.LENGTH_LONG).show(); } } public void executeHttpGet() throws Exception { dialog = new ProgressDialog(this); dialog.setCancelable(true); // set a message text dialog.setMessage("Loading..."); // show it // dialog.show(); BufferedReader in = null; DefaultHttpClient client = new DefaultHttpClient(); String url= "http://newdev.xxxxxxx.com/morris/interface/mobile.php?method=dealerLogin&username=xxxx&password=xxxxx"; String login = "xxxxx"; String pass = "xxxxx"; HttpGet request = new HttpGet(); client.getCredentialsProvider().setCredentials(new AuthScope("newdev.objectified.com", 80), new UsernamePasswordCredentials(login, pass)); request.setURI(new URI(url)); HttpResponse response = client.execute(request); in = new BufferedReader (new InputStreamReader(response.getEntity().getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) { sb.append(line + NL); } in.close(); String page = sb.toString(); DataHandler handler=new DataHandler(); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); xr.setContentHandler(handler); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(page)); xr.parse(is); UserData d=handler.getData(); String data=d.sid+"\n"+d.dtitle+"\n"+d.dcountry+"\n"+d.dcity; Toast.makeText(this, data, Toast.LENGTH_LONG).show(); // dialog.dismiss(); } } As above data is coming synchronously but i want to asynchronously please help how can I do this. A: use AsyncTask to download data asynchronously. You can also see the following link for more info. http://developer.android.com/resources/articles/painless-threading.html The above link will give you different methods to achieve the something. A: Look at Painless Threading and AsyncTask
{ "language": "en", "url": "https://stackoverflow.com/questions/7546769", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Does using NoSQL make sense for a non-distributed system? (trying to understand eventual consistency) I have been reading and learning about NoSQL and MongoDB, CouchDB, etc, for the last two days, but I still can't tell if this is the right kind of storage for me. What worries me is the eventual consistency thing. Does that type of consistency only kick in when using clusters? (I'm hosting my sites in a single dedicated server, so I don't know if I can benefit from NoSQL) For which kind of applications is OK to have eventual consistency (instead of ACID), and for which ones it isn't? Can you give me some examples? What's the worst thing that can happen in an application for which is OK to have eventual consistency? Another thing that I read is that MongoDB keeps a lot of things in memory. In the docs it says something about 32-bit systems having a 2gb limit of data. Is that because of the ram limitation for 32-bit systems? A: I can speak only for CouchDB but there is no need to choose between eventual consistency and ACID, they are not in the same category. CouchDB is fully ACID. A document update is atomic, consistent, isolated and durable (using CouchDB's recommended production setting of delayed_commits=false, your update is flushed to disk before the 201 success code is returned). What CouchDB does not provide is multi-item transactions (since these are very hard to scale when the items are stored in separate servers). The confusion between 'transaction' and 'ACID' is regrettable but excusable given that typical RDBMS's usually support both. Eventual consistency is about how database replicas converge on the same data set. Consider a master-slave setup in a traditional RDBMS. Some configurations of that relationship will use a distributed transaction mechanism, such that both master and slave are always in lock-step. However, it is common to relax this for performance reasons. The master can make transactions locally and then forward them lazily to the slave via a transaction journal. This is also 'eventual consistency', the two servers will converge on the same data set when the journal is fully drained. CouchDB goes further and removes the distinction between master and slaves. That is, CouchDB servers can be treated as equal peers, with changes made at any host being correctly replicated to the others. The trick to eventual consistency is in how updates to the same item at different hosts are handled. In CouchDB, these separate updates are detected as 'conflicts' on the same item, and replication ensures that all of conflicting updates are present at all hosts. CouchDB then chooses one of these to present as the current revision. This choice can be revised by deleting the conflicts one doesn't want to keep. A: * *I have been reading and learning about NoSQL and MongoDB, CouchDB, etc, for the last two days, but I still can't tell if this is the right kind of storage for me. NoSQL databases solve a set of problems, that are hard(er) to solve with traditional RDMS. NoSQL can be the right storage for you if any of your problems are in that set. * *Does eventual consistency only kick in when using clusters? Eventual consistency "kicks in" when you might read back different/previous version of data from the one that was just persisted. For example: You persist the same piece of data into MORE THAN ONE location, let's say A and B. Depending on the configuration, a persist operation may return after only persisting to A ( and not to B just yet ). Right after that you read that data from B, which is not yet there. Eventually it will be there, but unfortunately not when you read it back * *For which kind of applications it is OK to have eventual consistency (instead of ACID), and for which ones it isn't? NOT OK => You have a family bank account which has a $100 available. Now you and your spouse try to buy something at the same time (at different stores) for $100. If the bank had this implemented with "eventual consistency" model, over more than one node for example, your spouse could have spent $100 a couple of milliseconds after you already spent all of it. Would not be exactly a good day for the bank. OK => You have 10000 followers on Twitter. You tweeted "Hey who wants to do some hacking tonight?". 100% consistency would mean that ALL those 10000 would receive your invitation at the same time. But nothing bad would really happen, if John saw your tweet 2 seconds after Mary did. * *What's the worst thing that can happen in an application for which is OK to have eventual consistency? A huge latency between e.g. when node A gets the data, and node B gets the same data [they are in sync]. If NoSQL solution is any solid, that would be the worse thing that can happen. * *Another thing that I read is that MongoDB keeps a lot of things in memory. In the docs it says something about 32-bit systems having a 2gb limit of data. Is that because of the ram limitation for 32-bit systems? from MongoDB docs: "MongoDB is a server process that runs on Linux, Windows and OS X. It can be run both as a 32 or 64-bit application. We recommend running in 64-bit mode, since Mongo is limited to a total data size of about 2GB for all databases in 32-bit mode." A: Brewers CAP theorem is the best source to understand what are the options which are availbale to you. I can say that it all depends but if we talk about Mongo then it provides with the horizontally scalability out of the box and it is always nice in some situations. Now about consistency. Actually you have three options of keeping your data up-to-date: 1)First thing to consider is "safe" mode or "getLastError()" as indicated by Andreas. If you issue a "safe" write, you know that the database has received the insert and applied the write. However, MongoDB only flushes to disk every 60 seconds, so the server can fail without the data on disk. 2) Second thing to consider is "journaling" (v1.8+). With journaling turned on, data is flushed to the journal every 100ms. So you have a smaller window of time before failure. The drivers have an "fsync" option (check that name) that goes one step further than "safe", it waits for acknowledgement that the data has be flushed to the disk (i.e. the journal file). However, this only covers one server. What happens if the hard drive on the server just dies? Well you need a second copy. 3)Third thing to consider is replication. The drivers support a "W" parameter that says "replicate this data to N nodes" before returning. If the write does not reach "N" nodes before a certain timeout, then the write fails (exception is thrown). However, you have to configure "W" correctly based on the number of nodes in your replica set. Again, because a hard drive could fail, even with journaling, you'll want to look at replication. Then there's replication across data centers which is too long to get into here. The last thing to consider is your requirement to "roll back". From my understanding, MongoDB does not have this "roll back" capacity. If you're doing a batch insert the best you'll get is an indication of which elements failed. Anyhow there are a lot of scenarios when data consistency becomes developer's responsibility and it is up to you to be careful and include all the scenarios and adjust the DB schema because there is no "This is the right way to do it" in Mongo like we are used to in RDB-s. About memory - this is totally a performance question, MongoDB keeps indexes and "working set" in RAM. By limiting your RAM your limit your working set. You can actually have an SSD and smaller amount of RAM rather than huge ammount of RAM and a HDD - at least these are official recommendations. Anyhow this question is individual, you should do the performance tests for your specific use cases
{ "language": "en", "url": "https://stackoverflow.com/questions/7546775", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Uncompress GZIP http-response (using jersey client api, java) Could someone tell me what I need to do in order to uncompress a GZIP content when getting the response from some Http-call. To make the call I use the Jersey Client API, see code below: String baseURI = "http://api.stackoverflow.com/1.1/answers/7539863?body=true&comments=false"; ClientConfig config = new DefaultClientConfig(); Client client = Client.create(config); WebResource wr = client.resource(baseURI); ClientResponse response = null; response = wr.get(ClientResponse.class); String response_data = response.getEntity(String.class); System.out.println(response_data); However the output is GZIP’d and looks like: {J?J??t??`$?@??????.... It would be good if I could implement the following: * *being able to detect whether content is GZIP’d or not; *If not, process like normal in a String; if, so uncompress and get the content in String A: Don't retrieve the response as an entity. Retrieve it as an input stream and wrap it in a java.util.zip.GZIPInputStream: GZipInputStream is = new GZipInputStream(response.getEntityInputStream()); Then read the uncompressed bytes yourself and turn it into a String. Also, check whether the server is including the HTTP header Content-Encoding: gzip. If not, try including it in the response. Perhaps Jersey is smart enough to do the right thing. A: Simply add GZIPContentEncodingFilter to your client: client.addFilter(new GZIPContentEncodingFilter(false)); A: In Jersey 2.x (I use 2.26): WebTarget target = ... target.register(GZipEncoder.class); Then getEntity(String.class) can be used on the response as usual.
{ "language": "en", "url": "https://stackoverflow.com/questions/7546783", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: DTMF Tones take a while to play I am working on a phone app. I have a dial pad grid view with buttons. I have a tone generator object created in onResume method. I also use a lock object. On click of any digit, i use the tone generator object to play a DTMF tone corresponding to the digit dialed using .startTone method. In onPause method, am releasing the tone generator object if its not null and setting it to null. Facing following issues: a) On the dial pad when i start clicking on buttons, first digit's tone is little low and it increases in volume for subsequent button clicks b) If i go to another activity and come back to dial pad, and if try dialing digits, no tone is played for first 3-4 digits and it starts working fine after 5th dial onwards. Need advice on solving this issue. Thanks,
{ "language": "en", "url": "https://stackoverflow.com/questions/7546785", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: R with CGI Web Interface - Most flexible option I have been exploring some options for implementing an R Web interface where users will have the option of selecting certain criteria, for eg., date ranges, plot type, etc. The issue is that a number of the R web interfaces that are listed in CRAN seem to have been last updated 5-6 yrs back ... and the most recent / up-to-date implementation seems to be RApache. From the site of Jeffrey Oons, a number of good examples of how to use RApache with JSON was available that looked quite impressive. However, as of this time, it seems that RApache only runs on Debian / Ubuntu / Mac. I wanted to ask if anyone is aware of other R web-based implementation that can produce nice looking webpages (eg., display a dataframe within a scrollable widget, display ggplot2 objects, etc). Also - does anyone have RApache running on Redhat / Solaris ? A: There is an entire section in the R FAQ devoted on web interfaces to R. Also consider the relatively new Rook package which utilizes the web server embedded in R itself since release 2.13.0 (which R uses for its help system).
{ "language": "en", "url": "https://stackoverflow.com/questions/7546786", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Standard approach to determine success or failure of fork/exec (while parent is running simultaneously)? I made a program using fork() and exec*(). The problem is I can't determine success or failure of exec() from parent process because it's on separated child process. I think kind of signaling can be used to check this state, but I have no idea about this. * *What's the recommended/standard/widely-used way to check this? *And what's the pitfalls that I have to care about while doing this? Question Detail Update (Sorry for omission of important detail) I want to keep both processes are running so I can't just wait exiting of child process. In other words, I want to be notified about the child process' exec success or failure. A: Your parent process can use the pid of the child process to detect that it is alive or has exited (and can disambiguate the error code, and died-because-of-signal errors, see waitpid). You can use certain error codes or signals to notify the parent about specific error cases (e.g., in the forked child before the exec), but for a completely generic child, you may not be able to reserve any exit codes or signals (since the parent won't be able to tell if the exec succeeded and then the child exited with those values). Another approach often used is to create a pipe fd pair (see the 'pipe' syscall), and pass one end to the child (generally the write end) and the other to the parent. The child can use this to send specific error codes to the parent. And the parent can detect premature termination if the pipe is closed without getting any data. There are some pitfalls: SIGPIPE will be sent to the parent if it reads on a pipe with no active writers, and using up an fd (other than stdin/stdout/stderr) in a child process may confuse some badly-written child processes (though close-on-exec can help fix that). In general, all the code I've seen to make fork+exec robust is pretty hacky.
{ "language": "en", "url": "https://stackoverflow.com/questions/7546792", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: inheritance problem in php i am learning php for a few weeks now and wanted to know what programming technique should one use while writing web applications such as a user management system.. i googled about it but still didnt get a clear view whether it should be strictly object oriented like java or may use procedural methods like functions without classes..?? also i had a problem: a class 'user' containing details of a logging-in user such as name , uid, etc and a class 'dbman' which has variables and methods to handle database jobs such as verifying username and password and logging in and out entries and other stuff..now a third class 'usermanager' is there which is supposed to inherit the above two classes so that users details may be used to drive dbman from within usermanager and data of user and dbman remains hidden and the code remains clean.. but i dont think a class can inherit two classes simultaneously in php.. so i made user and dbman static and created an objects of both in usermanager..is it a good method (i dont think so!!) what should i do?? thanx for any help in advance.. A: I would suggest looking into PHP Frameworks. Many of them tend to be OO and use a MVC Design Pattern. Just google MVC(Model View Controller) and look at a few of the frameworks out there... my personal favorite is Code Igniter (http://codeigniter.com/), but many other are out there like Cake PHP, Symphony, Zend and many more. A Framework allows you to reuse code allowing you to focus on the logic that will make your application do what its suppose to.
{ "language": "en", "url": "https://stackoverflow.com/questions/7546793", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: javascript prototype confusion Possible Duplicate: Javascript - this Vs. prototype This article says that prototype object can also help you quickly add a custom method to an object that is reflected on all instances of it. But this code (without using prototype object) also adds method for all instances: function al(){ this.show = function(){alert('hi!')} } var x = new al(); x.show(); var y = new al(); y.show(); What could be the advantage of prototype object here? Did i misread that article? A: The difference here is you're adding the method show to the instance of al not the prototype. Adding to the prototype effects all instances of al while adding to the instance only affects that instance. Here's a sample that adds show to the prototype vs. the instance function al() { } al.prototype.show = function () { alert("hi"); }; The key here is that now every instance of al will have access to the single instance of show which is attached to the prototype. Even more powerful is the ability to augment existing objects via the prototype var x = new al(); console.log(x.Prop); // x.Prop === undefined al.prototype.Prop = 42; console.log(x.Prop); // x.Prop === 42 A: The main issue is with memory usage. Your first code sample will create a new copy of the function 'show' for each instance of your class. If you use the prototype method, there's a single copy of the function shared between all the instances. The 'this' operator in the function is then used to get access to the instance being edited. This may not matter all that much for two or three instances, but if there may be many hundreds or thousands of instances, each of them having separate copies of of the function will make a huge difference to the performance of your app. A: yes the difference is that when you do it the way you did, every al instance has its own copy of the show method. If you put it on the prototype, all instances share a copy of the method, with the context (i.e. scope) getting applied for you when the method is invoked. Its much more efficient to put the method on the prototype. A: What it means is that if you wanted to add a member function or variable to al after it is defined--especially if al were defined by someone else. If you didn't know about prototyping, you might try the following: function al(){ this.show = function(){alert('hi!')} } al.newfunction = function(){alert('hello!')} var x = new al(); x.show(); // THIS WILL FAIL x.newfunction(); Instead, you would need to say: al.prototype.newfunction = function(){alert('hello!')} var x = new al(); x.show(); // THIS WILL SUCCEED x.newfunction(); A: The show method you have defined is decalred as part of the al object. prototype would allow you to exetend an existing class. There's an example below that would add a 'trim' function to the string object. Once you have added the function to your code the 'trim' function would be available to all instances of the string object String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); }; A: See this example. <script> function al(){ this.show = function(){alert('hi!')} } var x = new al(); x.show(); var y = new al(); y.show(); y.test = function (){alert('no prototype!')}; y.test(); //x.test(); // error al.prototype.test2 = function (){alert('prototype!')}; // edit al prototype y.test2(); // no error x.test2(); // no error </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7546796", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: heroku run console returns 'Error connecting to process' I have deployed a rails 3.1 app to Heroku Cedar stack, and am trying to perform a: heroku run rake db:migrate it returns: Running console attached to terminal... Error connecting to process I also try to simply launch the console: heroku run console Any run command returns the same error. Running console attached to terminal... Error connecting to process Looking at the logs I get the error code: 2011-09-25T16:04:52+00:00 app[run.2]: Error R13 (Attach error) -> Failed to attach to process When I heroku ps to see the current processes, I can see my attempts are running: Process State Command ------------ ------------------ ------------------------------ run.2 complete for 26m bundle exec rails console run.3 up for 27s bundle exec rails console run.4 up for 3s bundle exec rake db:create web.1 up for 46s bundle exec thin start -p $PORT -e.. But again each of them are raising exceptions: 2011-09-25T16:31:47+00:00 app[run.3]: Error R13 (Attach error) -> Failed to attach to process 2011-09-25T16:31:47+00:00 heroku[run.3]: Process exited 2011-09-25T16:31:48+00:00 heroku[run.3]: State changed from up to complete 2011-09-25T16:32:11+00:00 app[run.4]: Error R13 (Attach error) -> Failed to attach to process 2011-09-25T16:32:11+00:00 heroku[run.4]: Process exited 2011-09-25T16:32:12+00:00 heroku[run.4]: State changed from up to complete Server Admin isnt my cup of tea, hence the decision to use Heroku. Both Heroku docs and Googling have not led me down a path that give me much to go on. Any ideas? This has not been my experience on the Bamboo stack. My other errors are obviously related to DB migrations not being performed. Until I can run the rake tasks, I'm stuck moving forward. A: I had the same problem, and although I did not solve the problem, I found a workaround. Instead of using: heroku run rake db:migrate You can use: heroku run:detached rake db:migrate This runs the command in the background, writing the output to the log. When it is finished you can view the log for the result. Not ideal, but when you are on an inadequate network, it will get you out of a hole :) A: It seems this happens for different reasons. For me it turned out to be I had an older version of the Heroku Toolbelt installed. It was prior to the self-updating version and I also had old versions of the heroku gems installed. Those had to be removed before updating the heroku toolbelt had any effect. This page proved helpful. Read it first: https://devcenter.heroku.com/articles/heroku-command#staying-up-to-date Find out which heroku toolbelt version (if any) you are using like this: $ heroku version heroku-toolbelt/2.xx.x If it is older than version 2.32.0 then it needs to be updated. If you don't see 'heroku-toolbelt' in the response, then you need to install it. Make sure you uninstal any old heroku gems first. Running the command below asked me if I wanted to remove the executables as well. The correct answer is YES! You can always bundle/install later if you need the gem for specific apps. $ gem uninstall heroku --all If you are using rbenv, you may need to rehash: $ rbenv rehash Once you clean out the old gems, download the current heroku toolbelt and install it. Everything should work after restarting the terminal. EDIT: I had to make sure my rbenv path didn't get set in front of the heroku cli path. Otherwise any bundle/install of the old heroku gem would hijack the heroku command again. I added the export path line at the end of my ~/.profile file so it would be appended before any rbenv path. $ vi ~/.profile export PATH=/usr/local/heroku/bin:$PATH Reloading the terminal showed this worked by running and the path not being in /usr/local/heroku $ which heroku /usr/local/heroku/bin/heroku A: This problem is typically caused by a connectivity or firewall issue. You can test your connection to the heroku run and heroku console servers by running the following commands: $ telnet rendezvous.heroku.com 5000 $ telnet s1.runtime.heroku.com 5000 (If you are successfully able to connect, press Ctrl+] and then type quit to exit the telnet session.) Some users have success after whitelisting these hostname+port combinations in their firewall. Heroku mentions this in the troubleshooting section of one-off processes: http://devcenter.heroku.com/articles/oneoff-admin-ps An application which takes a long time to boot can also exasperate connectivity issues. If the server does not respond quickly enough, your local connection will timeout before the app can boot. A: Try installing the latest version of the heroku gem and then running these "heroku run" commands again. A: It looks like a problem with a Heroku - I'm getting errors connecting to the console on applications of mine running on Cedar. You're certainly not doing anything wrong with the commands you are typing. A: Solved - tested with 3G tether and received responses, doesn't appear to be the firewall; maybe proxy, or ISP. A: For me, upgrading my heroku toolbelt and cli worked. I use brew so it looks like this: brew upgrade heroku-toolbelt
{ "language": "en", "url": "https://stackoverflow.com/questions/7546803", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "30" }
Q: Multiple Audio Player can someone please tell me how I could program a small app with page turning effects (sound). I want I someone click on the Next button the sound plays for 1sec and takes me to the second page, and from the second page, if you click on the Back button, another sound plays for 1sec and takes you back to the original page. Somehow I'm having a problem, when I click on the back button the simulator crashes with a "autorelease" error message. Please find below .h and .m file . Thanks for taking the time to read. This is the .m file for the 1st page #import "_0_RabbanasViewController.h" #import "Rabbana2.h" #import "InfoPage.h" @implementation _0_RabbanasViewController - (IBAction)info { // This part takes us to the info page InfoPage *info = [[InfoPage alloc] initWithNibName:@"InfoPage" bundle:nil]; [UIView beginAnimations:@"flipView" context:Nil]; [UIView setAnimationDuration:2]; [UIView setAnimationCurve:UIViewAnimationOptionCurveEaseInOut]; [UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:self.view cache:YES]; [self.view addSubview:info.view]; [info release]; [UIView commitAnimations]; // This part plays the next page turn noise NSURL *this = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/next.wav", [[NSBundle mainBundle] resourcePath]]]; NSError *error; pagePlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:this error:&error]; [pagePlayer setDelegate:self]; pagePlayer.numberOfLoops = 0; [pagePlayer play]; //[pagePlayer release]; //This will stop the music when turning page [audioPlayer stop]; [audioPlayer release]; clicked = 0; [start setImage:[UIImage imageNamed:@"Pplay.png"] forState:UIControlStateNormal]; } - (IBAction)next { // This part takes us to the next view Rabbana2 *next = [[Rabbana2 alloc] initWithNibName:@"Rabbana2" bundle:nil]; [UIView beginAnimations:@"flipView" context:Nil]; [UIView setAnimationDuration:2]; [UIView setAnimationCurve:UIViewAnimationOptionCurveEaseInOut]; [UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:self.view cache:YES]; [self.view addSubview:next.view]; //[next release]; [UIView commitAnimations]; // This part plays the next page turn noise NSURL *this = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/next.wav", [[NSBundle mainBundle] resourcePath]]]; NSError *error; pagePlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:this error:&error]; [pagePlayer setDelegate:self]; pagePlayer.numberOfLoops = 0; [pagePlayer play]; //[pagePlayer release]; //This will stop the music when turning page [audioPlayer release]; clicked = 0; [start setImage:[UIImage imageNamed:@"Pplay.png"] forState:UIControlStateNormal]; } // This button plays the audio - (IBAction)play { if(clicked == 0){ clicked = 1; NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/rabbana1.wav", [[NSBundle mainBundle] resourcePath]]]; NSError *error; audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error]; [audioPlayer setDelegate:self]; audioPlayer.numberOfLoops = 0; [audioPlayer play]; [start setImage:[UIImage imageNamed:@"Sstop.png"] forState:UIControlStateNormal]; } else{ [audioPlayer stop]; [audioPlayer release]; clicked = 0; [start setImage:[UIImage imageNamed:@"Pplay.png"] forState:UIControlStateNormal]; } } //If user does not do anything by the end of the sound set the button to start - (void) audioPlayerDidFinishPlaying: (AVAudioPlayer *) player successfully: (BOOL) flag { if (flag==YES) { clicked = 0; [start setImage:[UIImage imageNamed:@"Pplay.png"] forState:UIControlStateNormal]; } } /* // If user click on the next button while audio playing, Audio should stop - (void) audioPlayerDidNotFinishPlaying: (AVAudioPlayer *) player success: (BOOL) flag { if (flag==YES) { [audioPlayer stop]; [audioPlayer release]; clicked = 0; [start setImage:[UIImage imageNamed:@"Pplay.png"] forState:UIControlStateNormal]; } } */ - (void)dealloc { [super dealloc]; //[self.pagePlayer.delegate = nil]; //self.AVAudioPlayer = nil ; } - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren't in use. } #pragma mark - View lifecycle // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { [super viewDidLoad]; [scroll setScrollEnabled:YES]; [scroll setContentSize:CGSizeMake(275,445)]; } - (void)viewDidUnload { [super viewDidUnload]; //[audioPlayer release]; //[pagePlayer release]; // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations return (interfaceOrientation == UIInterfaceOrientationPortrait); } @end This is the .m file for the 2nd page #import "InfoPage.h" #import "_0_RabbanasViewController.h" @implementation InfoPage - (IBAction)back { [UIView beginAnimations:@"flipView" context:Nil]; [UIView setAnimationDuration:1]; [UIView setAnimationCurve:UIViewAnimationOptionCurveEaseInOut]; [UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:self.view.superview cache:YES]; [self.view removeFromSuperview]; [UIView commitAnimations]; // This part plays the back page turn noise NSURL *this = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/back.wav", [[NSBundle mainBundle] resourcePath]]]; NSError *error; pagePlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:this error:&error]; [pagePlayer setDelegate:self]; pagePlayer.numberOfLoops = 0; [pagePlayer play]; //This will stop the music when turning page [pagePlayer release]; clicked = 0; } - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)dealloc { // [InfoPage dealloc]; [super dealloc]; } - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // [pagePlayer release]; self.view = nil; // Release any cached data, images, etc that aren't in use. } #pragma mark - View lifecycle - (void)viewDidLoad { [super viewDidLoad]; [scroll setScrollEnabled:YES]; [scroll setContentSize:CGSizeMake(320,480)]; // Do any additional setup after loading the view from its nib. } - (void)viewDidUnload { [super viewDidUnload]; // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations return (interfaceOrientation == UIInterfaceOrientationPortrait); } @end
{ "language": "en", "url": "https://stackoverflow.com/questions/7546812", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Django inherited template causing malformed html I'm using django 1.3 and Python 2.6. I'm running into a problem with inherited templates not being rendered correctly in a browser. I've tested with Win32 Chrome, Firefox and IE8. The output looks perfectly fine when I use curl, and it certainly is well-formed in my text editor, but when it's interpreted by the browser, this happens (see image). I'm pretty sure it has to do with the double unicode sequence at the top of the file, but I'm pulling my hair out trying to get rid of it! What could be causing this? base.html: <!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8" /> <title>site {% block title %}test_title{% endblock%}</title> </head> <body> <div id="header">{% block header %}test_header{% endblock %}</div> <div id="content">{% block content %}test_content{% endblock %}</div> <div id="footer">{% block footer %}test_footer{% endblock %}</div> </body> </html> hexdump -C base.html 00000000 ef bb bf 3c 21 44 4f 43 54 59 50 45 20 48 54 4d |...<!DOCTYPE HTM| http://localhost/base/ <!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8" /> <title>site test_title</title> </head> <body> <div id="header">test_header</div> <div id="content">test_content</div> <div id="footer">test_footer</div> </body> </html> home.html: {% extends "base.html" %} {% block title %}Title{% endblock %} {% block header %}Header{% endblock %} {% block content %}Content{% endblock %} {% block footer %}Footer{% endblock %} hexdump -C home.html 00000000 ef bb bf 7b 25 20 65 78 74 65 6e 64 73 20 22 62 |...{% extends "b| http://localhost/home/ (with curl) <!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8" /> <title>clog Title</title> </head> <body> <div id="header">Header</div> <div id="content">Content</div> <div id="footer">Footer</div> </body> </html> url.py: urlpatterns = patterns('', (r'^home/','site.views.web_home'), (r'^base/','site.views.web_base'), ) views.py: def web_home(request): return render_to_response('home.html') def web_base(request): return render_to_response('base.html') settings.py: (potentially relevant settings only) LANGUAGE_CODE = 'en-us' DEFAULT_CONTENT_TYPE = 'text/html' DEFAULT_CHARSET='utf-8' FILE_CHARSET='utf-8' USE_I18N = True USE_L10N = True TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', )
{ "language": "en", "url": "https://stackoverflow.com/questions/7546821", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Eclipse 3.7 cannot install any plugins I just installed eclipse 3.7 and cannot install any plugins. In the dropins folder, from the market place or the software install option. Find-bugs, sub-eclipse, google plug in etc..., none will install. I keep getting a message like this: Unable to read repository at http://subclipse.tigris.org/update_1.6.x/plugins/org.tigris.subversion.subclipse.ui_1.6.18.jar. I tried installing jboss tools and got this: Unable to read repository at http://download.jboss.org/jbosstools/updates/JBossTools-3.3.0.M3/plugins/org.jboss.tools.hibernate.ui_3.4.0.v20110915-1559-H24-M3.jar. If anybody knows how to fix this please let me know, I tried everything, unchecking the software updates in preferences. starting as an admin, re installing eclipse, nothing seems to work. A: The message that you are getting sounds like you are not adding the correct url to the update manager. Did you use this: http://subclipse.tigris.org/update_1.6.x/plugins/org.tigris.subversion.subclipse.ui_1.6.18.jar or this: http://subclipse.tigris.org/update_1.6.x/ as the url for subclipse? The latter is correct.
{ "language": "en", "url": "https://stackoverflow.com/questions/7546823", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to display an image in GAE datastore? I read the tutorial and all the sources I could find about displaying an image saved in datastore and still I could not make it work. I appreciate any help. This is my previous question. The code below, for /displayimage shows broken link for the image; and for /image it gives BadKeyError: Invalid string key . According to Nick Johnson reply here I must be passing an empty string for img_id but logging.info in /display image shows this key: (((result.key():)))) agpkZXZ-dGluZy0xcg8LEghIb21lUGFnZRjOCAw. Thanks for your help. class HomePage(db.Model): thumbnail = db.BlobProperty() firm_name = db.StringProperty() class ImageUpload(webapp.RequestHandler): def get(self): ... self.response.out.write(""" <form action="/imagesave" enctype="multipart/form-data" method="post"> <div><label>firm name:</label> <input type="text" name="firm_name" size=40></div> <div><input type="file" name="img" /></div> <div><input type="submit" value="Upload image"></div> </form> """) class ImageSave(webapp.RequestHandler): def post(self): homepage = HomePage() thumbnail = self.request.get("img") firm_name = self.request.get("firm_name") homepage.thumbnail = db.Blob(thumbnail) homepage.firm_name = firm_name homepage.put() self.redirect("/imageupload") class ImageResize(webapp.RequestHandler): def post(self): q = HomepageImage.all() q.filter("firm_name", "mta") qTable = q.get() if qTable: qTable.thumbnail = db.Blob(images.resize(self.request.get("img"), 32, 32)) db.put(qTable) else: self.response.out.write("""firm not found""") self.redirect("/imageupload") class DisplayImage(webapp.RequestHandler): def get(self): ... query = HomePage.all() query.filter("firm_name", "mta") result = query.get() self.response.out.write("""firm name: %s""" % result.firm_name) #self.response.out.write("""<img src="img?img_id=%s"></img>""" % #chenged this line as systempuntoout's comment to: self.response.out.write("""<img src="/image?img_id=%s"></img>""" % result.key()) #but I still get the same error class Image(webapp.RequestHandler): def get(self): ... #I am adding the next line to show that "img_id" is an empty string. #why "img_id" empty here? img_id = self.request.get("img_id") logging.info("""**************************img_id: %s**************************""" % img_id) #**************************img_id: ************************** homepage = db.get(self.request.get("img_id")) if homepage.thumbnail: self.response.headers['Content-Type'] = "image/jpg" self.response.out.write(homepage.thumbnail) else: self.response.out.write("no image") application = webapp.WSGIApplication( [ ("/imageresize",ImageResize), ("/imageupload", ImageUpload), ("/displayimage", DisplayImage), ("/imagesave", ImageSave), ("/image", Image), ], debug=True ) def main(): run_wsgi_app(application) if __name__ == "__main__": main() A: You are pointing the image source to a not defined wrong img route . The correct link should point to /image like this: <img src="/image?img_id=%s"></img> I've tested your code with my correction and it works nicely: from google.appengine.ext import db from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app import logging class HomePage(db.Model): thumbnail = db.BlobProperty() firm_name = db.StringProperty() class ImageUpload(webapp.RequestHandler): def get(self): self.response.out.write(""" <form action="/imagesave" enctype="multipart/form-data" method="post"> <div><label>firm name:</label> <input type="text" name="firm_name" size=40></div> <div><input type="file" name="img" /></div> <div><input type="submit" value="Upload image"></div> </form> """) class ImageSave(webapp.RequestHandler): def post(self): homepage = HomePage() thumbnail = self.request.get("img") firm_name = self.request.get("firm_name") homepage.thumbnail = db.Blob(thumbnail) homepage.firm_name = firm_name homepage.put() self.redirect("/imageupload") class ImageResize(webapp.RequestHandler): def post(self): q = HomepageImage.all() q.filter("firm_name", "mta") qTable = q.get() if qTable: qTable.thumbnail = db.Blob(images.resize(self.request.get("img"), 32, 32)) db.put(qTable) else: self.response.out.write("""firm not found""") self.redirect("/imageupload") class DisplayImage(webapp.RequestHandler): def get(self): query = HomePage.all() query.filter("firm_name", "mta") result = query.get() self.response.out.write("""firm name: %s""" % result.firm_name) self.response.out.write("""<img src="/image?img_id=%s"></img>""" % result.key()) class Image(webapp.RequestHandler): def get(self): img_id = self.request.get("img_id") logging.info("""**************************img_id: %s**************************""" % img_id) homepage = db.get(self.request.get("img_id")) if homepage.thumbnail: self.response.headers['Content-Type'] = "image/jpg" self.response.out.write(homepage.thumbnail) else: self.response.out.write("no image") application = webapp.WSGIApplication( [ ("/imageresize",ImageResize), ("/imageupload", ImageUpload), ("/displayimage", DisplayImage), ("/imagesave", ImageSave), ("/image", Image), ], debug=True ) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
{ "language": "en", "url": "https://stackoverflow.com/questions/7546825", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Sharing Registry Space across Multiple Clusters in WSO2 By using this guide, I have accomplished to establish a cluster of Carbon products, and change configuration of individual nodes by changing deployment in _system/xxxConfig which is under resources in G-Reg(Governance Registry). On the other hand, I want to take this case one step further, I need a central G-Reg which shares registry space across other G-Regs (This G-Reg share its registry with the individual Carbon products). Consider such as an deployment: Suppose we have 5 clusters: 1-Cluster of DSSs with a G-Reg (Sharing Registry) 2-Cluster of DSSs with a G-Reg (Sharing Registry) 3-Cluster of ESBs with a G-Reg (Sharing Registry) 4-Cluster of ESBs with a G-Reg (Sharing Registry) 5-Cluster of ASs with a G-Reg (Sharing Registry) What I want to achieve is to connect all G-Regs above to a central G-Reg, and control all configuration from there. Is such a deployment possible with Carbon products, if yes, how can I accomplish this? A: Yes.. this type of a deployment is possible with GReg.. As you may know already - GReg has a separation of registries.. * *Local registry : Holds the resources specific to a given node *Config registry : Holds the resources related to all the nodes in a given cluster *Governance registry : Holds the resources shared across multiple clusters.. In your deployment you can have 5 config registries for 5 different clusters, mounted on the same central Registry - and have a single Governance registry for shared resources between clusters... A: You can refer [1] to have a clear understanding about this scenario [1] http://wso2.com/library/tutorials/2010/04/sharing-registry-space-across-multiple-product-instances/
{ "language": "en", "url": "https://stackoverflow.com/questions/7546826", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why doesn't child process continue running after receiving signal? The following is my code. Parent forks a child. Child pause until parent sends a signal to it, then it continues running. My question is why doesn't child process continue running after parent sending signal to him. Did I miss or misunderstand something? #include<stdio.h> #include<unistd.h> #include<signal.h> void sigusr1( int pidno ) { printf("Catched\n"); } int main() { pid_t pid; signal( SIGUSR1, sigusr1 ); if( (pid = fork()) == 0 ){ pause(); printf("Child\n"); } kill( pid , SIGUSR1 ); //parent sends signal to child pause(); } A: Here's what happens in the parent: * *Fork a child. *Send SIGUSR1 to the child. *Wait for a signal. Here's what happens in the child: * *Wait for a signal. *Print Child. *Call kill(0, SIGUSR1) (0 being the value of pid in the child). Calling kill with a process ID of 0 sends the signal to every process in the process group of the process that calls kill. *Wait for a signal. There are several possible behaviors for your program, depending on the order in which the parent and the child system calls are executed. Depending on the exact version of your operating system, on the fine-tuning of various kernel parameters, on how loaded your system is, and on random chance, you may or may not observe different behavior if you run the program several times or under a debugger. If the parent starts faster than the child, you may see this: * *Parent sends SIGUSR1 to the child. *Child receives SIGUSR1 and prints Catched. *Child calls pause. *Parent calls pause. With this execution order, both the parent and the child end up waiting forever (it's a deadlock). If the child starts faster than the parent, you may see this: * *Child calls pause. *Parent sends SIGUSR1 to the child. *Parent calls pause. *Child is unblocked and prints Catched. *Child prints Child. *Child sends SIGUSR1 to the process group. *Child prints Catched. *Child calls pause. *Parent is unblocked and prints Catched. *Parent exits. I don't think there's a way for the child to exit: it calls pause twice, and while it can receive up to two signals, one of these is sent from itself (the one from kill(0,SIGUSR1)) and that one is delivered synchronously, not during the execution of pause. This program is probably not what you meant to write, but since you don't describe the expected behavior, it's impossible to tell what you did mean to write. I do note that you do not follow the usual structure of a program that forks: pid = fork(); if (pid < 0) { /*error handling*/ } else if (pid == 0) { /*child code*/ exit(...); /*Usually, what follows the if is specific to the parent.*/ } A: Try this: #include<stdio.h> #include<unistd.h> #include<signal.h> void sigusr1( int pidno ) { fprintf(stderr, "Caught\n"); } int main() { pid_t pid; signal( SIGINT, sigusr1 ); if( (pid = fork()) == 0 ){ pause(); fprintf(stderr, "Child\n"); } else { fprintf(stderr, "Parent\n"); kill( pid , SIGINT ); //parent sends signal to child } pause(); return 0; } * *printf buffers input: perhaps it's being called, but it isn't being displayed when you expect. One workaround is fflush(). A better workaround is fprintf (stderr), which doesn't buffer in the first place. *You're calling kill() in both the parent and the child. I added an else to eliminate this. *Here's sample output: gcc -Wall -g -o z z.c ./z Parent Caught Child
{ "language": "en", "url": "https://stackoverflow.com/questions/7546828", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Help with jQuery Multiple File Upload Plugin please I am having some trouble with a jQuery plugin for multiple uploads. I am using this plug in http://www.fyneworks.com/jquery/multiple-file-upload I have followed all his instructions and got it to work locally however for some reason it does not show the multiple attachments remotely. Is there something I may have missed? This is my code: <input type="file" name="myfiles[]" class="multi" /> And I have his jQuery .js sheets attached. Any help would be appreciated. A: use http://swfupload.org/, but it's not jQuery plugin.
{ "language": "en", "url": "https://stackoverflow.com/questions/7546833", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What are the benefits of Interface in PHP5? As you know, we can use Interface and Implements in PHP5. I used Interface in Java SE but It's useful there only for listener or ... but I can't find any benefit of Interface in PHP5. Please help me understand benefits of Interface in PHP5. Thanks for your advice. A: In an object oriented language you can't deny the benefits of Interface, there are hundreds of benefits. Let me give you an example for Dummies: I assume you use MVC and Ajax. And during every focusout of input you pass the input value to the server as well as a model name which is stored in the data-model (custom) attribute. <input name="myfield" value="myvalue" data-model="user_model" onblur="send ajax request .." /> Now when you lost focus from the input it sends data to server like this {"a_model":"user_model","a_name":"myfield","a_value":"myvalue"} In the server you just call the model name which is received from ajax request. Something like this $this->{$a_model}->update($a_field,$a_value); Here the value of $a_model varies, so you can't make sure that this model would have update() method. Here interface comes into play. Interface forces all the implemented models(classes) to have an update() method so that you can run above code unconditionally. Hope this makes sense. A: One example. I work with a remote team, they build a system that I need it to interface with mine. I can write a complex document or just send them an interface file and tell them they must implement that interfac(es) in what they develop. b.t.w use of interfaces is language agnostic, mostly. The concepts are the same throughout.
{ "language": "en", "url": "https://stackoverflow.com/questions/7546835", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Refresh draggable/droppable I have draggable/dropable tree where user can add new elements. After user click add button new element adds to tree. How can i refresh tree, draggable and dropabble works on new added element : $("li.tree_item a").droppable({ tolerance : "pointer", hoverClass : "tree_hover", drop : function(event, ui){ var dropped = ui.draggable; dropped.css({top: 0, left: 0}); var me = $(this).parent(); if(me == dropped) return; var subbranch = $(me).children("ul"); if(subbranch.size() == 0) { me.find("a").after("<ul></ul>"); subbranch = me.find("ul"); } var oldParent = dropped.parent(); subbranch.eq(0).append(dropped); var oldBranches = $("li", oldParent); if (oldBranches.size() == 0) { $(oldParent).remove(); } var data = Object(); data.tree = Array(); data.tree = parseTree($("#tag_tree")); $.getJSON( urlJson, data, function(resp) { }); } }); $("li.tree_item").draggable({ opacity: 0.5, revert: true, }); and button which add ne to element to this tree $('#add').bind('click', function() { }); How can I refresh draggable droppable after add new element ?
{ "language": "en", "url": "https://stackoverflow.com/questions/7546837", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ant Fileset to Comma Separated List I'm trying to pass a fileset to a macrodef, and have the macro generate a comma separated list of the classes. More over, I also need to change the list to contain java package & class names instead of "/" delimmited names. We're using Ant, OSGi, and bnd and what I'm ultimately trying to do is create an entry in the Manifest that contains the fully qualified class name of each entry of the fileset. End Goal example: Manifest-Entry: org.foo.bar.ClassOne, org.foo.bar.ClassTo A: You could do this using the Ant pathconvert task with a nested mapper, for example: <property name="classes" location="classes" /> <fileset dir="${classes}" id="classes" /> <pathconvert dirsep="." refid="classes" property="manifest.entry" pathsep=", "> <mapper type="regexp" from="${classes}/(.*).class" to="\1" /> </pathconvert> <echo message="Manifest-Entry: ${manifest.entry}" /> A: Since you are using bnd, you could also try using the ${classes} macro in the bnd file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7546840", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Add UIView to Application at runtime I should add a UIView to an application, I use: UIWindow *window = [[UIApplication sharedApplication] keyWindow]; [window addSubview:view]; But it only work on SpringBoard. Have anyone an idea? A: There is nothing wrong with your code and it will work. If it doesn't, view might be nil or the view's frame might not be set correctly. Normally, you would use a view controller and, rather than adding views directly to the window, you would add them to the view controller's view.
{ "language": "en", "url": "https://stackoverflow.com/questions/7546842", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CakePHP - How do I link these models together (that requires use of a relation table)? I'm currently using CakePHP 2.0-RC1. Being pretty nifty and all, I've only come across one challenge that I can't wrap my mind around. I've read the documentation on linking models together (http://www.cakedocs.com/models/associations-linking-models-together.html), but how to I tell CakePHP to search trough a relation table and find the values I'm after? Let me explain. I have a database structure similar to the following (it has been simplified for the question. PK = Primary Key. FK = Foreign Key ) game - INT(11) id (PK) - VARCHAR(100) name - VARCHAR(40) year - VARCHAR(10) age category - INT(11) id (PK) - VARCHAR(50) name game_category - INT(11) game_id (FK) - INT(11) category_id (FK) Explanation to the relationship between these: A game can have one or more category. This relation is defined in "game_category" table. I want CakePHP to not only find what category id a game has, I want the category name as well when I do $this->Game->find('first') for instance. I would guess CakePHP needs to be told to "continue through the game_category table and onto the category table" and find what the name of each category actually is. I have these Models Game.php <?php class Game extends AppModel { var $useTable = 'game'; var $hasMany = array( 'GameCategory' => array( 'fields' => '*', 'className' => 'GameCategory', ) ); var $hasOne = 'Review'; } ?> GameCategory.php <?php class GameCategory extends AppModel { var $useTable = 'game_category'; var $belongsTo = 'category'; var $hasMany = array( 'Category' => array( 'fields' => '*', 'foreignKey' => 'category_id', 'className' => 'Category', 'conditions' => array('GameCategory.game_id' => 'Game.id', 'GameCategory.category_id' => 'Category.id'), ) ); } ?> Category.php <?php class Category extends AppModel { var $useTable = 'category'; var $belongsTo = 'GameCategory'; } ?> By the relations defined above, I get results like this: Array ( [Game] => Array ( [id] => 2 [name] => Colonization [year] => 1995 [age] => 7 ) [GameCategory] => Array ( [0] => Array ( [game_id] => 2 [category_id] => 19 ) [1] => Array ( [game_id] => 2 [category_id] => 16 ) ) ) The only thing remaining is just getting the actual name of each category. I hope some of this made any sense. Any help is appreciated. A: You should see hasAndBelongsToMany (HABTM) in book online and should change table name game_category to games_categories for correct conventions. Game.php <?php class Game extends AppModel { var $name = 'Game'; var $hasAndBelongsToMany = array( 'Category' => array( 'className' => 'Category', 'joinTable' => 'game_category', 'foreignKey' => 'game_id', 'associationForeignKey' => 'category_id', ) ); } ?> A: all table names must in plural ( games, categories ) wrong category association, must hasAndBelongsToMany use cake console ( ./cake bake ) to prevent future errors like this <?php class Category extends AppModel { var $name = 'Category'; var $displayField = 'name'; //The Associations below have been created with all possible keys, those that are not needed can be removed var $hasAndBelongsToMany = array( 'Game' => array( 'className' => 'Game', 'joinTable' => 'game_categories', 'foreignKey' => 'category_id', 'associationForeignKey' => 'game_id', 'unique' => true, 'conditions' => '', 'fields' => '', 'order' => '', 'limit' => '', 'offset' => '', 'finderQuery' => '', 'deleteQuery' => '', 'insertQuery' => '' ) ); } <?php class Game extends AppModel { var $name = 'Game'; var $displayField = 'name'; //The Associations below have been created with all possible keys, those that are not needed can be removed var $hasMany = array( 'GameCategory' => array( 'className' => 'GameCategory', 'foreignKey' => 'game_id', 'dependent' => false, 'conditions' => '', 'fields' => '', 'order' => '', 'limit' => '', 'offset' => '', 'exclusive' => '', 'finderQuery' => '', 'counterQuery' => '' ) ); } #games $games = $this->Game->Category->find('all');
{ "language": "en", "url": "https://stackoverflow.com/questions/7546845", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do you find out if a user has installed my app? I need to work out if a user has my app installed so I can display a slighlty different page. How do you do this? A: Ideally you'd want to capture their Facebook user ID in your own database when they originally install your app. When they come back, you can compare the current users Facebook user ID with your database to see if you find any matches. If you don't have a database, you can always check on a user permissions using the Graph API. You can find the code here: http://developers.facebook.com/blog/post/495 This will give you back an array that looks something like this: Array ( [data] => Array ( [0] => Array ( [installed] => 1 [bookmarked] => 1 ) ) ) In this case, the user has it installed and has bookmarked it. Now that you know that, you can display a slightly different page. A: You do this by using the FB JavaScript API and querying if the user is logged in. If it is (to you) it will have your app installed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7546847", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: MongoDb how to find previous and next item in a list suppose I have a collection with a following structure { '_id': 'some id', 'items': [item1, item2, ..., itemN] } .... can you help me, how I can find previous and next item if I know 'some id' and itemK Of course I can just return all items and later parse them on server side. But I think that there should be some solution A: You can selectively return individual fields but I can't see how you could return individual elements from an array in a field, and certainly not using a query based on relative positions within that array. Is the items field so large that you need to return less than the whole field?
{ "language": "en", "url": "https://stackoverflow.com/questions/7546848", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: httpclient redirect for newbies Possible Duplicate: Httpclient 4, error 302. How to redirect? I want to retrieve some information from my comcast account. Using examples on this site, I think I got pretty close. I am using firebug to see what to post, and I see that when I login I am being redirected. I don't understand how to follow the redirects. I have played with countless examples but just can't figure it out. I am new to programming and just not having any luck doing this. Here is my code. I make an initial login, then go to try to go to another URL which is where the redirects begin. Along the way, I see that I am acquiring lots of cookies, but not the important one s_lst. HttpPost httpPost = new HttpPost("https://login.comcast.net/login"); List <NameValuePair> nvps = new ArrayList <NameValuePair>(); nvps.add(new BasicNameValuePair("continue", "https://login.comcast.net/account")); nvps.add(new BasicNameValuePair("deviceAuthn", "false")); nvps.add(new BasicNameValuePair("forceAuthn", "true")); nvps.add(new BasicNameValuePair("ipAddrAuthn", "false")); nvps.add(new BasicNameValuePair("lang", "en")); nvps.add(new BasicNameValuePair("passwd", "mypassword")); nvps.add(new BasicNameValuePair("r", "comcast.net")); nvps.add(new BasicNameValuePair("rm", "2")); nvps.add(new BasicNameValuePair("s", "ccentral-cima")); nvps.add(new BasicNameValuePair("user", "me")); httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); System.out.println("executing request " + httpPost.getURI()); // Create a response handler ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpclient.execute(httpPost, responseHandler); String cima = StringUtils.substringBetween(responseBody, "cima.ticket\" value=\"", "\">"); System.out.println(cima); HttpPost httpPost2 = new HttpPost("https://customer.comcast.com/Secure/Home.aspx"); List <NameValuePair> nvps2 = new ArrayList <NameValuePair>(); nvps2.add(new BasicNameValuePair("cima.ticket", cima)); httpPost2.setEntity(new UrlEncodedFormEntity(nvps2, HTTP.UTF_8)); System.out.println("executing request " + httpPost2.getURI()); // Create a response handler ResponseHandler<String> responseHandler2 = new BasicResponseHandler(); String responseBody2 = httpclient.execute(httpPost2, responseHandler2); System.out.println(responseBody2); A: Here's a sample adapted from the 'Response Handling' example here. Your example is quite complicated - best to simplify your code while you figure out how to follow redirects (you can comment out the section I've highlighted to show the example failing to follow the redirect). import org.apache.http.*; import org.apache.http.client.*; import org.apache.http.client.methods.*; import org.apache.http.impl.client.*; import org.apache.http.protocol.*; public class ClientWithResponseHandler { public final static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); // Comment out from here (Using /* and */)... httpclient.setRedirectStrategy(new DefaultRedirectStrategy() { public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) { boolean isRedirect=false; try { isRedirect = super.isRedirected(request, response, context); } catch (ProtocolException e) { e.printStackTrace(); } if (!isRedirect) { int responseCode = response.getStatusLine().getStatusCode(); if (responseCode == 301 || responseCode == 302) { return true; } } return false; } }); // ...to here and the request will fail with "HttpResponseException: Moved Permanently" try { HttpPost httpPost = new HttpPost("http://news.bbc.co.uk/"); System.out.println("executing request " + httpPost.getURI()); // Create a response handler ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpclient.execute(httpPost, responseHandler); System.out.println(responseBody); // Add your code here... } finally { // When HttpClient instance is no longer needed, shut down the connection // manager to ensure immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7546849", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: FBML App - Important Questions for October 1 changes I have Some Questions for October 1 changes - * *For old FBML based Facebook Canvas Apps, do we need to enable secure canvas url? *Will the old FBML apps stop working if https is not enabled on the server? *What code change do we make to convert he old fbml app code to new system? A: * *I do not think you need a Secure URL. But test it by navigating Facebook with HTTPS (change your settings) and visiting your app. If it will require a Secure canvas URL it will prompt you to temporarly navigate facebook without HTTPS. *Should still work (try #1) *Depends on the Facebook Functionality on your page. One of the easiest ways is using the Facebook JS SDK. Here is a full tutorial that should let you get the initial setup and functionality: http://thinkdiff.net/facebook/new-javascript-sdk-oauth-2-0-based-fbconnect-tutorial/ A: FBML apps do not need secure canvas url. Here is the answer given by Douglas Purdy, the head of developer relations: http://www.facebook.com/groups/fbdevelopers/?view=permalink&id=251904368186418
{ "language": "en", "url": "https://stackoverflow.com/questions/7546854", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to Export wordpress database from web matrix I have WebMatrix version 1. I made a WordPress site and now it's time to publish it. From what I've read, the best option is to publish the site from web matrix using the web deploy option. But my hosting (godaddy) doesn't support this feature. So I have to upload my site via FTP. The problem is that I don't know how to export the databse from my webmatrix to my hosting. From reading some posts, I think the best option is to use phpMyAdmin, but I couldn't install it on my computer. Is that the easiest way to expot my database? And if that is the best option, can anybody explain me how to install phpMyAdmin on my computer. Thanks a lot Gonzalo A: Use the plugin http://wordpress.org/extend/plugins/portable-phpmyadmin/ to run phpmyadmin and export the database without actually installing phpmyadmin on your PC.
{ "language": "en", "url": "https://stackoverflow.com/questions/7546856", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: When does code belong in the model in ruby on rails? Currently putting in a lot of rails 3 practice and I was working on an authentication system and was following a tutorial on railscasts. Ryan from railscasts done a sort of update to that tutorial with some minor changes to take advantage of rails 3.1 e.g. has_secure_password So some of the code in my Sessions_controller changed to: class SessionsController < ApplicationController def new end def create user = User.find_by_username(params[:username]) if user && user.authenticate(params[:password]) session[:user_id] = user.id redirect_to root_path, :notice => "Logged In" else flash.now.alert = "Invalid Credentials" render "new" end end def destroy session[:user_id] = nil redirect_to root_path, :notice =>"Logged Out" end end What I would like to know is if some of the code in the create method/action should be in the model? Is it good or bad practice to have this code there? What rules should I be following as I want to learn the correct way and not pick up bad habits because I've gone past that part of learning a framework where things start to make sense much more usually than they don't. Advice is appreciate.. What I would like to know in particular is.. 1. When does a programmer know when code belongs in the model? How does he/she make that decision? A: This is one of the most important questions in OO programming. It's all about responsibilities. Place code in your model if you think that model is responsible for that piece of functionality. In your example you see that: * *The SessionController is only responsible creating and destroying the the user's session. *The User is responsible for authentication. All business logic goes into your models. Your controllers takes care of populating your views, handling the user's input and sending the user on their way. View simply display information, hardly contain any logic (if any). Also: take a look at existing projects for inspiration (for example, Shopify). A: My advice: In User model (pseudocode): function authenticate(username, pass) { /*get user by name return user_id (or user object if you need some user data in view) if auth ok, otherwise false */ } I think you should always keep controllers small as possible. The most important think in OOP is encapsulation so you should write all operation on user in user class, return to client code (in this case controller) only what controller need to do his job - add user id to session.
{ "language": "en", "url": "https://stackoverflow.com/questions/7546857", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: NSMutableArray adding/removing objects + NSUserDefaults I want to make a "Favorites" in my RSS reader. My RSS parser is parsing a RSS feed to NSMutableArray, and then object "item" is created from part of my rss (selected post). My code: //Creating mutable array and adding items: - (void)viewDidLoad { if (favoritedAlready == nil) { favoritedAlready = [[NSMutableArray alloc] init]; [[NSUserDefaults standardUserDefaults] setObject:favoritedAlready forKey:@"favorites"]; [[NSUserDefaults standardUserDefaults] synchronize]; NSLog(@"избранное с нуля"); } } - (void) addToFavorites { NSMutableArray* favoritedAlready = [[NSUserDefaults standardUserDefaults] objectForKey:@"favorites"]; [favoritedAlready addObject: item]; [[NSUserDefaults standardUserDefaults] setObject:favoritedAlready forKey:@"favorites"]; [[NSUserDefaults standardUserDefaults] synchronize]; NSLog(@"Добавлено в избранное. В избранном %i статей", [favoritedAlready count]); } //Removing items (another View) - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; rssItems = [[NSUserDefaults standardUserDefaults] objectForKey:@"favorites"]; [self.tableView reloadData]; NSLog(@"Загрузилось избранное, %i избранных статей", [rssItems count]); } - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { NSLog(@"Номерок строчки в которой удаляемый объект %i", indexPath.row+1); [rssItems removeObjectAtIndex:indexPath.row]; [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; [[NSUserDefaults standardUserDefaults] setObject:rssItems forKey:@"favorites"]; [[NSUserDefaults standardUserDefaults] synchronize]; } It worked perfectly initially, but when I added and removed items, it started crashing. Crash logs: I added object to Favorites and removed it: 2011-09-25 20:14:44.534 ARSSReader[36211:11303] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFArray removeObjectAtIndex:]: mutating method sent to immutable object' *** Call stack at first throw: ( 0 CoreFoundation 0x015505a9 __exceptionPreprocess + 185 1 libobjc.A.dylib 0x016a4313 objc_exception_throw + 44 2 CoreFoundation 0x01508ef8 +[NSException raise:format:arguments:] + 136 3 CoreFoundation 0x01508e6a +[NSException raise:format:] + 58 4 CoreFoundation 0x01547dd1 -[__NSCFArray removeObjectAtIndex:] + 193 5 ARSSReader 0x000a0ced -[FavoritesView tableView:commitEditingStyle:forRowAtIndexPath:] + 173 6 UIKit 0x00876037 -[UITableView(UITableViewInternal) animateDeletionOfRowWithCell:] + 101 7 UIKit 0x0080b4fd -[UIApplication sendAction:to:from:forEvent:] + 119 8 UIKit 0x0089b799 -[UIControl sendAction:to:forEvent:] + 67 9 UIKit 0x0089dc2b -[UIControl(Internal) _sendActionsForEvents:withEvent:] + 527 10 UIKit 0x0089c7d8 -[UIControl touchesEnded:withEvent:] + 458 11 UIKit 0x0082fded -[UIWindow _sendTouchesForEvent:] + 567 12 UIKit 0x00810c37 -[UIApplication sendEvent:] + 447 13 UIKit 0x00815f2e _UIApplicationHandleEvent + 7576 14 GraphicsServices 0x01c91992 PurpleEventCallback + 1550 15 CoreFoundation 0x01531944 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 52 16 CoreFoundation 0x01491cf7 __CFRunLoopDoSource1 + 215 17 CoreFoundation 0x0148ef83 __CFRunLoopRun + 979 18 CoreFoundation 0x0148e840 CFRunLoopRunSpecific + 208 19 CoreFoundation 0x0148e761 CFRunLoopRunInMode + 97 20 GraphicsServices 0x01c901c4 GSEventRunModal + 217 21 GraphicsServices 0x01c90289 GSEventRun + 115 22 UIKit 0x00819c93 UIApplicationMain + 1160 23 ARSSReader 0x00001e79 main + 121 24 ARSSReader 0x00001df5 start + 53 ) terminate called throwing an exception(gdb) But, if I added item, restarted app and then removed it, it worked perfectly. I added item, restarted app, removed item, and tried to add new item: 2011-09-25 20:19:19.212 ARSSReader[36461:11303] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFArray insertObject:atIndex:]: mutating method sent to immutable object' *** Call stack at first throw: ( 0 CoreFoundation 0x015505a9 __exceptionPreprocess + 185 1 libobjc.A.dylib 0x016a4313 objc_exception_throw + 44 2 CoreFoundation 0x01508ef8 +[NSException raise:format:arguments:] + 136 3 CoreFoundation 0x01508e6a +[NSException raise:format:] + 58 4 CoreFoundation 0x01547cf1 -[__NSCFArray insertObject:atIndex:] + 209 5 CoreFoundation 0x01544c14 -[__NSCFArray addObject:] + 68 6 ARSSReader 0x00004b35 -[DetailsViewController addToFavorites] + 149 7 UIKit 0x0080b4fd -[UIApplication sendAction:to:from:forEvent:] + 119 8 UIKit 0x00a1dcc3 -[UIBarButtonItem(UIInternal) _sendAction:withEvent:] + 156 9 UIKit 0x0080b4fd -[UIApplication sendAction:to:from:forEvent:] + 119 10 UIKit 0x0089b799 -[UIControl sendAction:to:forEvent:] + 67 11 UIKit 0x0089dc2b -[UIControl(Internal) _sendActionsForEvents:withEvent:] + 527 12 UIKit 0x0089c7d8 -[UIControl touchesEnded:withEvent:] + 458 13 UIKit 0x0082fded -[UIWindow _sendTouchesForEvent:] + 567 14 UIKit 0x00810c37 -[UIApplication sendEvent:] + 447 15 UIKit 0x00815f2e _UIApplicationHandleEvent + 7576 16 GraphicsServices 0x01c91992 PurpleEventCallback + 1550 17 CoreFoundation 0x01531944 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 52 18 CoreFoundation 0x01491cf7 __CFRunLoopDoSource1 + 215 19 CoreFoundation 0x0148ef83 __CFRunLoopRun + 979 20 CoreFoundation 0x0148e840 CFRunLoopRunSpecific + 208 21 CoreFoundation 0x0148e761 CFRunLoopRunInMode + 97 22 GraphicsServices 0x01c901c4 GSEventRunModal + 217 23 GraphicsServices 0x01c90289 GSEventRun + 115 24 UIKit 0x00819c93 UIApplicationMain + 1160 25 ARSSReader 0x00001e79 main + 121 26 ARSSReader 0x00001df5 start + 53 ) terminate called throwing an exception(gdb) A: In addToFavorites NSMutableArray* favoritedAlready = [[NSUserDefaults standardUserDefaults] objectForKey:@"favorites"]; will return an NSArray (it makes no difference it you save a mutable version), not an NSMutableArray You need to create a mutable version: NSMutableArray* favoritedAlready = [[[NSUserDefaults standardUserDefaults] objectForKey:@"favorites"] mutableCopy]; You can obviously not add items to a non-mutable array. Also just casting the return value to a NSMutableArray is wrong, it may work or it may not but that is irrelevant. A: The issue is that NSUserDefaults only returns immutable arrays, even if you put in a mutable array: Special Considerations: The returned array and its contents are immutable, even if the values you originally set were mutable. Therefore, when you fetch your array from NSUserDefaults, you'll have to convert it by using the mutable copy method, or by creating a new NSMutableArray using the returned NSArray. You may want to consolidate changes to fewer method calls to NSUserDefaults—perhaps in batches, perhaps at certain time intervals. Have a local array keep track of changes, then write the changes out, rather than grabbing the array from NSUserDefaults first. This will save one more trip to disk and will make your code more efficient as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7546859", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: jquery confusing code I am learning Jquery and Javascript from web examples. I have a good working knowledge but some code still trips me up. The following code is used for a shopping cart to hide the check out button and replace with a div displaying a message about minimum cart requirements. There is a part of the code throwing me off though. function getCollectionCount() { var totalCollectionCount = 0; var collection = $('td[alt*="Collection"]'); for (var i = 0; i < collection.length; i++) { var curVal = $(collection[i]).find("select").val(); if (curVal != undefined){ totalCollectionCount += parseInt(curVal); } } What does this part mean? var collection = $('td[alt*="Collection"]'); A: td[alt*="Collection"] selects all <td> elements whose alt attribute contains Collection, such as: <td alt="Collection"></td> <td alt="CollectionFoo"></td> <td alt="BarCollection12324343"></td> but not <td></td> <td alt=""></td> <td alt="Foo"></td> Side note: this is a pretty basic question that could easily be answered by read the jQuery selectors API documentation: * *element selector *attribute-contains selector Please do try to research before you ask! A: This is a jQuery attribute selector clause. It's selecting any td element which has an atrtibute named alt whose string contains the value Collection. Contains Selector: http://api.jquery.com/attribute-contains-selector/ jQuery has a number of useful attribute selectors. Here is the main reference page for them. Very much worth the read if you're just getting started with jQuery * *http://api.jquery.com/category/selectors/attribute-selectors/ A: That code returns every td element whose "alt" attribute contains "Collection". http://api.jquery.com/attribute-contains-selector/ jQuery is full of these funky shortcuts that take forever to learn, so I always keep a copy of jQuery in action on my desk at all times :) A: This code can be rewritten more simply and briefly like this: function getCollectionCount() { var totalCollectionCount = 0; $('td[alt*="Collection"] select').each(function() { var val = this.value || "0"; totalCollectionCount += parseInt(val, 10); }); return(totalCollectionCount); } And, this is how it works: * *Initialize totalCollectionCount to 0 *Find all td elements that have the string "Collection" in the alt attribute and then find select elements within that td *Iterate over all elements found that match the above condition *Initialize a local variable with either the value of the select object or "0" if there is no value or it's empty *Turn that value into a number (must pass the radix to parseInt so it won't guess) and add it to the sub-total so far. *return the total we found.
{ "language": "en", "url": "https://stackoverflow.com/questions/7546860", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is PDO::lastInsertId reliable with very rapid inserts? I'm using the Yii PHP framework which has a function PDO::lastInsertId that's apparently just an implementation of PDO::lastInsertId. If my application has very rapid inserts from possibly thousands of simultaneous users, will this function be reliable to get the Auto-incremented row ID of the data I just inserted? I need to get the id of the row I just inserted to do a bit of work after the insert itself, but want to make sure that if the insert rate is very high, it wont cause inconsistent results. Thanks! A: yes, of course, no worries about that, but you've to make sure to ask the lastInsertId just after the insert query. No other query should be executed on that connection in the meantime, each PHP process must have a separate connection. Also if you think that a table is going to have hundreds or thousands of insert per second, consider to not use indexes or use the minimum amount of indexes. In case of MySQL favour MyISAM tables.
{ "language": "en", "url": "https://stackoverflow.com/questions/7546861", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: MPMoviePlayerController notification question Good Evening Fellas! Is it possible for me to get a notification from an MPMoviePlayerController while it is playing a video. I mean, if i am able to get it every second, millisecond etc. I have an indicator for the video current playback time that i want it updated continuously. Thank you in advance. A: The simplest way is going to be to set up a repeating timer yourself, and use that to update your display. e.g.: [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTime:) userInfo:nil repeats:YES];
{ "language": "en", "url": "https://stackoverflow.com/questions/7546866", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Save to file open by openfiledialog (C# 2008) What I am trying to do is most likely very simple but afters spending hours I still cant figure out how to do it correctly. I am able to open a text file using the openfiledialog but cannot figure out to save back to that same file. I would like to also be able to check and see if the file is in use before writing to it. Here is my code for the open and save buttons: public void openToolStripMenuItem_Click(object sender, EventArgs e) { //This if statement checks if the user has saved any changes to the list boxes if (MessageBox.Show( "Have you saved your work?\nOpening a new file will clear out all list boxes.", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes) { //Clears out the listboxes this.itemListBox.Items.Clear(); this.priceListBox.Items.Clear(); this.qtyListBox.Items.Clear(); //This will open the file dialog windows to allow the user to chose a file OpenFileDialog fileDialog = new OpenFileDialog(); fileDialog.Title = "Harv's Hardware"; fileDialog.InitialDirectory = Directory.GetCurrentDirectory(); //File Filter fileDialog.Filter = "txt files (*.txt)|*.txt"; fileDialog.FilterIndex = 2; fileDialog.RestoreDirectory = true; //This if statement executes is the user hits OK if (fileDialog.ShowDialog() == DialogResult.OK) { //StreamReader readFile = File.OpenText(fileDialog.FileName); currentFile = new StreamWriter(OpenFileDialog.FileName); String inputString = null; while ((inputString = readFile.ReadLine()) != null) { this.itemListBox.Items.Add(inputString); inputString = readFile.ReadLine(); this.priceListBox.Items.Add(inputString); inputString = readFile.ReadLine(); this.qtyListBox.Items.Add(inputString); } } } } and save button //Closes and open files //Creates a new saveDialog SaveFileDialog saveDialog = new SaveFileDialog(); saveDialog.ShowDialog(); //Listens to the user input StreamWriter writeFile = File.CreateText(saveDialog.FileName); int indexInteger = 0; //Writes the actual File while (indexInteger < priceListBox.Items.Count) { writeFile.WriteLine(itemListBox.Text); writeFile.WriteLine(itemListBox.Text); writeFile.WriteLine(qtyListBox.Text); indexInteger++; } } Thanks for any help! A: Use SaveFileDialog instead of OpenFileDialog and can use FileStream to write to the file. To check if file is in use or not, this is what I do.. public bool IsFileInUse(String file) { bool retVal = false; try { using (Stream stream = new FileStream(file, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) { //file is not locked } } catch { retVal = true; } return retVal; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7546868", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to run "rails s" I have a problem running rails s in Ubuntu. When I type rails s it doesn't start the server, but instead it outputs: kyala@ubuntu:~/depot$ rails s Usage: rails new APP_PATH [options] Options: -r, [--ruby=PATH] # Path to the Ruby binary of your choice # Default: /home/kyala/.rvm/rubies/ruby-1.9.2-p290/bin/ruby -d, [--database=DATABASE] # Preconfigure for selected database (options: mysql/oracle/postgresql/sqlite3/frontbase/ibm_db)enter code here # Default: sqlite3 -b, [--builder=BUILDER] # Path to an application builder (can be a filesystem path or URL) -m, [--template=TEMPLATE] # Path to an application template (can be a filesystem path or URL) [--dev] # Setup the application with Gemfile pointing to your Rails checkout [--edge] # Setup the application with Gemfile pointing to Rails repository [--skip-gemfile] # Don't create a Gemfile -O, [--skip-active-record] # Skip Active Record files -T, [--skip-test-unit] # Skip Test::Unit files -J, [--skip-prototype] # Skip Prototype files -G, [--skip-git] # Skip Git ignores and keeps Runtime options: -f, [--force] # Overwrite files that already exist -p, [--pretend] # Run but do not make any changes -q, [--quiet] # Supress status output -s, [--skip] # Skip files that already exist Rails options: -v, [--version] # Show Rails version number and quit -h, [--help] # Show this help message and quit Description: The 'rails new' command creates a new Rails application with a default directory structure and configuration at the path you specify. Example: rails new ~/Code/Ruby/weblog This generates a skeletal Rails installation in ~/Code/Ruby/weblog. See the README in the newly created application to get going. A: Try to regenerate binstubs: rm bin/* rake rails:update:bin It should do the trick. For newer (5.2+) Rails versions use rake app:update:bin A: When the script folder is missing from the Rails application folder it shows the above error. I just copied it from another app and it worked for me. A: Before running the Rails server, you need to first create a Rails application. For example, to create a new app call "test_app", run the following: rails new test_app Once your application is created, you can cd into the directory and start your server: cd test_app rails server A: My first hunch would be that you are not in the root of your Rails application. On our deployment servers, I have to type ./script/rails s when in the root-folder of my Rails-app. I think that is because bin\rails is not known there. If that would not work, it seems to me that you are not at all inside a Rails root folder, which would also explain why rails s did not work. A Rails root project will contain at least the following directories: app, lib, config, script .... A: OK guyz just for the closure... this problem occurs only when we delete some(mostly script) folders in the rails app... (may be.. accidentally.).. I had this issue but was in a wrong app folder... A: I've seen a similar issue with Rails 2.x apps. They fire up fine with thin, unicorn and such, but to get just the webrick server I've had to run bundle exec script/server (or for the less careful script/server seems to work). I don't know the root issue at play here, but this seems to tide me over as I don't maintain any rails 2.x code (simply running ChiliProject 3.x, etc.). A: We had the same problem. Be sure you run the 'rails' command in the script folder and not the binary 'rails' that is different script/rails s It´s the same that if you go to your script folder and run the command: cd script ./rails s A: Check whether the 'script' folder exists in your application structure. A: I had the same issue. I had forgotten to run bundle after creating an app. From the root of your project directory run: bundle install A: While searching for an answer myself, I ended up trying a few things that proved useful to getting rails s to work for me. This resulted in 658 files changed, 102204 insertions, and 149 deletions. * *Look at the file that you're in by running ls. *Run git status. *Run git add .. *Run git commit -m "Notate whatever changes you are adding to github repository". *I tried to run git push and git push master but neither work, "go figure." My guess is that you can't push changes that belong to a different file or branch. *HERE's THE SECRET... For some strange reason, I was working in a different file so I had to run a git pull YourOtherFile. This is where everything started making sense. *Now, I ran another git status to understand what was going on within this file. There was modified and untracked content. *Next, cd back into the other file. *Run git status to view all of your modified and untracked files. *Run git add . and git commit -m "Notate your changes to this repository". *Watch the magic happen then run a git push. *Run gem update bundler. *Then I ran gem install rails_12factor. *Run another git status to view your modification. *Run git commit -m "Successfully added gem rails_12Factor". *Run git push. *I had issues with bcrypt being locked at 3.1.11 so I ran gem install 'bcrypt'. *Run gem install rails_12factor yet again. I believe that I had the "f" in "factor" capitalized. *Run gem update. *Run gem install pg. *Run git add .. *Run git commit -m "Updated Gemfile". *Run git push. *Run gem install 'pg' yet again. *I was running into all kind of issues but it was because I was trying to upgrade my gemfile to Rails 5. *Run gem install railties. *Run gem install activesupport. *If your Gemfile was already in another version of Rails (gem 'rails', '4.2.6'), make sure that you keep it there as there was not a significant difference in Rails 5. A: Run the following command inside your project folder: rails s Your project folder contains node_modules, Gemfile.lock, etc... A: Try "rails server" instead of the short form. Maybe you have it aliased for some reason. A: Just Run 'bundle update' command and start your application
{ "language": "en", "url": "https://stackoverflow.com/questions/7546869", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: XML: Back tracing parent element I am looking for solution to my problem related to XML in python. Though spectrum is not a root element let's suppose it's for this example. <spectrum index="2" id="controller=0 scan=3" defaultArrayLength="485"> <cvParam cvRef="MS" accession="MS:1000511" name="ms level" value="2"/> <cvParam cvRef="MS" accession="MS:1000580" name="MSn spectrum" value=""/> <cvParam cvRef="MS" accession="MS:1000127" name="centroid mass spectrum" value=""/> <precursorList count="1"> <precursor spectrumRef="controller=0 scan=2"> <isolationWindow> <cvParam cvRef="MS" accession="MS:1000040" name="m/z" value="810.78999999999996"/> <cvParam cvRef="MS" accession="MS:1000023" name="isolation width" value="2"/> </isolationWindow> <selectedIonList count="1"> <selectedIon> <cvParam cvRef="MS" accession="MS:1000040" name="m/z" value="810.78999999999996"/> </selectedIon> </selectedIonList> <activation> <cvParam cvRef="MS" accession="MS:1000133" name="collision-induced dissociation" value=""/> <cvParam cvRef="MS" accession="MS:1000045" name="collision energy" value="35"/> </activation> </precursor> </precursorList> <binaryDataArrayList count="2"> <binaryDataArray encodedLength="5176"> <cvParam cvRef="MS" accession="MS:1000523" name="64-bit float" value=""/> <cvParam cvRef="MS" accession="MS:1000576" name="no compression" value=""/> <cvParam cvRef="MS" accession="MS:1000514" name="m/z array" value="" unitCvRef="MS" unitAccession="MS:1000040" unitName="m/z"/> <binary>AAAAYHHsbEAAAADg3yptQAAAAECt7G1AAAAAAN8JbkAAAAAA.......hLJ==</binary> </binaryDataArray> <binaryDataArray encodedLength="2588"> <cvParam cvRef="MS" accession="MS:1000521" name="32-bit float" value=""/> <cvParam cvRef="MS" accession="MS:1000576" name="no compression" value=""/> <cvParam cvRef="MS" accession="MS:1000515" name="intensity array" value=""/> <binary>ZFzUQWmVo0FH/o9BRfUyQg+xjUOzkZdC5k66QWk6HUSpqyZCsV1NQ......uH=</binary> </binaryDataArray> </binaryDataArrayList> </spectrum> What I am trying to achieve is find all selectedIon element in the tree and backtrack it's parent element spectrum. If selectedIon element is found then SelectedIon information: Mass: 810.78999999999996 Spectra Info: ------------- index=2 id=controller=0 scan=3 length=485 General Info ------------ ms level=2 Msn spectrum= - centriod mass spectrum=- ..................... And all the cvParam name and value as above. Binary ------ m/z array = AAAAYHHsbEAAAADg3yptQAAAAECt7G1AAAA.....== intensity array = ZFzUQWmVo0FH/o9BRfUyQg+xjUOzkZdC5k66Q....5C77= What I have tried so far: import xml.etree.ElementTree as ET tree=ET.parse('file.mzml') NS="{http://psi.hupo.org/ms/mzml}" filesource=tree.findall('.//'+NS+'selectedIon') # Will get all selectedIon element from the tree Now how can I backtrace to spectrum element/subelement to parse out relevant information as above? How can I success? A: XPath will let you access an ancestor: "ancestor::spectrum" will return the <spectrum> element you are contained within. If you use lxml, you can use full XPath syntax to find elements you want. from lxml import etree tree = etree.XML('file.mzml') NS = "{http://psi.hupo.org/ms/mzml}" filesource = tree.findall('.//'+NS+'selectedIon') spectrum = filesource.xpath('ancestor::spectrum')[0] (I think, not tested...) UPDATED: code that actually works: from lxml import etree tree = etree.parse('foo.xml') for el in tree.findall(".//selectedIon"): for top in el.xpath("ancestor::spectrum"): print top A: If this is still a current issue, you might try pymzML, a python interface to mzML files. Printing all information from all MS2 spectra is just as easy as: import pymzml msrun = pymzml.run.Reader("your-file.mzML") for spectrum in msrun: if spectrum['ms level'] == 2: # spectrum is a dict, so you can just print it print(spectrum) (Disclosure: I'm one of the authors)
{ "language": "en", "url": "https://stackoverflow.com/questions/7546872", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Printing first field and (and only) matching fields in record, using awk I really don't know if awk would be the appropriate tool for that task... Maybe something in python would be better. Anyway, I thought asking here first for the feasibility of the task. Here we go : Datas : ### offspr84 175177 200172 312312 310326 338342 252240 226210 113129 223264 male28 197175 172200 308312 310338 262338 256252 190226 113129 223219 female13 197177 172172 312308 318326 342350 240248 210218 129113 267247 ### offspr85 181177 192160 320312 290362 358330 238238 214178 133129 263223 male65 197181 176192 320268 322286 358330 238244 206214 137133 267263 female17 181177 160172 280312 362346 350326 230238 126178 129129 223167 ### So basicaly I need to print the first field ($1) and matching (in bold) $9 in the first record and matching $2 and $6 in second record. Output file : offspr84 113129 male28 113129 offspr85 181177 female17 181177 offspr85 358330 male65 358330 Any hint on how I could accomplish that ? Thanx ! A: This code will produce the output you want. Maybe not the best way, but seems to work as expected. #data = [ #'offspr84 175177 200172 312312 310326 338342 252240 226210 113129 223264', #'male28 197175 172200 308312 310338 262338 256252 190226 113129 223219', #'female13 197177 172172 312308 318326 342350 240248 210218 129113 267247'] data = [ 'offspr85 181177 192160 320312 290362 358330 238238 214178 133129 263223', 'male65 197181 176192 320268 322286 358330 238244 206214 137133 267263', 'female17 181177 160172 280312 362346 350326 230238 126178 129129 223167' ] for i, line in enumerate(data): data[i] = line.split(' ') for item in data[0]: if data[1].count(item) > 0: print data[0][0], item print data[1][0], item if data[2].count(item) > 0: print data[0][0], item print data[2][0], item Update: With a nested list to include both list at once: datas = [[ 'offspr85 181177 192160 320312 290362 358330 238238 214178 133129 263223', 'male65 197181 176192 320268 322286 358330 238244 206214 137133 267263', 'female17 181177 160172 280312 362346 350326 230238 126178 129129 223167' ], [ 'offspr84 175177 200172 312312 310326 338342 252240 226210 113129 223264', 'male28 197175 172200 308312 310338 262338 256252 190226 113129 223219', 'female13 197177 172172 312308 318326 342350 240248 210218 129113 267247'] ] for data in datas: for i, line in enumerate(data): data[i] = line.split(' ') for data in datas: for item in data[0]: if data[1].count(item) > 0: print data[0][0], item print data[1][0], item if data[2].count(item) > 0: print data[0][0], item print data[2][0], item A: I'm not entirely sure on how you want the matching to work. but assuming the same pattern is applied to all fields, you can easily do this by looping over the fields e.g { for(i=2; i<=NF; i++) { if (match($i, "some regexp")) { print $1 $i } } } A: try this awk code awk '/###/{i++;next} i==1{if($0~/offspr84/){ a=$9;n=$1;next; } if($9==a){print n,a;print $1,$9}} i==2{if($0~/offspr85/){ m=$1;p=$2;q=$6;next;} if($2==p){print m,p;print $1,p} if($6==q){print m,q;print $1,q} }' yourFile A: awk ' /^offspr/ { for (i=1; i<=NF; i++) { offspr[i] = $i } next } { for (i=2; i<=NF; i++) { if ($i == offspr[i]) { print offspr[1] " " offspr[i] print $1 " " $i print "" break } } } '
{ "language": "en", "url": "https://stackoverflow.com/questions/7546880", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java: Help with basic outputting basic value arithmetic. Getting 0 for output, don't know why? I am having some issues doing basic math with Java. I don't know why I am getting 0 as a result of multiplying n*n*n only in one case. (see below) I need this not to be zero because I have to divide timing/n*n*n to get that big O performance. Also if I can get that working the output may look like 0.00000 but I want to multiply that by like 100,000 just so I can see numbers and find any trends in performance. You can see the values of n and timing in the first two number columns. * *n is Integer *timing is Long This is my output statement, System.out.println(fmt.format("%20s %20d %20d %20d %20d %20d%n", "Alg. 1", n, timing, n*n*n, timing/(n*n), timing /*((double)timing/((double)n*Math.log((double)n)))*/)); My results, Alg. 1 256 4 16777216 0 4 Alg. 1 512 22 134217728 0 22 Alg. 1 1024 173 1073741824 0 173 Alg. 1 2048 1362 0 0 1362 Please keep in mind I need to perform this log math also. Any tips or fixes for that would also be appreciated! Note: I am not dividing at all in the statement n*n*n and I am getting 0 in column four row four. Can someone also please tell me how to get this to output decimal places that are accurate not just 0.000000. My new arithmetic is ((float)(timing/((long)n)*n*n)*100000. I am multiplying by 100000 as said above because I want to see something in the decimal places. I should be seeing 0.0159139 with this equation when n is 2048 and timing is 1362. I just see 0.000000 though. Any suggestions? A: 20483 is 233 which overflows using 32-bit arithmetic. Use a long or a double to handle numbers this big. ((long) n) * n * n (Demo at ideone.com) A: If you divide one integer by another that's greater than it, you'll get a zero result. Make either numerator or denominator a double and you'll be fine. System.out.println(fmt.format("%20s %20d %20d %20d %20d %20d%n", "Alg. 1", n, timing, n*n*n, (double)timing/(n*n), timing)); A: 2048 cubed is 8589934592, much bigger than the max value of an int. It's actually 2 * (2^32). If you try to convert it to a signed 32-bit int, it wraps around twice and you end up with zero. Use longs!
{ "language": "en", "url": "https://stackoverflow.com/questions/7546883", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to read a file from a lift webapp I want to read xml file in my lift app: val data = XML.load(new java.io.InputStreamReader(new java.io.FileInputStream(filename), encoding)); However, I am getting java.io.FileNotFoundException. where should I put the file, and what is the correct path from my scala code? BTW - I am using embedded jetty for my testing, although I need a solution for dev env and production. A: There might be better solution for other paths but there is var LiftRules.getResource : (String) ⇒ Box[URL] or def LiftRules.doWithResource(name: String)(f: (InputStream) ⇒ T): Box[T] which usually point to files in src/main/resources/. There is also def LiftRules.loadResourceAsXml(name: String): Box[NodeSeq] which may be the method you are looking for. A: To solve this problem in the general case, new File("delme").createNewFile() and see where it ends up.
{ "language": "en", "url": "https://stackoverflow.com/questions/7546887", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Android two sliding drawer in a single view I have to insert 2 sliding drawer in my view. The slidings have to be at the same height( one at the right of the other) and when they open, they have to occupy the entire width of the screen. If I put them in a Relative layout and I use android:layout_toRightOf, at the open they occupy only an half of the screen's width. How can I resolve this problem? thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/7546892", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to make a simple dynamic slideshow/timelapse I have a folder where are saved images from a webcam each X time. I want to use these image to create a slideshow without transitions effects or music => i want to make a timelaps! These slideshow must be dynamic (i can use php to build the list of image, each time a user want to watch the "video"). Any sugguestion and code to do this? Javascript? Php? or others?? Thanx! A: That's the best way i found: simple and speedy <HTML> <HEAD> <TITLE>Video</TITLE> </HEAD> <BODY BGCOLOR="#000000"> <img name="foto"> <SCRIPT LANGUAGE="JavaScript"> var Pic = new Array(); Pic[0] = '/images/image1.jpg' Pic[1] = '/images/image2.jpg' Pic[2] = '/images/image3.jpg' //this part in real code is replaced with a PHP script that print image location dinamically var t; var j = 0; var p = Pic.length; var preLoad = new Array(); for (i = 0; i < p; i++) { preLoad[i] = new Image(); preLoad[i].src = Pic[i]; } //all images are loaded on client index = 0; function update(){ if (preLoad[index]!= null){ document.images['foto'].src = preLoad[index].src; index++; setTimeout(update, 1000); } } update(); </script> </BODY> </HTML> A: Have your PHP script send a meta refresh tag in the heading to reload the page with the latest image after the desired time. NOTE: There are better, more AJAX-like ways of doing this, but this is the simplest. Using AJAX to reload just the image and not the whole page would be harder to write but a better user experience.
{ "language": "en", "url": "https://stackoverflow.com/questions/7546894", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android and muting music when i want to play a custom voice message here's the requirement. While in the Gym working out, they play this training program in the loudspeakers, and every 30 min it say "Change Station". I cannot here this since i have my headphone music. I i create a small Timer controlled Service that, when i start it will say "Change Station" every 30 minute. If I have my own music on it will dim the music or stop the music in my device for a few seconds so i can here my own "Change Station" The biggest problem for me is how to dim the music? A: Look at the 'audio focus' feature in Android 2.2: http://developer.android.com/guide/topics/media/index.html#audiofocus This way your app can request 'focus', and can indicate that other audio on the system should fully surrender focus, or should "duck" (just lower its volume and keep playing). One problem is that you need the music app you're interrupting to support this, more than your own "change station" app needs to.
{ "language": "en", "url": "https://stackoverflow.com/questions/7546902", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: About UTF-8(Uyghur) language support on Android 3.2 OS I found there are no RTF-8 and RTL language support on Android OS 3.2. I use Sony tablet S, current system is Android 3.2 There are 10 million Uyghur people are living in this world. but I fount Uyghur language and some Arabic fonts become very strange mark on this system. If I use like "ROOT" to change system language , I may disable to continue SONY system guaranty. So, is anyone can help with this problem?! Is there any official support possibility for this problem. A: Bidirectional text support is a very popular feature request but it is not yet supported in the base platform.
{ "language": "en", "url": "https://stackoverflow.com/questions/7546905", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: iOS - Disable or editing animations of CATextLayer I working with a CATextLayer var and when try to increase the font or type something in this string there is an animation effect with these actions , How can I edit or disable the animation of CATextLayer ? A: You can do this by setting the actions dictionary on the layer to return [NSNull null] as an animation for the appropriate key. for example : NSDictionary *newActions = [[NSDictionary alloc] initWithObjectsAndKeys:[NSNull null], @"contents", nil]; normalTextLayer_.actions = newActions; [newActions release]; o disable fade in / out animations I believe the contents key is the one you're looking for A: [CATransaction setDisableActions:YES]; // Make changes to the text layer here... [CATransaction setDisableActions:NO];
{ "language": "en", "url": "https://stackoverflow.com/questions/7546906", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: HMAC-SHA1 Example not returning desired hash? I am using this example: http://msdn.microsoft.com/en-us/library/aa382379%28VS.85%29.aspx Directly copied and pasted, and using the following link as a reference for checking the digest: http://buchananweb.co.uk/security01.aspx I am confused on what I am doing wrong. This example is for HMAC-SHA1, correct? If anyone could tell me what is going wrong, or could point me into the right direction, that would be of much help. A: To start with don't try to use complex key derivation functions, just use a simple explicit key like { 0x00, 0x01, 0x02, 0x03 ... }. Alternatively find some HMAC-SHA1 test vectors, such as in FIPS 198a, and use those keys as explicitly given. The FIPS Test Vectors have the advantage of showing expected intermediate results as well so it is easier to pin down exactly where the problem is. Using different key derivation functions will give you different HMAC results because the actual key used will be different if it is derived differently.
{ "language": "en", "url": "https://stackoverflow.com/questions/7546911", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can I load a dll in such a way that it can be deleted while it's loaded? The title pretty much says it all.. What I'm trying to do is write a tool that will monitor a dll file containing a plugin and when I overwrite it, by recompiling, it should automatically reload it. I know I can make a copy, load the copy and monitor the original, but I thought there might be a better way.. If I understood it right the dll is completely loaded into memory so there shouldn't be a problem in deleting the file.. A: No, that's not how Windows works. Loading a DLL merely creates a memory mapped file, nothing is actually read from the file beyond the relocations (if necessary). Not until your code calls an exported function. Which causes a page fault because the code wasn't loaded yet. Now the code gets read from the file into RAM. If space is needed for other processes then the pages simply gets unmapped. Getting reloaded again on the next page fault. The MMF puts a hard lock on the file. You can only rename it, not overwrite or delete it. That would crash the program. Release the lock with FreeLibrary(). A: Haven't tried it, I'm not on my Windows machine right now, but I think that Windows locks the file against writing when loading a DLL. You should check that first, can you actually overwrite the DLL (e.g. by compiling a new version) or does the compiler complain with "permission denied". Otherwise I suppose you could use the file change notification API to achieve your goal.
{ "language": "en", "url": "https://stackoverflow.com/questions/7546912", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Page refresh (F5) always causing form to submit a bit new to CI, googled and overflowed alot and still got no answer * *User enters site. *After succesful auth got redirected to main page *Link on the url stays the same with class/method *If u refresh page on a main - u always got question about repopulate form (chrome/firefox 100%) the solution may be: after success redirect to another class or method but i don't know how to do it, documentation seems more like reference to me code is here: http://paste.ubuntu.com/696751/ line 28 - how to do redirect to another class or method with a redirection to another view too? A: Well an example in CodeIgniter may be: class login extends CI_Controller { function index () { $this->load->library('form_validation'); $this->load->helper('url'); //Set form validation rules here: http://codeigniter.com/user_guide/libraries/form_validation.html if ($this->form_validation->run() == TRUE) { //login user here redirect('login/sucLogin'); // or just redirect to '/' if you want to send them to your home page } else $this->load->view('loginForm'); //make form } function sucLogin () { echo 'Successfully logged in'; echo anchor('/', 'Go Home'); } } A: * *Check to see if the user submitted the form *Validate the login credentials *Redirect on success public function login() { if ($_POST) { $login = $this->input->post('login'); $password = md5($this->input->post('password')); $q = $this->db ->where('login', $login) ->where('password', $password) ->limit(1) ->get('userbase'); if ($q->num_rows > 0 ) { redirect('enter/main'); } } $returnlogin['login'] = $login; $this->load->helpers('form'); $this->load->view('login_form',$returnlogin); } public function main() { $this->load->view('main'); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7546918", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do i convert this Js function to Anonymous function in jquery this function is called on Load how do i convert this to jquery Anonymous function . I tried but it is giving me Object Expected Error . Moreover I have made call to the below setTab() in 20 files so i cannot Change the Signature of the calling it should be same as (setTab("Test")) but the Implementation needs to be changed to Anonymous function which accepts a parameter. //old JS func() function setTab(selection) { $("#"+selection).css('background', '#CC0000'); $("#"+selection).css('color', '#ffffff'); } //jquery Anonynous Func var setsTab = (function (selection) { $("#"+selection).css('background', '#CC0000'); $("#"+selection).css('color', '#ffffff'); })(); A: The problem is that you have setup a self executing anonymous function, meaning setsTab is set to what the function returns (undefined) because the function is called as soon as it is made (that's what the paren group at the end of the statement does, calls the function); What i would do is var setsTab = function(selection) { $("#"+selection).css('background', '#CC0000'); $("#"+selection).css('color', '#ffffff'); }; A: I guess you want it this way? var setsTab = function (selection) { $("#"+selection).css('background', '#CC0000'); $("#"+selection).css('color', '#ffffff'); } Edit: But this doesn't have anything to do with jQuery. (anonymous jquery function?)
{ "language": "en", "url": "https://stackoverflow.com/questions/7546926", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Web app using API for everything? I'm about to start planning an internal project management tool for my company. One thing that has always led me wondering is APIs. Would it be seen as bad practice / too inefficient to create a API first and build the actual site using those API calls rather than implement it twice? Let me know your thoughts! A: I completely agree that developing an API will give you a decoupled architecture, and I recommend that. However, I feel you should be warned that developing the API first increases your risk of developing the wrong API (PM, by the way, is largely about reducing project risk). You will also be tempted to gold-plate your API-- program features that may go unused, which wastes time. Developing the API in conjunction with the application guarantees that it correctly serves the actual application's or applications' needs. Unless you are confident in the accuracy of and your understanding of the requirements, I suggest programming the API one feature at a time with the application. For example, as you develop the application and discover the precise point at which you need to make an API call, create an interface (depending on the technology) that looks exactly like what you need. You can stub that interface to get the app to run, which is a great tool for checking that the app is still on track with user expectations. ("You want it to work like this, right?") Later, you can implement that interface. If by chance requirements suffer alteration, you won't have spent time building now obsolete infrastructure.
{ "language": "en", "url": "https://stackoverflow.com/questions/7546927", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to process huge XML file fast? I need to develop a program, for posix systems, for parsing an xml file, on average 300Mb, and inserting the data in a relational database. The time factor is very important, both in developing and running the programm. I have a certain generic background in C, Ruby, Python and Java, but not enough depth to make a good choice and in depth optimizations. I would like to know the opinions and experiences of other programmers, also I would like to have an opinion about functional languages. Many thanks. A: Proper design would properly matter more than the language. I.e. it's easy to make a design mistake which would negate all benefits of "fast" language. If you are limited to named languages, - use C or Java and use third-party parser such as Xerces. This will save both development time and you from making design mistakes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7546928", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: determine if array of bytes contains bytes in a specific order Possible Duplicate: byte[] array pattern search Let's say I have an array of bytes: byte[] myArray = new byte[]{1,2,3,4,5,6,7,1,9,3,4,3,4,7,6,5,6,7,8}; how can I determine if myArray contains bytes 9,3,4,3 in that order? do I have to iterate through the array appending each element to a string then use the String.Contains() method to know if that byte array contains those elements in that order? I know I can do semething like: String s = ""; foreach(byte b in myArray) { s = s + b.ToString(); } //then do s.Contains("9343") this is not to efficient on long arrays. What will be a more efficient way of doing this? A: Try the following public static bool ContainsSequence(byte[] toSearch, byte[] toFind) { for (var i = 0; i + toFind.Length < toSearch.Length; i++) { var allSame = true; for (var j = 0; j < toFind.Length; j++) { if (toSearch[i + j] != toFind[j]) { allSame = false; break; } } if (allSame) { return true; } } return false; } A: The simplest algorithm that works and is to rip through the byte array until you find a match on the first byte in the byte pattern that you're looking for then walk along through the two until you reach the end, or if you find a mismatch, continue from where you left off. This can "degrade" if you keep getting partial matches. Depending on your needs, this could be good enough (it's simple to write, simple to maintain). If that isn't fast enough for your purposes, you can easily adopt Boyer-Moore.
{ "language": "en", "url": "https://stackoverflow.com/questions/7546931", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Flash Player AS -> webcam get buffer bytes I am working on a flash video chat system. I need to get the video buffer bytes from the webcam to be able to transfer the video content over a socket server. I am not sure how to do this, does anyone have any ideas? Thanks. I know how to use the webcam basics, the code: var camera = Camera.getCamera(); var video = new Video(camera.width, camera.height); video.attachCamrea(camera); /* I need something like var byte_buffer = video.getBytes(); */ I don't know how to do this, any help would be much appreciated. A: No problem. You'll need to create a BitmapData object and 'draw' your display object - the one referenced by video variable - 'into' this bitmap data. You can then access the pixels through, say, the getPixels method which returns a ByteArray which is your de facto buffer class in Flash Player. The drawing is like taking a snapshot bitmap copy of your display object. Find out more at Adobe ActionScript 3 Reference which should be your best friend as long as you program the Flash Player: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/BitmapData.html Here is some code for illustration: var bd = new BitmapData(320, 240, false, 0x000000); bd.draw(video); var byte_buffer = bd.getPixels(); /// For example...
{ "language": "en", "url": "https://stackoverflow.com/questions/7546932", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Question about aggregate functions with GROUP BY SQL Server I have for example 10-15 fields in table different types (varchar, nvarchar, int, float, datetime e.t.c.) and i need to make GROUP BY, so. What function of aggregate i have to use on all of this fields? MAX or something else? Is it important? SELECT intFacilityRTOPID, MAX(ObjectSystem_r_Equipment) ObjectSystem_r_Equipment, MAX(ObjectBuilding_r_Equipment) ObjectBuilding_r_Equipment, MAX(intenum_EquipmentTypeID) intenum_EquipmentTypeID, MAX(correctionDate) correctionDate FROM [RTOPv4History].[dbo].[FacilityRTOP] WHERE cast(correctionDate as bigint) <= @correctionDate GROUP BY intFacilityRTOPID A: Sounds like you might not understand what Group By does. Group By establishes a set of "bins" or "buckets", defined by the values of the group By columns or expressions, that will control the output of the query. i.e., the result rows of the query will be constrained to unique combinations of the values defined by the group by columns and/or expressions, and all data in each row is constrained from the subset of the original table that mach that "definition".. Any columns in the eoutput that are not exactly the same as one of the group by column/expressions must use one of the many aggregate functions to specify and/or calculate what value to generate for that column. The value generated will be taken from actual table column values from only those rows in the original table that match the group By column/expression. So if you use MAX(), you get the biggest of that subset of the values, if you use AVG() you get the average, etc... If you really don't want to do any aggregation, then consider just using the Distinct keyword.... SELECT Distinct intFacilityRTOPID, ObjectSystem_r_Equipment ObjectSystem_r_Equipment, ObjectBuilding_r_Equipment ObjectBuilding_r_Equipment, intenum_EquipmentTypeID intenum_EquipmentTypeID, correctionDate correctionDate FROM [RTOPv4History].[dbo].[FacilityRTOP] WHERE cast(correctionDate as bigint) <= @correctionDate A: If the complementary column are all equal, you may want to SELECT * FROM ( SELECT DISTINCT(intFacilityRTOPID) FROM [RTOPv4History].[dbo].[FacilityRTOP] WHERE cast(correctionDate as bigint) <= @correctionDate ) a CROSS JOIN ( SELECT TOP(1) ObjectSystem_r_Equipment, ObjectBuilding_r_Equipment, intenum_EquipmentTypeID, correctionDate FROM [RTOPv4History].[dbo].[FacilityRTOP] WHERE cast(correctionDate as bigint) <= @correctionDate ) b which could perform better depending on the size of the table. Caveat: I haven't tried if this works and I am writing by memory :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7546938", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: get execution time in milliseconds in R I have read a solution to this using tic(), toc() functions tic <- function(gcFirst = TRUE, type=c("elapsed", "user.self", "sys.self")) { type <- match.arg(type) assign(".type", type, envir=baseenv()) if(gcFirst) gc(FALSE) tic <- proc.time()[type] assign(".tic", tic, envir=baseenv()) invisible(tic) } toc <- function() { type <- get(".type", envir=baseenv()) toc <- proc.time()[type] tic <- get(".tic", envir=baseenv()) print(toc - tic) invisible(toc) } tic(); -----code---- toc(); elapsed 0.15 But I would like to get a lot of precision in milliseconds? Also I was using this ptm <- proc.time() ---code proc.time() - ptm and get this user system elapsed 1.55 0.25 1.84 How to get more decimals or more precision? A: This one is good: options(digits.secs = 6) # This is set so that milliseconds are displayed start.time <- Sys.time() ...Relevant code... end.time <- Sys.time() time.taken <- end.time - start.time time.taken Taken from here. A: 1) Timing is operating-system dependent. On Windows you may only get milliseconds. 2) No need to define tic() and toc(), R has system.time(). Here is an example: R> system.time(replicate(100, sqrt(seq(1.0, 1.0e6)))) user system elapsed 2.210 0.650 2.867 R> 3) There are excellent add-on packages rbenchmark and microbenchmark. 3.1) rbenchmark is particularly useful for comparison of commands, but can also be used directly: R> library(rbenchmark) R> x <- seq(1.0, 1.0e6); benchmark(sqrt(x), log(x)) test replications elapsed relative user.self sys.self user.child sys.child 2 log(x) 100 5.408 2.85835 5.21 0.19 0 0 1 sqrt(x) 100 1.892 1.00000 1.62 0.26 0 0 R> 3.2) microbenchmark excels at highest precision measurements: R> library(microbenchmark) R> x <- seq(1.0, 1.0e6); microbenchmark(sqrt(x), log(x)) Unit: nanoseconds expr min lq median uq max 1 log(x) 50589289 50703132 55283301 55353594 55917216 2 sqrt(x) 15309426 15412135 15452990 20011418 39551819 R> and this last one, particularly on Linux, already gives you nano-seconds. It can also plot results etc so have a closer look at that package. A: Place start_time before your code and end_time after your code. i.e. start_time <- as.numeric(as.numeric(Sys.time())*1000, digits=15) # place at start -----code---- end_time <- as.numeric(as.numeric(Sys.time())*1000, digits=15) # place at end end_time - start_time # run time (in milliseconds) A: Take the difference of two Sys.time()s with a units= argument, ie. start_time <- Sys.time() ## ... code here ... end_time <- Sys.time() as.numeric(difftime(end_time, start_time, units="secs")) * 1000 The unit of time is specified, (otherwise "secs" will be used when difftime < 1 min, or "mins" will be used when 1 min <= difftime < 1 hour). As the smallest unit available to use with difftime() is "secs", we multiply the result by 1000 thereafter.
{ "language": "en", "url": "https://stackoverflow.com/questions/7546946", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "23" }
Q: How to remove a header in PHP below 5.3? How do we remove a header (e.g. Last-Modified) that has already been set but not yet sent over the wire? (It may have been set by Apache, "pre"-PHP, and whatnot.) I'm currently using PHP 5.2.17 and header_remove is an undefined function. To be clear, I do not want to send a blank header line like header("Foo-bar:"). I want to completely remove it from the output buffer and send nothing. A: Use mod_rewrite and modify .htaccess Header unset Last-Modified A: Update your PHP version or ask your hoster to update it. PHP 5.2 was EOLed several months ago and thus will not receive any further bug or security fixes. If you are 5.2 you are a security threat to yourself and everybody visiting your site. Updating your PHP version will additionally give you all the new features and performance improvements. Apart from that: Restructure your logic so that the header isn't set in the first place. There is no way to completely remove the header in 5.2.
{ "language": "en", "url": "https://stackoverflow.com/questions/7546947", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: What's the smoothest way to update haskell platform to latest? I'm on OSX 10.6 and I have platform 2010.2.0.0 currently. Should I just install 2011.2.0.1 on top or is there an update mechanism that will be smoother? A: I've definitely had bumpy upgrade experiences with the Haskell Platform. If you have enough trouble that you just want to wipe the thing and start fresh (you wouldn't be the first!), take a look here: Everywhere that GHC/Haskell Platform installs A: As far as I know there is no update mechanism. And I have never had any trouble with just installing one platform version on top of the other on OSX. A: I come from the future (06/2013) and I just had to nuke my entire installation of the haskell platform in order to successfully install a newer. So... there's still no smooth way of upgrading. (At least in OS X) A: Whether you need to nuke the existing platform depends on where cabal is configured to install packages. On Mac OS X, the supplied cabal-install is modified to create a config which separates packages by GHC version. If that's the config you used, you can just install the Haskell Platform on top of the old one. install-dirs user prefix: /Users/pgiarrusso/Library/Haskell/$compiler/lib/$pkgid -- [...] install-dirs global prefix: /Library/Haskell/$compiler/lib/$pkgid Installation-specific binaries, like the ones from gtk2hs-buildtools, are only separated with a configuration like the above. As far as I can tell, at least the actual package register (in ~/.ghc/$GHC_VERSION, used by ghc-pkg and cabal) is instead always per-GHC-version. The config generated by a vanilla cabal-install (from Hackage) does not take such precautions. install-dirs user -- prefix: /Users/pgiarrusso/.cabal [...] install-dirs global -- prefix: /usr/local If you have such a config, I expect you're going to get trouble unless you remove at least the data in ~/.cabal, and also the binaries in /usr/local from the old Haskell Platform — but don't nuke the whole directory, since /usr/local is often used for installing other software! The default config is only generated when no config exists, so to update the config you need to move away the existing one.
{ "language": "en", "url": "https://stackoverflow.com/questions/7546949", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: SVN Ignore situation I have a setup like this. * *SVN Repository *Live Site *Dev Site *Local Copy SVN Repository is identical to Live site. Every different sites have different config file, local.xml. Some clients are windows/toitoise and some clients are linux servers which I have SSH access to. My requirements are. * *I don't want local.xml to be changed neither on A. Repository when committing nor B. clients when updating. *I want local.xml to be part of every new checkouts. *I don't want local.xml files on clients lingering "modified" with question mark signs after being modified. *I don't want to manually "uncheck" local.xml on every commit as there are some more folders like cache and image files to be "ignored" too. I've tried, - Locking the file on Repo. That throws an ugly error when committing. I'm afraid it would break the rest of commits. - SVN:ignore local.xml. But seems it's still going through. Thanks for your help. A: I think I see what you want. The right way to do it by having a build process. In your repository, you will have a local.template.xmlfile and a local.properties.template file. There is no local.xml file or a local.properties file. Your developers will take the local.properties.template and make a local.properties file that will suit their needs. The developers will use the build process which will take their local.properties file and the local.template.xml file, and merge them into a local.xml file for their use. When the developers commit their code, they won't commit the local.xmlor the local.properties file. Since these won't be in the repository, the developers can freely update their working directory without worrying that it will somehow destroy their settings in the local.xml file. And, you can deploy on the server without worry since the new release won't rewrite the server's local.xml file. What you need is a pre-commit hook that can guarantee that developers won't add a local.xml or a local.properties to the repository. I have one that's pretty simple to install and use. It uses a control file to specify what files can be added and by whom. A: Having the file in the ignore list is needed, but it alone will not do the trick. You'll also need to delete the file from the repository. Run this to delete the file from SVN but keep the local file: svn rm --keep-local local.xml svn commit EDIT: A common way to keep local settings files in SVN is adding them with names like default.local.xml and copying them to local.xml and modifying the settings right after the first checkout. This way you won't risk overwriting of conflicting your actual settings file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7546965", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Issue with memcpy I am developing in Cocoa / Xcode and have an int * array containing values. When I want to use memcpy to shift values in the array, it transfers only 0s. e.g. * *Array contains values as 1 2 3 4 *memcpy(array,array+2*sizeof(int),2*sizeof(int)); result: 0,0,3,4 Is there a better alternative to memcpy, or something I am doing wrong ? A: I think the right way to do what you want is: memcpy(array, array + 2, 2*sizeof(int)); That's because in the 2nd argument of memcpy pointer arithmetic is being done, and anything that's being added to "array" pointer is considered as being a multiple of an integer's size. So in this case saying "array + 2" means "the integer pointer `array' plus two times the size of an integer". A: The manpage to memcpy says, that the regions should not overlap. Try memmove instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7546968", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problem with apache mod_rewrite and 404 pages I have a custom 404 error page, and a mod_rewrite rule. If I access a page that does not exist, I get my 404 error page. My problem is that if I issue a 404 header from my php page, it does not open my 404 page, instead, I get this: Not Found The requested URL /index.php was not found on this server. Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request. This is my .htaccess: RewriteEngine on ErrorDocument 404 /errors/404.php RewriteRule ^[A-Za-z0-9]{8}/$ /index.php This is my redirect from /index.php that will 404 only if the key does not exist. The $key is obtained from parsing the URL (e.g. http://localhost/aKeYCoDE/): <?php if (!key_exists($key)){ header('HTTP/1.0 404 Not Found'); exit; } ?> I am expecting it to redirect to my 404 page. UPDATE: It is definitely something about the fact that I am calling 404 from a page that was rewritten (/index.php). If I create a dummy page: /redirect.php, and then do nothing but issue the 404 from there, I get my custom 404 page. But, if I write a mod_rewrite rule for it, and try to access it that way, I get the default 404 error page. A: I found the answer - the problem was my assumption that a header 404 from php would redirect to a 404 page. That was wrong. The Apache server can issue 404 for pages that do not exist, but for pages that do exist, i.e., are being served by the php page, the 404 response goes to the browser. This thread was of a similar issue: http://www.webmasterworld.com/forum88/10955.htm To make php do what I want it to do (issue the 404 when key does not exist), I need to include the 404 page from php: <?php if (!key_exists($key)){ include($_SERVER["DOCUMENT_ROOT"]."/errors/404.php"); exit; } ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/7546969", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: CMakelists.txt is ridiculously complex to get windows and mac to work, is there a better way? I have been getting a CMakeLists.txt together to compile what right now is an SFML sample in preparation to do my own source code. It feels like a hack, even though it works (Mac Makefile, VS nmake, VS solution) right now. The main repository is at https://github.com/iaefai/Spider-Fish/ Any suggestions are welcome. cmake_minimum_required(VERSION 2.8) PROJECT(Spider-Fish) FIND_PACKAGE(OpenGL REQUIRED) FIND_PACKAGE(SFML REQUIRED) IF (WIN32) # Windows link_directories(${SFML_INCLUDE_DIR}/../lib) set(RESOURCE_HANDLER ${CMAKE_CURRENT_SOURCE_DIR}/src/windows/resources.cpp) # link_directories(${FIND_SFML_LIB_PATHS}) ELSEIF(APPLE) # Mac SET(RESOURCE_HANDLER ${CMAKE_CURRENT_SOURCE_DIR}/src/mac/resources.mm) SET(MACOSX_BUNDLE_GUI_IDENTIFER "com.iaefai.Spider-Fish") SET(MACOSX_BUNDLE_BUNDLE_NAME ${PROJECT_NAME}) if (NOT CMAKE_OSX_ARCHITECTURES) set(CMAKE_OSX_ARCHITECTURES "i386;x86_64" CACHE STRING "Build architectures for OSX" FORCE) endif() if(EXISTS /Developer/SDKs/MacOSX10.7.sdk) set(CMAKE_OSX_SYSROOT "/Developer/SDKs/MacOSX10.7.sdk" CACHE STRING "Defaults to 10.7" FORCE) else() # use default SDK endif() find_library(COCOA_LIB Cocoa) SET(EXTRA_LIBS ${COCOA_LIB} ${OPENGL_LIBRARIES}) ELSE() # Linux // Assumed?? ENDIF() #include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include}) include_directories(${SFML_INCLUDE_DIR}) SET(RESOURCES ${CMAKE_CURRENT_SOURCE_DIR}/assets/background.jpg ${CMAKE_CURRENT_SOURCE_DIR}/assets/blur.sfx ${CMAKE_CURRENT_SOURCE_DIR}/assets/colorize.sfx ${CMAKE_CURRENT_SOURCE_DIR}/assets/edge.sfx ${CMAKE_CURRENT_SOURCE_DIR}/assets/fisheye.sfx ${CMAKE_CURRENT_SOURCE_DIR}/assets/nothing.sfx ${CMAKE_CURRENT_SOURCE_DIR}/assets/pixelate.sfx ${CMAKE_CURRENT_SOURCE_DIR}/assets/sansation.ttf ${CMAKE_CURRENT_SOURCE_DIR}/assets/sprite.png ${CMAKE_CURRENT_SOURCE_DIR}/assets/wave.jpg ${CMAKE_CURRENT_SOURCE_DIR}/assets/wave.sfx) SET (SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/src/Shader.cpp) #SET (HEADERS include/resources.h) add_executable(${PROJECT_NAME} ${SOURCES} ${RESOURCE_HANDLER}) The biggest hack seems to be the stuff to copy resources. That would be ideal to have a special command that could do that on multiplatform. Not entirely certain how to do that — I suspect a set_target_resources would be a good name. IF (APPLE) set_target_properties(${PROJECT_NAME} PROPERTIES MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/src/mac/Spider-Fish-Info.plist MACOSX_BUNDLE TRUE) # add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD COMMAND echo copying resources... #${RESOURCES} COMMAND mkdir -p ./${PROJECT_NAME}.app/Contents/Resources COMMAND cp ${RESOURCES} ./${PROJECT_NAME}.app/Contents/Resources ) # add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD COMMAND echo ${PROJECT_NAME}.app/Contents/Resources) ENDIF (APPLE) IF (WIN32) set_target_properties(${PROJECT_NAME} PROPERTIES WIN32_EXECUTABLE FALSE) I would worry about this custom stuff on windows because of how specialized it is getting. set(EXTRA_LIBS sfml-main ${OPENGL_LIBRARIES}) # note we can add stuff to ADDITIONAL_MAKE_CLEAN_FILES string(COMPARE EQUAL ${CMAKE_GENERATOR} "NMake Makefiles" NMAKE) if (NMAKE) add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD COMMAND echo copying dlls... COMMAND copy ${SFML_INCLUDE_DIR}\\..\\bin\\*.dll . COMMAND echo copying resources... from ${CMAKE_CURRENT_SOURCE_DIR} COMMAND -mkdir resources COMMAND copy \"${CMAKE_CURRENT_SOURCE_DIR}\\assets\\*.*\" resources) else () add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD COMMAND echo copying dlls... COMMAND copy ${SFML_INCLUDE_DIR}\\..\\bin\\*.dll . COMMAND echo copying resources... from ${CMAKE_CURRENT_SOURCE_DIR} # Visual Studio does not support the '-' to ignore errors COMMAND rmdir /s /q resources COMMAND mkdir resources COMMAND copy \"${CMAKE_CURRENT_SOURCE_DIR}\\assets\\*.*\" resources) endif (NMAKE) ENDIF (WIN32) #if (APPLE) target_link_libraries(${PROJECT_NAME} sfml-system sfml-window sfml-network sfml-graphics sfml-audio ${EXTRA_LIBS}) #endif (APPLE) A: Have you tried using the INSTALL command instead of the custom post build steps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7546971", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Random resize problems Android tablets I have app on the Android Market called Speed Anatomy. It has been working and stable for months. Now before Android 3.2 came out with its pixel-scaling feature, my (canvas based) app appeared un-scaled on some tablets with a large black border. I ended up implementing pixel scaling myself therefore it doesn't use the new 3.2 mechanism. This was fairly easy public void setSurfaceSize(int width, int height) { synchronized (mSurfaceHolder) { matrix.reset(); float cancasScaleFactorY=height/(480.0f*scale); float cancasScaleFactorX=width/(320.0f*scale); float cancasScaleFactor=Math.min(cancasScaleFactorY, cancasScaleFactorX); matrix.postScale(cancasScaleFactor,cancasScaleFactor); ... public void doDraw(Canvas canvas) { canvas.setMatrix(matrix); ... boolean doTouchEvent(MotionEvent event) { float[] xy=new float[2]; xy[0]=event.getX(); xy[1]=event.getY(); matrixI.set(matrix); matrixI.invert(matrixI); //revert touch coordinate to the original unscaled coordinate space. matrixI.mapPoints(xy); ... This works with all devices I have tested, including most tablets, the simulators on 3.0, 3.1 etc. Last week I received an e-mail from a user, saying he had a Sony S with Android 3.2 tablet and the touch coordinates were off by a few centimeters. As I don't have an actual tablet, I went to my local Staples store where they have multiple Android tablets on display. Loaded my app on an eee Transformer with Android 3.2 and a Galaxy tab 10.1 with Android 3.1 and they both ran my app flawlessly. So I figured the user had made a mistake and used an older version of my app (although he specifically told me he had the latest version of my app from the Android Market). Yesterday night I was at a concert and there was a booth from Canadian carrier Telus with some Galaxy Tabs 10.1 on display. As I was waiting for some friends and had some time to kill, I loaded my apps on it to do one last test. To my surprise, the touch detection was all off! Basically it acted like the scaling was done on doDraw(), that is the app was full screen and pixel scaled (except for text which gets rendered at hi-res with my method) but the touch coordinates were not scaled, that is, I had to touch the screen in the top left 320x480 corner or the touches would register outside the screen. So I have two Galaxy tabs 10.1 with Android 3.1 on it, touches scale properly on one but not the other. I also have a user which claim problems on a Sony S with Android 3.2 and I have it working correctly on a transformer with 3.2. There seems to be a problem with matrix operations on those that don't work correctly. Either it's an intermittent problem or there is some other factor that I haven't thought of. Oh I just thought about the fact that it is probable that the second GT10.1 was a 3g since it was outside on the street while the others were wifi, (I don't know about the user's) but I can't see this affecting matrix transformations, right? I've never had problems with Android Fragmentation before this, in fact it has been easier than dealing with the different iOS versions. Any clue what could be causing this and how I fix the problem? There is a free version of the app if you want to try it. Let me know if it works on your device. EDIT:I just thought of something else. Is it possible that the Android Market is randomly serving an older version of my app once in a while? I'm not sure but I think this bug may have existed in a version that was briefly up on the Market. It has been fixed and updated more than a month ago however. A: After weeks of struggle, I believe I have found the source of the problem in the method: void android.graphics.Matrix.mapPoints(float[] dst, float[] src) Since: API Level 1 Apply this matrix to the array of 2D points specified by src, and write the transformed points into the array of points specified by dst. The two arrays represent their "points" as pairs of floats [x, y]. Parameters dst The array of dst points (x,y pairs) src The array of src points (x,y pairs) On some devices, this function cannot take the same array for src and dst. I myself has never been able to reproduce the bug. I debugged this blindly by changing things in my code, making releases and asking some users who had reported the problem if it was fixed. Changing every instance of: matrix.mapPoints(xy,xy); to float[] tempxy = new float[2]; tempxy[0] = xy[0]; tempxy[1] = xy[1]; matrix.mapPoints(xy,tempxy); seems to have fixed things. I found another dev reported the issue here: http://androidforums.com/developer-101/172225-android-graphics-matrix-mappoints-fail.html This dev mentions it only happening on older versions of Android whereas to me it seems like a regression happening when users upgrade to Gingerbread. Although it doesn't affect all gingerbread devices as my Galaxy SII X was never affected. I was unable to reproduce it on the Android simulator. Another hint that Gingerbread is affected is that lately with its rising popularity, users have been reporting the issue more often and the active installation count of my app started to go down. After I implemented the fix, it started going up again. I hope this helps someone. A: Matrix invert_m = new Matrix(); matrixI.invert(invert_m); invert_m.mapPoints(xy ); You need a new instance of Matrix for return the invert one;
{ "language": "en", "url": "https://stackoverflow.com/questions/7546976", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How would I run jquery code once a value is selected from a dropdown list? The HTML involved is similar to this: http://i.stack.imgur.com/a88XG.png I cannot change the html, it is auto generated. I need to perform an event once a specific "option" is picked from the dropdown list, however at the moment I can't reference it, as nothing in the html seems to change. For example, once changed to option 2, call an alert. Thanks guys. A: What you can do is listen for the change event with jQuery which is raised when the seletion is changed. After which you can query to see if the particular one you're interested in is selected $(document).ready(function() { $('#EditForm.SR').change( function() { if ($('#EditForm.SR option:selected').val() === 'Option2') { // Option 2 is selected } }); }); A: Your elements' IDs have spaces in them which is not allowed: ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods ("."). But you could try getting the <select> by class name: $('select.inputControl').bind('change', function() { // Do what you need to here. });
{ "language": "en", "url": "https://stackoverflow.com/questions/7546978", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android ListView shows only last item I'm working on project with listview,but I have a little problem. I'm using SimpleAdapter so I can change the view of my listview,but it shows only the last element.Here is the code : private ArrayList <HashMap<String, Object>> items; private final String TIME = ""; @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.plovdiv); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); ListView schedule = (ListView) findViewById(R.id.pld_schedule); items = new ArrayList<HashMap<String,Object>>(); HashMap<String, Object> hm = new HashMap<String, Object>(); hm.put(TIME, "06:00"); items.add(hm); hm.put(TIME, "06:30"); items.add(hm); hm.put(TIME, "07:00"); items.add(hm); hm.put(TIME, "07:30"); items.add(hm); hm.put(TIME, "08:00"); items.add(hm); hm.put(TIME, "09:15"); items.add(hm); hm.put(TIME, "10:00"); items.add(hm); hm.put(TIME, "10:45"); items.add(hm); hm.put(TIME, "11:30"); items.add(hm); hm.put(TIME, "12:15"); items.add(hm); hm.put(TIME, "13:00"); items.add(hm); hm.put(TIME, "13:45"); items.add(hm); hm.put(TIME, "14:30"); items.add(hm); hm.put(TIME, "15:15"); items.add(hm); hm.put(TIME, "16:00"); items.add(hm); hm.put(TIME, "16:30"); items.add(hm); hm.put(TIME, "17:00"); items.add(hm); hm.put(TIME, "17:30"); items.add(hm); hm.put(TIME, "18:00"); items.add(hm); hm.put(TIME, "18:40"); items.add(hm); hm.put(TIME, "19:30"); items.add(hm); hm.put(TIME, "20:00"); items.add(hm); hm.put(TIME, "20:40"); items.add(hm); hm.put(TIME, "21:40"); items.add(hm); hm.put(TIME, "22:30"); items.add(hm); SimpleAdapter adapter = new SimpleAdapter(this, items, R.layout.main_listview, new String[]{TIME}, new int[]{ R.id.text}); schedule.setAdapter(adapter); schedule.setChoiceMode(ListView.CHOICE_MODE_SINGLE); } Here is plovdiv.xml : <?xml version="1.0" encoding="UTF-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#FFFFFF"> <DigitalClock android:id="@+id/clock" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:textSize="40dp" android:textColor="#000000" android:textStyle="bold" android:layout_centerHorizontal="true"/> <ListView android:id="@+id/pld_schedule" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@+id/clock" android:cacheColorHint="#FFFFFF" /> </RelativeLayout> And this is main_listview.xml : <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#FFFFFF"> <TextView android:id="@+id/text" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textSize="45dp" android:textColor="#000000" android:textStyle="bold" android:layout_alignParentLeft="true" /> </RelativeLayout> As a result I get a listview with only the last item added : 22:30. Any ideas how to fix that? A: You keep overwriting your hashmap every time you add it, you need to make a new hashmap for each entry: { HashMap<String, Object> hm = new HashMap<String, Object>(); hm.put(TIME, "06:00"); items.add(hm); } { HashMap<String, Object> hm = new HashMap<String, Object>(); hm.put(TIME, "06:30"); items.add(hm); } etc. A: your TIME variable is constant, so your hashMap will finally have only 1 item at the end of adding all items. so i suggest you to keep changing the TIME variable, for every item you add. hm.put(TIME + "time1", "06:00"); items.add(hm); hm.put(TIME + "time2", "06:30"); items.add(hm); use something like given above, you should change the key value. A: you can not use the same key for every entry in your hashmap.. take a look at HashMap put java doc here
{ "language": "en", "url": "https://stackoverflow.com/questions/7546979", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Editing a BIG XML via DOM parser If there is a very big XML and DOM parser is used to parse it. Now there is a requirement to add/delete elements from the XML i.e edit the XML How to edit the XML as the entire XML will not be loaded due to memory constraints ? What could be the strategy to solve this ? A: You may consider to use a SAX parser instead, which doesn't keep the whole document in memory. It will be faster and will also use much less memory. A: As two other answers mentioned already, a SAX parser will do the trick. Your other alternative to DOM is a StAX parser. Traditionally, XML APIs are either: * *DOM based - the entire document is read into memory as a tree structure for random access by the calling application *event based - the application registers to receive events as entities are encountered within the source document. Both have advantages; the former (for example, DOM) allows for random access to the document, the latter (e.g. SAX) requires a small memory footprint and is typically much faster. These two access metaphors can be thought of as polar opposites. A tree based API allows unlimited, random access and manipulation, while an event based API is a 'one shot' pass through the source document. StAX was designed as a median between these two opposites. In the StAX metaphor, the programmatic entry point is a cursor that represents a point within the document. The application moves the cursor forward - 'pulling' the information from the parser as it needs. This is different from an event based API - such as SAX - which 'pushes' data to the application - requiring the application to maintain state between events as necessary to keep track of location within the document. A: StAX is my preferred approach for handling large documents. If DOM is a requirement, check out DOM implementations like Xerces that support lazy construction of DOM nodes: * *http://xerces.apache.org/xerces-j/faq-write.html#faq-4 A: Your assumption of memory constraint loading the XML document may only apply to DOM. VTD-XML loads the entire XML in memory, and does it efficiently (1.3x the size of XML document)... both in memory and performance... http://sdiwc.us/digitlib/journal_paper.php?paper=00000582.pdf Another distinct benefit, which none other XML framework in existence has, is its incremental update capability... http://www.devx.com/xml/Article/36379 A: As stivlo mentioned you can use a SAX parser for reading the XML. But for writing the XML you can write into fileoutput stream as plain text. I am sure that you will get requirement that mentions after which tag or under which tag the new data should be inserted.
{ "language": "en", "url": "https://stackoverflow.com/questions/7546981", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Rackspace CloudFiles .NET library: delimiter query parameter? Is the 'delimiter' query parameter implemented in the c# (.NET) library? I could not find it. Ref.: http://docs.rackspace.com/files/api/v1/cf-devguide/content/List_Objects-d1e1284.html A: Changes implemented and closed issue #52 on Github Download here
{ "language": "en", "url": "https://stackoverflow.com/questions/7546983", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error when using OleDB or ODBC in C# application I have a windows application and I have this code: private void saveToDatabase_Click(object sender, EventArgs e) { // Save the DataSet Appointments table to the database. KaznetiTableAdapter ta = new KaznetiTableAdapter(); ta.Adapter.RowUpdated += new OleDbRowUpdatedEventHandler(Adapter_RowUpdated); ta.Update(kbDataSet.Kazneti); } void Adapter_RowUpdated(object sender,OdbcRowUpdatedEventArgs e) { if (e.RecordsAffected == 0) { MessageBox.Show( e.Row["Adresa"].ToString() "Optimistic Concurrency Error - Notes Not Saved", MessageBoxButtons.OK, MessageBoxIcon.Warning ); e.Status = UpdateStatus.SkipCurrentRow; } } I got an error message: Error 1 No overload for 'Adapter_RowUpdated' matches delegate 'System.Data.OleDb.OleDbRowUpdatedEventHandler' If I change OleDb in the bolded code in Odbc I got an error again: Error 1 Cannot implicitly convert type 'System.Data.Odbc.OdbcRowUpdatedEventHandler' to 'System.Data.OleDb.OleDbRowUpdatedEventHandler' A: I guess that the error message you're getting is pretty obvious: Cannot implicitly convert type 'System.Data.Odbc.OdbcRowUpdatedEventHandler' to 'System.Data.OleDb.OleDbRowUpdatedEventHandler' So, change the line void Adapter_RowUpdated(object sender,OdbcRowUpdatedEventArgs e) to void Adapter_RowUpdated(object sender,OleDbRowUpdatedEventArgs e) Edited to answer a comment Then I think you could try something like this: ta.Adapter.RowUpdated += (sender, e) => { if (e.RecordsAffected == 0) { MessageBox.Show( e.Row["Adresa"].ToString() "Optimistic Concurrency Error - Notes Not Saved", MessageBoxButtons.OK, MessageBoxIcon.Warning ); e.Status = UpdateStatus.SkipCurrentRow; } } A: if you using OleDbDataAdapter adapter.RowUpdating += new OleDbRowUpdatingEventHandler(OnRowUpdating); create handler as protected static void OnRowUpdating(object sender, OleDbRowUpdatingEventArgs args) { // code } if you using SqlDataAdapter adapter.RowUpdating += new SqlRowUpdatingEventHandler( OnRowUpdating ); create handler as private static void OnRowUpdating(object sender, SqlRowUpdatingEventArgs e) { // code } you can easily generate event on visual studio by pressing tab key twice ones you type += A: I think your delegate needs to be static: static void Adapter_RowUpdated(object sender,OdbcRowUpdatedEventArgs e)
{ "language": "en", "url": "https://stackoverflow.com/questions/7546986", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: using ++counter instead of counter++ in for loops Possible Duplicate: Is there a performance difference between i++ and ++i in C++? I saw many places where they use for loops like this: for(i = 0; i < size; ++i){ do_stuff(); } instead of (which I -& most of people- use) for(i = 0; i < size; i++){ do_stuff(); } ++i should exactly give the same result as i++ (unless operators overloaded differential). I saw it for normal for-loops and STL iterated for loops. Why do they use ++i instead of i++? does any coding rules recommends this? EDIT: closed cause I found that it is exact duplicate of Is there a performance difference between i++ and ++i in C++? A: simply put: ++x is pre-increment and x++ is post-increment that is in the first x is incremented before being used and in the second x is incremented after being used. example code: int main() { int x = 5; printf("x=%d\n", ++x); printf("x=%d\n", x++); printf("x=%d\n", x); } o/p: x=6 x=6 x=7 A: The two are indeed identical, as the third part is executed after each iteration of the loop and it's return value is not used for anything. It's just a matter of preference.
{ "language": "en", "url": "https://stackoverflow.com/questions/7546988", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Achartengine legend location Does anyone know how to change the location of the legend? I am trying to expand the graph to make use of all the space. So far I have mRenderer.setMargins(new int[] { 20, 30, -50, 0 }); This expands the graph lower but the legend stays in the same location so it is now above the x axis I tried mRenderer.setLegendHeight(5); with both negative and positive values. I'm not sure what this is supposed to do but it makes my graph go wayyyy low on the the screen (turns it into a scrollable view). Also, may not be important but this is in a fragment and is a XYChart type. A: The property setLegendHeight(..) moves the position of the legend. Try to change the values you are using in both functions, that would work. cheers. Harry. A: This works: renderer.setYLabelsAlign(Align.LEFT, 0) A: In addition to using the advice above I found the following useful… // Temporarily show margins so I can work out what is going on renderer.setMarginsColor(Color.RED); // Legend was being cropped or not shown at all until I did this renderer.setFitLegend(true); In the end I had both the bottom margin and the legend height set to zero but still saw it on the screen with margins showing up in Red (from my diagnostic above). I think some margins must be auto calculated for the legend from the setFitLegend.
{ "language": "en", "url": "https://stackoverflow.com/questions/7546990", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How do I get jQuery to pull xml from webservice I've been trying to get data from http://www.webservicex.net/CurrencyConvertor.asmx/ConversionRate?FromCurrency=USD&ToCurrency=GBP I want to be able to use jQuery to extract the data, I've tried $.ajax and even : $.get('http://www.webservicex.net/CurrencyConvertor.asmx/ConversionRate?FromCurrency=USD&ToCurrency=GBP', function(data) { console.log(data); }); It works fine in my browser (firefox) as a url, however fails in jQuery. How can I extract the currency rate from the web service using jQuery without it throwing up an error? A: Due to the same origin policy restriction that is built into browsers you cannot send AJAX requests to different domains than the one that hosted the page containing this javascript (which I suspect is not http://www.webservicex.net). To workaround this issue you could write a server side script on your domain that will act as a bridge between your domain and the distant domain and then send an AJAX request to your script: $.get('/myscript?FromCurrency=USD&ToCurrency=GBP', function(data) { console.log(data); }); The server side script will simply take the two query string parameters and send them as HTTP request to the remote domain and return the results. The way to implement this script will of course depend on the server side language you are using. Another approach is to use JSONP but this only works if the remote domain supports it. If it doesn't you need a server side bridge.
{ "language": "en", "url": "https://stackoverflow.com/questions/7546992", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to embed my facebook fanpage wall in my iframe tab? I'm quite new to facebook. I'd like to have an i-frame tab on my facebook fanpage with the wall embedded on the same tab as the example: http://www.facebook.com/avrillavigne?sk=app_178091127385 I have searched for it but haven't found how exactly I can do this. Do I need the Graph API, Java SDK or PHP SDK to do this? Are there any examples? Thanks in advance. A: You can't just "embed" a Facebook page inside your app, you need to retrieve the Page's feeds through the Graph API or just use the Like Box. A: You need to get the Feed using the Graph API. Here is the initial documentation on how to use it: https://developers.facebook.com/docs/reference/api/ This second link might not work when you click on it, but if you go to the examples on the first link and use the news feed example from the second list you can swap out "me/feed" for "your_page/feed" and get the feed. With that you just need to format it so it looks like the wall. https://graph.facebook.com/cocacola/feed?access_token=2227470867|2.AQBnDvmcD3XoWI_F.3600.1316984400.0-515157640|hp7gwy_E3M9wLtyhBPxrsobi__E
{ "language": "en", "url": "https://stackoverflow.com/questions/7546997", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Sending developed dom through chrome extension to a webservice I am trying to create an extension to send the developed dom of the current tab to a web service at the push of a button, any one knows how I would go about it? methodology,code or simple advice will be appreciated. I am noob :( A: You need innerHTML: var html = document.getElementById("element1").innerHTML;
{ "language": "en", "url": "https://stackoverflow.com/questions/7547005", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: php object array properties if they don't exist First of I think I have tried all the solutions I have come across and still have an issue none the less.. facebookResponse Object ( [__construct:facebookResponse:private] => [__resp] => stdClass Object ( [data] => stdClass Object ( [id] => 00000000000 [name] => Random.User [first_name] => Random [last_name] => User [link] => http://www.facebook.com/Random.User [username] => Random.User [birthday] => 11/10/1980 [gender] => male [email] => xxxx@Random.User.com [timezone] => -7 [locale] => en_US [verified] => 1 [updated_time] => 2011-08-22T02:56:33+0000 ) [code] => 200 [time] => 0.600512 [length] => 386 [type] => text/javascript; charset=UTF-8 ) ) above is an example of the output object. I am looking for specifics, some of which sometimes don't exist. Where if they don't exist I just want to catch the fact flag it as "none" for my DB and move on to the next. For me Im not so lucky. no matter how I approach it I am running into errors.. whether i do isset() !isset() empty() !empty() or some combination of the above trying to catch it, as empty, null, undefined, blank, or just not even present. Example you will see that there is no location->name object in the above sample output. So my latest attemt(s) to catch it as not there is if((isset($fb_result->location->name)) AND(!empty($fb_result->location->name)) AND(trim($fb_result->location->name) !== "")) { $currenthome = $fb_result->location->name; } else { $currenthome = "none"; } my error with the above is "Undefined property: stdClass::$location" and no matter how I try to catch it, i still get the same thing. A: You might want to look at the Reflection API. A: You need to check for "location" attribute first, then go deeper if(!empty($fb_result->location) && !empty($fb_result->location->name)) $currenthome = $fb_result->location->name; else $currenthome = 'none';
{ "language": "en", "url": "https://stackoverflow.com/questions/7547010", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use .show() and .hide() with opener? I have a page with few photos, when a photo is clicked, a div opens using the whole avaliable screen's space to show an album ... like the facebook's photo viewer. Now, I want to press the ESC key and back to the first page ... PS: inside the div showAlbumDiv I call an Iframe, and by jquery.css property I chance the iframe's src property. Its because i have to passa an variable by get to the album viewer ! im using the following code in the album viewer: jQuery(document).ready(function($) { //closingDiv $(document).keyup(function(e) { if (e.keyCode == 27) { $('#showAlbumDiv', window.opener).hide(); $('.allOfIt', window.opener).show(); $('#showAlbumDiv',window.opener).css('visibility','hidden'); } // esc }); The opener has the divs allOfIt and showAlbumDiv .... the online sample is in http://videoarts.com.br/newSite/portifolio ... only the album viewer: http://videoarts.com.br/newSite/album/40 Any help !? thns ! A: window.opener tries to operate on another window - the one that opened this window. By your comment, it sounds like you're opening a new div in the same window. If that's the case, then window.opener is the wrong code. You want to operate in the same window and thus don't need to pass a context to the jQuery functions as they default to the current document. If you do mean to operate on another window, then (as I asked in my comment), please describe how a new window actually gets opened. Clicking on a photo does not open a new window, it just displays additional content in the current window. If you're using embedded iframes, then you may want window.parent, not window.opener to get the parent document.
{ "language": "en", "url": "https://stackoverflow.com/questions/7547011", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to echo date parts separately I have found place online where they answer different things, but I still don't get how I can apply it to my code. Basically I want the month in one echo-line, and the day-number in another echo. Is there away to do that in my code? <?php // Connects to your Database $data = mysql_query("SELECT id, title, description, location, date FROM Calendar") or die(mysql_error()); while($row = mysql_fetch_array( $data )) { echo "<article>"; echo "<date>"; echo "<h3>" .$row['date(month)'] . "</h3>"; echo "<h4>" .$row['date(day)'] . "</h4>"; echo "</date>"; echo "</article>"; } ?> A: You should be able to just pass the date straight through strtotime: $month = date('m', strtotime($row['date'])); $day = date('d', strtotime($row['date'])); But this will depend on the format the date is stored in the database. This should work for a TIMESTAMP type column or a UNIX timestamp, or (for the most part) a string representation of a date. A: Here's a way to get them ahead of time in your MySQL query, as an alternative to parsing them out later in PHP. $data = mysql_query("SELECT id, title, description, location, DATE_FORMAT(date, '%m') AS `month`, DATE_FORMAT(date, '%d') AS `day` FROM Calendar") or die(mysql_error()); Then to access them: while($row = mysql_fetch_array( $data )) { echo $row['month']; echo $row['day']; } Alternatively to get the month's name instead of number, use DATE_FORMAT(date, '%M') as month MySQL DATE_FORMAT() documentation A: You first get the unix time of the date and then format two different strings. A: If you want to echo date as exactly the name of the month, you can use 'F'. Like this: $month = date('F', strtotime($row['dateRepaired']));
{ "language": "en", "url": "https://stackoverflow.com/questions/7547017", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Problem with foreach for an array in PHP while($row = mysql_fetch_object($all)) { $name = $row->name; $email = $row->email; $id = $row->id; $finished_text = ''; $news_content = ''; $buffer = ''; [...] foreach($text_in_array as $word) { if($word == '[NAME]'){ $buffer = $name; }else if($word == '[NAME].'){ $buffer = $name.'.'; }else if($word == '[NAME],'){ $buffer = $name.','; }else if($word == '[NAME]!'){ $buffer = $name.'!'; }else if($word == '[NAME]"'){ $buffer = $name.'"'; }else if($word == '"[NAME]'){ $buffer = '"'.$name; }else if($word == '"[NAME]"'){ $buffer = '"'.$name.'"'; }else if($word == '[NAME]."'){ $buffer = $name.'."'; }else if($word == '[NAME],"'){ $buffer = $name.',"'; }else if($word == '[NAME]!"'){ $buffer = $name.'!"'; }else if($word == '*[NAME]*'){ $buffer = '*'.$name.'*'; }else if($word == '**[NAME]**'){ $buffer = '**'.$name.'**'; }else if($word == '[EMAIL]'){ $buffer = $email; }else if($word == '[EMAIL].'){ $buffer = $email.'.'; }else if($word == '[EMAIL],'){ $buffer = $email.','; }else if($word == '[EMAIL]!'){ $buffer = $email.'!'; }else if($word == '[EMAIL]"'){ $buffer = $email.'"'; }else if($word == '"[EMAIL]'){ $buffer = '"'.$email; }else if($word == '"[EMAIL]"'){ $buffer = '"'.$email.'"'; }else if($word == '[EMAIL]."'){ $buffer = $email.'."'; }else if($word == '[EMAIL],"'){ $buffer = $email.',"'; }else if($word == '[EMAIL]!"'){ $buffer = $email.'!"'; }else if($word == '*[EMAIL]*'){ $buffer = '*'.$email.'*'; }else if($word == '**[EMAIL]**'){ $buffer = '**'.$email.'**'; }else{ $buffer = $word; } $news_content .= ' '.$buffer; } $finished_text .= Markdown($news_content); [...] mail( 'xxxxxxxxxx@gmail.com', //just test later it will be set to $email $betreff, $message, $header ); } I don't know why, but sometimes it works perfectly and sometimes it doesn't. Also interesting: Before I created a HTML email with this script, it only worked after I had changed the email address as the last change… I hope someone can help me. Thanks. A: * *You should be using a switch statement instead of that long string of ifs. *What's wrong with $buffer = str_replace(Array("[NAME]","[EMAIL]"),Array($name,$email),$wort);? *After cleaning that up, if you still get problems, please be more specific on what problems you are having.
{ "language": "en", "url": "https://stackoverflow.com/questions/7547018", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQLite: Optimize table scans In my table I have some columns that have no index on them, searching for a value in those columns can take very long because SQLite does a full table scan. In my specific case the row I'm looking for (the values are unique) is almost always among the most recently inserted. I suspect that SQLite starts from the oldest (first) row when doing the scan, is there any way to instruct SQLite to do the table-scan in reverse order? UPDATE: I found this in the changelog: The optimizer will now scan tables in the reverse if doing so will satisfy an ORDER BY ... DESC clause. So maybe this means I can just do add an ORDER BY clause, to speed it up. A: The solution was: ORDER BY rowid DESC LIMIT 1 It made the lookups lightning fast! A: The order of the scan (oldest-to-youngest or youngest-to-oldest) is irrelevant because a FULL table scan is required. Every row must be visited. Although you mention 'the row I'm looking for' the condition .... where col = 'a' might return one row, or it might return 10 rows, or 500 rows. SQLite cannot simply stop and call it a good day's work when the first matching row is encountered unless you use the LIMIT directive. EDIT: What you could do, however, is use a timestamp column, index it, and then use an inline view to get the relatively recent rows: select * from ( select * from T where datecreated > {somerecentdate} ) as myView where myView.someColumn = 'a' or simply select * from T where datecreated > {some date} and somecolumn = 'a' That approach could be an iterative process -- if no rows are returned you may need to requery with a wider time-window. But if you're going to index datecreated you might as well index [someColumn].
{ "language": "en", "url": "https://stackoverflow.com/questions/7547022", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why does IE8 remove the Uri fragment (#myvar=1234) from window.open? I have an issue opening a popup window using Javascript that only seems to occur in IE 8 (8.0.7600) I'm trying to window.open a uri with a fragment, eg: http://davidlaing.com#UserName=CC735158 If I past this into the address bar; it works correctly (javascript on the loaded page can access the uri fragment). However, if I try to open the same uri from javascript: window.open("http://davidlaing.com#UserName=CC735158",'',''); the window is opened up without the fragment (that is, the address bar in the popup window shows only http://davidlaing.com, and the javascript on the loaded page cannot see any Uri fragment) The same Javascript works correctly from other browsers (IE9, FF6, Chrome). I'm pretty sure its not the popup blocker, since a window is "popped up", it just has a url without the fragment. Any pointers as to what might be wrong and how to fix it would be much appreciated. A: It seems to be a problem with your build version of IE8. I can confirm that IE 8.0.6001.18702 retains the hash fragment of a URI when opened in a javascript window.open("http://davidlaing.com#UserName=CC735158",'',''); FYI: I've used the XP IE6 VPC (http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=11575) and immediately upgraded to IE8 with the shortcut that Microsoft thoughtfully left on the desktop.
{ "language": "en", "url": "https://stackoverflow.com/questions/7547028", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Separate an Access db into distinct data and interface files? I've seen it done once, but didn't understand why the builder did this. What's the advantage, and if there is one, why is there no example of such an architecture in the literature? I'm just looking for a best-practice approach for a small office of around <10 or so users before I begin it (an office that wants specifically to migrate to an Access db). Thanks. A: Tons of links on how and why to split your app and database into separate files. In your application each user has a local copy of the app file which is linked to the data file in some sort of shared folder. Performance is improved. Network traffic is limited. Unique copies of temp/cached data can be maintained if needed. Backups on the data are slightly smaller. Not all users require the same features, so you can have different apps using the same data. A manager that just needs a few reports doesn't need a file with 50 forms in it. I'd like to know what you see as the downside. Linking tables isn't that hard (If it is, get someone else to build this app.). Sending everyone an updated app file to save on their local machine isn't that hard especially in a LAN setting. A: Ah, you mean two distinct Access files, one with only the system interface, and the other with the database, right? If that's the case the answer is pretty simple. Doing like so will provide means to update the interface without any downtime of the system operation and can help on the backup of the data. Access files can store both the data and the user interface, if you're using the Access like this, so, any modification in the file affects every one that uses the system. However, for the scenario that you're painting, I'd upgrade that to a SQL Server Express and an actual software developed for the company.
{ "language": "en", "url": "https://stackoverflow.com/questions/7547029", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: iPhone - sorting "10, 20, 30" the correct order with core data I have a string field on an entity. Every time I want to retrieve a sort list of entries and the entries contain numbers, the list comes like this: car 1 car 10 car 11 car 2 car 21 etc. instead of car 1 car 2 car 10 car 11 car 21 How do I force the request to sort the numbers correctly in a string property? I am using this: NSSortDescriptor *sortByItem = [NSSortDescriptor sortDescriptorWithKey:key ascending:YES selector:@selector(compare:)]; NSArray *sortDescriptors = [NSArray arrayWithObject:sortByItem]; [request setSortDescriptors:sortDescriptors]; thanks. A: Write your own comparison method that looks like this: - (NSComparisonResult)numericCompare:(NSString *)aString { return [self compare:aString options:NSNumericSearch]; } Then pass this method's selector to the sort descriptor. A: I have found an easier way. Simply use localizedStandardCompare: instead of compare: and it sorts numbers on strings correctly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7547032", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: FragmentActivity and Fragments: popBackStack My FragmentActivity manages 4 listfragments (for every listfragment I keep trace of its backstack ) within tabhost. The ListFragment shares a FrameLayout in which they attach their content. Every ListFragment when onListItemClick is fired let's the FragmentActivity start a new Fragment so that the content of the current fragment is replaced with the new fragment. If you call A the fragmetn currently showing (managed by ListFragment A) and B the fragment that would replace A (managed for instance by ListFragment B) happens when switching between fragment that the content A overlaps with the content of B, at least that i clear the backstack of the fragment switched off (A in the example). In order between fragment I do if (activeTab != tv) { if (activeTab != null) { Log.i(TAG, "tag: " + activeTab.getTag() + " detaching..."); FragmentInfo fragmentInfo = fragments.get(activeTab.getTag()); //detach the current fragment //getSupportFragmentManager().popBackStack((String)activeTab.getTag(), FragmentManager.POP_BACK_STACK_INCLUSIVE); ft.detach(fragmentInfo.fragment); } //get the new FragmentInfo fragmentInfo = fragments.get(tv.getTag()); Log.i(TAG, "tag: " + tv.getTag() + " fragment: " + fragmentInfo.mClass.getName()); if (fragmentInfo != null) { if (fragmentInfo.fragment == null) { fragmentInfo.fragment = Fragment.instantiate(this, fragmentInfo.mClass.getName(), fragmentInfo._args); ft.add(R.id.mytabcontent, fragmentInfo.fragment, fragmentInfo._tag); } else { Log.i(TAG, "attacching fragment: " + fragmentInfo.mClass.getName()); ft.attach(fragmentInfo.fragment); } } } while when I need to change the listfragment content when OnListemItemClick is fired I use private void replaceFragment(Fragment fragment, String tag, String backstack) { FragmentTransaction ft = manager.beginTransaction(); ft.replace(R.id.mytabcontent, fragment, tag); ft.setTransition(FragmentTransaction.TRANSIT_NONE); ft.addToBackStack(backstack); ft.commit(); } Could you please help me understand why? Thanks in advance and sorry for my bad english EDIT: my question is why I need to clear the backstack everytime I switch between ListFragment in order to avoid that content of the Fragment overlaps. What I am making wrong A: Ok, so this answer assumes you want to wipe each tabs back history every time you swap tabs. What I mean by that is Tab 1 starts on frag 1, then you click and change it to frag 2. If you select Tab 2, you will be undoing the history of Tab 1 and next time you click Tab 1 you will be back to frag 1. With that said here is the solution: Replace your onTabUnselected with the below public void onTabUnselected(Tab tab, FragmentTransaction ft) { if (mFragment != null) { //this segment removes the back history of everything in the tab you are leaving so when you click on the tab again you go back to a fresh start FragmentManager man = mActivity.getFragmentManager(); if(man.getBackStackEntryCount()>0) //this check is required to prevent null point exceptions when clicking off of a tab with no history man.popBackStack(man.getBackStackEntryAt(0).getName(), FragmentManager.POP_BACK_STACK_INCLUSIVE); //this pops the stack back to index 0 so you can then detach and then later attach your initial fragment //also it should be noted that if you do popbackstackimmediate here instead of just popbackstack you will see a flash as the gui changes back to the first fragment when the code executes //end ft.detach(mFragment); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7547043", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: trying to setup a basic join :has_many :through I have a basic Users / Memberships / Groups I want a user to navigate to the Groups#show if the user is logged in they are shown a "Join" button, if the user is not logged they are offered a link to the login/registration. I can handle the if logged in stuff using devise. The piece I don't know how to do is the Join... The real piece I am trying to figure out is the view code I think. I don't need anyone to write the code. just point me in the right direction and I'll figure it out... I have all the basic code for this setup. The the tables are created, the models exist... the relationship is instantiated. My current membership controller def create @membership = current_user.memberships.build(:group_id => params[:group_id]) if @membership.save flash[:notice] = "You have joined this group." redirect_to :back else flash[:error] = "Unable to join." redirect_to :back end end def destroy @membership = current_user.memberships.find(params[:id]) @membership.destroy flash[:notice] = "Removed membership." redirect_to :back end end any direction would be great A: You say you don't want the actual code, so here are a few pointers: * *You need a form. *This form needs to post to the create action you've shown in your question. *You need to post the correct group_id. Do you need any more pointers? Check out the Rails Guides, they're pretty good!
{ "language": "en", "url": "https://stackoverflow.com/questions/7547053", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Changing endianness in PHP So i'm making a class in PHP to parse the VPK file format. However i've hit a problem: object(VPKHeader)#2 (3) { ["Signature"]=> string(8) "3412aa55" ["Version"]=> string(4) "1000" ["DirectoryLength"]=> int(832512) } The signature is supposed to be 0x55aa1234, however the signature I'm reading is 0x3412aa55. How do I switch the endianness in PHP? A: If your hex values will always be strings, you can use the following function : function swapEndianness($hex) { return implode('', array_reverse(str_split($hex, 2))); } Agreed, it's not the most efficient, but the code is quite elegant in my opinion. Also, it works with all sizes of numbers. A: You have to convert the value manually. The algorithm will be the same as it is in C++, so just port this code (you only need the one that works on int afaik): inline void endian_swap(unsigned short& x) { x = (x>>8) | (x<<8); } // this is the one you need inline void endian_swap(unsigned int& x) { x = (x>>24) | ((x<<8) & 0x00FF0000) | ((x>>8) & 0x0000FF00) | (x<<24); } // __int64 for MSVC, "long long" for gcc inline void endian_swap(unsigned __int64& x) { x = (x>>56) | ((x<<40) & 0x00FF000000000000) | ((x<<24) & 0x0000FF0000000000) | ((x<<8) & 0x000000FF00000000) | ((x>>8) & 0x00000000FF000000) | ((x>>24) & 0x0000000000FF0000) | ((x>>40) & 0x000000000000FF00) | (x<<56); } Source: http://www.codeguru.com/forum/showthread.php?t=292902
{ "language": "en", "url": "https://stackoverflow.com/questions/7547056", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: SQL Server - DateTime Conversion field Issue Got following fields in table: Run Date : 2011-09-25 00:00:00.000 Run Time : 05:00:00 Run Duration : 03:22:51 What I need is in Dateformat Run Date + Run Time = Start Time of Job (DateTime Format) Run Date + (Run Time + Run Duration) = End Time of Job (DateTime Format) I'm struggling to do conversion. Can anyone please help. This is the STORED PROCEDURE which I'm using - can anyone advise how to monitor this: ALTER PROCEDURE [dbo].[Sp_listjobrunhistory] @dateparam DATETIME, @JobName VARCHAR(100) AS BEGIN SELECT --sysjobhistory.server, sysjobs.name AS job_name, CASE sysjobhistory.run_status WHEN 0 THEN 'Failed' WHEN 1 THEN 'Succeeded' ELSE '???' END AS run_status, CAST( Isnull(Substring(CONVERT(VARCHAR(8), run_date), 1, 4) + '-' + Substring(CONVERT(VARCHAR (8), run_date), 5, 2) + '-' + Substring(CONVERT(VARCHAR( 8), run_date), 7, 2), '') AS DATETIME) AS [Run DATE], Isnull(Substring(CONVERT(VARCHAR(7), run_time+1000000), 2, 2) + ':' + Substring(CONVERT(VARCHAR(7), run_time+1000000), 4, 2 ) + ':' + Substring(CONVERT(VARCHAR(7), run_time+1000000), 6, 2), '') AS [Run TIME], Isnull(Substring(CONVERT(VARCHAR(7), run_duration+1000000), 2, 2) + ':' + Substring(CONVERT(VARCHAR(7), run_duration+1000000), 4, 2) + ':' + Substring(CONVERT(VARCHAR(7), run_duration+1000000), 6, 2), '' ) AS [Duration], Isnull(Substring(CONVERT(VARCHAR(7), run_time+run_duration+1000000), 2, 2) + ':' + Substring(CONVERT(VARCHAR(7), run_time+run_duration+1000000), 4, 2 ) + ':' + Substring(CONVERT(VARCHAR(7), run_time+run_duration+1000000), 6, 2), '') AS [Total TIME], sysjobhistory.step_id, sysjobhistory.step_name, sysjobhistory.MESSAGE FROM msdb.dbo.sysjobhistory INNER JOIN msdb.dbo.sysjobs ON msdb.dbo.sysjobhistory.job_id = msdb.dbo.sysjobs.job_id WHERE sysjobhistory.run_date <= Datepart(yyyy, @dateparam) * 10000 + Datepart(mm, @dateparam) * 100 + Datepart ( dd, @dateparam) AND sysjobs.name = @JobName --remove this line if you want to show all jobs for the specified day ORDER BY instance_id DESC END Regards A: In SQL Server 2008, no conversion is required. declare @T table ( RunDate datetime, RunTime time, RunDuration time ) insert into @T values('2011-09-25 00:00:00.000', '05:00:00', '03:22:51') select RunDate + RunTime as StartTimeOfJob, RunDate + RunTime + RunDuration as EndTimeOfJob from @T And in versions before 2008 it could be like this. declare @T table ( RunDate datetime, RunTime varchar(8), RunDuration varchar(8) ) insert into @T values( '2011-09-25 00:00:00.000', '05:00:00', '03:22:51') select RunDate + RunTime as StartTimeOfJob, RunDate + RunTime + RunDuration as EndTimeOfJob from @T Ooops. No conversions needed there either. A: Here is the code to accomplish what you are looking for: create table dbo.RunDurationTest ( RunDate datetime not null, RunTime time not null, RunDuration time not null ) insert into rundurationtest values ('2011-09-25 00:00:00.000', '05:00:00', '03:22:51') select (RunDate + RunTime) as RunDateTime, (RunDate + RunTime + RunDuration) as EndRunDateTime, * from rundurationtest A: Assuming that the [Run Time] and [Run Duration] are varchar fields, I'd have the following: select StartJob = [Run Date] + convert(datetime, [Run Time]) select EndJob = StartJob + convert(datetime, [Run Duration])
{ "language": "en", "url": "https://stackoverflow.com/questions/7547060", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Store and display image file in Apache Cassandra I have read jpg/png file through string buffer using cassandra Hector APIs. Now i want to show that file on html page. Is there any way to show that file on html page without creating temporary file on local file system. Because I have set up Cassandra in Cluster mode and do not want to restrict me to one machine to store these temporary files. A: Since you have retrieved the image data, you have kind of service for serving the byte array of the image. You can map a servlet to certain URL(for ex. /imagepreview), in the URL you will have the id of the image. The id can be part of the path (in RESTful manner) or as URL parameter - it is your choice. Next in your HTML file you can add image tag "img" and the "src" attribute will have the URL to the servlet with certain image id. Like this : <img src="/imagepreview?id=83745"></img> Here is simplified path of serving the request: * *The servlet will "know" how to read the image id *it will use the image service to retrieve the image bytes *it will full-fill the HTTP response with the bytes and will set the necessary headers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7547061", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: how to safely replace all whitespaces with underscores with ruby? This works for any strings that have whitespaces in them str.downcase.tr!(" ", "_") but strings that dont have whitespaces just get deleted So "New School" would change into "new_school" but "color" would be "", nothing! A: Old question, but... For all whitespace you probably want something more like this: "hey\t there world".gsub(/\s+/, '_') # hey_there_world This gets tabs and new lines as well as spaces and replaces with a single _. The regex can be modified to suit your needs. E.g: "hey\t there world".gsub(/\s/, '_') # hey__there___world A: str.downcase.tr(" ", "_") Note: No "!" A: The docs for tr! say Translates str in place, using the same rules as String#tr. Returns str, or nil if no changes were made. I think you'll get the correct results if you use tr without the exclamation. A: If you're interested in getting a string in snake case, then the proposed solution doesn't quite work, because you may get concatenated underscores and starting/trailing underscores. For example 1.9.3-p0 :010 > str= " John Smith Beer " => " John Smith Beer " 1.9.3-p0 :011 > str.downcase.tr(" ", "_") => "__john___smith_beer_" This solution below would work better: 1.9.3-p0 :010 > str= " John Smith Beer " => " John Smith Beer " 1.9.3-p0 :012 > str.squish.downcase.tr(" ","_") => "john_smith_beer" squish is a String method provided by Rails A: str = "Foo Bar" str.tr(' ','').underscore => "foo_bar" A: If you are using rails 5 and above you can achieve the same thing with str.parameterize(separator: '_') A: Pass '_' as parameter to parameterize(separator: '-'). For Rails 4 and below, use str.parameterize('_') Examples: with space str = "New School" str.parameterize(separator: '_') => "new_school" without space str = "school" str.parameterize(separator: '_') => "school" You can also solve this by chaining underscore to parameterize. Examples: with space str = "New School" str.parameterize.underscore => "new_school" without space str = "school" str.parameterize.underscore => "school" A: You can also do str.gsub(" ", "_")
{ "language": "en", "url": "https://stackoverflow.com/questions/7547065", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "84" }
Q: Best way to store large amounts of different types of data? I want to store a buffer data. I will have to append data to data in the form of BYTEs, WORDs, and DWORDs. What is the best way to implement data? Is there something in the STL for this? A: From the little you've said, it sounds like you want to have different types in an STL container. There are two ways to do this: * *Have a hierarchy of objects and store a reference/pointer to them (i.e. std::vector< boost::shared_ptr<MyBaseObject> > *Use boost::variant (i.e. std::vector< boost::variant<BYTE, WORD, DWORD> >) If, however, you need to interface with some legacy C code, or send raw data over the network, this might not be the best solution. A: If you want to create a contiguous buffer of completely unstructured data, consider using std::vector<char>: // Add an item to the end of the buffer, ignoring endian issues template<class T> addToVector(std::vector<char>& v, T t) { v.insert(v.end(), reinterpret_cast<char*>(&t), reinterpret_cast<char*>(&t+1)); } // Add an item to end of the buffer, with consistent endianness template<class T> addToVectorEndian(std::vector<char>&v, T t) { for(int i = 0; i < sizeof(T); ++i) { v.push_back(t); t >>= 8; // Or, better: CHAR_BIT } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7547067", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can not use template argument in function declaration I'm struggling to find a good reason why the following code does not compile. It gives me the following error. Error 2 error C2923: 'std::pair' : 'std::set::iterator' is not a valid template type argument for parameter '_Ty1' I need a little insight, as to why C++ does not allow me to use the template parameter in the function declaration, because it I use set< int >::iterator instead of set< T >::iterator the program works. #include<iostream> #include<set> using namespace std; template <typename T> void print(const pair< set<T>::iterator, bool> &p) //<- Here is the problem { cout<<"Pair "<<*(p.first)<<" "<<p.second<<"\n"; } int main() { set<int> setOfInts; setOfInts.insert(10); pair<set<int>::iterator, bool > p = setOfInts.insert(30); } A: All you need is the "typename" keyword. Since your print function is templatized with T, you have to tell the compiler the set::iterator is not a value but a type. This is how. #include<iostream> #include<set> #include <utility> using namespace std; template <typename T> void print(const pair< typename set<T>::iterator, bool> &p) //<- Here is the problem { cout<<"Pair "<<*(p.first)<<" "<<p.second<<"\n"; } int main() { set<int> setOfInts; setOfInts.insert(10); pair<set<int>::iterator, bool > p = setOfInts.insert(30); } A: It seems you need the typename keyword before set<T>::iterator. This is because the compiler doesn't know that set<T>::iterator is a type, as set<T> is not a specific instantiation. set<T>::iterator could be anything and the compiler assumes it's a static member by default. So you need typename set<T>::iterator to tell him that iterator is a type. You don't need this for set<int> because that is a specific instantiation and the compiler knows about all its members. A: You need to tell the compiler that set<T>::iterator is a type. You do that using the typename keyword, as follows: void print(const pair< typename set<T>::iterator, bool> &p) //<- Here is the problem
{ "language": "en", "url": "https://stackoverflow.com/questions/7547068", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: updating user profile fields django Should be a simple answer but I can't figure out what's wrong here... I have a user profile with a couple of simple fields. I'm trying to update them like so: if data['dob'] != None: request.user.profile.dob = data['dob'] request.user.profile.save() This doesn't seem to have any effect at all though. p.s. i am using a nice little trick in my UserProfile class that looks like this: User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0]) Could this be part of the problem? A: It might be easier to use the suggested method of tying a profile to a django user: https://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users In the meantime, remove the [0] at the end of the UserProfile.objects.get_or_create(user=u) as that method only returns a single object regardless A: Think about what happens in your code. If there's a dob in your data, you call request.user.profile. This calls your property, which makes a request to the database and gets or creates a Profile instance. Next, you call request.user.profile again. Guess what this does? Makes a fresh call to the database, and gets an instance of the Profile again. But of course this is a new instance, even though it's referring to the same database row, so it won't have the value for dob you just set on the last version. Now, potentially you could solve this by storing the profile in a local variable: profile = request.user.profile profile.dob = data['dob'] profile.save() But to be honest, I'd drop the whole hacking around with the profile property. It's going to cause you all sorts of problems.
{ "language": "en", "url": "https://stackoverflow.com/questions/7547069", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Bookmarklet that adds a JavaScript function I am currently trying to make a bookmarklet that adds, among other things, a DIV element to the page. I'm doing this by adding the HTML code to body.innerHTML and that works fine. On this DIV element is a button that should allow to hide the added DIV. I therefore tried to add via JavaScript a JavaScript function to the innerHTML called function hideDiv(). The new JavaScript is added to the body and it looks fine. But it doesn't work. Short example: javascript:var b = document.body.InnerHTML; b=b+'<input type="button" onclick="javascript:alert("hello")"/>'; document.body.innerHTML = b; This bookmarklet should add a button that shows an alert if its clicked. It adds the button but nothing happens when clicking on it. Is this a general issue? Can JavaScript add (working) JavaScript to a page? A: I think you should set an id and then just add the function to the element. Like this: javascript:var b = document.body.InnerHTML; b=b+'<input type="button" id="test"/>'; document.body.innerHTML = b; document.getElementById('test').onclick = function () { alert('hi')} A: The javascript: prefix is only used in href attributes (or action for forms). It is NOT used in onclick or any other events. Remove the javascript: and your code should work fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7547074", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Create nested set model without top level item I'm creating a nested set model for a taxonomy database. Basically, I've re-created the same type of setup that wordpress uses for taxonomy, however instead of using parent_id for the term_taxonomy, I'd like to implement a nested set model for taxonomies that are hierarchical. The issue I'm finding is that terms aren't placed into the term_taxonomy table, until there is an actual term or category name. However, with a nested set model, you need one entry to be that top level item. Is it possible to do a nested set model, without having a top level? Instead you could have 5 top levels and subsets, etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7547077", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Matlab Generating a Matrix I am trying to generate a matrix in matlab which I will use to solve a polynomial regression formula. Here is how I am trying to generate the matrix: I have an input vector X containing N elements and an integer d. d is the integer to know how many times we will add a new column to the matrix we are trying to generate int he following way. N = [X^d X^{d-1} ... X^2 X O] O is a vector of same length as X with all 1's. Everytime d > 2 it does not work. Can you see any errors in my code (i am new to matlab): function [ PR ] = PolyRegress( X, Y, d ) O = ones(length(X), 1) N = [X O] for j = 2:d tmp = power(X, j) N = [tmp N] end %TO DO: compute PR end A: It looks like the matlab function vander already does what you want to do. A: The VANDER function will only generate powers of the vector upto d = length(X)-1. For a more general solution, you can use the BSXFUN function (works with any value of d): N = bsxfun(@power, X(:), d:-1:0) Example: >> X = (1:.5:2); >> d = 5; >> N = bsxfun(@power, X(:), d:-1:0) N = 1 1 1 1 1 1 7.5938 5.0625 3.375 2.25 1.5 1 32 16 8 4 2 1 I'm not sure if this is the order you want, but it can be easily reversed: use 0:d instead of d:-1:0...
{ "language": "en", "url": "https://stackoverflow.com/questions/7547080", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I declare a C++ prototype with a void * pointer so that it can take any pointer type? I want to create a function prototype in C++ so that there is a void * argument that can take pointers of any type. I know that this is possible in C. Is it possible in C++? [EDIT] Here is a simplified version of the code that I am trying to get to work: #include <stdio.h> void func(void (f)(const void *)) { int i = 3; (*f)(&i); } void func_i(const int *i) { printf("i=%p\n",i); } void func_f(const float *f) { printf("f=%p\n",f); } void bar() { func(func_i); } And here is the compiler output: $ g++ -c -Wall x.cpp x.cpp: In function ‘void bar()’: x.cpp:21: error: invalid conversion from ‘void (*)(const int*)’ to ‘void (*)(const void*)’ x.cpp:21: error: initializing argument 1 of ‘void func(void (*)(const void*))’ $ % A: You may use void*, just as with C, but you'll need to cast your argument when calling it. I suggest you use a template function template<typename T> void doSomething(T* t) {...} A: How about: void func(void *); exactly like in C? : P A: Yes. int i = 345; void * ptr = &i; int k = *static_cast&lt int* &gt(ptr); UPDATE :: What you have shown in the code certainly cannot be done in C++. Casting between void and any other must always be explicitly done. Check these SO link for more details on what the C -standard has to say: 1) http://stackoverflow.com/questions/188839/function-pointer-cast-to-different-signature 2) http://stackoverflow.com/questions/559581/casting-a-function-pointer-to-another-type
{ "language": "en", "url": "https://stackoverflow.com/questions/7547082", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cytoscape equivalent of graphviz URL/href node attribute when exporting SVG? In the past I've using graphviz's node "label", "URL" (or "href") and "tooltip" attributes to generate SVG graphics where the nodes have the text label, mouse-over displays the tooltip, and clicking the node (assuming your browser is displaying the svg) takes you to the URL target (and all those strings can be different). Right now I'm trying to generate the same sort of thing in Cytoscape. Exporting svg works nicely, but linkage of nodes to external URLs seems all tied up with Cytoscape's "linkout" feature; while this seems very powerful while you're actually using Cytoscape, it's not clear to me whether there's some way of getting it to produce clickable nodes or labels (I'd settle for either) in an exported SVG. The URLs I want to link to are a node attribute of my imported graph. Is there something I'm missing in Cytoscape which will create links in exported SVG ? Any suggestions for alternative approaches ? e.g some way of getting labels to be arbitrary HTML including <a href=...>...</a> ? My "plan B" is to postprocess the exported SVG, but it'd be nicer to have Cytoscape do it all. A: So far as my further use of the tool permitted me to determine, Cytoscape just doesn't have this capability.
{ "language": "en", "url": "https://stackoverflow.com/questions/7547083", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Getting the status of the phone I have a remote service wich my phone is talking to. When Application_Deactivated gets called it doesn't have enough time to notify the service that is has gone into 'tombstoned' state. How can my service know wether the device is active or tombstoned? Edit: I could imagine polling the service with my phone and when the service doesn't receive any events it will set the phone's status to tombstoned. But that would mean a massive increase in traffic.
{ "language": "en", "url": "https://stackoverflow.com/questions/7547085", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use LocationListener without "implements LocationListener"? i finally reached an app that get's the GPS position of the user, but i reached it implementing LocationListener. it works fine, but i need to do it without implementing it, because i have to do a class that doesn't implement methods. I searched for a lot of tutorials and check a lot of websites and i try to transform my code to not implement LocationListener but i can't do it, every thing i tested broken my app and stop getting the GPS position of the user. Please, if someone expert on this can transform my code for not be using "implements LocationListener" i'll be grated to him this is the code to transform: public class GpsMiniActivity extends Activity implements LocationListener{ private LocationManager mLocMgr; private TextView tv1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FrameLayout rl = new FrameLayout(this.getApplicationContext()); LinearLayout ll= new LinearLayout(this.getApplicationContext()); ll.setOrientation(LinearLayout.VERTICAL); setContentView(rl); rl.addView(ll); tv1=new TextView(getApplicationContext()); ll.addView(tv1); //setContentView(R.layout.main); mLocMgr = (LocationManager) getSystemService(LOCATION_SERVICE); mLocMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 0, this); } @Override public void onLocationChanged(Location location) { tv1.setText("Lat " + location.getLatitude() + " Long " + location.getLongitude()); } public void onProviderDisabled(String provider) {} public void onProviderEnabled(String provider) {} public void onStatusChanged(String provider, int status, Bundle extras) {} } A: public class GpsMiniActivity extends Activity { private LocationManager mLocMgr; private TextView tv1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FrameLayout rl = new FrameLayout(this.getApplicationContext()); LinearLayout ll= new LinearLayout(this.getApplicationContext()); ll.setOrientation(LinearLayout.VERTICAL); setContentView(rl); rl.addView(ll); tv1=new TextView(getApplicationContext()); ll.addView(tv1); //setContentView(R.layout.main); mLocMgr = (LocationManager) getSystemService(LOCATION_SERVICE); mLocMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 0, ll); } } private LocationListener ll = new LocationListener(){ public void onLocationChanged(Location location) { tv1.setText("Lat " + location.getLatitude() + " Long " + location.getLongitude()); } public void onProviderDisabled(String provider) {} public void onProviderEnabled(String provider) {} public void onStatusChanged(String provider, int status, Bundle extras) {} } } There you go. A: For that you will have to create a seperate LocationListener outside the onCreate() and give the reference of it to the LocationManager's requestLocationUpdates like this LocationListener mLocationListener = new LocationListener() { @Override public void onStatusChanged(String provider, int status, Bundle extras) {} @Override public void onProviderEnabled(String provider) {} @Override public void onProviderDisabled(String provider) {} @Override public void onLocationChanged(Location location) { tv1.setText("Lat " + location.getLatitude() + " Long " + location.getLongitude()); } }; And after that you will have to reference this LocationListener like this inside the onCreate() mLocMgr = (LocationManager) getSystemService(LOCATION_SERVICE); mLocMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 0, mLocationListener);
{ "language": "en", "url": "https://stackoverflow.com/questions/7547094", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How does Amazon EC2 Auto Scaling work? I am trying to understand how Amazon implements the auto scaling feature. I can understand how it is triggered but I don't know what exactly happens during the auto scaling. How does it expand. For instance, If I set the triggering condition as cpu>90. Once the vm's cpu usage increases above 90: * *Does it have a template image which will be copied to the new machine and started? *How long will it take to start servicing the new requests ? *Will the old vm have any downtime ? I understand that it has the capability to provide load balancing between the VMs. But, I cannot find any links/paper which explains how Amazon auto scaling works. It will be great if you can provide me some information regarding the same. Thank you. A: Essentially, in the set up you register an AMI, and a set of EC2 start parameters - a launch configuration (Instance size, userdata, security group, region, availability zone etc) You also set up scaling policies. * *Your scaling trigger fires *Policies are examined to determine which launch configuration pplies *ec2 run instance is called with the registered AMI and the launch configuration parameters. At this point, an instance is started which is a combination of the AMI and the launch configuration. It registers itself with an IP address into the AWS environment. As part of the initial startup (done by ec2config or ec2run - going from memory here) - the newly starting instance can connect to instance meta data and run the script stored in "userdata". This script can bootstrap software installation, operating system configuration, settings, anything really that you can do with a script. Once it's completed, you've got a newly created instance. Now - if this process was kicked off by auto-scale and elastic-load-balancing, at the point that the instance is "Windows is ready" (Check ec2config.log), the load balancer will add the instance to itself. Once it's responding to requests, it will be marked healthy, and the ELB will start routing traffic. The gold standard is to have a generic AMI, and use your bootstrap script to install all the packages / msi's / gems or whatever you need onto the server. But what often happens is that people build a golden image, and register that AMI for scaling. The downside to the latter method is that every release requires a new AMI to be created, and the launch configurations to be updated. Hope that gives you a bit more info. A: may be this can help you http://www.cardinalpath.com/autoscaling-your-website-with-amazon-web-services-part-2/ http://www.cardinalpath.com/autoscaling-your-website-with-amazon-web-services-part-1/ this post helped me achiving this A: Have a read of this chaps blog, it helped me when I doing some research on the subject. http://www.codebelay.com/blog/2009/08/02/how-to-load-balance-and-auto-scale-with-amazons-ec2/
{ "language": "en", "url": "https://stackoverflow.com/questions/7547097", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Flash AS3: How to prevent MouseEvent.MOUSE_OUT when you mouse_over a child sprite All, Here's my situation... The UI of my Flash application is a grid. Each row of the grid is a sprite that contains a number of child sprites (UI controls) that respond to mouse events Each row of the grid should have a hover effect - i.e., when you hover over the row, the row's background should change color. This is accomplished easily: rowSprite.addEventListener(MouseEvent.MOUSE_OVER, highlightRow, false, 0, true); rowSprite.addEventListener(MouseEvent.MOUSE_OUT, unhighlightRow, false, 0, true); This works fine, EXCEPT that when the user rolls over any of the row's child sprites, the row's MOUSE_OUT event is fired, and the row is "unhighlighted". This isn't what I want. In other words - I'd like the row to be unhighlighted only when you roll OUTSIDE of the row, not when you roll over a child sprite within the row. A possible solution: in the unhighlightRow function, test whether the user's mouse position is still within the row sprites bounds. But I'm guessing that's not the most elegant or efficient solution. This must be an incredibly common problem. What's the best solution? Thanks in advance! A: You can use ROLL_OVER and ROLL_OUT instead of MOUSE_OVER and MOUSE_OUT in such cases: http://kinderas.blogspot.com/2008/12/quicktip-mouseover-vs-rollover.html A: Yes, it is a very common problem, and Adobe have provided a solution. You can use the mouseChildren property - set it to false to prevent children generating (yes, generating) mouse related events, which in your case will rid you from unwanted mouseOut events as there would be no correspoding mouseOver event generated when your cursor enters a childs area. mouseChildren is available for DisplayObjectContainer objects. http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/DisplayObjectContainer.html#mouseChildren A: rowSprite.addEventListener(MouseEvent.MOUSE_OVER, highlightRow, false, 0, true); rowSprite.addEventListener(MouseEvent.MOUSE_OUT, unhighlightRow, false, 0, true); function unhighlightRow (e:MouseEvent):void { if(Sprite(e.target).contains(e.currentTarget)) { return } } didn't test it but it should work A: To disable the children from receiving mouse events set. That would fix your problem: rowSprite.mouseChildren = false;
{ "language": "en", "url": "https://stackoverflow.com/questions/7547098", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }