Search Results

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

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

  • How can I totally flatten a PDF in Mac OS on the command line?

    - by Matthew Leingang
    I use Mac OS X Snow Leopard. I have a PDF with form fields, annotations, and stamps on it. I would like to freeze (or "flatten") that PDF so that the form fields can't be changed and the annotations/stamps are no longer editable. Since I actually have many of these PDFs, I want to do this automatically on the command line. Some things I've tried/considered, with their degree of success: Open in Preview and Print to File. This creates a totally flat PDF without changing the file size. The only way to automate seems to be to write a kludgy UI-based AppleScript, though, which I've been trying to avoid. Open in Acrobat Pro and use a JavaScript function to flatten. Again, not sure how to automate this on the command line. Use pdftk with the flatten option. But this only flattens form fields, not stamps and other annotations. Use cupsfilter which can create PDF from many file formats. Like pdftk this flattened only the form fields. Use cups-pdf to hook into the Mac's printserver and save a PDF file instead of print. I used the macports version. The resulting file is flat but huge. I tried this on an 8MB file; the flattened PDF was 358MB! Perhaps this can be combined with a ghostscript call as in Ubuntu Tip:Howto reduce PDF file size from command line. Any other suggestions would be appreciated.

    Read the article

  • How to write a recursive function that returns a linked list of nodes, when given a binary tree of n

    - by Jian Lin
    I was once asked of this in an interview: How to write a recursive function that returns a linked list of nodes, when given a binary tree of nodes? (flattening the data) For some reason, I tend to need more than 3 to 5 minutes to solve any recursive problem. Usually, 15 to 20 minutes will be more like it. How could we attack this problem, such as a very systematic way of reaching a solution, so that they can be solved in 3 to 5 minute time frame?

    Read the article

  • How to Serialize Binary Tree

    - by Veljko Skarich
    I went to an interview today where I was asked to serialize a binary tree. I implemented an array-based approach where the children of node i (numbering in level-order traversal) were at the 2*i index for the left child and 2*i + 1 for the right child. The interviewer seemed more or less pleased, but I'm wondering what serialize means exactly? Does it specifically pertain to flattening the tree for writing to disk, or would serializing a tree also include just turning the tree into a linked list, say. Also, how would we go about flattening the tree into a (doubly) linked list, and then reconstructing it? Can you recreate the exact structure of the tree from the linked list? Thank you/

    Read the article

  • Haskell FlatMap

    - by mvid
    I am a beginner interested in Haskell, and I have been trying to implement the flatmap (=) on my own to better understand it. Currently I have flatmap :: (t -> a) -> [t] -> [a] flatmap _ [] = [] flatmap f (x:xs) = f x : flatmap f xs which implements the "map" part but not the "flat". Most of the modifications I make result in the disheartening and fairly informationless Occurs check: cannot construct the infinite type: a = [a] When generalising the type(s) for `flatmap' error. What am I missing?

    Read the article

  • How to flatten list of options using higher order functions?

    - by Synesso
    Using Scala 2.7.7: If I have a list of Options, I can flatten them using a for-comprehension: val listOfOptions = List(None, Some("hi"), None) listOfOptions: List[Option[java.lang.String]] = List(None, Some(hi), None) scala> for (opt <- listOfOptions; string <- opt) yield string res0: List[java.lang.String] = List(hi) I don't like this style, and would rather use a HOF. This attempt is too verbose to be acceptable: scala> listOfOptions.flatMap(opt => if (opt.isDefined) Some(opt.get) else None) res1: List[java.lang.String] = List(hi) Intuitively I would have expected the following to work, but it doesn't: scala> List.flatten(listOfOptions) <console>:6: error: type mismatch; found : List[Option[java.lang.String]] required: List[List[?]] List.flatten(listOfOptions) Even the following seems like it should work, but doesn't: scala> listOfOptions.flatMap(_: Option[String]) <console>:6: error: type mismatch; found : Option[String] required: (Option[java.lang.String]) => Iterable[?] listOfOptions.flatMap(_: Option[String]) ^ The best I can come up with is: scala> listOfOptions.flatMap(_.toList) res2: List[java.lang.String] = List(hi) ... but I would much rather not have to convert the option to a list. That seems clunky. Any advice?

    Read the article

  • Ruby - Subclassing array to make it randomize when flattened

    - by Markus O'Reilly
    I'm trying to subclass Array in ruby to make it randomize its elements when flatten! is called. Looking at the source code for Array#flatten (http://ruby-doc.org/core/classes/Array.src/M002218.html), it looks like it should recursively call flatten! on any array contained within an array. So, I tried doing something like this: class RandArray < Array def randomize! self.sort!{rand(3)-1} end def flatten! randomize! super end end However, when a normal array contains my RandArray and flatten is called on the normal array, flatten! is never called in my array. I figure ruby is just calling some other method to flatten the arrays recursively, but I can't figure out what that is. Any tips?

    Read the article

  • Convert args to flat list?

    - by Mark
    I know this is very similar to a few other questions, but I can't quite get this function to work correctly. def flatten(*args): return list(item for iterable in args for item in iterable) The output I'm looking for is: flatten(1) -> [1] flatten(1,[2]) -> [1, 2] flatten([1,[2]]) -> [1, 2] The current function, which I from another SO answer doesn't seem to produce correct results at all: >>> flatten([1,[2]]) [1, [2]] I wrote the following function which seems to work for 0 or 1 levels of nesting, but not deeper: def flatten(*args): output = [] for arg in args: if hasattr(arg, '__iter__'): output += arg else: output += [arg] return output

    Read the article

  • Flattening a Jagged Array with LINQ

    - by PSteele
    Today I had to flatten a jagged array.  In my case, it was a string[][] and I needed to make sure every single string contained in that jagged array was set to something (non-null and non-empty).  LINQ made the flattening very easy.  In fact, I ended up making a generic version that I could use to flatten any type of jagged array (assuming it's a T[][]): private static IEnumerable<T> Flatten<T>(IEnumerable<T[]> data) { return from r in data from c in r select c; } Then, checking to make sure the data was valid, was easy: var flattened = Flatten(data); bool isValid = !flattened.Any(s => String.IsNullOrEmpty(s)); You could even use method grouping and reduce the validation to: bool isValid = !flattened.Any(String.IsNullOrEmpty); Technorati Tags: .NET,LINQ,Jagged Array

    Read the article

  • RecursiveIterator: used to explode tree structure, or only flatten?

    - by Stephen J. Fuhry
    There are tons of examples of using the RecursiveIterator to flatten a tree structure.. but what about using it to explode a tree structure? Is there an elegant way to use this, or some other SPL library to recursively build a tree (read: turn a flat array into array of arbitrary depth) given a table like this: SELECT id, parent_id, name FROM my_tree EDIT: You know how you can do this with Directories? $it = new RecursiveDirectoryIterator("/var/www/images"); foreach(new RecursiveIteratorIterator($it) as $file) { echo $file . PHP_EOL; } .. What if you could do something like this: $it = new RecursiveParentChildIterator($result_array); foreach(new RecursiveIteratorIterator($it) as $group) { echo $group->name . PHP_EOL; echo implode(PHP_EOL, $group->getChildren()) . PHP_EOL . PHP_EOL; } :END EDIT

    Read the article

  • How do I flatten an associative array into an array with only values in PHP?

    - by aalaap
    I have an array that has keys and values. For eg: Array ( [name] => aalaap [age] => 29 [location] => mumbai ) I want to convert the keys from this into values, but I want the values to apear right after the keys. For eg: Array ( [0] => name [1] => aalaap [2] => age [3] => 29 [4] => location [5] => mumbai ) I can easily write an iteration function that will do this... for eg: array_flatten($arr) { foreach ($arr as $arrkey => $arrval) { $arr_new[] = $arrkey; $arr_new[] = $arrval; } return $arr_new; } ...but I'm trying to find out if there's any way this can be accomplished using array_combine, array_keys, array_values and/or array_merge, preferably in one, so i don't need to use a custom function. Is there?

    Read the article

  • How can I perform an idiomatic non-recursive flatten in ruby?

    - by nasmorn
    I have a method that returns an array of arrays. For convenience I use collect on a collection to gather them together. arr = collection.collect {|item| item.get_array_of_arrays} Now I would like to have a single array that contains all the arrays. Of course I can loop over the array and use the + operator to do that. newarr = [] arr.each {|item| newarr += item} But this is kind of ugly, is there a better way?

    Read the article

  • Python - Flatten a dict of lists into unique values?

    - by Jonathan Vanasco
    I have a dict of lists in python: content = {88962: [80, 130], 87484: [64], 53662: [58,80]} I want to turn it into a list of the unique values [58,64,80,130] I wrote a manual solution, but it's a manual solution. I know there are more concise and more elegant way to do this with list comprehensions, map/reduce , itertools , etc. anyone have a clue ? content = {88962: [80, 130], 87484: [64], 53662: [58,80]} result = set({}) for k in content.keys() : for i in content[k]: result.add(i) # and list/sort/print just to compare the output r2 = list( result ) r2.sort() print r2

    Read the article

  • How can I cleanly turn a nested Perl hash into a non-nested one?

    - by knorv
    Assume a nested hash structure %old_hash .. my %old_hash; $old_hash{"foo"}{"bar"}{"zonk"} = "hello"; .. which we want to "flatten" (sorry if that's the wrong terminology!) to a non-nested hash using the sub &flatten(...) so that .. my %h = &flatten(\%old_hash); die unless($h{"zonk"} eq "hello"); The following definition of &flatten(...) does the trick: 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 given works it is not very readable or clean. My question is two-fold: In what ways does the given code not correspond to modern Perl best practices? Be harsh! :-) How would you clean it up?

    Read the article

  • Turning a nested hash structure into a non-nested hash structure - is this the cleanest way to do it

    - by knorv
    Assume a nested hash structure %old_hash .. my %old_hash; $old_hash{"foo"}{"bar"}{"zonk"} = "hello"; .. which we want to "flatten" (sorry if that's the wrong terminology!) to a non-nested hash using the sub &flatten(...) so that .. my %h = &flatten(\%old_hash); die unless($h{"zonk"} eq "hello"); The following definition of &flatten(...) does the trick: 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 given works it is not very readable or clean. My question is two-fold: In what ways does the given code not correspond to modern Perl best practices? Be harsh! :-) How would you clean it up?

    Read the article

  • Flattening hash into string in Ruby

    - by fahadsadah
    Is there a way to flatten a hash into a string, with optional delimiters between keys and values, and key/value pairs? For example, print {:a => :b, :c => :d}.flatten('=','&') should print a=b&c=d I wrote some code to do this, but I was wondering if there was a neater way: class Hash def flatten(keyvaldelimiter, entrydelimiter) string = "" self.each do |key, value| key = "#{entrydelimiter}#{key}" if string != "" #nasty hack string += "#{key}#{keyvaldelimiter}#{value}" end return string end end print {:a => :b, :c => :d}.flatten('=','&') #=> 'c=d&a=b' Thanks

    Read the article

  • One Exception to Aggregate Them All

    - by João Angelo
    .NET 4.0 introduced a new type of exception, the AggregateException which as the name implies allows to aggregate several exceptions inside a single throw-able exception instance. It is extensively used in the Task Parallel Library (TPL) and besides representing a simple collection of exceptions can also be used to represent a set of exceptions in a tree-like structure. Besides its InnerExceptions property which is a read-only collection of exceptions, the most relevant members of this new type are the methods Flatten and Handle. The former allows to flatten a tree hierarchy removing the need to recur while working with an aggregate exception. For example, if we would flatten the exception tree illustrated in the previous figure the result would be: The other method, Handle, accepts a predicate that is invoked for each aggregated exception and returns a boolean indicating if each exception is handled or not. If at least one exception goes unhandled then Handle throws a new AggregateException containing only the unhandled exceptions. The following code snippet illustrates this behavior and also another scenario where an aggregate exception proves useful – single threaded batch processing. static void Main() { try { ConvertAllToInt32("10", "x1x", "0", "II"); } catch (AggregateException errors) { // Contained exceptions are all FormatException // so Handle does not thrown any exception errors.Handle(e => e is FormatException); } try { ConvertAllToInt32("1", "1x", null, "-2", "#4"); } catch (AggregateException errors) { // Handle throws a new AggregateException containing // the exceptions for which the predicate failed. // In this case it will contain a single ArgumentNullException errors.Handle(e => e is FormatException); } } private static int[] ConvertAllToInt32(params string[] values) { var errors = new List<Exception>(); var integers = new List<int>(); foreach (var item in values) { try { integers.Add(Int32.Parse(item)); } catch (Exception e) { errors.Add(e); } } if (errors.Count > 0) throw new AggregateException(errors); return integers.ToArray(); }

    Read the article

  • Binary file email attachment problem

    - by Alan Harris-Reid
    Hi there, Using Python 3.1.2 I am having a problem sending binary attachment files (jpeg, pdf, etc.) - MIMEText attachments work fine. The code in question is as follows... for file in self.attachments: part = MIMEBase('application', "octet-stream") part.set_payload(open(file,"rb").read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % file) msg.attach(part) # msg is an instance of MIMEMultipart() server = smtplib.SMTP(host, port) server.login(username, password) server.sendmail(from_addr, all_recipients, msg.as_string()) However, way down in the calling-stack (see traceback below), it looks as though msg.as_string() has received an attachment which creates a payload of 'bytes' type instead of string. Has anyone any idea what might be causing the problem? Any help would be appreciated. Alan builtins.TypeError: string payload expected: File "c:\Dev\CommonPY\Scripts\email_send.py", line 147, in send server.sendmail(self.from_addr, all_recipients, msg.as_string()) File "c:\Program Files\Python31\Lib\email\message.py", line 136, in as_string g.flatten(self, unixfrom=unixfrom) File "c:\Program Files\Python31\Lib\email\generator.py", line 76, in flatten self._write(msg) File "c:\Program Files\Python31\Lib\email\generator.py", line 101, in _write self._dispatch(msg) File "c:\Program Files\Python31\Lib\email\generator.py", line 127, in _dispatch meth(msg) File "c:\Program Files\Python31\Lib\email\generator.py", line 181, in _handle_multipart g.flatten(part, unixfrom=False) File "c:\Program Files\Python31\Lib\email\generator.py", line 76, in flatten self._write(msg) File "c:\Program Files\Python31\Lib\email\generator.py", line 101, in _write self._dispatch(msg) File "c:\Program Files\Python31\Lib\email\generator.py", line 127, in _dispatch meth(msg) File "c:\Program Files\Python31\Lib\email\generator.py", line 155, in _handle_text raise TypeError('string payload expected: %s' % type(payload))

    Read the article

  • How can I export PDF from InDesign so that transparency renders properly on all platforms?

    - by strangeronyourtrain
    Gradients, including drop shadows, all show up as solid blocks when I view my document on an Android phone. I tried different PDF compression and compatibility settings in an attempt to flatten and rasterize all the graphics, but it's clearly not working, as the Android viewer still identifies the outlines of transparent shapes instead of the blended pixels. Is there any way to truly flatten these PDF graphics, so that it doesn't matter whether a PDF viewer supports transparency, while keeping the text as text?

    Read the article

  • Inlining the LaTeX \input Command

    - by reprogrammer
    I'm looking a program to recursively inline all \input{} commands in a LaTeX file. By "recursively", I mean doing the inlining iteratively until no \input{} command remains in the final LaTeX file. I've already come across the flatten package. But, for some reason, my TeXLive distribution doesn't install it. When I execute the command sudo tlmgr show flatten, I get the error message: tlmgr: cannot find flatten. So, I'm looking for alternative tools that are more standard and easier to install.

    Read the article

  • Problem understanding treesort in Haskell

    - by Jerry
    I am trying to figure out how exactly does treesort from here work (I understand flatten, insert and foldr). I suppose what's being done in treesort is applying insert for each element on the list thus generating a tree and then flattening it. The only problem I can't overcome here is where the list (that is the argument of the function) is hiding (because it is not written anywhere as an argument except for the function type declaration). One more thing: since dot operator is function composition, why is it an error when I change: treesort = flatten . foldr insert Leaf to treesort = flatten( foldr insert Leaf )?

    Read the article

  • Unicode replacement characters for text matching

    - by Christian Harms
    I have some fun with unicode text sources (all correct encodet) and I want to match names. The classic problem, one source comes correctly, an other has more flatten names: "Elblag" vs. "Elblag" (see the character a) How can I "flatten" a, á, â or à to a for better matching? Are there unicode to ascii- matching tables?

    Read the article

  • Ruby on Rails Associations

    - by Eef
    Hey all, I am starting to create my sites in Ruby on Rails these days instead of PHP. I have picked up the language easily but still not 100% confident with associations :) I have this situation: User Model has_and_belongs_to_many :roles Roles Model has_and_belongs_to_many :users Journal Model has_and_belongs_to_many :roles So I have a roles_users table and a journals_roles table I can access the user roles like so: user = User.find(1) User.roles This gives me the roles assigned to the user, I can then access the journal model like so: journals = user.roles.first.journals This gets me the journals associated with the user based on the roles. I want to be able to access the journals like so user.journals In my user model I have tried this: def journals self.roles.collect { |role| role.journals }.flatten end This gets me the journals in a flatten array but unfortunately I am unable to access anything associated with journals in this case, e.g in the journals model it has: has_many :items When I try to access user.journals.items it does not work as it is a flatten array which I am trying to access the has_many association. Is it possible to get the user.journals another way other than the way I have shown above with the collect method? Hope you guys understand what I mean, if not let me know and ill try to explain it better. Cheers Eef

    Read the article

  • How to reshape matrices in Mathematica

    - by speciousfool
    When manipulating matrices it is often convenient to change their shape. For instance, to turn an N x M sized matrix into a vector of length N X M. In MATLAB a reshape function exists: RESHAPE(X,M,N) returns the M-by-N matrix whose elements are taken columnwise from X. An error results if X does not have M*N elements. In the case of converting between a matrix and vector I can use the Mathematica function Flatten which takes advantage of Mathematica's nested list representation for matrices. As a quick example, suppose I have a matrix X: With Flatten[X] I can get the vector {1,2,3,...,16}. But what would be far more useful is something akin to applying Matlab's reshape(X,2,8) which would result in the following Matrix: This would allow creation of arbitrary matrices as long as the dimensions equal N*M. As far as I can tell, there isn't anything built in which makes me wonder if someone hasn't coded up a Reshape function of their own.

    Read the article

< Previous Page | 1 2 3 4 5 6 7  | Next Page >