Search Results

Search found 834 results on 34 pages for 'looping'.

Page 24/34 | < Previous Page | 20 21 22 23 24 25 26 27 28 29 30 31  | Next Page >

  • Optimising RSS parsing on App Engine to avoid high CPU warnings

    - by Danny Tuppeny
    I'm pulling some RSS feeds into a datastore in App Engine to serve up to an iPhone app. I use cron to schedule updating the RSS every x minutes. Each task only parses one RSS feed (which has 15-20 items). I frequently get warnings about high CPU usage in the App Engine dashboard, so I'm looking for ways to optimise my code. Currently, I use minidom (since it's already there on App Engine), but I suspect it's not very efficient! Here's the code: dom = minidom.parseString(urlfetch.fetch(url).content) if dom: items = [] for node in dom.getElementsByTagName('item'): item = RssItem( key_name = self.getText(node.getElementsByTagName('guid')[0].childNodes), title = self.getText(node.getElementsByTagName('title')[0].childNodes), description = self.getText(node.getElementsByTagName('description')[0].childNodes), modified = datetime.now(), link = self.getText(node.getElementsByTagName('link')[0].childNodes), categories = [self.getText(category.childNodes) for category in node.getElementsByTagName('category')] ); items.append(item); db.put(items); def getText(self, nodelist): rc = '' for node in nodelist: if node.nodeType == node.TEXT_NODE: rc = rc + node.data return rc There isn't much going on, but the scripts often take 2-6 seconds CPU time, which seems a bit excessive for looping through 20ish items and reading a few attributes. What can I do to make this faster? Is there anything particularly bad in the above code, or should I change to another way of parsing? Are there are any libraries (that work on App Engine) that would be better, or would I be better parsing the RSS myself?

    Read the article

  • Designing a fluent Javascript interface to abstract away the asynchronous nature of AJAX

    - by Anurag
    How would I design an API to hide the asynchronous nature of AJAX and HTTP requests, or basically delay it to provide a fluid interface. To show an example from Twitter's new Anywhere API: // get @ded's first 20 statuses, filter only the tweets that // mention photography, and render each into an HTML element T.User.find('ded').timeline().first(20).filter(filterer).each(function(status) { $('div#tweets').append('<p>' + status.text + '</p>'); }); function filterer(status) { return status.text.match(/photography/); } vs this (asynchronous nature of each call is clearly visible) T.User.find('ded', function(user) { user.timeline(function(statuses) { statuses.first(20).filter(filterer).each(function(status) { $('div#tweets').append('<p>' + status.text + '</p>'); }); }); }); It finds the user, gets their tweet timeline, filters only the first 20 tweets, applies a custom filter, and ultimately uses the callback function to process each tweet. I am guessing that a well designed API like this should work like a query builder (think ORMs) where each function call builds the query (HTTP URL in this case), until it hits a looping function such as each/map/etc., the HTTP call is made and the passed in function becomes the callback. An easy development route would be to make each AJAX call synchronous, but that's probably not the best solution. I am interested in figuring out a way to make it asynchronous, and still hide the asynchronous nature of AJAX.

    Read the article

  • std::vector iterator or index access speed question

    - by Simone Margaritelli
    Just a stupid question . I have a std::vector<SomeClass *> v; in my code and i need to access its elements very often in the program, looping them forward and backward . Which is the fastest access type between those two ? Iterator access std::vector<SomeClass *> v; std::vector<SomeClass *>::iterator i; std::vector<SomeClass *>::reverse_iterator j; // i loops forward, j loops backward for( i = v.begin(), j = v.rbegin(); i != v.end() && j != v.rend(); i++, j++ ){ // some operations on v items } Subscript access (by index) std::vector<SomeClass *> v; unsigned int i, j, size = v.size(); // i loops forward, j loops backward for( i = 0, j = size - 1; i < size && j >= 0; i++, j-- ){ // some operations on v items } And, does const_iterator offer a faster way to access vector elements in case i do not have to modify them? Thank you in advantage.

    Read the article

  • Is there a PHP benchmark that meets these specific criteria? [closed]

    - by Alex R
    I'm working on a tool which converts PHP code to Scala. As one of the finishing touches, I'm in need of a really good (er, somewhat biased) benchmark. By dumb luck my first benchmark attempt was with some code which uses bcmath extensively, which unfortunately is 1000x slower in Java, making the Scala code 22x slower overall than the original PHP. So I'm looking for some meaningful PHP benchmark with the following characteristics: The PHP source needs to be in a single file. It should solve a real-world problem. No silly looping over empty methods etc. I need it to be simple to setup - no databases, hard-to-find input files, etc. Simple text input and output preferred. It should not use features that are slow in Java (BigInteger, trigonometric functions, etc). It should not use exoteric or dynamic PHP functions (e.g. no "eval" or "variable vars"). It should not over-rely on built-in libraries, e.g. MD5, crypt, etc. It should not be I/O bound. A CPU-bound memory-hungry algorithm is preferred. Basically, intensive OO operations, integer and string manipulation, recursion, etc would be great. Thanks

    Read the article

  • Save QList<int> to QSettings

    - by Tobias
    Hello, I want to save a QList<int> to my QSettings without looping through it. I know that I could use writeArray() and a loop to save all items or to write the QList to a QByteArray and save this but then it is not human readable in my INI file.. Currently I am using the following to transform my QList<int> to QList<QVariant>: QList<QVariant> variantList; //Temp is the QList<int> for (int i = 0; i < temp.size(); i++) variantList.append(temp.at(i)); And to save this QList<Variant> to my Settings I use the following code: QVariant list; list.setValue(variantList); //saveSession is my QSettings object saveSession.setValue("MyList", list); The QList is correctly saved to my INI file as I can see (comma seperated list of my ints) But the function crashes on exit. I already tried to use a pointer to my QSettings object instead but then it crashes on deleting the pointer ..

    Read the article

  • Android Loading listview items from service results in hang

    - by Isaac Waller
    Hello, In my Android application, I have a ListActivity. This ListActivity uses a SimpleAdapter that I fill with items from my service. So, in my code, I do: MySuperCoolService.Binder serviceBinder = null; private ServiceConnection serviceConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { Log.d(TAG, "Service connection: connected!"); serviceBinder = (MySuperCoolService.Binder)service; } public void onServiceDisconnected(ComponentName className) { Log.d(TAG, "Service connection: disconnected"); serviceBinder = null; } }; bindService(new Intent(this, MySuperCoolService.class), serviceConnection, BIND_AUTO_CREATE); while(serviceBinder==null) { Thread.Sleep(1000); } // now retrieve from service using binder and set list adapter This whole operation takes hardly any time (less than a second), so I want it to run in the UI thread. See my onCreate: public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); fillDataUsingCodeAbove(); } The reason I want this to run in the UI thread is that if you have a list item selected, or you have scrolled to a certain position in the ListView, and you rotate the device or take out the keyboard or something (to trigger a configuration change) when my activity is restarted, Android will try to restore the state right after onCreate. But, if I run it in a separate thread, it will not. Also there is a cool fadein animation too :) The problem I am having with running it in the UI thread is that when I try to bind to the service, that service bind request gets put onto the message queue. But then when I go into my loop, I stop the message queue from looping. So my program hangs, because it's waiting for the service to get bound, and the service won't get bound until the loop ends. I have thought of putting Looper.loop() inside my loop, but that just hangs it at Looper.loop() (I don't know why.) Sorry for such a long question, Isaac Waller

    Read the article

  • Alternative Control Structures

    - by Brock Woolf
    I've been wondering about alternative ways to write control structures. One that you learn early on for if statements is a replacement for this: if ( x ) { // true } else { // false } with this (sometimes this is more readable compared to lots of brackets): x ? true : false It got me thinking. Can we replace anything else incase it's more readable. We of course replace if statements like this: if (a < b) { return true; } else { return false; } with things like this: return a < b; We can save a long if with something like this (pretty much same as the one above): bool xCollisionTrue = (object.xPos < aabb.maxX && object.xPos > aabb.minX); So those are the ones I can think of off the top of my head for the if statement and doing comparisons. So I'm wondering what about looping constructs, for, while, etc. Maybe the code obfuscators might have some ideas.

    Read the article

  • Dynamic Table CheckBoxes not having a "Checked" true value

    - by LuvlyOvipositor
    I have been working on a web app using ASP.NET with the code base as C#. I have a dynamic table that resizes based on a return from a SQL query; with a check box added in the third cell of each row. The checkbox is assigned an ID according to an index and the date. When users hit the submit button, the code is supposed to get a value from each row that is checked. However, when looping through the rows, none of the check boxes ever have a value of true for the Checked property. The ID persists, but the value of the checkbox seems to be lost. Code for adding the Checkboxes: cell = new TableCell(); CheckBox cb = new CheckBox(); cell.ApplyStyle(TS); cb.ID = index.ToString() + " " + lstDate.SelectedItem.Text.ToString(); if (reader["RestartStatus"].ToString() == "0") { cb.Checked = false; cb.Enabled = true; } else { cb.Checked = true; } cell.Controls.Add(cb); The code for getting the checkbox value: for (int i = 0; i < CompTable.Rows.Count; i++) { int t3 = CompTable.Rows[i].Cells[2].Controls.Count; Control temp = null; if (t3 0) { temp = CompTable.Rows[i].Cells[2].Controls[0]; } string t2 = i.ToString() + " " + lstDate.SelectedItem.Text.ToString(); if ( temp != null && ((CheckBox)temp).ID == i.ToString() + " " + lstDate.SelectedItem.Text.ToString()) { //Separated into 2 if statements for debugging purposes //ID is correct, but .Checked is always false (even if all of the boxes are checked) if (((CheckBox)temp).Checked == true) { tlist.Add(CompTable.Rows[i].Cells[0].Text.ToString()); } } }

    Read the article

  • C#JSON serialization

    - by Bridget the Midget
    I'm trying out the HighStock library for creating stock charts. To fill the chart with data, their example specifies this source. The first parameter is unixtime in milliseconds and the second parameter is the stock closing price. I don't know if this is valid json, but I would argue that the following would be a more appropriate way of writing json. [{"Closing":63.15000,"Date":1262559600000},{"Closing":64.75000,"Date":1262646000000}, ... I guess that I have no other option than to adapt to HighStocks syntax. I could solve this by looping and add correct syntax to a string, but that seems rudimentary. Would it be more wise to serialize C# objects to create my json, and if that's the case - how can I reach the syntax specified in the example? Lets just say this is my c# object: public class Quote { public double Date { get; set; } public decimal Closing { get; set; } } Am I making it unnecessary complex? Should I just format a json string?

    Read the article

  • dynamic check_box using field_for in rails

    - by Craig Whitley
    I have a many-to-many relationship with a link box, and I want to pull those models together into one form so I can update from the same page. I'm really struggling with getting the check_box to even show all the elements of my array - I've scoured the net and been working on this literally all day, and I'm finding it difficult to apply the information I'm reading to my problem. I'm also extremely new to RoR and I've been following a bit of an outdated video tutorial (pre 2.0) so apologies for my code. So far, I've got it to output only one key pair in the array (the last one) - although outside the form, the code used in the tutorial works exactly how it should. Thats of little use though! Host is the model for which the main form is for, and Billing is the outside model that I'm trying to add to the form. This is the code that works outside of the form from the tutorial: <% for billing in @billings -%> <%= check_box_tag('billing_title[]', billing.id, @host.billings.collect {|obj| obj.id}.include?(billing.id))%> <%= billing.title %><br /> <% end -%> I just need to know how to make it work inside the form. This is the aforementioned code that only retrieves the last array keypair after looping through them: <% f.fields_for :billings do |obj| %><br /> <%= check_box_tag('billing_title[]', billing.id, @billings.collect {|obj| obj.id}.include?(billing.id))%> <%= billing.title %><br /> <% end %> The debug(@billings) : --- - !ruby/object:Billing attributes: title: Every Month id: "1" attributes_cache: {} - !ruby/object:Billing attributes: title: 12 Months id: "2" attributes_cache: {} - !ruby/object:Billing attributes: title: 6 Months id: "5" attributes_cache: {} Any help really appreciated.

    Read the article

  • for loop not suitable?

    - by Luke
    I have created a for loop. I am trying to loop through lots of members and create a row for each member in a table. It's looping through too many times. Is it the right type of loop to use? <?php for ($i = 1; $i = count($u); $i++) { ?> <tr> <?php echo "<td>$i</td>"; ?> <?php foreach ($u as $username) { echo "<td>$username</td>"; } ?> <?php foreach ($p as $points) { echo "<td>$points</td>"; } ?> </tr> <? } ?> $u and $p are arrays. Thanks

    Read the article

  • What is the best way to determine the path to the ISV directory?

    - by Luke Baulch
    MSCRM 4.0 Problem: I'm currently storing xml files in the ISV directory along with my web applications. From a plugin (or potentially a seperate app), I need to find an easy way to navigate to the ISV directory to read these xml files. This routine will be called extremely often, so processing minimization should be a strong consideration. Potential solutions: Registry: There is a registry key called 'WebSitePath' with the data 'C:\Inetpub\wwwroot\CRM'. Could potentially use this to build the path. (Will this be the same on all systems/installations?) IIS directory data: Looping through the DirectoryEntries of path '"IIS://localhost/W3SVC"' I could obtain the the web application where description is equal to "Microsoft Dynamics CRM". (Will this be the same on all systems/installations?) Webservice: Create one to read and return the data contained in these xml files The webservice would have easy access to its executing directory. Database: Store the data of these files in the database. Help: Can anyone suggest a simpler solution to obtaining and reading a file from the ISV directory? If not, which of the above solutions would be the quickest to process? Thanks for any and all contributions.

    Read the article

  • String.Format Phone Numbers with Extension

    - by ChiliYago
    I am trying to create a an function that formats US phone numbers -- hopefully without looping through each digit. When 10 digits are passed in all is fine. How ever when more than 10 digits are passed in I want the String.Format method to append the extension digits on the right. For example: When 14 digits passed in the result should be:(444)555-2222 x8888 When 12 digits passed in the result should be:(444)555-2222 x88 etc. However what I get with my current attempt is: Passing in 12 digits returns this string '() -949 x555444433' here is what I have so far. public static string _FormatPhone(object phonevalue) { Int64 phoneDigits; if (Int64.TryParse(phonevalue.ToString(), out phoneDigits)) { string cleanPhoneDigits = phoneDigits.ToString(); int digitCount = cleanPhoneDigits.Length; if (digitCount == 10) return String.Format("{0:(###) ###-####}", phoneDigits); else if (digitCount > 10) return String.Format("{0:(###) ###-#### x#########}", phoneDigits); else return cleanPhoneDigits; } return "Format Err#"; } Thanks in advance.

    Read the article

  • What is the correct way to create dynamic javascript in ASP.net MVC2?

    - by sabbour
    I'm creating a Google Maps partial view/user control in my project that is passed a strongly typed list of objects containing latitude and longitude values. Currently, this is the code I have for the partial: <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<Project.Models.Entities.Location>>" %> <!-- Place for google to put the map --> <div id="report_map_canvas" style="width: 100%; height: 728px; margin-bottom: 2px;"> </div> <script type='text/javascript'> google.load("maps", "2"); $(document).ready(initializeMap); function initializeMap() { if (GBrowserIsCompatible()) { var map = new GMap2(document.getElementById('report_map_canvas')); map.setCenter(new GLatLng(51.5, -0.1167), 2); <% foreach (var item in Model) { %> map.addOverlay(new GMarker(new GLatLng('<%= Html.Encode(item.latitude)%>','<%= Html.Encode(item.longitude)%>'),{ title: '<%= Html.Encode(String.Format("{0:F}",item.speed)) %> km/h '})); <% } %> map.setUIToDefault(); } } </script> Is it right to dynamically create the javascript file this way by looping over the list and emitting javascript? Is there a better way to do it?

    Read the article

  • Why avoid increment ("++") and decrement ("--") operators in JavaScript?

    - by artlung
    I'm a big fan of Douglas Crockford's writing on JavaScript, particularly his book JavaScript: The Good Parts. It's made me a better JavaScript programmer and a better programmer in general. One of his tips for his jslint tool is this : ++ and -- The ++ (increment) and -- (decrement) operators have been known to contribute to bad code by encouraging excessive trickiness. They are second only to faulty architecture in enabling to viruses and other security menaces. There is a plusplus option that prohibits the use of these operators. This has always struck my gut as "yes, that makes sense," but has annoyed me when I've needed a looping condition and can't figure out a better way to control the loop than a while( a < 10 )do { a++ } or for (var i=0;i<10;i++) { } and use jslint. It's challenged me to write it differently. I also know in the distant past using things, in say PHP like $foo[$bar++] has gotten me in trouble with off-by-one errors. Are there C-like languages or other languages with similarities that that lack the "++" and "--" syntax or handle it differently? Are there other rationales for avoiding "++" and "--" that I might be missing? UPDATE -- April 9, 2010: In the video Crockford on JavaScript -- Part 5: The End of All Things, Douglas Crockford addresses the ++ issue more directly and with more detail. It appears at 1:09:00 in the timeline. Worth a watch.

    Read the article

  • Using multiple sockets, is non-blocking or blocking with select better?

    - by JPhi1618
    Lets say I have a server program that can accept connections from 10 (or more) different clients. The clients send data at random which is received by the server, but it is certain that at least one client will be sending data every update. The server cannot wait for information to arrive because it has other processing to do. Aside from using asynchronous sockets, I see two options: Make all sockets non-blocking. In a loop, call recv on each socket and allow it to fail with WSAEWOULDBLOCK if there is no data available and if I happen to get some data, then keep it. Leave the sockets as blocking. Add all sockets to a fd_set and call select(). If the return value is non-zero (which it will be most of the time), loop through all the sockets to find the appropriate number of readable sockets with FD_ISSET() and only call recv on the readable sockets. The first option will create a lot more calls to the recv function. The second method is a bigger pain from a programming perspective because of all the FD_SET and FD_ISSET looping. Which method (or another method) is preferred? Is avoiding the overhead on letting recv fail on a non-blocking socket worth the hassle of calling select()? I think I understand both methods and I have tried both with success, but I don't know if one way is considered better or optimal. Only knowledgeable replies please!

    Read the article

  • Enumerating a string

    - by JamesB
    I have a status which is stored as a string of a set length, either in a file or a database. I'm looking to enumerate the possible status' I have the following type to define the possible status' Type TStatus = (fsNormal = Ord('N'),fsEditedOnScreen = Ord('O'), fsMissing = Ord('M'),fsEstimated = Ord('E'),fsSuspect = Ord('s'), fsSuspectFromOnScreen = Ord('o'),fsSuspectMissing = Ord('m'), fsSuspectEstimated = Ord('e')); Firstly is this really a good idea? or should I have a seperate const array storing the char conversions? That would mean more than one place to update. Now convert a string to a status array I have the following, but how can I check if a char is valid without looping through the enumeration? Function StrToStatus(Value : String):TStatusArray; var i: Integer; begin if Trim(Value) = '' then begin SetLength(Result,0); Exit; end; SetLength(Result,Length(Value)); for i := 1 to Length(Value) do begin Result[i] := TStatus(Value[i]); // I don't think this line is safe. end; end; AFAIK this should be fine for converting back again. Function StatusToStr(Value : TStatusArray):String; var i: Integer; begin for i := 0 to Length(Value) - 1 do Result := Result + Chr(Ord(Value[i])) end; I'm using Delphi 2007

    Read the article

  • Java Performance measurement

    - by portoalet
    Hi, I am doing some Java performance comparison between my classes, and wondering if there is some sort of Java Performance Framework to make writing performance measurement code easier? I.e, what I am doing now is trying to measure what effect does it have having a method as "synchronized" as in PseudoRandomUsingSynch.nextInt() compared to using an AtomicInteger as my "synchronizer". So I am trying to measure how long it takes to generate random integers using 3 threads accessing a synchronized method looping for say 10000 times. I am sure there is a much better way doing this. Can you please enlighten me? :) public static void main( String [] args ) throws InterruptedException, ExecutionException { PseudoRandomUsingSynch rand1 = new PseudoRandomUsingSynch((int)System.currentTimeMillis()); int n = 3; ExecutorService execService = Executors.newFixedThreadPool(n); long timeBefore = System.currentTimeMillis(); for(int idx=0; idx<100000; ++idx) { Future<Integer> future = execService.submit(rand1); Future<Integer> future1 = execService.submit(rand1); Future<Integer> future2 = execService.submit(rand1); int random1 = future.get(); int random2 = future1.get(); int random3 = future2.get(); } long timeAfter = System.currentTimeMillis(); long elapsed = timeAfter - timeBefore; out.println("elapsed:" + elapsed); } the class public class PseudoRandomUsingSynch implements Callable<Integer> { private int seed; public PseudoRandomUsingSynch(int s) { seed = s; } public synchronized int nextInt(int n) { byte [] s = DonsUtil.intToByteArray(seed); SecureRandom secureRandom = new SecureRandom(s); return ( secureRandom.nextInt() % n ); } @Override public Integer call() throws Exception { return nextInt((int)System.currentTimeMillis()); } } Regards

    Read the article

  • how to continuously send data without blocking?

    - by Donal Rafferty
    I am trying to send rtp audio data from my Android application. I currently can send 1 RTP packet with the code below and I also have another class that extends Thread that listens to and receives RTP packets. My question is how do I continuously send my updated buffer through the packet payload without blocking the receiving thread? public void run() { isRecording = true; android.os.Process.setThreadPriority (android.os.Process.THREAD_PRIORITY_URGENT_AUDIO); int buffersize = AudioRecord.getMinBufferSize(8000, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT); Log.d("BUFFERSIZE","Buffer size = " + buffersize); arec = new AudioRecord(MediaRecorder.AudioSource.MIC, 8000, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, buffersize); short[] readBuffer = new short[80]; byte[] buffer = new byte[160]; arec.startRecording(); while(arec.getRecordingState() == AudioRecord.RECORDSTATE_RECORDING){ int frames = arec.read(readBuffer, 0, 80); @SuppressWarnings("unused") int lenghtInBytes = codec.encode(readBuffer, 0, buffer, frames); RtpPacket rtpPacket = new RtpPacket(); rtpPacket.setV(2); rtpPacket.setX(0); rtpPacket.setM(0); rtpPacket.setPT(0); rtpPacket.setSSRC(123342345); rtpPacket.setPayload(buffer, 160); try { rtpSession2.sendRtpPacket(rtpPacket); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (RtpException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } So when I send on one device and receive on another I get decent audio, but when I send and receive on both I get broken sound like its taking turns to send and receive audio. I have a feeling it could be to do with the while loop? it could be looping around in there and not letting anything else run?

    Read the article

  • C#: Accessing PerformanceCounters for the ".NET CLR Memory category"

    - by Mads Ravn
    I'm trying to access the performance counters located in ".NET CLR Memory category" through C# using the PerformanceCounter class. However a cannot instantiate the categories with what I would expect was the correct category/counter name new PerformanceCounter(".NET CLR Memory", "# bytes in all heaps", Process.GetCurrentProcess().ProcessName); I tried looping through categories and counters using the following code string[] categories = PerformanceCounterCategory.GetCategories().Select(c => c.CategoryName).OrderBy(s => s).ToArray(); string toInspect = string.Join(",\r\n", categories); System.Text.StringBuilder interestingToInspect = new System.Text.StringBuilder(); string[] interestingCategories = categories.Where(s => s.StartsWith(".NET") || s.Contains("Memory")).ToArray(); foreach (string interestingCategory in interestingCategories) { PerformanceCounterCategory cat = new PerformanceCounterCategory(interestingCategory); foreach (PerformanceCounter counter in cat.GetCounters()) { interestingToInspect.AppendLine(interestingCategory + ":" + counter.CounterName); } } toInspect = interestingToInspect.ToString(); But could not find anything that seems to match. Is it not possible to observe these values from within the CLR or am I doing something wrong. The environment, should it matter, is .NET 4.0 running on a 64-bit windows 7 box.

    Read the article

  • How do I combine two arrays in PHP based on a common key?

    - by Eoghan O'Brien
    Hi, I'm trying to join two associative arrays together based on an entry_id key. Both arrays come from individual database resources, the first stores entry titles, the second stores entry authors, the key=value pairs are as follows: array ( 'entry_id' => 1, 'title' => 'Test Entry' ) array ( 'entry_id' => 1, 'author_id' => 2 I'm trying to achieve an array structure like: array ( 'entry_id' => 1, 'author_id' => 2, 'title' => 'Test Entry' ) Currently, I've solved the problem by looping through each array and formatting the array the way I want, but I think this is a bit of a memory hog. $entriesArray = array(); foreach ($entryNames as $names) { foreach ($entryAuthors as $authors) { if ($names['entry_id'] === $authors['entry_id']) { $entriesArray[] = array( 'id' => $names['entry_id'], 'title' => $names['title'], 'author_id' => $authors['author_id'] ); } } } I'd like to know is there an easier, less memory intensive method of doing this?

    Read the article

  • Loop XML including all its children using xpath and SimpleXMLElement

    - by Andersson
    Im having a big xml tree with a simple structure. All I want to do is get a node by its attribute using xpath and loop the children. param1 - correct language param1 & param3 - correct node by its id and the parents id. (Need to use parent id when multiplie id appears. The id is not declared as id in DTD) public function getSubmenuNodesRe($language, $id1,$id2) { $result = $this->xml->xpath("//*[@language='$language']//*[@id='$id1']//menuitem[@id='$id2']/*"); return $result; } This works well, I get the node Im expecting. I having no problems looping the array returned by the xpath query. But when i try to loop childnodes all attributes are gone and many of the methods also. Except getName(). function printNodeName($node) { echo $node->getName(). " - \"" . $node['id']. "\"<br>"; if($node->children()->getName() == "menuitem") { $s = $node->children(); printNodeName($s); } } $result = $xmlNode->getSubmenuNodesRe($_GET['language'], 'foo','bar'); if ($result) { while(list( , $node) = each($result)) { if ($node->getName() == "menuitem") { printNodeName($node); } } } Why is that? only the name will be printed for the $s. Really need help to solve this one, any assistance is deeply appreciated! Thanks for your time.

    Read the article

  • Django: Overriding the save() method: how do I call the delete() method of a child class

    - by Patti
    The setup = I have this class, Transcript: class Transcript(models.Model): body = models.TextField('Body') doPagination = models.BooleanField('Paginate') numPages = models.PositiveIntegerField('Number of Pages') and this class, TranscriptPages(models.Model): class TranscriptPages(models.Model): transcript = models.ForeignKey(Transcript) order = models.PositiveIntegerField('Order') content = models.TextField('Page Content', null=True, blank=True) The Admin behavior I’m trying to create is to let a user populate Transcript.body with the entire contents of a long document and, if they set Transcript.doPagination = True and save the Transcript admin, I will automatically split the body into n Transcript pages. In the admin, TranscriptPages is a StackedInline of the Transcript Admin. To do this I’m overridding Transcript’s save method: def save(self): if self.doPagination: #do stuff super(Transcript, self).save() else: super(Transcript, self).save() The problem = When Transcript.doPagination is True, I want to manually delete all of the TranscriptPages that reference this Transcript so I can then create them again from scratch. So, I thought this would work: #do stuff TranscriptPages.objects.filter(transcript__id=self.id).delete() super(Transcript, self).save() but when I try I get this error: Exception Type: ValidationError Exception Value: [u'Select a valid choice. That choice is not one of the available choices.'] ... and this is the last thing in the stack trace before the exception is raised: .../django/forms/models.py in save_existing_objects pk_value = form.fields[pk_name].clean(raw_pk_value) Other attempts to fix: t = self.transcriptpages_set.all().delete() (where self = Transcript from the save() method) looping over t (above) and deleting each item individually making a post_save signal on TranscriptPages that calls the delete method Any ideas? How does the Admin do it? UPDATE: Every once in a while as I'm playing around with the code I can get a different error (below), but then it just goes away and I can't replicate it again... until the next random time. Exception Type: MultiValueDictKeyError Exception Value: "Key 'transcriptpages_set-0-id' not found in " Exception Location: .../django/utils/datastructures.py in getitem, line 203 and the last lines from the trace: .../django/forms/models.py in _construct_form form = super(BaseInlineFormSet, self)._construct_form(i, **kwargs) .../django/utils/datastructures.py in getitem pk = self.data[pk_key]

    Read the article

  • How do i write this jpql query? java

    - by Nitesh Panchal
    Hello, Say i have 5 tables, tblBlogs tblBlogPosts tblBlogPostComment tblUser tblBlogMember BlogId BlogPostsId BlogPostCommentId UserId BlogMemberId BlogTitle BlogId CommentText FirstName UserId PostTitle BlogPostsId BlogId BlogMemberId Now i want to retrieve only those blogs and posts for which blogMember has actually commented. So in short, how do i write this plain old sql :- Select b.BlogTitle, bp.PostTitle, bpc.CommentText from tblBlogs b Inner join tblBlogPosts bp on b.BlogId = bp.BlogId Inner Join tblBlogPostComment bpc on bp.BlogPostsId = bpc.BlogPostsId Inner Join tblBlogMember bm On bpc.BlogMemberId = bm.BlogMemberId Where bm.UserId = 1; As you can see, everything is Inner join, so only that row will be retrieved for which the user has commented on some post of some blog. So, suppose he has joined 3 blogs whose ids are 1,2,3 (The blogs which user has joined are in tblBlogMembers) but the user has only commented in blog 2 (of say BlogPostId = 1). So that row will be retrieved and 1,3 won't as it is Inner Join. How do i write this kind of query in jpql? In jpql, we can only write simple queries like say :- Select bm.blogId from tblBlogMember Where bm.UserId = objUser; Where objUser is supplied using :- em.find(User.class,1); Thus once we get all blogs(Here blogId represents a blog object) which user has joined, we can loop through and do all fancy things. But i don't want to fall in this looping business and write all this things in my java code. Instead, i want to leave that for database engine to do. So, how do i write the above plain sql into jpql? and what type of object the jpql query will return? because i am only selecting few fields from all table. In which class should i typecast the result to? I think i posted my requirement correctly, if i am not clear please let me know. Thanks in advance :).

    Read the article

  • Redirect Desktop Internal Pages to Correct Mobile Internal Pages with Htaccess

    - by Luis Alejandro Ramrez Gallardo
    I have built a Mobile site in a sub-domain. I have successfully implemented the redirect 302 from: www.domain.com to m.domain.com in htaccess. What I'm looking to achieve now it to redirect users from: www.domain.com/internal-page/ > 302 > m.domain.com/internal-page.html Notice that URL name for desktop and mobile is not the same. The code I'm using looks like this: # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress # Mobile Redirect # Verify Desktop Version Parameter RewriteCond %{QUERY_STRING} (^|&)ViewFullSite=true(&|$) # Set cookie and expiration RewriteRule ^ - [CO=mredir:0:www.domain.com:60] # Prevent looping RewriteCond %{HTTP_HOST} !^m.domain.com$ # Define Mobile agents RewriteCond %{HTTP_ACCEPT} "text\/vnd\.wap\.wml|application\/vnd\.wap\.xhtml\+xml" [NC,OR] RewriteCond %{HTTP_USER_AGENT} "sony|symbian|nokia|samsung|mobile|windows ce|epoc|opera" [NC,OR] RewriteCond %{HTTP_USER_AGENT} "mini|nitro|j2me|midp-|cldc-|netfront|mot|up\.browser|up\.link|audiovox"[NC,OR] RewriteCond %{HTTP_USER_AGENT} "blackberry|ericsson,|panasonic|philips|sanyo|sharp|sie-"[NC,OR] RewriteCond %{HTTP_USER_AGENT} "portalmmm|blazer|avantgo|danger|palm|series60|palmsource|pocketpc"[NC,OR] RewriteCond %{HTTP_USER_AGENT} "smartphone|rover|ipaq|au-mic,|alcatel|ericy|vodafone\/|wap1\.|wap2\.|iPhone|android"[NC] # Verify if not already in Mobile site RewriteCond %{HTTP_HOST} !^m\. # We need to read and write at the same time to set cookie RewriteCond %{QUERY_STRING} !(^|&)ViewFullSite=true(&|$) # Verify that we previously haven't set the cookie RewriteCond %{HTTP_COOKIE} !^.*mredir=0.*$ [NC] # Now redirect the users to the Mobile Homepage RewriteRule ^$ http://m.domain.com [R] RewriteRule $/internal-page/ http://m.domain.com/internal-page.html [R,L]

    Read the article

< Previous Page | 20 21 22 23 24 25 26 27 28 29 30 31  | Next Page >