Search Results

Search found 165 results on 7 pages for 'flatten'.

Page 1/7 | 1 2 3 4 5 6 7  | Next Page >

  • PHP : flatten array - fastest way?

    - by Industrial
    Is there any fast way to flatten an array and select subkeys ('key'&'value' in this case) without running a foreach loop, or is the foreach always the fastest way? Array ( [0] => Array ( [key] => string [value] => a simple string [cas] => 0 ) [1] => Array ( [key] => int [value] => 99 [cas] => 0 ) [2] => Array ( [key] => array [value] => Array ( [0] => 11 [1] => 12 ) [cas] => 0 ) ) To: Array ( [int] => 99 [string] => a simple string [array] => Array ( [0] => 11 [1] => 12 ) )

    Read the article

  • How can I "merge", "flatten" or "pivot" results from a query which returns multiple rows into a sing

    - by dsm
    I have a simple query over a table, which returns results like the following: id id_type id_ref 2702 5 31 2702 16 14 2702 17 3 2702 40 1 2702 26 4 And I would like to merge the results into a single row, for instance: id concatenation 2702 5,16,17,40,26:31,14,3,1,4 Is there any way to do this within a trigger? NB: I know I can use a cursor, but I would really prefer not to unless there is no better way.

    Read the article

  • How can I "merge" or "flatten" results from a query which returns multiple rows into a single result

    - by dsm
    I have a simple query over a table, which returns results like the following: id id_type id_ref 2702 5 31 2702 16 14 2702 17 3 2702 40 1 2702 26 4 And I would like to merge the results into a single row, for instance: id concatenation 2702 5,16,17,40,26:31,14,3,1,4 Is there any way to do this within a trigger? NB: I know I can use a cursor, but I would really prefer not to unless there is no better way.

    Read the article

  • Flatten (an irregular) list of lists in Python

    - by telliott99
    Yes, I know this subject has been covered before (here, here, here, here), but AFAIK, all solutions save one choke on a list like this: L = [[[1, 2, 3], [4, 5]], 6] where the desired output is [1, 2, 3, 4, 5, 6] or perhaps even better, an iterator. The only solution I saw that works for an arbitrary nesting is from @Alabaster Codify here: def flatten(x): result = [] for el in x: if hasattr(el, "__iter__") and not isinstance(el, basestring): result.extend(flatten(el)) else: result.append(el) return result flatten(L) So to my question: is this the best model? Did I overlook something? Any problems?

    Read the article

  • Flatten Word document

    - by user126389
    I have a document with some precise formatting, created in Word. This doc was converted to PDF for distribution. Now the original is lost, and reconverting to Word using a PDF to word add-on from Microsoft results in many text boxes in the new DOC file. How can I 'flatten' this to remove the text boxes and retain most of the formatting in order to update the contents? Recreating the original formatting would take a long time.

    Read the article

  • How to flatten already filled out PDF form using iTextSharp

    - by andryuha
    I'm using iTextSharp to merge a number of pdf files together into a single file. I'm using method described in iTextSharp official tutorials, specifically here, which merges files page by page via PdfWriter and PdfImportedPage. Turns out some of the files I need to merge are filled out PDF Forms and using this method of merging form data is lost. I've see several examples of using PdfStamper to fill out forms and flatten them. What I can't find, is a way to flatten already filled out PDF Form and hopefully merge it with the other files without saving it flattened out version first. Thanks

    Read the article

  • PHP Flatten Array with multiple leaf nodes

    - by tafaju
    What is the best way to flatten an array with multiple leaf nodes so that each full path to leaf is a distinct return? array("Object"=>array("Properties"=>array(1, 2))); to yield Object.Properties.1 Object.Properties.2 I'm able to flatten to Object.Properties.1 but 2 does not get processed with recursive function: function flattenArray($prefix, $array) { $result = array(); foreach ($array as $key => $value) { if (is_array($value)) $result = array_merge($result, flattenArray($prefix . $key . '.', $value)); else $result[$prefix . $key] = $value; } return $result; } I presume top down will not work when anticipating multiple leaf nodes, so either need some type of bottom up processing or a way to copy array for each leaf and process (althought that seems completely inefficient)

    Read the article

  • Erlang : flattening a list of strings

    - by ErJab
    I have a list like this: [["str1","str2"],["str3","str4"],["str5","str6"]] And I need to convert it to ["str1", "str2", "str3", "str4", "str5", "str6"] How do I do this? The problem is that I'm dealing with lists of strings, so when I do lists:flatten([["str1","str2"],["str3","str4"],["str5","str6"]]) I get "str1str2str3str4str5str6" However, if the elements of the original list where just atoms, then lists:flatten would have given me what I needed. How do I achieve the same with strings?

    Read the article

  • Flatten a PHP array

    - by deadkarma
    Say I have a form with these fields, and cannot rename them: <input type="text" name="foo[bar]" /> <input type="text" name="foo[baz]" /> <input type="text" name="foo[bat][faz]" /> When submitted, PHP turns this into an array: Array ( [foo] => Array ( [bar] => foo bar [baz] => foo baz [bat] => Array ( [faz] => foo bat faz ) ) ) What methods are there to convert or flatten this array into a data structure such as: Array ( [foo[bar]] => foo bar [foo[baz]] => foo baz [foo[bat][faz]] => foo bat faz )

    Read the article

  • Cleaning up code - flatten a nested hash structure

    - by knorv
    The following Perl sub flattens a nested hash structure: sub flatten { my $hashref = shift; my %hash; my %i = %{$hashref}; foreach my $ii (keys(%i)) { my %j = %{$i{$ii}}; foreach my $jj (keys(%j)) { my %k = %{$j{$jj}}; foreach my $kk (keys(%k)) { my $value = $k{$kk}; $hash{$kk} = $value; } } } return %hash; } While the code works it is not very readable or clean. My question is two-fold: In what ways does it not correspond to modern Perl best practices? How would you clean it up?

    Read the article

  • Array Flatten does not work (Instance variable nil)

    - by Nick
    I was trying to write a simple array flatten method, but it does not work using instance variable. It works only using class variables. Can anyone tell me why? and how to make it work using instance variables. class Array @y = [] def flatten_array self.each do |x| if x.class.to_s != 'Array' @y << x else x.flatten_array end end return @y end end a = [1,2,3,4,5] b = [6,7,8] c = [9,10] a1 = [12,13,a,b,c] puts a1.inspect b1 = a1.flatten_array puts b1.inspect

    Read the article

  • Array Flatten does not work (Instnace variable nil)

    - by Nick
    I was trying to write a simple array flatten method, but it does not work using instance variable. It works only using class variables. Can anyone tell me why? and how to make it work using instance variables. class Array @y = [] def flatten_array self.each do |x| if x.class.to_s != 'Array' @y << x else x.flatten_array end end return @y end end a = [1,2,3,4,5] b = [6,7,8] c = [9,10] a1 = [12,13,a,b,c] puts a1.inspect b1 = a1.flatten_array puts b1.inspect

    Read the article

  • Array Flatten does not work (Instanace variable nil)

    - by Nick
    I was trying to write a simple array flatten method, but it does not work using instance variable. It works only using class variables. Can anyone tell me why? and how to make it work using instance variables. class Array @y = [] def flatten_array self.each do |x| if x.class.to_s != 'Array' @y << x else x.flatten_array end end return @y end end a = [1,2,3,4,5] b = [6,7,8] c = [9,10] a1 = [12,13,a,b,c] puts a1.inspect b1 = a1.flatten_array puts b1.inspect

    Read the article

  • Flatten XML using XSLT but based on nesting level

    - by user2532750
    I'm new to XSLT and I'm trying to write some XSLT that will flatten any given XML such that a new line occurs whenever the nesting level changes. My input can be any XML document, with any number of nested levels so the structure isn't known to the XSLT. Due to the tools available to me, my solution has to use XSLT version 1.0. For example. <?xml version="1.0"?> <ROWSET> <ROW> <CUSTOMER_ID>0</CUSTOMER_ID> <NAME>Default Company</NAME> <BONUSES> <BONUSES_ROW> <BONUS_ID>21</BONUS_ID> <DESCRIPTION>Performance Bonus</DESCRIPTION> </BONUSES_ROW> <BONUSES_ROW> <BONUS_ID>26</BONUS_ID> <DESCRIPTION>Special Bonus</DESCRIPTION> </BONUSES_ROW> </BONUSES> </ROW> <ROW> <CUSTOMER_ID>1</CUSTOMER_ID> <NAME>Dealer 1</NAME> <BONUSES> <BONUSES_ROW> <BONUS_ID>27</BONUS_ID> <DESCRIPTION>June Bonus</DESCRIPTION> <BONUS_VALUES> <BONUS_VALUES_ROW> <VALUE>10</VALUE> <PERCENT>N</PERCENT> </BONUS_VALUES_ROW> <BONUS_VALUES_ROW> <VALUE>11</VALUE> <PERCENT>Y</PERCENT> </BONUS_VALUES_ROW> </BONUS_VALUES> </BONUSES_ROW> </BONUSES> </ROW> <ROWSET> needs to becomes.... 0, Default Company 21, Performance Bonus 26, Special Bonus 1, Dealer 1 27, June Bonus 10, N 11, Y The XSLT I've written so far is... <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text" encoding="iso-8859-1"/> <xsl:strip-space elements="*" /> <xsl:template match="/*/child::*"> <xsl:apply-templates select="*"/> </xsl:template> <xsl:template match="*"> <xsl:value-of select="text()" /> <xsl:if test="position()!= last()"><xsl:text>,</xsl:text></xsl:if> <xsl:if test="position()= last()"><xsl:text>&#xD;</xsl:text></xsl:if> <xsl:apply-templates select="./child::*"/> </xsl:template> </xsl:stylesheet> but my output just isn't correct, with gaps and unnecessary data. 0,Default Company, ,21,Performance Bonus 26,Special Bonus 1,Dealer 1, 27,June Bonus, ,10,N 11,Y It seems there needs to be a check as whether or not a node can contain text, but I'm stuck and could do with an XSLT expert's help.

    Read the article

  • amazon mws orders help simplify, flatten xml

    - by Scott Kramer
    XDocument doc = XDocument.Load( filename ); var ele = doc.Elements("AmazonEnvelope") //.Elements("Header") .Elements("Message") .Elements("OrderReport") .Elements("Item") .Select(element => new { AmazonOrderItemCode = (string)element.Element("AmazonOrderItemCode"), SKU = (string)element.Element("SKU"), Title = (string)element.Element("Title"), Quantity = (string)element.Element("Quantity"), }) //.Elements("ItemPrice") //.Elements("Component") //.Select(element => new //{ // Type = (string)element.Element("Type"), // Amount = (string)element.Element("Amount"), // }) .ToList(); foreach (var x in ele) { Console.WriteLine(x.ToString()); }

    Read the article

  • Programming pattern to flatten deeply nested ajax callbacks?

    - by chiborg
    I've inherited JavaScript code where the success callback of an Ajax handler initiates another Ajax call where the success callback may or may not initiate another Ajax call. This leads to deeply nested anonymous functions. Maybe there is a clever programming pattern that avoids the deep-nesting and is more DRY. jQuery.extend(Application.Model.prototype, { process: function() { jQuery.ajax({ url:myurl1, dataType:'json', success:function(data) { // process data, then send it back jQuery.ajax({ url:myurl2, dataType:'json', success:function(data) { if(!data.ok) { jQuery.ajax({ url:myurl2, dataType:'json', success:mycallback }); } else { mycallback(data); } } }); } }); } });

    Read the article

  • Use Automapper to flatten sub-class of property

    - by Neil
    Given the classes: public class Person { public string Name { get; set; } } public class Student : Person { public int StudentId { get; set; } } public class Source { public Person Person { get; set; } } public class Dest { public string PersonName { get; set; } public int? PersonStudentId { get; set; } } I want to use Automapper to map Source - Dest. This test obviously fails: Mapper.CreateMap<Source, Dest>(); var source = new Source() { Person = new Student(){ Name = "J", StudentId = 5 }}; var dest = Mapper.Map<Source, Dest>(source); Assert.AreEqual(5, dest.PersonStudentId); What would be the best approach to mapping this given that "Person" is actually a heavily used data-type throughout our domain model.

    Read the article

  • Flatten date range memberships retaining only the highest priority membership (TRANSACT-SQL)

    - by shadowranger
    Problem statement: A table contains an item_id, a category_id and a date range (begin_date and end_date). No item may be in more than one category on any given date (in general; during daily rebuilding it can be in an invalid state temporarily). By default, all items are added (and re-added if removed) to a category (derived from outside data) automatically on a daily basis, and their membership in that category matches the lifespan of the item (items have their own begin and end date, and usually spend their entire lives in the same category, which is why this matches). For items in category X, it is occasionally desirable to override the default category by adding them to category Y. Membership in category Y could entirely replace membership in category X (that is, the begin and end dates for membership in category Y would match the begin and end dates of the item itself), or it could override it for an arbitrary period of time (at the beginning, middle or end the item's lifespan, possibly overriding for short periods at multiple times). Membership in category Y is not renewed automatically and additions to that category is done by manual data entry. Every day, when category X is rebuilt, we get an overlap, where any item in category Y will now be in category X as well (which is forbidden, as noted previously). Goal: After each repopulation of category X (which is done in a rather complicated and fragile manner, and ideally would be left alone), I'm trying to find an efficient means of writing a stored procedure that: Identifies the overlaps Changes existing entries, adds new ones where necessary (such as in the case where an item starts in category X, switches to category Y, then eventually switches back to category X before ending), or removes entries (when an item is in category Y for its entire life) such that every item remains in category Y (and only Y) where specified, while category X membership is maintained when not overridden by category Y. Does not affect memberships of categories A, B, C, Z, etc., which do not have override categories and are built separately, by completely different rules. Note: It can be assumed that X membership covers the entire lifespan of the item before this procedure is called, so it is unnecessary to query any data outside this table. Bonus credit: If for some reason there are two adjacent or overlapping memberships in for the same item in category Y, stitching them together into a single entry is appreciated, but not necessary. Example: item_id category_id begin_date end_date 1 X 20080101 20090628 1 Y 20090101 20090131 1 Y 20090601 20090628 2 X 20080201 20080731 2 Y 20080201 20080731 Should become: item_id category_id begin_date end_date 1 X 20080101 20081231 1 Y 20090101 20090131 1 X 20090201 20090531 1 Y 20090601 20090628 2 Y 20080201 20080731 If it matters, this needs to work on SQL Server 2005 and SQL Server 2008

    Read the article

  • Simplest way to flatten document to a view in RavenDB

    - by degorolls
    Given the following classes: public class Lookup { public string Code { get; set; } public string Name { get; set; } } public class DocA { public string Id { get; set; } public string Name { get; set; } public Lookup Currency { get; set; } } public class ViewA // Simply a flattened version of the doc { public string Id { get; set; } public string Name { get; set; } public string CurrencyName { get; set; } // View just gets the name of the currency } I can create an index that allows client to query the view as follows: public class A_View : AbstractIndexCreationTask<DocA, ViewA> { public A_View() { Map = docs => from doc in docs select new ViewA { Id = doc.Id, Name = doc.Name, CurrencyName = doc.Currency.Name }; Reduce = results => from result in results group on new ViewA { Id = result.Id, Name = result.Name, CurrencyName = result.CurrencyName } into g select new ViewA { Id = g.Key.Id, Name = g.Key.Name, CurrencyName = g.Key.CurrencyName }; } } This certainly works and produces the desired result of a view with the data transformed to the structure required at the client application. However, it is unworkably verbose, will be a maintenance nightmare and is probably fairly inefficient with all the redundant object construction. Is there a simpler way of creating an index with the required structure (ViewA) given a collection of documents (DocA)? FURTHER INFORMATION The issue appears to be that in order to have the index hold the data in the transformed structure (ViewA), we have to do a Reduce. It appears that a Reduce must have both a GROUP ON and a SELECT in order to work as expected so the following are not valid: INVALID REDUCE CLAUSE 1: Reduce = results => from result in results group on new ViewA { Id = result.Id, Name = result.Name, CurrencyName = result.CurrencyName } into g select g.Key; This produces: System.InvalidOperationException: Variable initializer select must have a lambda expression with an object create expression Clearly we need to have the 'select new'. INVALID REDUCE CLAUSE 2: Reduce = results => from result in results select new ViewA { Id = result.Id, Name = result.Name, CurrencyName = result.CurrencyName }; This prduces: System.InvalidCastException: Unable to cast object of type 'ICSharpCode.NRefactory.Ast.IdentifierExpression' to type 'ICSharpCode.NRefactory.Ast.InvocationExpression'. Clearly, we also need to have the 'group on new'. Thanks for any assistance you can provide. (Note: removing the type (ViewA) from the constructor calls has no effect on the above)

    Read the article

  • Flatten old history in Git

    - by schoetbi
    I have a git project that has run for a while and now I want to throw away the old history, say from start to two years back from now. With throw away I mean replace the many commits within this time with one single commit doing the same. I checked "git rebase -i " but this does not remove the other (full) history containing all commits from git. Here a graphical representation (d being the changesets): (base) -> d1 -> d2 -> d3 -> (HEAD) What I want is: (base,d1,d2) -> d3 -> (HEAD) How could this be done? Thanks.

    Read the article

  • How To Query Many-to-Many Table (one table's values becomes column headers)

    - by CRice
    Given this table structure, I want to flatten out the many-to-many relationships and make the values in the Name field of one table into column headers and the quantities from the same table into column values. The current idea which will work is to put the values into a Dictionary (hashtable) and represent this data in code but im wondering if there is a SQL way to do this. I am also using Linq-to-SQL for data access so a Linq-to-SQL solution would be ideal. [TableA] (int Id) [TableB] (int id, string Name) [TableAB] (int tableAId, int tableBId, int Quantity) fk: TableA.Id joins to TableAB.tableAId fk: TableB.Id joins to TableAB.tableBId Is there a way I can query the three tables and return one result for example: TableA [Id] 1 TableB [Id], [Name] 1, "Red" 2, "Green" 3, "Blue" TableAB [TableAId], [TableBId], [Quantity] 1 1 5 1 2 6 1 3 7 Query Result: [TableA.Id], [Red], [Green], [Blue] 1, 5, 6, 7

    Read the article

  • Why doesn't Python have a "flatten" function for lists?

    - by Hubro
    Erlang and Ruby both come with functions for flattening arrays. It seems like such a simple and useful tool to add to a language. One could do this: >>> mess = [[1, [2]], 3, [[[4, 5]], 6]] >>> mess.flatten() [1, 2, 3, 4, 5, 6] Or even: >>> import itertools >>> mess = [[1, [2]], 3, [[[4, 5]], 6]] >>> list(itertools.flatten(mess)) [1, 2, 3, 4, 5, 6] Instead, in Python, one has to go through the trouble of writing a function for flattening arrays from scratch. This seems silly to me, flattening arrays is such a common thing to do. It's like having to write a custom function for concatenating two arrays. I have Googled this fruitlessly, so I'm asking here; is there a particular reason why a mature language like Python 3, which comes with a hundred thousand various batteries included, doesn't provide a simple method of flattening arrays? Has the idea of including such a function been discussed and rejected at some point?

    Read the article

  • AutoMapper and flattening nested arrays

    - by Bryan Slatner
    I'm trying to use AutoMapper to flatten multiple levels of arrays. Consider the following source classes: class X { public string A { get; set; } public Y[] B { get; set; } } class Y { public string C { get; set; } public Z[] D { get; set; } } class Z { public string E { get; set; } public string F { get; set; } } And the following destination: class Destination { public string A { get; set; } public string C { get; set; } public string E { get; set; } public string F { get; set; } } What I'd like to be able to do is get a List from one or more X, e.g.: Mapper.Map<IEnumerable<X>, IEnumerable<Destination>>(arrayOfX); I'm unable to figure out what sort of mapping configuration to use to achieve this. MapFrom seems like the way to go for 1:1 compositions, but doesn't seem to be able to handle the array (or other enumerable) unless I use AutoMapper's destination naming convention. Any insights on how to achieve this?

    Read the article

1 2 3 4 5 6 7  | Next Page >