Search Results

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

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

  • MSDN Example of handling an exception from the TPL - Is this a race condition?

    - by David
    I'm looking at the TPL exception handling example from MSDN @ http://msdn.microsoft.com/en-us/library/dd537614(v=VS.100).aspx The basic form of the code is: Task task1 = Task.Factory.StartNew(() => { throw new IndexOutOfRangeException(); }); try { task1.Wait(); } catch (AggregateException ae) { throw ae.Flatten(); } My question is: Is this a race condition? What happens if task1 throws before the try has executed? Am I missing something that stops this being a race? Shouldn't it be written like this instead: try { Task task1 = Task.Factory.StartNew(() => { throw new IndexOutOfRangeException(); }); task1.Wait(); } catch (AggregateException ae) { throw ae.Flatten(); }

    Read the article

  • Bundler isn't loading gems

    - by Garrett
    I have been having a problem with using Bundler and being able to access my gems without having to require them somewhere, as config.gem used to do that for me (as far as I know). In my Rails 3 app, I defined my Gemfile like so: clear_sources source "http://gemcutter.org" source "http://gems.github.com" bundle_path "vendor/bundler_gems" ## Bundle edge rails: git "git://github.com/rails/arel.git" git "git://github.com/rails/rack.git" gem "rails", :git => "git://github.com/rails/rails.git" ## Bundle gem "mongo_mapper", :git => "git://github.com/jnunemaker/mongomapper.git" gem "bluecloth", ">= 2.0.0" Then I run gem bundle, it bundles it all up like expected. Inside the environment.rb file that is included within boot.rb it looks like this: # DO NOT MODIFY THIS FILE module Bundler file = File.expand_path(__FILE__) dir = File.dirname(file) ENV["PATH"] = "#{dir}/../../../../bin:#{ENV["PATH"]}" ENV["RUBYOPT"] = "-r#{file} #{ENV["RUBYOPT"]}" $LOAD_PATH.unshift File.expand_path("#{dir}/gems/builder-2.1.2/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/builder-2.1.2/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/text-hyphen-1.0.0/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/text-hyphen-1.0.0/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/i18n-0.3.3/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/i18n-0.3.3/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/dirs/arel/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/dirs/arel/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/dirs/rails/activemodel/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/dirs/rails/activemodel/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/jnunemaker-validatable-1.8.1/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/jnunemaker-validatable-1.8.1/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/abstract-1.0.0/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/abstract-1.0.0/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/erubis-2.6.5/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/erubis-2.6.5/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/mime-types-1.16/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/mime-types-1.16/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/mail-2.1.2/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/mail-2.1.2/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/rake-0.8.7/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/rake-0.8.7/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/dirs/rails/railties/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/dirs/rails/railties/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/memcache-client-1.7.7/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/memcache-client-1.7.7/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/dirs/rack/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/dirs/rack/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/rack-test-0.5.3/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/rack-test-0.5.3/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/rack-mount-0.4.5/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/rack-mount-0.4.5/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/dirs/rails/actionpack/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/dirs/rails/actionpack/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/bluecloth-2.0.7/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/bluecloth-2.0.7/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/bluecloth-2.0.7/ext") $LOAD_PATH.unshift File.expand_path("#{dir}/dirs/rails/activerecord/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/dirs/rails/activerecord/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/text-format-1.0.0/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/text-format-1.0.0/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/dirs/rails/actionmailer/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/dirs/rails/actionmailer/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/tzinfo-0.3.16/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/tzinfo-0.3.16/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/dirs/rails/activesupport/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/dirs/rails/activesupport/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/dirs/rails/activeresource/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/dirs/rails/activeresource/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/dirs/rails/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/dirs/rails/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/mongo-0.18.2/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/mongo-0.18.2/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/dirs/mongomapper/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/dirs/mongomapper/lib") @gemfile = "#{dir}/../../../../Gemfile" require "rubygems" unless respond_to?(:gem) # 1.9 already has RubyGems loaded @bundled_specs = {} @bundled_specs["builder"] = eval(File.read("#{dir}/specifications/builder-2.1.2.gemspec")) @bundled_specs["builder"].loaded_from = "#{dir}/specifications/builder-2.1.2.gemspec" @bundled_specs["text-hyphen"] = eval(File.read("#{dir}/specifications/text-hyphen-1.0.0.gemspec")) @bundled_specs["text-hyphen"].loaded_from = "#{dir}/specifications/text-hyphen-1.0.0.gemspec" @bundled_specs["i18n"] = eval(File.read("#{dir}/specifications/i18n-0.3.3.gemspec")) @bundled_specs["i18n"].loaded_from = "#{dir}/specifications/i18n-0.3.3.gemspec" @bundled_specs["arel"] = eval(File.read("#{dir}/specifications/arel-0.2.pre.gemspec")) @bundled_specs["arel"].loaded_from = "#{dir}/specifications/arel-0.2.pre.gemspec" @bundled_specs["activemodel"] = eval(File.read("#{dir}/specifications/activemodel-3.0.pre.gemspec")) @bundled_specs["activemodel"].loaded_from = "#{dir}/specifications/activemodel-3.0.pre.gemspec" @bundled_specs["jnunemaker-validatable"] = eval(File.read("#{dir}/specifications/jnunemaker-validatable-1.8.1.gemspec")) @bundled_specs["jnunemaker-validatable"].loaded_from = "#{dir}/specifications/jnunemaker-validatable-1.8.1.gemspec" @bundled_specs["abstract"] = eval(File.read("#{dir}/specifications/abstract-1.0.0.gemspec")) @bundled_specs["abstract"].loaded_from = "#{dir}/specifications/abstract-1.0.0.gemspec" @bundled_specs["erubis"] = eval(File.read("#{dir}/specifications/erubis-2.6.5.gemspec")) @bundled_specs["erubis"].loaded_from = "#{dir}/specifications/erubis-2.6.5.gemspec" @bundled_specs["mime-types"] = eval(File.read("#{dir}/specifications/mime-types-1.16.gemspec")) @bundled_specs["mime-types"].loaded_from = "#{dir}/specifications/mime-types-1.16.gemspec" @bundled_specs["mail"] = eval(File.read("#{dir}/specifications/mail-2.1.2.gemspec")) @bundled_specs["mail"].loaded_from = "#{dir}/specifications/mail-2.1.2.gemspec" @bundled_specs["rake"] = eval(File.read("#{dir}/specifications/rake-0.8.7.gemspec")) @bundled_specs["rake"].loaded_from = "#{dir}/specifications/rake-0.8.7.gemspec" @bundled_specs["railties"] = eval(File.read("#{dir}/specifications/railties-3.0.pre.gemspec")) @bundled_specs["railties"].loaded_from = "#{dir}/specifications/railties-3.0.pre.gemspec" @bundled_specs["memcache-client"] = eval(File.read("#{dir}/specifications/memcache-client-1.7.7.gemspec")) @bundled_specs["memcache-client"].loaded_from = "#{dir}/specifications/memcache-client-1.7.7.gemspec" @bundled_specs["rack"] = eval(File.read("#{dir}/specifications/rack-1.1.0.gemspec")) @bundled_specs["rack"].loaded_from = "#{dir}/specifications/rack-1.1.0.gemspec" @bundled_specs["rack-test"] = eval(File.read("#{dir}/specifications/rack-test-0.5.3.gemspec")) @bundled_specs["rack-test"].loaded_from = "#{dir}/specifications/rack-test-0.5.3.gemspec" @bundled_specs["rack-mount"] = eval(File.read("#{dir}/specifications/rack-mount-0.4.5.gemspec")) @bundled_specs["rack-mount"].loaded_from = "#{dir}/specifications/rack-mount-0.4.5.gemspec" @bundled_specs["actionpack"] = eval(File.read("#{dir}/specifications/actionpack-3.0.pre.gemspec")) @bundled_specs["actionpack"].loaded_from = "#{dir}/specifications/actionpack-3.0.pre.gemspec" @bundled_specs["bluecloth"] = eval(File.read("#{dir}/specifications/bluecloth-2.0.7.gemspec")) @bundled_specs["bluecloth"].loaded_from = "#{dir}/specifications/bluecloth-2.0.7.gemspec" @bundled_specs["activerecord"] = eval(File.read("#{dir}/specifications/activerecord-3.0.pre.gemspec")) @bundled_specs["activerecord"].loaded_from = "#{dir}/specifications/activerecord-3.0.pre.gemspec" @bundled_specs["text-format"] = eval(File.read("#{dir}/specifications/text-format-1.0.0.gemspec")) @bundled_specs["text-format"].loaded_from = "#{dir}/specifications/text-format-1.0.0.gemspec" @bundled_specs["actionmailer"] = eval(File.read("#{dir}/specifications/actionmailer-3.0.pre.gemspec")) @bundled_specs["actionmailer"].loaded_from = "#{dir}/specifications/actionmailer-3.0.pre.gemspec" @bundled_specs["tzinfo"] = eval(File.read("#{dir}/specifications/tzinfo-0.3.16.gemspec")) @bundled_specs["tzinfo"].loaded_from = "#{dir}/specifications/tzinfo-0.3.16.gemspec" @bundled_specs["activesupport"] = eval(File.read("#{dir}/specifications/activesupport-3.0.pre.gemspec")) @bundled_specs["activesupport"].loaded_from = "#{dir}/specifications/activesupport-3.0.pre.gemspec" @bundled_specs["activeresource"] = eval(File.read("#{dir}/specifications/activeresource-3.0.pre.gemspec")) @bundled_specs["activeresource"].loaded_from = "#{dir}/specifications/activeresource-3.0.pre.gemspec" @bundled_specs["rails"] = eval(File.read("#{dir}/specifications/rails-3.0.pre.gemspec")) @bundled_specs["rails"].loaded_from = "#{dir}/specifications/rails-3.0.pre.gemspec" @bundled_specs["mongo"] = eval(File.read("#{dir}/specifications/mongo-0.18.2.gemspec")) @bundled_specs["mongo"].loaded_from = "#{dir}/specifications/mongo-0.18.2.gemspec" @bundled_specs["mongo_mapper"] = eval(File.read("#{dir}/specifications/mongo_mapper-0.6.10.gemspec")) @bundled_specs["mongo_mapper"].loaded_from = "#{dir}/specifications/mongo_mapper-0.6.10.gemspec" def self.add_specs_to_loaded_specs Gem.loaded_specs.merge! @bundled_specs end def self.add_specs_to_index @bundled_specs.each do |name, spec| Gem.source_index.add_spec spec end end add_specs_to_loaded_specs add_specs_to_index def self.require_env(env = nil) context = Class.new do def initialize(env) @env = env && env.to_s ; end def method_missing(*) ; yield if block_given? ; end def only(*env) old, @only = @only, _combine_only(env.flatten) yield @only = old end def except(*env) old, @except = @except, _combine_except(env.flatten) yield @except = old end def gem(name, *args) opt = args.last.is_a?(Hash) ? args.pop : {} only = _combine_only(opt[:only] || opt["only"]) except = _combine_except(opt[:except] || opt["except"]) files = opt[:require_as] || opt["require_as"] || name files = [files] unless files.respond_to?(:each) return unless !only || only.any? {|e| e == @env } return if except && except.any? {|e| e == @env } if files = opt[:require_as] || opt["require_as"] files = Array(files) files.each { |f| require f } else begin require name rescue LoadError # Do nothing end end yield if block_given? true end private def _combine_only(only) return @only unless only only = [only].flatten.compact.uniq.map { |o| o.to_s } only &= @only if @only only end def _combine_except(except) return @except unless except except = [except].flatten.compact.uniq.map { |o| o.to_s } except |= @except if @except except end end context.new(env && env.to_s).instance_eval(File.read(@gemfile), @gemfile, 1) end end module Gem @loaded_stacks = Hash.new { |h,k| h[k] = [] } def source_index.refresh! super Bundler.add_specs_to_index end end But when I try to access any of my gems, e.g. MongoMapper, Paperclip, Haml, etc. I get: NameError: uninitialized constant MongoMapper The same goes for any other gem. Does Bundler not include gems like the old Rails 2.0 did? Or is something messed up with my system? Any help would be appreciated, thank you!

    Read the article

  • HasMany relation inside a Join Mapping

    - by Sean McMillan
    So, I'm having a problem mapping in fluent nhibernate. I want to use a join mapping to flatten an intermediate table: Here's my structure: [Vehicle] VehicleId ... [DTVehicleValueRange] VehicleId DTVehicleValueRangeId AverageValue ... [DTValueRange] DTVehicleValueRangeId RangeMin RangeMax RangeValue Note that DTValueRange does not have a VehicleID. I want to flatten DTVehicleValueRange into my Vehicle class. Tgis works fine for AverageValue, since it's just a plain value, but I can't seem to get a ValueRange collection to map correctly. public VehicleMap() { Id(x => x.Id, "VehicleId"); Join("DTVehicleValueRange", x => { x.Optional(); x.KeyColumn("VehicleId"); x.Map(y => y.AverageValue).ReadOnly(); x.HasMany(y => y.ValueRanges).KeyColumn("DTVehicleValueRangeId"); // This Guy }); } The HasMany mapping doesn't seem to do anything if it's inside the Join. If it's outside the Join and I specify the table, it maps, but nhibernate tries to use the VehicleID, not the DTVehicleValueRangeId. What am I doing wrong?

    Read the article

  • Getting Vars to bind properly across multiple files

    - by Alex Baranosky
    I am just learning Clojure and am having trouble moving my code into different files. I keep detting this error from the appnrunner.clj - Exception in thread "main" java.lang.Exception: Unable to resolve symbol: -run-application in this context It seems to be finding the namespaces fine, but then not seeing the Vars as being bound... Any idea how to fix this? Here's my code: APPLICATION RUNNER - (ns src/apprunner (:use src/functions)) (def input-files [(resource-path "a.txt") (resource-path "b.txt") (resource-path "c.txt")]) (def output-file (resource-path "output.txt")) (defn run-application [] (sort-files input-files output-file)) (-run-application) APPLICATION FUNCTIONS - (ns src/functions (:use clojure.contrib.duck-streams)) (defn flatten [x] (let [s? #(instance? clojure.lang.Sequential %)] (filter (complement s?) (tree-seq s? seq x)))) (defn resource-path [file] (str "C:/Users/Alex and Paula/Documents/SoftwareProjects/MyClojureApp/resources/" file)) (defn split2 [str delim] (seq (.split str delim))) (defstruct person :first-name :last-name) (defn read-file-content [file] (apply str (interpose "\n" (read-lines file)))) (defn person-from-line [line] (let [sections (split2 line " ")] (struct person (first sections) (second sections)))) (defn formatted-for-display [person] (str (:first-name person) (.toUpperCase " ") (:last-name person))) (defn sort-by-keys [struct-map keys] (sort-by #(vec (map % [keys])) struct-map)) (defn formatted-output [persons output-number] (let [heading (str "Output #" output-number "\n") sorted-persons-for-output (apply str (interpose "\n" (map formatted-for-display (sort-by-keys persons (:first-name :last-name)))))] (str heading sorted-persons-for-output))) (defn read-persons-from [file] (let [lines (read-lines file)] (map person-from-line lines))) (defn write-persons-to [file persons] (dotimes [i 3] (append-spit file (formatted-output persons (+ 1 i))))) (defn sort-files [input-files output-file] (let [persons (flatten (map read-persons-from input-files))] (write-persons-to output-file persons)))

    Read the article

  • d3.js force layout increase linkDistance

    - by user1159833
    How to increase linkDistance without affecting the node alignment, example: http://mbostock.github.com/d3/talk/20110921/force.html when I try to increase the circle radius and linkDistance the it collapse <script type="text/javascript"> var w = 1280, h = 800, z = d3.scale.category20c(); var force = d3.layout.force() .size([w, h]); var svg = d3.select("#chart").append("svg:svg") .attr("width", w) .attr("height", h); svg.append("svg:rect") .attr("width", w) .attr("height", h); d3.json("flare.json", function(root) { var nodes = flatten(root), links = d3.layout.tree().links(nodes); force .nodes(nodes) .links(links) .start(); var link = svg.selectAll("line") .data(links) .enter().insert("svg:line") .style("stroke", "#999") .style("stroke-width", "1px"); var node = svg.selectAll("circle.node") .data(nodes) .enter().append("svg:circle") .attr("r", 4.5) .style("fill", function(d) { return z(d.parent && d.parent.name); }) .style("stroke", "#000") .call(force.drag); force.on("tick", function(e) { link.attr("x1", function(d) { return d.source.x; }) .attr("y1", function(d) { return d.source.y; }) .attr("x2", function(d) { return d.target.x; }) .attr("y2", function(d) { return d.target.y; }); node.attr("cx", function(d) { return d.x; }) .attr("cy", function(d) { return d.y; }); }); }); function flatten(root) { var nodes = []; function recurse(node, depth) { if (node.children) { node.children.forEach(function(child) { child.parent = node; recurse(child, depth + 1); }); } node.depth = depth; nodes.push(node); } recurse(root, 1); return nodes; } </script>

    Read the article

  • how to determine if a character vector is a valid numeric or integer vector

    - by Andrew Barr
    I am trying to turn a nested list structure into a dataframe. The list looks similar to the following (it is serialized data from parsed JSON read in using the httr package). myList <- list(object1 = list(w=1, x=list(y=0.1, z="cat")), object2 = list(w=2, x=list(y=0.2, z="dog"))) unlist(myList) does a great job of recursively flattening the list, and I can then use lapply to flatten all the objects nicely. flatList <- lapply(myList, FUN= function(object) {return(as.data.frame(rbind(unlist(object))))}) And finally, I can button it up using plyr::rbind.fill myDF <- do.call(plyr::rbind.fill, flatList) str(myDF) #'data.frame': 2 obs. of 3 variables: #$ w : Factor w/ 2 levels "1","2": 1 2 #$ x.y: Factor w/ 2 levels "0.1","0.2": 1 2 #$ x.z: Factor w/ 2 levels "cat","dog": 1 2 The problem is that w and x.y are now being interpreted as character vectors, which by default get parsed as factors in the dataframe. I believe that unlist() is the culprit, but I can't figure out another way to recursively flatten the list structure. A workaround would be to post-process the dataframe, and assign data types then. What is the best way to determine if a vector is a valid numeric or integer vector?

    Read the article

  • How to store child objects on GAE using JDO from Scala

    - by Gero
    Hi, I'm have a parent-child relation between 2 classes, but the child objects are never stored. I do get an warning: "org.datanucleus.store.appengine.MetaDataValidator checkForIllegalChildField: Unable to validate relation net.vermaas.kivanotify.model.UserCriteria.internalCriteria" but it is unclear to me why this occurs. Already tried several alternatives without luck. The parent class is "UserCriteria" which has a List of "Criteria" as children. The classes are defined as follows (Scala): class UserCriteria(tu: String, crit: Map[String, String]) extends LogHelper { @PrimaryKey @Persistent{val valueStrategy = IdGeneratorStrategy.IDENTITY} var id = KeyFactory.createKey("UserCriteria", System.nanoTime) @Persistent var twitterUser = tu @Persistent var internalCriteria: java.util.List[Criteria] = flatten(crit) def flatten(crits: Map[String, String]) : java.util.List[Criteria] = { val list = new java.util.ArrayList[Criteria] for (key <- crits.keySet) { list.add(new Criteria(this, key, crits(key))) } list } def criteria: Map[String, String] = { val crits = mutable.Map.empty[String, String] for (i <- 0 to internalCriteria.size-1) { crits(internalCriteria.get(i).name) = internalCriteria.get(i).value } Map.empty ++ crits } // Stripped the equals, canEquals, hashCode, toString code to keep the code snippet short... } @PersistenceCapable @EmbeddedOnly class Criteria(uc: UserCriteria, nm: String, vl: String) { @Persistent var userCriteria = uc @Persistent var name = nm @Persistent var value = vl override def toString = { "Criteria name: " + name + " value: " + value } } Any ideas why the childs are not stored? Or why I get the error message? Thanks, Gero

    Read the article

  • rails named_scope issue with eager loading

    - by Craig
    Two models (Rails 2.3.8): User; username & disabled properties; User has_one :profile Profile; full_name & hidden properties I am trying to create a named_scope that eliminate the disabled=1 and hidden=1 User-Profiles. Moreover, while the User model is usually used in conjunction with the Profile model, I would like the flexibility to be able specify this using the :include = :profile syntax. I have the following User named_scope: named_scope :visible, { :joins => "INNER JOIN profiles ON users.id=profiles.user_id", :conditions => ["users.disabled = ? AND profiles.hidden = ?", false, false] } This works as expected when just reference the User model: >> User.visible.map(&:username).flatten => ["user a", "user b", "user c", "user d"] However, when I attempt to include the Profile model: User.visible(:include=> :profiles).profile.map(&:full_name).flatten I get an error that reads: NoMethodError: undefined method `profile' for #<User:0x1030bc828> Am I able to cross model-collection boundaries in this manner?

    Read the article

  • Top n items in a List ( including duplicates )

    - by Krishnan
    Trying to find an efficient way to obtain the top N items in a very large list, possibly containing duplicates. I first tried sorting & slicing, which works. But this seems unnnecessary. You shouldn't need to sort a very large list if you just want the top 20 members. So I wrote a recursive routine which builds the top-n list. This also works, but is very much slower than the non-recursive one! Question: Which is my second routine (elite2) so much slower than elite, and how do I make it faster ? My code is attached below. Thanks. import scala.collection.SeqView import scala.math.min object X { def elite(s: SeqView[Int, List[Int]], k:Int):List[Int] = { s.sorted.reverse.force.slice(0,min(k,s.size)) } def elite2(s: SeqView[Int, List[Int]], k:Int, s2:List[Int]=Nil):List[Int] = { if( k == 0 || s.size == 0) s2.reverse else { val m = s.max val parts = s.force.partition(_==m) val whole = if( parts._1.size > 1) parts._1.tail:::parts._2 else parts._2 elite2( whole.view, k-1, m::s2 ) } } def main(args:Array[String]) = { val N = 1000000/3 val x = List(N to 1 by -1).flatten.map(x=>List(x,x,x)).flatten.view println(elite2(x,20)) println(elite(x,20)) } }

    Read the article

  • Automating the choice between JPEG and PNG with a script

    - by MHC
    Choosing the right format to save your images in is crucial for preserving image quality and reducing artifacts. Different formats follow different compression methods and come with their own set of advantages and disadvantages. JPG, for instance is suited for real life photographs that are rich in color gradients. The lossless PNG, on the other hand, is far superior when it comes to schematic figures: Picking the right format can be a chore when working with a large number of files. That's why I would love to find a way to automate it. A little bit of background on my particular use case: I am working on a number of handouts for a series of lectures at my unversity. The handouts are rich in figures, which I have to extract from PDF-formatted slides. Extracting these images gives me lossless PNGs, which are needlessly large at times. Converting these particular files to JPEG can reduce their size to up to less than 20% of their original file size, while maintaining the same quality. This is important as working with hundreds of large images in word processors is pretty crash-prone. Batch converting all extracted PNGs to JPEGs is not an option I am willing to follow, as many if not most images are better suited to be formatted as PNGs. Converting these would result in insignificant size reductions and sometimes even increases in filesize - that's at least what my test runs showed. What we can take from this is that file size after compression can serve as an indicator on what format is suited best for a particular image. It's not a particularly accurate predictor, but works well enough. So why not use it in form of a script: I included inotifywait because I would prefer for the script be executed automatically as soon as I drag an extracted image into a folder. This is a simpler version of the script that I've been using for the last couple of weeks: #!/bin/bash inotifywait -m --format "%w%f" --exclude '.jpg' -r -e create -e moved_to --fromfile '/home/MHC/.scripts/Workflow/Conversion/include_inotifywait' | while read file; do mogrify -format jpg -quality 92 "$file" done The advanced version of the script would have to be able to handle spaces in file names and directory names preserve the original file names flatten PNG images if an alpha value is set compare the file size between the temporary converted image and its original determine if the difference is greater than a given precentage act accordingly The actual conversion could be done with imagemagick tools: convert -quality 92 -flatten -background white file.png file.jpg Unfortunately, my bash skills aren't even close to advanced enough to convert the scheme above into an actual script, but I am sure many of you can. My reputation points on here are pretty low, but I will gladly award the most helpful answer with the highest bounty I can set. References: http://www.formortals.com/introducing-cnb-imageguide/, http://www.turnkeylinux.org/blog/png-vs-jpg Edit: Also see my comments below for some more information on why I think this script would be the best solution to the problem I am facing.

    Read the article

  • Microsoft Word Image Flattening?

    - by CaMiX
    I'm trying to find a way to flatten images in a MS Word 2007 document. I want the images that have text/labels placed/layered on top of them to be merged into a single image. Are there any tools or AddIns for Word that can do this? With a 100+ page document I'm trying to avoid a manual process... I can't believe Word doesn't have a feature or option hidden somewhere that can do this out of the box.

    Read the article

  • CAM XML Editor version 2.2.1 now available.

    - by drrwebber
    CAM Editor v2.2.1 release is now available. Lots of nice enhancements, CAMV performance boost and important bug fixes for DoD, NIEM and LEXS schema. Download is available from the CAM XML Editor Resource Site. The CAM editor is the leading open source XML Editor/Validation/Schema designer for rapidly building and deploying complete XML information exchanges. Provides a visual WYSIWYG structure with rule entry wizards and drag and drop dictionary components. Will import, analyze and refactor existing XML Schema. Oracle is a proud sponsor of the project and its use on the NIEM.gov initiative.Creates XSD schema + JAXB bindings, Mindmap or UML models (XMI), XML test suite examples, HTML documentation + spreadsheets (NIEM IEPDs). XSD schema export in default, flatten, NIEM, and OASIS modes. Generates canonical component dictionaries from schema sets, ERwin models, or spreadsheets.

    Read the article

  • How can I give my client "full access" to their PHP application's MySQL database?

    - by Micah Delane Bolen
    I am building a PHP application for a client and I'm seriously considering WordPress or a simple framework that will allow me to quickly build out features like forums, etc. However, the client is adamant about having "full access" to the database and the ability to "mine the data." Unfortunately, I'm almost certain they will be disappointed when they realize they won't be able to easily glean meaningful insight by looking at serialized fields in wp_usermeta, etc. One thought I had was to replicate a variation on the live database where I flatten out all of those ambiguous and/or serialized fields into something that is then parsable by a mere mortal using a tool as simple as phpMyAdmin. Unfortunately, the client is not going to settle for a simple backend dashboard where I create the custom reports for them even though I know that would be the easiest and most sane approach.

    Read the article

  • AbcPDF renders the same page multiple times

    - by Steven
    I need to retrieve several pages and output this in a PDF document. I have the following page structure: Page 1 Sub 1 Sub 2 Sub 3 On page one, I have a link which executes the below code. What it does, is to retrieve child pages (one level) and put them in a page collection. Then I loop trough the page collection and retrieve each sub pages URL. This works. I've tested and seen that it retrieves 3 different URL's. The problem is that my PDF gets three pages of Page 1. It does not render Sub 1 to 3. Why isn't docID = document.AddImageUrl(pageLink) retrieving the pages? Websupergoo refers to a caching problem which may occur. But their solution did not help me. Any good suggestions anyone? protected void linkBtnCreateMultipagePDF_Click(object sender, EventArgs e) { string baseURL = Request.Url.ToString(); PageDataCollection pdc = GetChildren(CurrentPageLink); //Create PDF document Doc document = new Doc(); document.Rect.Inset(10, 20); int docID; string pageLink = string.Empty; foreach (PageData pd in pdc) { //This lops goes through the different pages and retrieves that pages URL pageLink = baseURL + pd.LinkURL; document.Page = document.AddPage(); // But for some reason, the same page is added here. docID = document.AddImageUrl(pageLink); //Chain pages together while (true) { if (!document.Chainable(docID)) break; document.Page = document.AddPage(); docID = document.AddImageToChain(docID); } } //Flatten file for (int i = 1; i <= document.PageCount; i++) { document.PageNumber = i; document.Flatten(); } byte[] theData = document.GetData(); Response.Clear(); Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "inline; filename=MyPDF.PDF"); Response.AddHeader("content-length", theData.Length.ToString()); Response.BinaryWrite(theData); Response.End(); }

    Read the article

  • Rails/ActiveRecord Sub collection

    - by Jake
    I have three models: Store, Author, Books Store has many Authors which has many Books. What is the cleanest way to get a collection of all the books at the store? This works: @store.authors.collect{|a| a.books}.flatten Is there something in Active Record that I'm missing that makes this cleaner? Jake

    Read the article

  • Parse and transform XML with missing elements into table structure

    - by dnlbrky
    I'm trying to parse an XML file. A simplified version of it looks like this: x <- '<grandparent><parent><child1>ABC123</child1><child2>1381956044</child2></parent><parent><child2>1397527137</child2></parent><parent><child3>4675</child3></parent><parent><child1>DEF456</child1><child3>3735</child3></parent><parent><child1/><child3>3735</child3></parent></grandparent>' library(XML) xmlRoot(xmlTreeParse(x)) ## <grandparent> ## <parent> ## <child1>ABC123</child1> ## <child2>1381956044</child2> ## </parent> ## <parent> ## <child2>1397527137</child2> ## </parent> ## <parent> ## <child3>4675</child3> ## </parent> ## <parent> ## <child1>DEF456</child1> ## <child3>3735</child3> ## </parent> ## <parent> ## <child1/> ## <child3>3735</child3> ## </parent> ## </grandparent> I'd like to transform the XML into a data.frame / data.table that looks like this: parent <- data.frame(child1=c("ABC123",NA,NA,"DEF456",NA), child2=c(1381956044, 1397527137, rep(NA, 3)), child3=c(rep(NA, 2), 4675, 3735, 3735)) parent ## child1 child2 child3 ## 1 ABC123 1381956044 NA ## 2 <NA> 1397527137 NA ## 3 <NA> NA 4675 ## 4 DEF456 NA 3735 ## 5 <NA> NA 3735 If each parent node always contained all of the possible elements ("child1", "child2", "child3", etc.), I could use xmlToList and unlist to flatten it, and then dcast to put it into a table. But the XML often has missing child elements. Here is an attempt with incorrect output: library(data.table) ## Flatten: dt <- as.data.table(unlist(xmlToList(x)), keep.rownames=T) setnames(dt, c("column", "value")) ## Add row numbers, but they're incorrect due to missing XML elements: dt[, row:=.SD[,.I], by=column][] column value row 1: parent.child1 ABC123 1 2: parent.child2 1381956044 1 3: parent.child2 1397527137 2 4: parent.child3 4675 1 5: parent.child1 DEF456 2 6: parent.child3 3735 2 7: parent.child3 3735 3 ## Reshape from long to wide, but some value are in the wrong row: dcast.data.table(dt, row~column, value.var="value", fill=NA) ## row parent.child1 parent.child2 parent.child3 ## 1: 1 ABC123 1381956044 4675 ## 2: 2 DEF456 1397527137 3735 ## 3: 3 NA NA 3735 I won't know ahead of time the names of the child elements, or the count of unique element names for children of the grandparent, so the answer should be flexible.

    Read the article

  • QAS custom address layout

    - by DaveC
    I have been given a new format to add to the QAS ini file Qawserve.ini and want to use this format in the GetFormattedAddress() method call. How do I specify that I want to use this new custom layout? I have tried using the name as specified above the layout in [Custom Layout], for example: objAddress = new QuickAddress(AppSettings.ReadSetting("qasServer")) { Engine = QuickAddress.EngineTypes.Singleline, Flatten = false }.GetFormattedAddress(Picklist.Items[selectedValue].Moniker, "Custom Layout");

    Read the article

  • How do you display a binary search tree?

    - by fakeit
    I'm being asked to display a binary search tree in sorted order. The nodes of the tree contain strings. I'm not exactly sure what the best way is to attack this problem. Should I be traversing the tree and displaying as I go? Should I flatten the tree into an array and then use a sorting algorithm before I display? I'm not looking for the actual code, just a guide where to go next.

    Read the article

  • How can I represent a line of music notes in a way that allows fast insertion at any index?

    - by chairbender
    For "fun", and to learn functional programming, I'm developing a program in Clojure that does algorithmic composition using ideas from this theory of music called "Westergaardian Theory". It generates lines of music (where a line is just a single staff consisting of a sequence of notes, each with pitches and durations). It basically works like this: Start with a line consisting of three notes (the specifics of how these are chosen are not important). Randomly perform one of several "operations" on this line. The operation picks randomly from all pairs of adjacent notes that meet a certain criteria (for each pair, the criteria only depends on the pair and is independent of the other notes in the line). It inserts 1 or several notes (depending on the operation) between the chosen pair. Each operation has its own unique criteria. Continue randomly performing these operations on the line until the line is the desired length. The issue I've run into is that my implementation of this is quite slow, and I suspect it could be made faster. I'm new to Clojure and functional programming in general (though I'm experienced with OO), so I'm hoping someone with more experience can point out if I'm not thinking in a functional paradigm or missing out on some FP technique. My current implementation is that each line is a vector containing maps. Each map has a :note and a :dur. :note's value is a keyword representing a musical note like :A4 or :C#3. :dur's value is a fraction, representing the duration of the note (1 is a whole note, 1/4 is a quarter note, etc...). So, for example, a line representing the C major scale starting on C3 would look like this: [ {:note :C3 :dur 1} {:note :D3 :dur 1} {:note :E3 :dur 1} {:note :F3 :dur 1} {:note :G3 :dur 1} {:note :A4 :dur 1} {:note :B4 :dur 1} ] This is a problematic representation because there's not really a quick way to insert into an arbitrary index of a vector. But insertion is the most frequently performed operation on these lines. My current terrible function for inserting notes into a line basically splits the vector using subvec at the point of insertion, uses conj to join the first part + notes + last part, then uses flatten and vec to make them all be in a one-dimensional vector. For example if I want to insert C3 and D3 into the the C major scale at index 3 (where the F3 is), it would do this (I'll use the note name in place of the :note and :dur maps): (conj [C3 D3 E3] [C3 D3] [F3 G3 A4 B4]), which creates [C3 D3 E3 [C3 D3] [F3 G3 A4 B4]] (vec (flatten previous-vector)) which gives [C3 D3 E3 C3 D3 F3 G3 A4 B4] The run time of that is O(n), AFAIK. I'm looking for a way to make this insertion faster. I've searched for information on Clojure data structures that have fast insertion but haven't found anything that would work. I found "finger trees" but they only allow fast insertion at the start or end of the list. Edit: I split this into two questions. The other part is here.

    Read the article

  • Limiting records in a model action...

    - by bgadoci
    How do I limit the number of records that I am outputting with the following code to only 3 records: User.rb def workouts_on_which_i_commented comments.map{|x|x.workout}.uniq end def comment_stream workouts_on_which_i_commented.map do |w| w.comments end.flatten.sort{|x,y| y.created_at <=> x.created_at} end html.erb file <% current_user.comment_stream.each do |comment| %> ... <% end %> UPDATE: I'm using Rails 2.3.9

    Read the article

  • RiverTrail - JavaScript GPPGU Data Parallelism

    - by JoshReuben
    Where is WebCL ? The Khronos WebCL working group is working on a JavaScript binding to the OpenCL standard so that HTML 5 compliant browsers can host GPGPU web apps – e.g. for image processing or physics for WebGL games - http://www.khronos.org/webcl/ . While Nokia & Samsung have some protype WebCL APIs, Intel has one-upped them with a higher level of abstraction: RiverTrail. Intro to RiverTrail Intel Labs JavaScript RiverTrail provides GPU accelerated SIMD data-parallelism in web applications via a familiar JavaScript programming paradigm. It extends JavaScript with simple deterministic data-parallel constructs that are translated at runtime into a low-level hardware abstraction layer. With its high-level JS API, programmers do not have to learn a new language or explicitly manage threads, orchestrate shared data synchronization or scheduling. It has been proposed as a draft specification to ECMA a (known as ECMA strawman). RiverTrail runs in all popular browsers (except I.E. of course). To get started, download a prebuilt version https://github.com/downloads/RiverTrail/RiverTrail/rivertrail-0.17.xpi , install Intel's OpenCL SDK http://www.intel.com/go/opencl and try out the interactive River Trail shell http://rivertrail.github.com/interactive For a video overview, see  http://www.youtube.com/watch?v=jueg6zB5XaM . ParallelArray the ParallelArray type is the central component of this API & is a JS object that contains ordered collections of scalars – i.e. multidimensional uniform arrays. A shape property describes the dimensionality and size– e.g. a 2D RGBA image will have shape [height, width, 4]. ParallelArrays are immutable & fluent – they are manipulated by invoking methods on them which produce new ParallelArray objects. ParallelArray supports several constructors over arrays, functions & even the canvas. // Create an empty Parallel Array var pa = new ParallelArray(); // pa0 = <>   // Create a ParallelArray out of a nested JS array. // Note that the inner arrays are also ParallelArrays var pa = new ParallelArray([ [0,1], [2,3], [4,5] ]); // pa1 = <<0,1>, <2,3>, <4.5>>   // Create a two-dimensional ParallelArray with shape [3, 2] using the comprehension constructor var pa = new ParallelArray([3, 2], function(iv){return iv[0] * iv[1];}); // pa7 = <<0,0>, <0,1>, <0,2>>   // Create a ParallelArray from canvas.  This creates a PA with shape [w, h, 4], var pa = new ParallelArray(canvas); // pa8 = CanvasPixelArray   ParallelArray exposes fluent API functions that take an elemental JS function for data manipulation: map, combine, scan, filter, and scatter that return a new ParallelArray. Other functions are scalar - reduce  returns a scalar value & get returns the value located at a given index. The onus is on the developer to ensure that the elemental function does not defeat data parallelization optimization (avoid global var manipulation, recursion). For reduce & scan, order is not guaranteed - the onus is on the dev to provide an elemental function that is commutative and associative so that scan will be deterministic – E.g. Sum is associative, but Avg is not. map Applies a provided elemental function to each element of the source array and stores the result in the corresponding position in the result array. The map method is shape preserving & index free - can not inspect neighboring values. // Adding one to each element. var source = new ParallelArray([1,2,3,4,5]); var plusOne = source.map(function inc(v) {     return v+1; }); //<2,3,4,5,6> combine Combine is similar to map, except an index is provided. This allows elemental functions to access elements from the source array relative to the one at the current index position. While the map method operates on the outermost dimension only, combine, can choose how deep to traverse - it provides a depth argument to specify the number of dimensions it iterates over. The elemental function of combine accesses the source array & the current index within it - element is computed by calling the get method of the source ParallelArray object with index i as argument. It requires more code but is more expressive. var source = new ParallelArray([1,2,3,4,5]); var plusOne = source.combine(function inc(i) { return this.get(i)+1; }); reduce reduces the elements from an array to a single scalar result – e.g. Sum. // Calculate the sum of the elements var source = new ParallelArray([1,2,3,4,5]); var sum = source.reduce(function plus(a,b) { return a+b; }); scan Like reduce, but stores the intermediate results – return a ParallelArray whose ith elements is the results of using the elemental function to reduce the elements between 0 and I in the original ParallelArray. // do a partial sum var source = new ParallelArray([1,2,3,4,5]); var psum = source.scan(function plus(a,b) { return a+b; }); //<1, 3, 6, 10, 15> scatter a reordering function - specify for a certain source index where it should be stored in the result array. An optional conflict function can prevent an exception if two source values are assigned the same position of the result: var source = new ParallelArray([1,2,3,4,5]); var reorder = source.scatter([4,0,3,1,2]); // <2, 4, 5, 3, 1> // if there is a conflict use the max. use 33 as a default value. var reorder = source.scatter([4,0,3,4,2], 33, function max(a, b) {return a>b?a:b; }); //<2, 33, 5, 3, 4> filter // filter out values that are not even var source = new ParallelArray([1,2,3,4,5]); var even = source.filter(function even(iv) { return (this.get(iv) % 2) == 0; }); // <2,4> Flatten used to collapse the outer dimensions of an array into a single dimension. pa = new ParallelArray([ [1,2], [3,4] ]); // <<1,2>,<3,4>> pa.flatten(); // <1,2,3,4> Partition used to restore the original shape of the array. var pa = new ParallelArray([1,2,3,4]); // <1,2,3,4> pa.partition(2); // <<1,2>,<3,4>> Get return value found at the indices or undefined if no such value exists. var pa = new ParallelArray([0,1,2,3,4], [10,11,12,13,14], [20,21,22,23,24]) pa.get([1,1]); // 11 pa.get([1]); // <10,11,12,13,14>

    Read the article

  • Convert png sequence to x264 with ffmpeg

    - by Thucydides411
    I am trying to convert a series of pngs into an mp4 video. I am using ffmpeg, and want to encode the video with the x264 codec. Using the command ffmpeg -y -r 30 -b 1800k -i _tmp%04d.png -vcodec libx264 out.mp4 I get the following warning message Incompatible pixel format 'bgra' for codec 'libx264', auto-selecting format 'yuv420p' My understanding is that there is an alpha channel in the pngs, which the x264 encoder cannot handle. Is there a way to get around this problem? Is there, for example, a way to get the encoder to ignore the alpha channel (my pngs don't actually have any transparent elements)? I'm aware that I could batch convert the pngs beforehand to strip the alpha channel, but the sequence of images is produced by another program, and having to preprocess the images each time I make a video would be less than optimal. Edit: After stripping the alpha channel from each frame using the command convert in.png -background white -flatten +matte out.png ffmpeg gives the warning message Incompatible pixel format 'pal8' for codec 'libx264', auto-selecting format 'yuv420p' so still no dice.

    Read the article

  • Setting up autotest with rspec in ubuntu

    - by Reactor5
    I'm trying to set up autotest on Ubuntu, and no matter what my configuration, I get this: loading autotest/rails_rspec2 style: RailsRspec2 /home/brian/.rvm/gems/ruby-1.9.2-rc2@rails3tutorial/gems/redgreen-1.2.2/lib/redgreen/autotest.rb:6:in `<top (required)>': uninitialized constant Object::PLATFORM (NameError) the .autotest (~/.autotest) file I have is as follows: #!/usr/bin/env ruby require 'redgreen/autotest' def self.notify title, msg, img, pri='low', time=3000 `notify-send -i #{img} -u #{pri} -t #{time} '#{msg}'` end Autotest.add_hook :ran_command do |at| results = [at.results].flatten.join("\n") output = results.slice(/(\d+)\s+examples?,\s*(\d+)\s+failures?(,\s*(\d+)\s+not implemented)?(,\s*(\d+)\s+pending)?/) folder = "~/Pictures/autotest/" if output =~ /([123456789]|[\d]{2,})\sfailures?/ notify "FAIL:", "#{output}", folder+"rails_fail.png", 'critical', 10000 elsif output =~ /[1-9]\d*\spending?/ notify "PENDING:", "#{output}", folder+"rails_pending.png", 'normal', 10000 else notify "PASS:", "#{output}", folder+"rails_ok.png" end end what am I doing wrong here?

    Read the article

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