Search Results

Search found 968 results on 39 pages for 'lambda'.

Page 30/39 | < Previous Page | 26 27 28 29 30 31 32 33 34 35 36 37  | Next Page >

  • C++ boost or STL `y += f(x)` type algorithm

    - by aaa
    hello. I know I can do this y[i] += f(x[i]) using transform with two input iterators. however it seems somewhat counterintuitive and more complicated than for loop. Is there a more natural way to do so using existing algorithm in boost or Stl. I could not find clean equivalent. here is transform (y = y + a*x): using boost::lambda; transform(y.begin(), y.end(), x.begin(), y.begin(), (_1 + scale*_2); // I thought something may exist: transform2(x.begin(), x.end(), y.begin(), (_2 + scale*_1); // it does not, so no biggie. I will write wrapper Thanks

    Read the article

  • How to always return a set number of records when using find_related_tags with acts-as-taggable-on

    - by hadees
    I'm using the acts-as-taggable-on gem and I need to use find_related_tags on my survey model to get back 3 surveys every time. In the event there aren't always 3 related I need to pick how ever many are related plus some random ones to get to 3. Additionally I have a method I wrote called completed_survey_ids which return an array of survey_ids that shouldn't be used because the user has already completed them. Also there is a rare case that there won't be enough surveys because the user has completed them all so in that event it is okay to return less surveys then requested. I did write a named_scope to handle getting rid of the completed_survey_ids that I think works named_scope :not, lambda { |survey_ids| {:conditions => "id NOT IN (#{survey_ids.join(',')})" } }

    Read the article

  • Rails / JBuilder - Entity array with has_many attributes

    - by seufagner
    I have two models, Person and Image and I want return an json array of Persons with your Images. But I dont want return all Image attributes, but produces a different result. Code below: class Person < ActiveRecord::Base has_many :images, as: :imageable validates :name, presence: true accepts_nested_attributes_for :images, :reject_if => lambda { |img| img['asset'].blank? } end class Image < ActiveRecord::Base belongs_to :imageable, polymorphic: true mount_uploader :asset, ImageUploader validates :asset, presence: true end zzz.jbuilder.json template json.persons(@rodas, :id, :name, :images) json produced: { "rodas": [{ "id": 4, "name": "John", "images": [ { "asset": { "url": "/uploads/image/xxxx.png" } }, { "asset": { "url": "/uploads/image/yyyyy.jpeg" } } ]}, { "id": 19, "name": "Mary", "images": [ { "asset": { "url": "/uploads/image/kkkkkkk.png" } } ] }] } I want something like: { "rodas": [ { "id": 4, "name": "John", "images": [ "/uploads/image/xxxx.png" , "/uploads/image/yyyy.jpeg" ] }, { "id": 10, "name": "Mary", "images": [ "/uploads/image/dddd.png" , "/uploads/image/xxxx.jpeg" ] } ]}

    Read the article

  • What, if any, is wrong with this definition of letrec in Scheme?

    - by Lajla
    R5RS gives proposed macro definitions for library forms of syntax: http://schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-10.html#%_sec_7.3 Which also defines letrec, in a very complicated way, certainly not how I would define it, I would simply use: (define-syntax letrec2 (syntax-rules () ((letrec2 ((name val) ...) body bodies ...) ((lambda () (define name val) ... body bodies ...))))) As far as I understand the semantics of letrec, which I use very often as a named let. It works in this way, however as I've had my fair share of debates with philosophers who think they can just disprove special relativity or established phonological theories, I know that when you think you have a simple solution to a complex problem, it's probably WRONG. There has got to be some point where this macro does not satify the semantics of letrec else they'd probably have used it. In this definition, the definitions are local to the body of the letrec, they can refer to each other for mutual recursion, I'm not quite sure what (if any) is wrong.

    Read the article

  • How to binding to bit datatype in SQL to Booleans/CheckBoxes in ASP.NET MVC 2 with DataAnnotations

    - by nvtthang
    I've got problem with binding data type boolean to checkbox in MVC 2 data annotations Here's my code sample: label> Is Hot </label> <%=Html.CheckBoxFor(model => model.isHot, new {@class="input" })%> It always raise this error message below at (model=model.isHot). Cannot convert lambda expression to delegate type 'System.Func<Framework.Models.customer,bool>' because some of the return types in the block are not implicitly convertible to the delegate return type Cannot implicitly convert type 'bool?' to 'bool'. An explicit conversion exists (are you missing a cast?) Please suggest me how can I solve this problem? Thanks in advance.

    Read the article

  • Error using MVCContrib TestHelper

    - by Brian McCord
    While trying to implement the second answer to a previous question, I am receiving an error. I have implemented the methods just as the post shows, and the first three work properly. The fourth one (HomeController_Delete_Action_Handler_Should_Redirect_If_Model_Successfully_Delete) gives this error: Could not find a parameter named 'controller' in the result's Values collection. If I change the code to: actual .AssertActionRedirect() .ToAction("Index"); it works properly, but I don't like the "magic string" in there and prefer to use the lambda method that the other poster used. My controller method looks like this: [HttpPost] public ActionResult Delete(State model) { try { if( model == null ) { return View( model ); } _stateService.Delete( model ); return RedirectToAction("Index"); } catch { return View( model ); } } What am I doing wrong?

    Read the article

  • Should I use C++0x Features Now?

    - by svu2g
    With the official release of VS 2010, is it safe for me to start using the partially-implemented C++0x feature set in my new code? The features that are of interest to me right now are both implemented by VC++ 2010 and recent versions of GCC. These are the only two that I have to support. In terms of the "safety" mentioned in the first sentence: can I start using these features (e.g., lambda functions) and still be guaranteed that my code will compile in 10 years on a compiler that properly conforms to C++0x when it is officially released? I guess I'm asking if there is any chance that VC++ 2010 or GCC will end up like VC++ 6; it was released before the language was officially standardized and consequently allowed grossly ill-formed code to compile. After all, Microsoft does say that "10 is the new 6". ;)

    Read the article

  • Paperclip - Validate File Type but not Presence

    - by Lowgain
    I am using paperclip to handle my file uploads, and in one situation I don't want the file to be mandatory. I do however want to make sure it is a specific file type when it is present. I have this: class TestModel < ActiveRecord::Base #stuff has_attached_file :sound #etc... validates_attachment_content_type :sound, :content_type => ['audio/mp3', 'application/x-mp3'] end And when I have no sound file present, it tells me it is not one of the valid content types. I've tried adding '' to the :content_type array, which also doesn't work! I also attempted creating a lambda procedure for the :if property, but I can't get it to run without some kind of error. Anything missing here?

    Read the article

  • Can I configure AutoMapper to read from custom column names when mapping from IDataReader?

    - by rohancragg
    Psuedo code for mapping configuration (as below) is not possible since the lambda only lets us access Type IDataReader, wheras when actually mapping, AutoMapper will reach into each "cell" of each IDataRecord while IDataReader.Read() == true: var mappingConfig = Mapper.CreateMap<IDataReader, IEnumerable<MyDTO>>(); mappingConfig.ForMember( destination => destination.???, options => options.MapFrom(source => source.???)); Can anyone think of a way to do this using AutoMapper configuration at runtime or just some other dynamic approach that meets the requirement below. The requirement is to support any incoming IDataReader which may have column names that don't match the property names of MyDTO and there is no naming convention I can rely on. Instead we'll ask the user at runtime to cross-reference the expected column names with the actual column names found in the IDataReader via IDataReader.GetSchemaTable().

    Read the article

  • Access to nested methods when DSL

    - by Vyacheslav Loginov
    class Warcraft def initialize &block instance_eval &block end def method_missing name, *args, &block instance_variable_set("@#{name}".to_sym, args[0]) self.class.send(:define_method, name, proc { instance_variable_get("@#{name}")}) end def game &block @game = Game.new &block end class Game def initialize &block instance_eval &block end def method_missing name, *args, &block instance_variable_set("@#{name}".to_sym, args[0]) self.class.send(:define_method, name, proc { instance_variable_get("@#{name}")}) end end end warcraft = Warcraft.new do name "Warcraft III" battle_net :iccup game do side :sentinels hero "Furion" rune_appear_every 2 end end puts warcraft.inspect # => #<Warcraft:0x00000000be3e80 @name="Warcraft III", @battle_net=:iccup, @game=#<Warcraft::Game:0x000000009c6c38 @side=:sentinels, @hero="Furion", @rune_appear_every=2>> How to access nested methods? puts warcraft.battle_net # => iccup puts warcraft.side #=> #<Proc:[email protected]:9 (lambda)> puts warcraft.game #=> dsl.rb:18:in `instance_eval': block not supplied (ArgumentError) puts warcraft.game.side #=> dsl.rb:18:in `instance_eval': block not supplied (ArgumentError)

    Read the article

  • How to sort a list by the 2nd tuple element in python and C#

    - by user350468
    I had a list of tuples where every tuple consists of two integers and I wanted to sort by the 2nd integer. After looking in the python help I got this: sorted(myList, key=lambda x: x[1]) which is great. My question is, is there an equally succinct way of doing this in C# (the language I have to work in)? I know the obvious answer involving creating classes and specifying an anonymous delegate for the whole compare step but perhaps there is a linq oriented way as well. Thanks in advance for any suggestions.

    Read the article

  • make tree in scheme

    - by ???
    (define (entry tree) (car tree)) (define (left-branch tree) (cadr tree)) (define (right-branch tree) (caddr tree)) (define (make-tree entry left right) (list entry left right)) (define (mktree order items_list) (cond ((= (length items_list) 1) (make-tree (car items_list) '() '())) (else (insert2 order (car items_list) (mktree order (cdr items_list)))))) (define (insert2 order x t) (cond ((null? t) (make-tree x '() '())) ((order x (entry t)) (make-tree (entry t) (insert2 order x (left-branch t)) (right-branch t))) ((order (entry t) x ) (make-tree (entry t) (left-branch t) (insert2 order x (right-branch t)))) (else t))) The result is: (mktree (lambda (x y) (< x y)) (list 7 3 5 1 9 11)) (11 (9 (1 () (5 (3 () ()) (7 () ()))) ()) ()) But I'm trying to get: (7 (3 (1 () ()) (5 () ())) (9 () (11 () ()))) Where is the problem?

    Read the article

  • How to save and load an array of complex numbers using numpy.savetxt?

    - by ptomato
    I want to use numpy.savetxt() to save an array of complex numbers to a text file. Problems: If you save the complex array with the default format string, the imaginary part is discarded. If you use fmt='%s', then numpy.loadtxt() can't load it unless you specify dtype=complex, converters={0: lambda s: complex(s)}. Even then, if there are NaN's in the array, loading still fails. It looks like someone has inquired about this multiple times on the Numpy mailing list and even filed a bug, but has not gotten a response. Before I put something together myself, is there a canonical way to do this?

    Read the article

  • How do I write a scheme macro that defines a variable and also gets the name of that variable as a s

    - by Jason Baker
    This is mostly a follow-up to this question. I decided to just keep YAGNI in mind and created a global variable (libpython). I set it to #f initially, then set! it when init is called. I added a function that should handle checking if that value has been initialized: (define (get-cpyfunc name type) (lambda args (if libpython (apply (get-ffi-obj name libpython type) args) (error "Call init before using any Python C functions")))) So now here's what I want to do. I want to define a macro that will take the following: (define-cpyfunc Py_Initialize (_fun -> _void)) And convert it into this: (define Py_Initialize (get-cpyfunc "Py_Initialize" (_fun -> _void))) I've been reading through the macro documentation to try figuring this out, but I can't seem to figure out a way to make it work. Can anyone help me with this (or at least give me a general idea of what the macro would look like)? Or is there a way to do this without macros?

    Read the article

  • Rewriting usort function because of fatal error (PHP bug)

    - by Lionel
    The two following usort functions throw fatal error Base lambda function for closure not found in our productive environment (PHP 5.4). This seems to be a known PHP bug that should be fixed by now (https://bugs.php.net/bug.php?id=52144), but it still occurs for us. Anyway, we unfortunately don't have time to figure out what's wrong with our PHP configurations etc. We would like to rewrite these two functions without the use of anonymous functions, so that the error doesn't occur anymore. Ordering of a multidimensional array ($array) by value of key "position": usort($array, function($a, $b) { return $a['position'] - $b['position']; }); Ordering of a multidimensional array ($array) according to the order of a second array ($position_order): usort($array, function($a, $b) use($position_order) { return (isset($position_order[$a['ftid']]) ? ($position_order[$a['ftid']] - $position_order[$b['ftid']]) : 1); }); Especially the latter causes some headache, as we don't know how to pass the "outside" array $position_order.

    Read the article

  • Intellisense in Visual Studio 2010

    - by Erik
    For some reason the Intellisense in vb.net stopped working when I use an Aggregate Lambda expression inside a With statement. With Me.SalesPackage .WebLinks = Sales.Where(Function(f) f.Current.BookerWeb > 0).Count .WebAmount = Aggregate o In Sales.Where(Function(f) f.Current.WebBooker > 0) Into Sum(o.Current.WebPrice) End With If I insert a new line between .WebLinks and .WebAmount and start typing, it works. But it won't work if I do it after the Aggregate statement... Any ideas?

    Read the article

  • Apply function to one element of a list in Python

    - by user189637
    I'm looking for a concise and functional style way to apply a function to one element of a tuple and return the new tuple, in Python. For example, for the following input: inp = ("hello", "my", "friend") I would like to be able to get the following output: out = ("hello", "MY", "friend") I came up with two solutions which I'm not satisfied with. One uses a higher-order function. def apply_at(arr, func, i): return arr[0:i] + [func(arr[i])] + arr[i+1:] apply_at(inp, lambda x: x.upper(), 1) One uses list comprehensions (this one assumes the length of the tuple is known). [(a,b.upper(),c) for a,b,c in [inp]][0] Is there a better way? Thanks!

    Read the article

  • Running Python code from Java program, shoudl i be doing this?

    - by Space Rocker
    i have a scenario where i draw a network and set all it's paraments on swing based gui, after that i have to translate this network into a python based script which another framework reads and realize this network in the form of virtual machines. As an example have look here: from mininet.topo import Topo, Node class MyTopo( Topo ): def *__init__*( self, enable_all = True ): super( MyTopo, self ).__init__() Host = 1 Switch = 2 self.add_node( Switch, Node( is_switch=True ) ) self.add_node( Host, Node( is_switch=False ) ) self.add_edge( Host, Switch ) self.enable_all() topos = { 'mytopo': ( lambda: MyTopo() ) } It simply connects a host to a switch and realize this topology on mininet framework. Now for now in order to realize the drawn network on java GUI here is what i am doing: I simply take the information from GUI and creates a new python file like the one above using java code and then run this file in mininet, which works fine somehow. I want to know, is this the correct and robust way how i am doing this or should i be looking further into java-python bridge like scenarios to be more effective or so as to say more professional.

    Read the article

  • define method for instance of class

    - by aharon
    Let there be class Example defined as: class Example def initialize(test='hey') self.class.send(:define_method, :say_hello, lambda { test }) end end On calling Example.new; Example.new I get a warning: method redefined; discarding old say_hello. This, I conclude, must be because it defines a method in the actual class (which makes sense, from the syntax). And that, of course, would prove disastrous should there be multiple instances of Example with different values in their methods. Is there a way to create methods just for the instance of a class from inside that instance? Thanks so much.

    Read the article

  • Rails: has_many association with a table in another database and without foreign key

    - by Fernando
    Here is my situation. I have model called Account. An account can have one or more contracts. The problem is that i'm dealing with a legacy application and each account's contracts are stored in a different database. Example: Account 1's contract are in account1_db.contracts. Account 2's contract are in account2_db.contracts. The database name is a field stored in accounts table. How can i make rails association work with this? This is a legacy PHP application and i simply can't change it to store everything in one table. I need to make it work somehow. I tried this, but it didn't worked: has_many :contracts, :conditions => [lambda{ Contract.set_table_name(self.database + '.contracts'); return '1' }] Any ideas?

    Read the article

  • C# ToDictionary can valueSelector give null?

    - by Trimack
    Hi, I want to make a dictionary out of list in a way, that the list becomes keys and values would be empty. I have following code Dictionary<XmlTest, int?> testBattery = new XmlTests().GetRandomTestBattery(id). ToDictionary(k => k, v => null); But I am getting the error "Cannot convert lambda expression to type System.Collections.Generic.IEqualityComparer' because it is not a delegate type" Any ideas how could I fix it? (I know I could iterate through and fill the dict one element at a time, but I simply want to use something more elegant)

    Read the article

  • What are the other new features of C# 4.0, after dynamic and optional parameters?

    - by Abel
    So, C# 4.0 came out yesterday. It introduced the much-debated dynamic keyword, named and optional parameters. Smaller improvements were the implicit ref and recognizing of indexed and default properties on COM methods, contra- and co-variance (really a .NET CLR feature, not C# only) and... Is that really it? Are dynamic and optional/named params the only real improvements to C#? Or did I miss something? Not that I'm complaining, but it seems a bit meager after C# 2.0 (generics) and C# 3.0 (lambda, LINQ). Maybe the language just reached actual maturity?

    Read the article

  • Is there an easy way in Python to wait until certain condition is true?

    - by Checkers
    I need to wait in a script until a certain number of conditions become true? I know I can roll my own eventing using condition variables and friends, but I don't want to go through all the trouble of implementing it, since some object property changes come from external thread in a wrapped C++ library (Boost.Python), so I can't just hijack __setattr__ in a class and put a condition variable there, which leaves me with either trying to create and signal a Python condition variable from C++, or wrap a native one and wait on it in Python, both of which sound fiddly, needlessly complicated and boring. Is there an easier way to do it, barring continuous polling of the condition? Ideally it would be along the lines of res = wait_until(lambda: some_predicate, timeout) if (not res): print 'timed out'

    Read the article

  • Is it possible to refactor this C# if(..) statement?

    - by Pure.Krome
    Hi folks, simple question :- i have the following simple if (..) statements :- if (foo == Animal.Cat || foo == Animal.Dog) { .. } if (baa == 1|| baa == 69) { .. } is it possible to refactor these into something like ... DISCLAIMER: I know this doesn't compile .. but this is sorta what i'm trying to get... if (foo == (Animal.Cat || Animal.Dog)) { .. } if (baa == (1 || 69)) { .. } Cheers :) EDIT I wonder if a lambda expression extension could do this? :P

    Read the article

  • How do I bind a key to "the function represented by the following key sequence"?

    - by katrielalex
    I'm just starting to learn emacs (woohoo!) and I've been mucking around in my .emacs quite happily. Unfortunately, I don't know Lisp yet, so I'm having issues with the basics. I've already remapped a few keys until I fix my muscle memory: (global-set-key (kbd "<f9>") 'recompile) That's fine. But how can I tell a key to 'simulate pressing several keys'? For instance, I don't know, make <f1> do the same as C-u 2 C-x } (widen buffer by two chars). One way is to look up that C-x } calls shrink-window-horizontally, and do some sort of lambda thing. This is of course the neat and elegant way (how do you do this?). But surely there's a way to define <f1> to send the keystrokes C-u 2 C-x }?

    Read the article

< Previous Page | 26 27 28 29 30 31 32 33 34 35 36 37  | Next Page >