Search Results

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

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

  • Get the current array key in a multi dimensional array

    - by johlton
    Hi *, I have a session array *$_SESSION['cart']* with some items in it. The structure ist like this (via *print_r*): Array ( [2-1] => Array ( [color] => 7 [articlenumber] => WRG70 10 [quantity] => 1 [price] => 17.50 ) [3-8] => Array ( [color] => 2 [articlenumber] => QRG50 02 [quantity] => 1 [price] => 13.50 ) ) Looping over the values for display is fine ... foreach($_SESSION['cart'] as $item_array) { foreach($item_array as $item => $value) { echo $value . ' | '; } } ... since it results in something like this: 7 | WRG70 10 | 1 | 17.50 | 2 | QRG50 02 | 1 | 13.50 | But Now: How can I output the matching key (e.g. '2-1') as well? I tried some array functions like key() & current but couldn't get it to work (one of these days). Any quick hint on this? Thanks a lot and best from Berlin Fabian

    Read the article

  • How do I make the following interaction with mySQL more efficient?

    - by Travis
    I've got an array that contains combinations of unique MySql IDs: For example: [ [1,10,11], [2,10], [3,10,12], [3,12,13,20], [4,12] ] In total there are a couple hundred different combinations of IDs. Some of these combinations are "valid" and some are not. For example, [1,10,11] may be a valid combination, whereas [3,10,12] may be invalid. Combinations are valid or invalid depending on how the data is arranged in the database. Currently I am using a SELECT statement to determine whether or not a specific combination of IDs is valid. It looks something like this: SELECT id1 FROM table WHERE id2 IN ($combination) GROUP BY id1 HAVING COUNT(distinct id2) = $number ...where $combination is one possible combination of IDs (eg 1,10,11) and $number is the number of IDs in that combination (in this case, 3). An invalid combination will return 0 rows. A valid combination will return 1 or more rows. However, to solve the entire set of possible combinations means looping a couple hundred SELECT statements, which I would rather not be doing. I am wondering: Are there any tricks for making this more efficient? Is it possible to submit the entire dataset to mySQL in one go, and have mySQL iterate through it? Any suggestions would be much appreciated. Thanks in advance!

    Read the article

  • MS SQL : Can you help me with this query?

    - by rlb.usa
    I want to run a diagnostic report on our MS SQL 2008 database server. I am looping through all of the databases, and then for each database, I want to look at each table. But, when I go to look at each table (with tbl_cursor), it always picks up the tables in the database 'master'. I think it's because of my tbl_cursor selection : SELECT table_name FROM information_schema.tables WHERE table_type = 'base table' How do I fix this? Here's the entire code: SET NOCOUNT ON DECLARE @table_count INT DECLARE @db_cursor VARCHAR(100) DECLARE database_cursor CURSOR FOR SELECT name FROM sys.databases where name<>N'master' OPEN database_cursor FETCH NEXT FROM database_cursor INTO @db_cursor WHILE @@Fetch_status = 0 BEGIN PRINT @db_cursor SET @table_count = 0 DECLARE @table_cursor VARCHAR(100) DECLARE tbl_cursor CURSOR FOR SELECT table_name FROM information_schema.tables WHERE table_type = 'base table' OPEN tbl_cursor FETCH NEXT FROM tbl_cursor INTO @table_cursor WHILE @@Fetch_status = 0 BEGIN DECLARE @table_cmd NVARCHAR(255) SET @table_cmd = N'IF NOT EXISTS( SELECT TOP(1) * FROM ' + @table_cursor + ') PRINT N'' Table ''''' + @table_cursor + ''''' is empty'' ' --PRINT @table_cmd --debug EXEC sp_executesql @table_cmd SET @table_count = @table_count + 1 FETCH NEXT FROM tbl_cursor INTO @table_cursor END CLOSE tbl_cursor DEALLOCATE tbl_cursor PRINT @db_cursor + N' Total Tables : ' + CAST( @table_count as varchar(2) ) PRINT N'' -- print another blank line SET @table_count = 0 FETCH NEXT FROM database_cursor INTO @db_cursor END CLOSE database_cursor DEALLOCATE database_cursor SET NOCOUNT OFF

    Read the article

  • Need help writing jQuery to loop through table and inject markers into google map?

    - by abemonkey
    I am new to jQuery. I've done some simple things with it but what I am attempting now is a over my head and I need some help. I am building a locator for all the firearms dealers in the US for a client. I am working within Drupal. I have a proximity search by zip code that works great. If you search by zip a list of paginated results shows up in an html table that can by paged through via ajax. I would like a map to be above this list with markers corresponding to the names and addresses being listed. I already have all the lat and long values in the table results. I want the script to update the markers and automatically zoom to fit the markers in the view when a user changes the sort order of the table or pages through the results. Also, I'd like to have a hover highlight effect over the rows of the table that simultaneously highlight the corresponding marker, and have a click on the table row equal a click on a marker that pops up a marker info window to be populated using jQuery to read the name and address fields of the table. Hope this all makes sense. I know I'm putting a lot out there, I'm not asking for someone to write the whole script, just wanted to give as many details as possible. Thanks for any help. I'm just lost when it comes to looping and moving data around. If you want to check out what I have so far on the project please visit: www.axtsweapons.com and login with the username: "test" and the password: "1234" and then visit this direct link: www.axtsweapons.com/ffllocator. For just a simple page that would be easy to manipulate and play with goto: http://www.axtsweapons.com/maptest.html Thanks!

    Read the article

  • How do you efficiently bulk index lookups?

    - by Liron Shapira
    I have these entity kinds: Molecule Atom MoleculeAtom Given a list(molecule_ids) whose lengths is in the hundreds, I need to get a dict of the form {molecule_id: list(atom_ids)}. Likewise, given a list(atom_ids) whose length is in the hunreds, I need to get a dict of the form {atom_id: list(molecule_ids)}. Both of these bulk lookups need to happen really fast. Right now I'm doing something like: atom_ids_by_molecule_id = {} for molecule_id in molecule_ids: moleculeatoms = MoleculeAtom.all().filter('molecule =', db.Key.from_path('molecule', molecule_id)).fetch(1000) atom_ids_by_molecule_id[molecule_id] = [ MoleculeAtom.atom.get_value_for_datastore(ma).id() for ma in moleculeatoms ] Like I said, len(molecule_ids) is in the hundreds. I need to do this kind of bulk index lookup on almost every single request, and I need it to be FAST, and right now it's too slow. Ideas: Will using a Molecule.atoms ListProperty do what I need? Consider that I am storing additional data on the MoleculeAtom node, and remember it's equally important for me to do the lookup in the molecule-atom and atom-molecule directions. Caching? I tried memcaching lists of atom IDs keyed by molecule ID, but I have tons of atoms and molecules, and the cache can't fit it. How about denormalizing the data by creating a new entity kind whose key name is a molecule ID and whose value is a list of atom IDs? The idea is, calling db.get on 500 keys is probably faster than looping through 500 fetches with filters, right?

    Read the article

  • Handle order dependence in loops

    - by Matt
    Hey all, I'm making a templating system where I instantiate each tag using a foreach loop. The issue is that some of the tags rely on each other so, I'm wondering how to get around that ordering from the looping. Here's an example: Class A { public $width; __construct() { $this->width = $B->width; // Undefined! Or atleast not set yet.. } } Class B { public $width; __construct() { $this->width = "500px"; } __tostring() { return "Hello World!"; } } Template.php $tags = array("A", "B"); foreach ($tags as $tag) { $TagObj[$tag] = new $tag(); } echo $TagObj['A']->width; // Nadamundo! EDIT: Ok just to clarify.. My main problem is that Class A relies on Class B, but class A is instantiated before class B, so therefore width has not yet been defined in class B. I am looking for a good way to make sure all the classes are loaded for everyone allowing the interdependencies to exist. For the future, please don't consider any syntax errors.. I just made up this example on the spot. Also assume that I have access to class B from class A after class B gets instantiated. I know this has applications elsewhere and I'm sure this has been solved before, if someone could enlighten me or point me in the right direction that'd be great! Thanks! Matt Mueler

    Read the article

  • How to automatically read in calculated values with PHPExcel?

    - by Edward Tanguay
    I have the following Excel file: I read it in by looping over every cell and getting the value with getCell(...)->getValue(): $highestColumnAsLetters = $this->objPHPExcel->setActiveSheetIndex(0)->getHighestColumn(); //e.g. 'AK' $highestRowNumber = $this->objPHPExcel->setActiveSheetIndex(0)->getHighestRow(); $highestColumnAsLetters++; for ($row = 1; $row < $highestRowNumber + 1; $row++) { $dataset = array(); for ($columnAsLetters = 'A'; $columnAsLetters != $highestColumnAsLetters; $columnAsLetters++) { $dataset[] = $this->objPHPExcel->setActiveSheetIndex(0)->getCell($columnAsLetters.$row)->getValue(); if ($row == 1) { $this->column_names[] = $columnAsLetters; } } $this->datasets[] = $dataset; } However, although it reads in the data fine, it reads in the calculations literally: I understand from discussions like this one that I can use getCalculatedValue() for calculated cells. The problem is that in the Excel sheets I am importing, I do not know beforehand which cells are calculated and which are not. Is there a way for me to read in the value of a cell in a way that automatically gets the value if it has a simple value and gets the result of the calculation if it is a calculation? Answer: It turns out that getCalculatedValue() works for all cells, makes me wonder why this isn't the default for getValue() since I would think one would usually want the value of the calculations instead of the equations themselves, in any case this works: ...->getCell($columnAsLetters.$row)->getCalculatedValue();

    Read the article

  • Python script to calculate aded combinations from a dictionary

    - by dayde
    I am trying to write a script that will take a dictionary of items, each containing properties of values from 0 - 10, and add the various elements to select which combination of items achieve the desired totals. I also need the script to do this, using only items that have the same "slot" in common. For example: item_list = { 'item_1': {'slot': 'top', 'prop_a': 2, 'prop_b': 0, 'prop_c': 2, 'prop_d': 1 }, 'item_2': {'slot': 'top', 'prop_a': 5, 'prop_b': 0, 'prop_c': 1, 'prop_d':-1 }, 'item_3': {'slot': 'top', 'prop_a': 2, 'prop_b': 5, 'prop_c': 2, 'prop_d':-2 }, 'item_4': {'slot': 'mid', 'prop_a': 5, 'prop_b': 5, 'prop_c':-5, 'prop_d': 0 }, 'item_5': {'slot': 'mid', 'prop_a':10, 'prop_b': 0, 'prop_c':-5, 'prop_d': 0 }, 'item_6': {'slot': 'mid', 'prop_a':-5, 'prop_b': 2, 'prop_c': 3, 'prop_d': 5 }, 'item_7': {'slot': 'bot', 'prop_a': 1, 'prop_b': 3, 'prop_c':-4, 'prop_d': 4 }, 'item_8': {'slot': 'bot', 'prop_a': 2, 'prop_b': 2, 'prop_c': 0, 'prop_d': 0 }, 'item_9': {'slot': 'bot', 'prop_a': 3, 'prop_b': 1, 'prop_c': 4, 'prop_d':-4 }, } The script would then need to select which combinations from the "item_list" dict that using 1 item per "slot" that would achieve a desired result when added. For example, if the desired result was: 'prop_a': 3, 'prop_b': 3, 'prop_c': 8, 'prop_d': 0, the script would select 'item_2', 'item_6', and 'item_9', along with any other combination that worked. 'item_2': {'slot': 'top', 'prop_a': 5, 'prop_b': 0, 'prop_c': 1, 'prop_d':-1 } 'item_6': {'slot': 'mid', 'prop_a':-5, 'prop_b': 2, 'prop_c': 3, 'prop_d': 5 } 'item_9': {'slot': 'bot', 'prop_a': 3, 'prop_b': 1, 'prop_c': 4, 'prop_d':-4 } 'total': 'prop_a': 3, 'prop_b': 3, 'prop_c': 8, 'prop_d': 0 Any ideas how to accomplish this? It does not need to be in python, or even a thorough script, but just an explanation on how to do this in theory would be enough for me. I have tried working out looping through every combination, but that seems to very quickly get our of hand and unmanageable. The actual script will need to do this for about 1,000 items using 20 different "slots", each with 8 properties. Thanks for the help!

    Read the article

  • Inner join on 2 arrays?

    - by russ
    I'm trying to find a solution to the following (I'm thinking with Linq) to the following: I need to pull down certain files from a larger list of files on an ftp server that have a similar file name. For example, we send an order file to some company for processing then they return a response file that we can download. So, I could send them the files "order_123.txt" and "order_456.txt". After a certain amount of time I need to go look for and download the responses for those files that will be named "order_123.resp" and "order_456.resp". The kicker is that in some cases I can have multiple responses in which case they would create "order_123-1.resp" and "order_123-2.resp" and also the files don't get removed from the server. I know this can be accomplished by looping through the files I know I need responses to then loop through all the files on the server until I find files that match but I'm hoping that I don't have to loop through the files on the server more than once. This example may help clarify: I've sent "order_222.txt" and "order_333.txt" they processed them and the ftp server contains: "order_111-1.resp" "order_001.resp" "order_222-1.resp" "order_222-2.resp" "order_333.resp" I need to download the 3rd, 4th, and 5th file. Thanks.

    Read the article

  • Use of Syntactic Sugar / Built in Functionality

    - by Kyle Rozendo
    I was busy looking deeper into things like multi-threading and deadlocking etc. The book is aimed at both pseudo-code and C code and I was busy looking at implementations for things such as Mutex locks and Monitors. This brought to mind the following; in C# and in fact .NET we have a lot of syntactic sugar for doing things. For instance (.NET 3.5): lock(obj) { body } Is identical to: var temp = obj; Monitor.Enter(temp); try { body } finally { Monitor.Exit(temp); } There are other examples of course, such as the using() {} construct etc. My question is when is it more applicable to "go it alone" and literally code things oneself than to use the "syntactic sugar" in the language? Should one ever use their own ways rather than those of people who are more experienced in the language you're coding in? I recall having to not use a Process object in a using block to help with some multi-threaded issues and infinite looping before. I still feel dirty for not having the using construct in there. Thanks, Kyle

    Read the article

  • Python Regular Expressions: Capture lookahead value (capturing text without consuming it)

    - by Lattyware
    I wish to use regular expressions to split words into groups of (vowels, not_vowels, more_vowels), using a marker to ensure every word begins and ends with a vowel. import re MARKER = "~" VOWELS = {"a", "e", "i", "o", "u", MARKER} word = "dog" if word[0] not in VOWELS: word = MARKER+word if word[-1] not in VOWELS: word += MARKER re.findall("([%]+)([^%]+)([%]+)".replace("%", "".join(VOWELS)), word) In this example we get: [('~', 'd', 'o')] The issue is that I wish the matches to overlap - the last set of vowels should become the first set of the next match. This appears possible with lookaheads, if we replace the regex as follows: re.findall("([%]+)([^%]+)(?=[%]+)".replace("%", "".join(VOWELS)), word) We get: [('~', 'd'), ('o', 'g')] Which means we are matching what I want. However, it now doesn't return the last set of vowels. The output I want is: [('~', 'd', 'o'), ('o', 'g', '~')] I feel this should be possible (if the regex can check for the second set of vowels, I see no reason it can't return them), but I can't find any way of doing it beyond the brute force method, looping through the results after I have them and appending the first character of the next match to the last match, and the last character of the string to the last match. Is there a better way in which I can do this? The two things that would work would be capturing the lookahead value, or not consuming the text on a match, while capturing the value - I can't find any way of doing either.

    Read the article

  • How to get a handle to all JCheckBox objects in order to loop?

    - by EmmyS
    I'm very new to Java and am having some issues looping through JCheckBoxes on a UI. The idea is that I have a bunch of checkboxes (not in a group because more than one can be selected.) When I click a JButton, I want to build a string containing the text from each selected checkbox. The issue I'm having is that our instructor told us that the checkboxes need to be created via a method, which means (see code below) that there isn't a discrete instance name for each checkbox. If there were, I could say something like if(checkBox1.isSelected()) { myString.append(checkBox.getText()); } That would repeat for checkBox2, checkBox3, and so on. But the method provided to us for adding checkboxes to a panel looks like this: public class CheckBoxPanel extends JPanel { private static final long serialVersionUID = 1L; public CheckBoxPanel(String title, String... options) { setBorder(BorderFactory.createTitledBorder(BorderFactory .createEtchedBorder(), title)); setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); // make one checkbox for each option for (String option : options) { JCheckBox b = new JCheckBox(option); b.setActionCommand(option); add(b); } } } This is called like this: toppingPanel = new CheckBoxPanel("Each Topping $1.50", "Tomato", "Green Pepper", "Black Olives", "Mushrooms", "Extra Cheese", "Pepperoni", "Sausage"); So I now have a panel that contains a border with the title "Each Topping $1.50", and 7 visible checkboxes. What I need to do is get a list of all the selected toppings. We are not supposed to use an ActionListener for each checkbox, but rather get the list when a button is clicked. I'm feeling really clueless here, but I just can't figure out how to get the isSelected property of the checkboxes when the individual checkboxes don't have instance names. Ideally I'd like to somehow add all the checkboxes to an array and loop through the array in the button's action listener to determine which ones are checked, but if I have to check each one individually I will. I just can't figure out how to refer to an individual checkbox when they've been created dynamically.

    Read the article

  • Checking for valid email addresses

    - by Roland
    I'm running a website with more than 60 000 registered users. Every week notifications are send to these users via email, now I've noticed some of the mail addresses do not exists anymore eg. the domain address is valid but the email name en asdas@ is not valid anymore since person does not work at a company anymore etc. Now I'm looping through the database and doing some regular expression checks and checking if the MX records exist with the following two functions function verify_email($email){ if(!preg_match('/^[_A-z0-9-]+((\.|\+)[_A-z0-9-]+)*@[A-z0-9-]+(\.[A-z0-9-]+)*(\.[A-z]{2,4})$/',$email)){ return false; } else { return true; } } // Our function to verify the MX records function verify_email_dns($email){ list($name, $domain) = split('@',$email); if(!checkdnsrr($domain,'MX')){ return false; } else { return true; } } If the email address is in an invalid format or the domain does not exists I delete the users account. Are there any methods I could use to check if the email address still exists or not if the domain name is valid and the email address is in the correct format? For example [email protected] does not exist anymore but test.com is a valid domain name.

    Read the article

  • Collision detections and how efficient they are

    - by Shadow
    How exactly do you implement collision detection? What are the costs involved? Do different platforms(c/c++, java, cocoa/iphone, flash, directX) have different optimizations for calculating collisions. And lastly are there libraries available to do this for me, or some that I can just interpret for my platform of choice? As I understand it you would need to loop through the collision map and find the area in question and then compair the input thing(e.g. a sprite) to the type of pixel that is in the questioned area. I understand the very basic idea, but I don't understand the underlying implementation or even a higher level one for that matter. It would seem that this type of detection, or any for that matter, is very costly. Tile map? Bit array? How are these created from an image(I would guess looping and doing stuff)? The reason I ask this question is to get a better understanding of the efficiency behind the scenes and to understand exactly what is going on. Links, references, or examples would be very helpful. I know this question is a bit longwinded so any help or references would be very welcome. Thanks SO!

    Read the article

  • How can I tell whether a webpart that has been deployed to a site is a native webpart that ships wit

    - by program247365
    I have a SharePoint 2007 MOSS instance, and I'm on a fact-finding mission. There have been multiple developers, developing multiple webparts and deploying them (using VS2005/2008 SharePoint Extensions). I thought maybe I could look at the fields in the "Web Part Gallery" list in my site, and look by "Modified by", but it looks like a developer's name is on some of the out-of-the-box webparts somehow, and on ones I know are custom developed, they say "System Account" - so looking at that field in this list is a no go. I thought then maybe I could look at the "Group" to which each webpart was assigned but it looks like they were arbitrarily assigned to many different groups inconsistently - so using that piece of information is a no go. Here is my code I have for just looping through and getting the names of all the webparts. Is there any property I can access on the list items of webparts that would tell me whether it's a custom developed webpart? Any way to distinguish the custom webparts from the out-of-the-box ones? Is there another way to do this? #region Misc Site Collection Methods public static List<string> GetAllWebParts(string connectedSPInstanceUrl) { List<string> lstWebParts = new List<string>(); try { using (SPSite site = new SPSite(connectedSPInstanceUrl)) { using (SPWeb web = site.OpenWeb()) { SPList list = web.Lists["Web Part Gallery"]; foreach (SPListItem item in list.Items) { lstWebParts.Add(item.Name); } } } } catch (Exception ex) { lstWebParts.Add("Error"); lstWebParts.Add("Message: " + ex.Message); lstWebParts.Add("Inner Exception: " + ex.InnerException.ToString()); lstWebParts.Add("Stack Trace: " + ex.StackTrace); } return lstWebParts; } #endregion

    Read the article

  • Overloading operator>> to a char buffer in C++ - can I tell the stream length?

    - by exscape
    I'm on a custom C++ crash course. I've known the basics for many years, but I'm currently trying to refresh my memory and learn more. To that end, as my second task (after writing a stack class based on linked lists), I'm writing my own string class. It's gone pretty smoothly until now; I want to overload operator that I can do stuff like cin my_string;. The problem is that I don't know how to read the istream properly (or perhaps the problem is that I don't know streams...). I tried a while (!stream.eof()) loop that .read()s 128 bytes at a time, but as one might expect, it stops only on EOF. I want it to read to a newline, like you get with cin to a std::string. My string class has an alloc(size_t new_size) function that (re)allocates memory, and an append(const char *) function that does that part, but I obviously need to know the amount of memory to allocate before I can write to the buffer. Any advice on how to implement this? I tried getting the istream length with seekg() and tellg(), to no avail (it returns -1), and as I said looping until EOF (doesn't stop reading at a newline) reading one chunk at a time.

    Read the article

  • Generating two thumbnails from the same image in Django

    - by Titus
    Hello, this seems like quite an easy problem but I can't figure out what is going on here. Basically, what I'd like to do is create two different thumbnails from one image on a Django model. What ends up happening is that it seems to be looping and recreating the same image (while appending an underscore to it each time) until it throws up an error that the filename is to big. So, you end up something like: OSError: [Errno 36] File name too long: 'someimg________________etc.jpg' Here is the code: def save(self, *args, **kwargs): if self.image: iname = os.path.split(self.image.name)[-1] fname, ext = os.path.splitext(iname) tlname, tsname = fname + '_thumb_l' + ext, fname + '_thumb_s' + ext self.thumb_large.save(tlname, make_thumb(self.image, size=(250,250))) self.thumb_small.save(tsname, make_thumb(self.image, size=(100,100))) super(Artist, self).save(*args, **kwargs) def make_thumb(infile, size=(100,100)): infile.seek(0) image = Image.open(infile) if image.mode not in ('L', 'RGB'): image.convert('RGB') image.thumbnail(size, Image.ANTIALIAS) temp = StringIO() image.save(temp, 'png') return ContentFile(temp.getvalue()) I didn't show imports for the sake of brevity. Assume there are two ImageFields on the Artist model: thumb_large, and thumb_small. If this isn't the correct way to do it, I'd appreciate any feedback. Thanks!

    Read the article

  • Using fields from an association (has_many) model with formtastic in rails

    - by pduersteler
    I searched and tried a lot, but I can't accomplish it as I want.. so here's my problem. class Moving < ActiveRecord::Base has_many :movingresources, :dependent => :destroy has_many :resources, :through => :movingresources end class Movingresource < ActiveRecord::Base belongs_to :moving belongs_to :resource end class Resource < ActiveRecord::Base has_many :movingresources has_many :movings, :through => :movingresources end Movingresources contains additional fields, like "quantity". We're working on the views for 'bill'. Thanks to formtastic to simplify the whole relationship thing by just writing <%= form.input :workers, :as => :check_boxes %> and i get a real nice checkbox list. But what I haven't found out so far is: How can i use the additional fields from 'movingresource', next or under each checkbox my desired fields from that model? I saw different approaches, mainly with manually looping through an array of objects and creating the appropriate forms, using :for in a form.inputs part, or not. But none of those solutions were clean (e.g. worked for the edit view but not for new because the required objects were not built or generated and generating them caused a mess). I want to know your solutions for this! :-)

    Read the article

  • How to prevent PHP variables from being arrays?

    - by MJB
    I think that (the title) is the problem I am having. I set up a MySQL connection, I read an XML file, and then I insert those values into a table by looping through the elements. The problem is, instead of inserting only 1 record, sometimes I insert 2 or 3 or 4. It seems to depend on the previous values I have read. I think I am reinitializing the variables, but I guess I am missing something -- hopefully something simple. Here is my code. I originally had about 20 columns, but I shortened the included version to make it easier to read. $ctr = 0; $sql = "insert into csd (id,type,nickname,hostname,username,password) ". "values (?,?,?,?,?,?)"; $cur = $db->prepare($sql); for ($ctr = 0; $ctr < $expected_count; $ctr++) { list ( $lbl, $type, $nickname, $hostname, $username, $password) = ""; $bind_vars = array(); $lbl = "csd_{$ctr}"; $type = $ref->itm->csds->$lbl->type; $nickname = $ref->itm->csds->$lbl->nickname; $hostname = $ref->itm->csds->$lbl->hostname; $username = $ref->itm->csds->$lbl->username; $password = $ref->itm->csds->$lbl->password; $bind_vars = array($id,$type,$nickname,$hostname,$username,$password); $res = $db->execute($cur, $bind_vars); # this is a separate function which works, but which only # does SELECTS and cannot be the problem. I include it because I # want to count the total rows. printf ("%d CSDs on that ITEM now.\n", CountCSDs($id_to_sync)); } P.S. I also tagged this SimpleXML because that is how I am reading the file, though that code is not included above. It looks like this: $Ref = simplexml_load_file($file);

    Read the article

  • Using Scala and StringTemplate, how do I loop through a Map

    - by Marcus Kazmierczak
    I have my environment setup nicely using Scala, StringTempalte within the Google AppEngine. I am having trouble looping through a Map and getting it to display in the template. When I assign a simple List of just Strings to the template it works using: In Scala Servlet: var photos = List[String]() //... get photo url and title ... photos = photo_url :: photos template.setAttribute("photos", photos: _*) In Template: $photos: { photo| <div><img src="$photo$_s.jpg"></div> }$ The above works. However, any attempt of creating a Map using url and title and assigning to the template gives me an error. Here is my attempt, which does not work: In Scala Servlet: var photos = List[Map[String,String]]() //... get photo url and title ... photos = Map("url" -> url, "title" -> title) :: photos template.setAttribute("photos", photos: _*) In Template: $photos: { photo| <div><img src="$photo.url$_s.jpg" title="$photo.title$"></div> }$ This gives me the following error Class scala.collection.immutable.Map$Map2 has no such attribute: title in template context Thoughts / Ideas ?

    Read the article

  • How to automatically read in calculated values with PHPExcel?

    - by Edward Tanguay
    I have the following Excel file: I read it in by looping over every cell and getting the value with getCell(...)->getValue(): $highestColumnAsLetters = $this->objPHPExcel->setActiveSheetIndex(0)->getHighestColumn(); //e.g. 'AK' $highestRowNumber = $this->objPHPExcel->setActiveSheetIndex(0)->getHighestRow(); $highestColumnAsLetters++; for ($row = 1; $row < $highestRowNumber + 1; $row++) { $dataset = array(); for ($columnAsLetters = 'A'; $columnAsLetters != $highestColumnAsLetters; $columnAsLetters++) { $dataset[] = $this->objPHPExcel->setActiveSheetIndex(0)->getCell($columnAsLetters.$row)->getValue(); if ($row == 1) { $this->column_names[] = $columnAsLetters; } } $this->datasets[] = $dataset; } However, although it reads in the data fine, it reads in the calculations literally: I understand from discussions like this one that I can use getCalculatedValue() for calculated cells. The problem is that in the Excel sheets I am importing, I do not know beforehand which cells are calculated and which are not. Is there a way for me to read in the value of a cell in a way that automatically gets the value if it has a simple value and gets the result of the calculation if it is a calculation?

    Read the article

  • Disable control in .aspx from Masterpage conditionally

    - by miccet
    Ok, this might be a bit weird, so I'll start with explaining what I'm trying to do. I have several masterpages for my site, and in they inherit each other. In the second of them (4 in total) I have a background image. Here comes the trick, I'd like to override this image from the final aspx page. I can't change the position of this image, it has to be in masterpage 2, since some pages uses that very page as masterpage. One idea I had was to create a ContentPlaceHolder next to the image and if there are any images in that (check in Page_Load) then the main image would be hidden. I did this with a recursive function, that finds the image by looping through the ContentPlaceHolder's controls. When I set the visibility property to false though, nothing happens. Any other ideas to how this could be done, or why the above doesn't work? Edit: It's not about changing items in the master pages, rather the other way around, that from the Masterpages codebehind dig down into the page that is displayed currently and see if it has controls in a specific ContentPlaceHolder.

    Read the article

  • Ignore folders with certain filetypes

    - by gavin19
    I'm trying in vain to rewrite my old Powershell script found here - "$_.extension -eq" not working as intended? - for Python.I have no Python experience or knowledge and my 'script' is a mess but it mostly works. The only thing missing is that I would like to be able to ignore folders which don't contain 'mp3s', or whichever filetype I specify. Here is what I have so far - import os, os.path, fnmatch path = raw_input("Path : ") for filename in os.listdir(path): if os.path.isdir(filename): os.chdir(filename) j = os.path.abspath(os.getcwd()) mp3s = fnmatch.filter(os.listdir(j), '*.txt') if mp3s: target = open("pls.m3u", 'w') for filename in mp3s: target.write(filename) target.write("\n") os.chdir(path) All I would like to be able to do (if possible) is that when the script is looping through the folders that it ignores those which do NOT contain 'mp3s', and removes the 'pls.m3u'. I could only get the script to work properly if I created the 'pls.m3u' by default. The problem is that that creates a lot of empty 'pls.m3u' files in folders which contain only '.jpg' files for example. You get the idea. I'm sure this script is blasphemous to Python users but any help would be greatly appreciated.

    Read the article

  • Query next/previous record

    - by Rob
    I'm trying to find a better way to get the next or previous record from a table. Let's say I have a blog or news table: CREATE TABLE news ( news_id INT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT, news_datestamp DATETIME NOT NULL, news_author VARCHAR(100) NOT NULL, news_title VARCHAR(100) NOT NULL, news_text MEDIUMTEXT NOT NULL ); Now on the frontend I want navigation buttons for the next or previous records, if i'm sorting by news_id, I can do something rather simple like: SELECT MIN(news_id) AS next_news_id FROM news WHERE news_id > '$old_news_id' LIMIT 1 SELECT MAX(news_id) AS prev_news_id FROM news WHERE news_id < '$old_news_id' LIMIT 1 But the news can be sorted by any field, and I don't necessarily know which field is sorted on, so this won't work if the user sorts on news_author for example. I've resorted to the rather ugly and inefficient method of sorting the entire table and looping through all records until I find the record I need. $res = mysql_query("SELECT news_id FROM news ORDER BY `$sort_column` $sort_way"); $found = $prev = $next = 0; while(list($id) = mysql_fetch_row($res)) { if($found) { $next = $id; break; } if($id == $old_news_id) { $found = true; continue; } $prev = $id; } There's got to be a better way.

    Read the article

  • Common Lisp condition system for transfer of control

    - by Ken
    I'll admit right up front that the following is a pretty terrible description of what I want to do. Apologies in advance. Please ask questions to help me explain. :-) I've written ETLs in other languages that consist of individual operations that look something like: // in class CountOperation IEnumerable<Row> Execute(IEnumerable<Row> rows) { var count = 0; foreach (var row in rows) { row["record number"] = count++; yield return row; } } Then you string a number of these operations together, and call The Dispatcher, which is responsible for calling Operations and pushing data between them. I'm trying to do something similar in Common Lisp, and I want to use the same basic structure, i.e., each operation is defined like a normal function that inputs a list and outputs a list, but lazily. I can define-condition a condition (have-value) to use for yield-like behavior, and I can run it in a single loop, and it works great. I'm defining the operations the same way, looping through the inputs: (defun count-records (rows) (loop for count from 0 for row in rows do (signal 'have-value :value `(:count ,count @,row)))) The trouble is if I want to string together several operations, and run them. My first attempt at writing a dispatcher for these looks something like: (let ((next-op ...)) ;; pick an op from the set of all ops (loop (handler-bind ((have-value (...))) ;; records output from operation (setq next-op ...) ;; pick a new next-op (call next-op))) But restarts have only dynamic extent: each operation will have the same restart names. The restart isn't a Lisp object I can store, to store the state of a function: it's something you call by name (symbol) inside the handler block, not a continuation you can store for later use. Is it possible to do something like I want here? Or am I better off just making each operation function explicitly look at its input queue, and explicitly place values on the output queue?

    Read the article

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