Search Results

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

Page 34/39 | < Previous Page | 30 31 32 33 34 35 36 37 38 39  | Next Page >

  • How can I modify/merge Jinja2 dictionaries?

    - by Brian M. Hunt
    I have a Jinja2 dictionary and I want a single expression that modifies it - either by changing its content, or merging with another dictionary. >>> import jinja2 >>> e = jinja2.Environment() Modify a dict: Fails. >>> e.from_string("{{ x[4]=5 }}").render({'x':{1:2,2:3}}) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "jinja2/environment.py", line 743, in from_string return cls.from_code(self, self.compile(source), globals, None) File "jinja2/environment.py", line 469, in compile self.handle_exception(exc_info, source_hint=source) File "<unknown>", line 1, in template jinja2.exceptions.TemplateSyntaxError: expected token 'end of print statement', got '=' Two-stage update: Prints superfluous "None". >>> e.from_string("{{ x.update({4:5}) }} {{ x }}").render({'x':{1:2,2:3}}) u'None {1: 2, 2: 3, 4: 5}' >>> e.from_string("{{ dict(x.items()+ {3:4}.items()) }}").render({'x':{1:2,2:3}}) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "jinja2/environment.py", line 868, in render return self.environment.handle_exception(exc_info, True) File "<template>", line 1, in top-level template code TypeError: <lambda>() takes exactly 0 arguments (1 given) Use dict(x,**y): Fails. >>> e.from_string("{{ dict((3,4), **x) }}").render({'x':{1:2,2:3}}) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "jinja2/environment.py", line 868, in render return self.environment.handle_exception(exc_info, True) File "<template>", line 1, in top-level template code TypeError: call() keywords must be strings So how does one modify the dictionary x in Jinja2 by changing an attribute or merging with another dictionary? This question is similar to: How can I merge two Python dictionaries as a single expression? -- insofar as Jinja2 and Python are analogous.

    Read the article

  • .net MVC RenderPartial renders information that is not in the model

    - by Andreas
    Hi, I have a usercontrol that is rendering a list of items. Each row contains a unique id in a hidden field, a text and a delete button. When clicking on the delete button I use jquery ajax to call the controller method DeleteCA (seen below). DeleteCA returns a new list of items that replaces the old list. [HttpPost] public PartialViewResult DeleteCA(CAsViewModel CAs, Guid CAIdToDelete) { int indexToRemove = CAs.CAList.IndexOf(CAs.CAList.Single(m => m.Id == CAIdToDelete)); CAs.CAList.RemoveAt(indexToRemove); return PartialView("EditorTemplates/CAs", CAs); } I have checked that DeleteCA is really removing the correct item. The modified list of CAs passed to PartialView no longer contains the deleted item. Something weird happens when the partial view is rendered. The number of items in the list is reduced but it is always the last element that is removed from the list. The rendered items does not correspond to the items in the list/model sent to PartialView. In the usercontrol file (ascx) I'm using both Model.CAList and lambda expression m = m.CAList. How is it possible for the usercontrol to render stuff that is not in the model sent to PartialView? Thanx Andreas

    Read the article

  • Yahoo BOSS Python Library, ExpatError

    - by Wraith
    I tried to install the Yahoo BOSS mashup framework, but am having trouble running the examples provided. Examples 1, 2, 5, and 6 work, but 3 & 4 give Expat errors. Here is the output from ex3.py: gpython examples/ex3.py examples/ex3.py:33: Warning: 'as' will become a reserved keyword in Python 2.6 Traceback (most recent call last): File "examples/ex3.py", line 27, in <module> digg = db.select(name="dg", udf=titlef, url="http://digg.com/rss_search?search=google+android&area=dig&type=both&section=news") File "/usr/lib/python2.5/site-packages/yos/yql/db.py", line 214, in select tb = create(name, data=data, url=url, keep_standards_prefix=keep_standards_prefix) File "/usr/lib/python2.5/site-packages/yos/yql/db.py", line 201, in create return WebTable(name, d=rest.load(url), keep_standards_prefix=keep_standards_prefix) File "/usr/lib/python2.5/site-packages/yos/crawl/rest.py", line 38, in load return xml2dict.fromstring(dl) File "/usr/lib/python2.5/site-packages/yos/crawl/xml2dict.py", line 41, in fromstring t = ET.fromstring(s) File "/usr/lib/python2.5/xml/etree/ElementTree.py", line 963, in XML parser.feed(text) File "/usr/lib/python2.5/xml/etree/ElementTree.py", line 1245, in feed self._parser.Parse(data, 0) xml.parsers.expat.ExpatError: syntax error: line 1, column 0 It looks like both examples are failing when trying to query Digg.com. Here is the query that is constructed in ex3.py's code: diggf = lambda r: {"title": r["title"]["value"], "diggs": int(r["diggCount"]["value"])} digg = db.select(name="dg", udf=diggf, url="http://digg.com/rss_search?search=google+android&area=dig&type=both&section=news") Any help is appreciated. Thanks!

    Read the article

  • Looking for examples of "real" uses of continuations

    - by Sébastien RoccaSerra
    I'm trying to grasp the concept of continuations and I found several small teaching examples like this one from the Wikipedia article: (define the-continuation #f) (define (test) (let ((i 0)) ; call/cc calls its first function argument, passing ; a continuation variable representing this point in ; the program as the argument to that function. ; ; In this case, the function argument assigns that ; continuation to the variable the-continuation. ; (call/cc (lambda (k) (set! the-continuation k))) ; ; The next time the-continuation is called, we start here. (set! i (+ i 1)) i)) I understand what this little function does, but I can't see any obvious application of it. While I don't expect to use continuations all over my code anytime soon, I wish I knew a few cases where they can be appropriate. So I'm looking for more explicitely usefull code samples of what continuations can offer me as a programmer. Cheers!

    Read the article

  • How do people know so much about programming?

    - by Luciano
    I see people in this forums with a lot of points, so I assume they know about a lot of different programming stuff. When I was young I knew about basic (commodore) and the turbo pascal (pc). Then in college I learnt about C, memory management, x86 set, loop invariants, graphs, db query optimization, oop, functional, lambda calculus, prolog, concurrency, polymorphism, newton method, simplex, backtracking, dynamic programming, heuristics, np completeness, LR, LALR, neural networks, static & dynamic typing, turing, godel, and more in between. Then in industry I started with Java several years ago and learnt about it, and its variety of frameworks, and also design patterns, architecture patterns, web development, server development, mobile development, tdd, bdd, uml, use cases, bug trackers, process management, people management if you are a tech lead, profiling, security concerns, etc. I started to forget what I learnt in college... And then there is the stuff I don't know yet, like python, .net, perl, JVM stuff like groovy or scala.. Of course Google is a must for rapid documentation access to know if a problem has been solved already and how, and to keep informed about new stuff by blogs and places like this one. It's just too much or I just have a bad memory.. how do you guys manage it?

    Read the article

  • F# Active Pattern List.filter or equivalent

    - by akaphenom
    I have a records of types type tradeLeg = { id : int ; tradeId : int ; legActivity : LegActivityType ; actedOn : DateTime ; estimates : legComponents ; entryType : ShareOrDollarBased ; confirmedPrice: DollarsPerShare option; actuals : legComponents option ; type trade = { id : int ; securityId : int ; ricCode : string ; tradeActivity : TradeType ; enteredOn : DateTime ; closedOn : DateTime ; tradeLegs : tradeLeg list ; } Obviously the tradeLegs are a type off of a trade. A leg may be settled or unsettled (or unsettled but price confirmed) - thus I have defined the active pattern: let (|LegIsSettled|LegIsConfirmed|LegIsUnsettled|) (l: tradeLeg) = if Helper.exists l.actuals then LegIsSettled elif Helper.exists l.confirmedPrice then LegIsConfirmed else LegIsUnsettled and then to determine if a trade is settled (based on all legs matching LegIsSettled pattern: let (|TradeIsSettled|TradeIsUnsettled|) (t: trade) = if List.exists ( fun l -> match l with | LegIsSettled -> false | _ -> true) t.tradeLegs then TradeIsSettled else TradeIsUnsettled I can see some advantages of this use of active patterns, however i would think there is a more efficient way to see if any item of a list either matches (or doesn't) an actie pattern without having to write a lambda expression specifically for it, and using List.exist. Question is two fold: is there a more concise way to express this? is there a way to abstract the functionality / expression (fun l - match l with | LegIsSettled - false | _ - true) Such that let itemMatchesPattern pattern item = match item with | pattern -> true | _ -> false such I could write (as I am reusing this design-pattern): let curriedItemMatchesPattern = itemMatchesPattern LegIsSettled if List.exists curriedItemMatchesPattern t.tradeLegs then TradeIsSettled else TradeIsUnsettled Thoughts?

    Read the article

  • Trace PRISM / CAL events (best practice?)

    - by Christian
    Ok, this question is for people with either a deep knowledge of PRISM or some magic skills I just lack (yet). The Background is simple: Prism allows the declaration of events to which the user can subscribe or publish. In code this looks like this: _eventAggregator.GetEvent<LayoutChangedEvent>().Subscribe(UpdateUi, true); _eventAggregator.GetEvent<LayoutChangedEvent>().Publish("Some argument"); Now this is nice, especially because these events are strongly typed, and the declaration is a piece of cake: public class LayoutChangedEvent : CompositePresentationEvent<string> { } But now comes the hard part: I want to trace events in some way. I had the idea to subscribe using a lambda expression calling a simple log message. Worked perfectly in WPF, but in Silverlight there is some method access error (took me some time to figure out the reason).. If you want to see for yourself, try this in Silverlight: eA.GetEvent<VideoStartedEvent>().Subscribe(obj => TraceEvent(obj, "vSe", log)); If this would be possible, I would be happy, because I could easily trace all events using a single line to subscribe. But it does not... The alternative approach is writing a different functions for each event, and assign this function to the events. Why different functions? Well, I need to know WHICH event was published. If I use the same function for two different events I only get the payload as argument. I have now way to figure out which event caused the tracing message. I tried: using Reflection to get the causing event (not working) using a constructor in the event to enable each event to trace itself (not allowed) Any other ideas? Chris PS: Writing this text took me most likely longer than writing 20 functions for my 20 events, but I refuse to give up :-) I just had the idea to use postsharp, that would most likely work (although I am not sure, perhaps I end up having only information about the base class).. Tricky and so unimportant topic...

    Read the article

  • Using the groupby method in Python, example included

    - by randombits
    Trying to work with groupby so that I can group together files that were created on the same day. When I say same day in this case, I mean the dd part in mm/dd/yyyy. So if a file was created on March 1 and April 1, they should be grouped together because the "1" matches. Here's the code I have so far: #!/usr/bin/python import os import datetime from itertools import groupby def created_ymd(fn): ts = os.stat(fn).st_ctime dt = datetime.date.fromtimestamp(ts) return dt.year, dt.month, dt.day def get_files(): files = [] for f in os.listdir(os.getcwd()): if not os.path.isfile(f): continue y,m,d = created_ymd(f) files.append((f, d)) return files files = get_files() for key, group in groupby(files, lambda x: x[1]): for file in group: print "file: %s, date: %s" % (file[0], key) print " " The problem is, I get lots of files that get grouped together based on the day. But then I'll see multiple groups with the same day. Meaning I might have 4 files grouped that were created on the 17th. Later on I'll see another unique set of 2 files that are also created on the 17th. Where am I going wrong?

    Read the article

  • Rails: unable to set any attribute of child model

    - by Bryan Roth
    I'm having a problem instantiating a ListItem object with specified attributes. For some reason all attributes are set to nil even if I specify values. However, if I specify attributes for a List, they retain their values. Attributes for a List retain their values: >> list = List.new(:id => 20, :name => "Test List") => #<List id: 20, name: "Test List"> Attributes for a ListItem don't retain their values: >> list_item = ListItem.new(:id => 17, :list_id => 20, :name => "Test Item") => #<ListItem id: nil, list_id: nil, name: nil> UPDATE #1: I thought the id was the only attribute not retaining its value but realized that setting any attribute for a ListItem gets set to nil. list.rb: class List < ActiveRecord::Base has_many :list_items, :dependent => :destroy accepts_nested_attributes_for :list_items, :reject_if => lambda { |a| a[:name].blank? }, :allow_destroy => true end list_item.rb: class ListItem < ActiveRecord::Base belongs_to :list validates_presence_of :name end schema.rb ActiveRecord::Schema.define(:version => 20100506144717) do create_table "list_items", :force => true do |t| t.integer "list_id" t.string "name" t.datetime "created_at" t.datetime "updated_at" end create_table "lists", :force => true do |t| t.string "name" t.datetime "created_at" t.datetime "updated_at" end end

    Read the article

  • Practical Scheme Programming

    - by Ixmatus
    It's been a few months since I've touched Scheme and decided to implement a command line income partitioner using Scheme. My initial implementation used plain recursion over the continuation, but I figured a continuation would be more appropriate to this type of program. I would appreciate it if anyone (more skilled with Scheme than I) could take a look at this and suggest improvements. I'm that the multiple (display... lines is an ideal opportunity to use a macro as well (I just haven't gotten to macros yet). (define (ab-income) (call/cc (lambda (cc) (let ((out (display "Income: ")) (income (string->number (read-line)))) (cond ((<= income 600) (display (format "Please enter an amount greater than $600.00~n~n")) (cc (ab-income))) (else (let ((bills (* (/ 30 100) income)) (taxes (* (/ 20 100) income)) (savings (* (/ 10 100) income)) (checking (* (/ 40 100) income))) (display (format "~nDeduct for bills:---------------------- $~a~n" (real->decimal-string bills 2))) (display (format "Deduct for taxes:---------------------- $~a~n" (real->decimal-string taxes 2))) (display (format "Deduct for savings:-------------------- $~a~n" (real->decimal-string savings 2))) (display (format "Remainder for checking:---------------- $~a~n" (real->decimal-string checking 2)))))))))) Invoking (ab-income) asks for input and if anything below 600 is provided it (from my understanding) returns (ab-income) at the current-continuation. My first implementation (as I said earlier) used plain-jane recursion. It wasn't bad at all either but I figured every return call to (ab-income) if the value was below 600 kept expanding the function. (please correct me if that apprehension is incorrect!)

    Read the article

  • Dynamic Linq Property Converting to Sql

    - by Matthew Hood
    I am trying to understand dynamic linq and expression trees. Very basically trying to do an equals supplying the column and value as strings. Here is what I have so far private IQueryable<tblTest> filterTest(string column, string value) { TestDataContext db = new TestDataContext(); // The IQueryable data to query. IQueryable<tblTest> queryableData = db.tblTests.AsQueryable(); // Compose the expression tree that represents the parameter to the predicate. ParameterExpression pe = Expression.Parameter(typeof(tblTest), "item"); Expression left = Expression.Property(pe, column); Expression right = Expression.Constant(value); Expression e1 = Expression.Equal(left, right); MethodCallExpression whereCallExpression = Expression.Call( typeof(Queryable), "Where", new Type[] { queryableData.ElementType }, queryableData.Expression, Expression.Lambda<Func<tblTest, bool>>(e1, new ParameterExpression[] { pe })); // Create an executable query from the expression tree. IQueryable<tblTest> results = queryableData.Provider.CreateQuery<tblTest>(whereCallExpression); return results; } That works fine for columns in the DB. But fails for properties in my code eg public partial class tblTest { public string name_test { get { return name; } } } Giving an error cannot be that it cannot be converted into SQL. I have tried rewriting the property as a Expression<Func but with no luck, how can I convert simple properties so they can be used with linq in this dynamic way? Many Thanks

    Read the article

  • What would be the equivalent VB.NET code for this C# FluentNHibernate component mapping?

    - by Will Marcouiller
    I'm a C# programmer constrained to write VB.NET code. While exploring NHibernate further for my current client, I encountered FluentNHibernate, which I find real attractive. But now, I wonder how to "translate" this C# code for component mapping into VB.NET code: Component(x => x.Address, m => { m.Map(x => x.Number); m.Map(x => x.Street); m.Map(x => x.PostCode); }); I know from here: Component(Of Client)(Function(c) c.Address, ...) what I miss is how to continue with the brackets in VB.NET, since there's no Begin End keywords or so. EDIT 1: Following Mr. JaredPar instructions, I figured that his solution might work. If we take the time to read his answer, we may notice that we both don't know what the MType is within his solution. I might have found out that the MType is: FluentNHibernate.Mapping.ComponentPart(Of TComponent) Thus, TComponent is, from my understanding, an anonymous type that I shall parameter to use. From this point of view, since I wish to map the properties of my Address object, replacing TComponent in my help method signature seems not to work. Private Sub MapAdresseHelper(Of Adresse)(ByVal a As FluentNHibernate.Mapping.ComponentPart(Of Adresse)) a.Map(Function(m) m.Number) a.Map(Function(m) m.Street).Length(50) a.Map(Function(m) m.PostCode).Length(10) End Sub The error I get is that my Address class doesn't have a property member named Street, for instance. It sees my Address type, it recognizes it, but it seems buggy somehow. I guess VBNET is poorly designed for lambda expressions and is less evolved than C# (Sorry, a bit of frustration due to the constraint of working with it and not being capable of doing things VERY easily done in C#.) Thanks!

    Read the article

  • Why is Microsoft under-supporting or under-developping VBNET?

    - by Will Marcouiller
    I ran into a situation where the lack of some features has become somewhat frustrating while developping in VB.NET 2.0. Since my first day of programming, I've always been a C programmer, and still am. Naturally, I chose C# as my favorite .NET language. Recently, a customer of mine has obliged that all of his development projects which disregard SharePoint development have to be written in VB.NET 2.0, that is to avoid conflictual systems to come into some problems. That is a legitimate choice of his which I approve somehow, since he's running some old central systems and is slowly migrating toward latest technologies. As for me, I would have prefered to go with C#, but then, never having done much VB in my life, I see it as an opportunity to learn somethings new, how to handle this and that in VBNET, etc. Except that the syntax is really too verbose for me, which is a pain! I got used to it and that is fine. However, I recently wanted to use the InternalsVisibleToAttribute which I discovered lastly here on SO. But then, in addition to not being able to have lambda expression that returns no value, which I discovered months ago, today I learn that I can't use the attribute in VBNET! Here is what I have read in an article: [...] Sorry VB.Net developers, Microsoft is again shunning you guys and this attribute is NOT available to you.... :( And here is the link: InternalsVisibleTo: Testing internal methods in .Net 2.0 I have heard from Anders Hejlsberg mouth while watching a Webcast from his presentation of .NET 4.0 Framework that the VBNET team was working or has worked in collaboration with the C# team (Eric Lippert and others) in order to bring VBNET to offer the same features as C# offers. But then, I say to myself that the VBNET team has a huge step forward to make, if already in .NET 2.0, some of the most important features lacked! So my question is this: Why is Microsoft under-supporting or under-developping VBNET? Will VBNET ever be lacking the C# features?

    Read the article

  • F# passing an operator with arguments to a function

    - by dan
    Can you pass in an operation like "divide by 2" or "subtract 1" using just a partially applied operator, where "add 1" looks like this: List.map ((+) 1) [1..5];; //equals [2..6] // instead of having to write: List.map (fun x-> x+1) [1..5] What's happening is 1 is being applied to (+) as it's first argument, and the list item is being applied as the second argument. For addition and multiplication, this argument ordering doesn't matter. Suppose I want to subtract 1 from every element (this will probably be a common beginners mistake): List.map ((-) 1) [1..5];; //equals [0 .. -4], the opposite of what we wanted 1 is applied to the (-) as its first argument, so instead of (list_item - 1), I get (1 - list_item). I can rewrite it as adding negative one instead of subtracting positive one: List.map ((+) -1) [1..5];; List.map (fun x -> x-1) [1..5];; // this works too I'm looking for a more expressive way to write it, something like ((-) _ 1), where _ denotes a placeholder, like in the Arc language. This would cause 1 to be the second argument to -, so in List.map, it would evaluate to list_item - 1. So if you wanted to map divide by 2 to the list, you could write: List.map ((/) _ 2) [2;4;6] //not real syntax, but would equal [1;2;3] List.map (fun x -> x/2) [2;4;6] //real syntax equivalent of the above Can this be done or do I have to use (fun x -> x/2)? It seems that the closest we can get to the placeholder syntax is to use a lambda with a named argument.

    Read the article

  • How do i refactor this code by using Action<t> or Func<t> delegates

    - by user330612
    I have a sample program, which needs to execute 3 methods in a particular order. And after executing each method, should do error handling. Now i did this in a normal fashion, w/o using delegates like this. class Program { public static void Main() { MyTest(); } private static bool MyTest() { bool result = true; int m = 2; int temp = 0; try { temp = Function1(m); } catch (Exception e) { Console.WriteLine("Caught exception for function1" + e.Message); result = false; } try { Function2(temp); } catch (Exception e) { Console.WriteLine("Caught exception for function2" + e.Message); result = false; } try { Function3(temp); } catch (Exception e) { Console.WriteLine("Caught exception for function3" + e.Message); result = false; } return result; } public static int Function1(int x) { Console.WriteLine("Sum is calculated"); return x + x; } public static int Function2(int x) { Console.WriteLine("Difference is calculated "); return (x - x); } public static int Function3(int x) { return x * x; } } As you can see, this code looks ugly w/ so many try catch loops, which are all doing the same thing...so i decided that i can use delegates to refactor this code so that Try Catch can be all shoved into one method so that it looks neat. I was looking at some examples online and couldnt figure our if i shud use Action or Func delegates for this. Both look similar but im unable to get a clear idea how to implement this. Any help is gr8ly appreciated. I'm using .NET 4.0, so im allowed to use anonymous methods n lambda expressions also for this Thanks

    Read the article

  • Emacs key binding fallback

    - by rejeep
    Hey, I have a minor mode. If that mode is active and the user hits DEL, I want to do some action, but only if some condition holds. If the condition holds and the action is executed I want to do nothing more after that. But if the condition fails, I don't want to do anything and let the default DEL action execute. Not sure how I could solve this. But I guess I could do it in two ways: 1) I could rebind the DEL key to a function in the minor mode and then check if the conditions holds ot not. But then how do I know what the default command to DEL is? 2) I could add a pre command hook like this. Execute the command and then break the chain. But how do I break the chain? (add-hook 'pre-command-hook (lambda() (when (equal last-input-event 'backspace) ;; Do something and then stop (do not execute the ;; command that backspace is bound to) ))) In what way would you solve it? Thanks!

    Read the article

  • BindingFlags.DeclaredOnly alternative to avoid ambiguous properties of derived classes

    - by JoeBilly
    I'am looking for a solution to access 'flatten' (lowest) properties values of a class and its derived via reflection by property names. ie access either Property1 or Property2 from the ClassB or ClassC type : public class ClassA { public virtual object Property1 { get; set; } public object Property2 { get; set; } } public class ClassB : ClassA { public override object Property1 { get; set; } } public class ClassC : ClassB { } Using simple reflection works until you have virtual properties that are overrired (ie Property1 from ClassB). Then you get a AmbiguousMatchException because the searcher don't know if you want the property of the main class or the derived. Using BindingFlags.DeclaredOnly avoid the AmbiguousMatchException but unoverrided virtual properties or derived classes properties are ommited (ie Property2 from ClassB). Is there an alternative to this poor workaround : // Get the main class property with the specified propertyName PropertyInfo propertyInfo = _type.GetProperty(propertyName, BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static); // If not found, get the property wherever it is if (propertyInfo == null) propertyInfo = _type.GetProperty(propertyName); Furthermore, this workaround not resolve the reflection of 2nd level properties : getting Property1 from ClassC and AmbiguousMatchException is back. My thoughts : I have no choice except loop... Erk... ?? I'am open to Emit, Lambda (is the Expression.Call can handle this?) even DLR solution. Thanks !

    Read the article

  • Best Practice - Removing item from generic collection in C#

    - by Matt Davis
    I'm using C# in Visual Studio 2008 with .NET 3.5. I have a generic dictionary that maps types of events to a generic list of subscribers. A subscriber can be subscribed to more than one event. private static Dictionary<EventType, List<ISubscriber>> _subscriptions; To remove a subscriber from the subscription list, I can use either of these two options. Option 1: ISubscriber subscriber; // defined elsewhere foreach (EventType event in _subscriptions.Keys) { if (_subscriptions[event].Contains(subscriber)) { _subscriptions[event].Remove(subscriber); } } Option 2: ISubscriber subscriber; // defined elsewhere foreach (EventType event in _subscriptions.Keys) { _subscriptions[event].Remove(subscriber); } I have two questions. First, notice that Option 1 checks for existence before removing the item, while Option 2 uses a brute force removal since Remove() does not throw an exception. Of these two, which is the preferred, "best-practice" way to do this? Second, is there another, "cleaner," more elegant way to do this, perhaps with a lambda expression or using a LINQ extension? I'm still getting acclimated to these two features. Thanks. EDIT Just to clarify, I realize that the choice between Options 1 and 2 is a choice of speed (Option 2) versus maintainability (Option 1). In this particular case, I'm not necessarily trying to optimize the code, although that is certainly a worthy consideration. What I'm trying to understand is if there is a generally well-established practice for doing this. If not, which option would you use in your own code?

    Read the article

  • Simplest possible rack app -> permission error

    - by 7stud
    Here's the program(1.rb) blah blah blah blah blah blah: require 'rack' my_rack = lambda { |env| [200, {}, ["Hello. The time is: #{Time.now}"]] } handler = Rack::Handler::WEBrick handler.run(my_rack, :PORT => 12_500) Here's the error (blah blah blah blah blah): ~/ruby_programs$ ruby 1.rb [2012-12-07 21:49:09] INFO WEBrick 1.3.1 [2012-12-07 21:49:09] INFO ruby 1.9.3 (2012-04-20) [x86_64-darwin10.8.0] [2012-12-07 21:49:09] WARN TCPServer Error: Permission denied - bind(2) [2012-12-07 21:49:09] WARN TCPServer Error: Permission denied - bind(2) /Users/7stud/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/webrick/utils.rb:85:in `initialize': Permission denied - bind(2) (Errno::EACCES) from /Users/7stud/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/webrick/utils.rb:85:in `new' from /Users/7stud/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/webrick/utils.rb:85:in `block in create_listeners' from /Users/7stud/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/webrick/utils.rb:82:in `each' from /Users/7stud/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/webrick/utils.rb:82:in `create_listeners' from /Users/7stud/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/webrick/server.rb:82:in `listen' from /Users/7stud/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/webrick/server.rb:70:in `initialize' from /Users/7stud/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/webrick/httpserver.rb:45:in `initialize' from /Users/7stud/.rvm/gems/ruby-1.9.3-p194@programming/gems/rack-1.4.1/lib/rack/handler/webrick.rb:10:in `new' from /Users/7stud/.rvm/gems/ruby-1.9.3-p194@programming/gems/rack-1.4.1/lib/rack/handler/webrick.rb:10:in `run' from 1.rb:5:in `<main>' ~/ruby_programs$ Here's line 85 of ../webrick/utils.rb: sock = TCPServer.new(ai[3], port) If I replace the code in 1.rb with this: require 'socket' server = TCPServer.new 12_000 # Server bind to port 2000 loop do client = server.accept # Wait for a client to connect client.puts "Hello !" client.puts "Time is #{Time.now}" client.close end I don't get any errors, and if I enter the address: http://localhost:12000/ in my browser, I get the expected output: Hello ! Time is 2012-12-07 18:58:15 -0700

    Read the article

  • Can someone help me with m Django localization?

    - by alex
    I have a template with has text in it. It's located in /templates under my project directory. I'm trying to do Japanese now. I create a directory called "locale" in my project directory. Then, I set up this in my settings: gettext = lambda s: s LANGUAGES = ( ('de', gettext('German')), ('en', gettext('English')), ('ja', gettext('Japanese')), ) After that, I run this command: django-admin.py makemessages -l ja The only problem is, this doesn't work! In my locale/ja/LC_MESSAGES/django.po: Isn't it supposed to scan my templates with .html extension and grab all the strings? # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR. # #, fuzzy msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2010-05-20 22:45+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n" "Language-Team: LANGUAGE <[email protected]>\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" #: settings.py:101 msgid "German" msgstr "" #: settings.py:102 msgid "English" msgstr "" #: settings.py:103 msgid "Japanese" msgstr ""

    Read the article

  • Sending items in a LINQ sequence to a method that returns void

    - by generalt
    Hello all. Often while I'm dealing with LINQ sequences, I want to send each item to a method returning void, avoiding a foreach loop. However, I haven't found an elegant way to do this. Today, I wrote the following code: private StreamWriter _sw; private void streamToFile(List<ErrorEntry> errors) { if (_sw == null) { _sw = new StreamWriter(Path.Combine (Path.GetDirectoryName(_targetDatabasePath), "errors.txt")); } Func<ErrorEntry, bool> writeSelector = (e) => { _sw.WriteLine(getTabDelimititedLine(e)); return true; }; errors.Select(writeSelector); _sw.Flush(); } As you can see, I write a lambda function that just returns true, and I realize that the Select method will return a sequence of booleans- I'll just ignore that sequence. However, this seems a little bit noobish and jank. Is there any elegant way to do this? Or am I just misapplying LINQ? Thanks.

    Read the article

  • Pronunciation of programming structures (particularly in c#)

    - by Andrzej Nosal
    As a non-English speaking person I often have problems pronouncing certain programming structures and abbreviations. I've been watching some video tutorials and listening to podcasts as well, though I couldn't catch them all. My question is what is the common or correct pronunciation of the following code snippets? Generics, like IEnumerable<int> or in a method void Swap<T>(T lhs, T rhs) Collections indexing and indexer access e.g. garage[i], rectangular arrays myArray[2,1] or jagged[1][2][3] Lambda operator =>, e.g. in a where extension method .Where(animal => animal.Color == Color.Brown) or in an anonymous method () => { return false;} Inheritance class Derived : Base (extends?) class SomeClass : IDisposable (implements?) Arithemtic operators += -= *= /= %= ! Are += and -= pronounced the same for events? Collections initializers new int[] { 4, 5, 8, 9, 12, 13, 16, 17 }; Casting MyEnum foo = (MyEnum)(int)yourFloat; (as?) Nullables DateTime? dt = new DateTime?(); I tagged the question with C# as some of them are specific to C# only.

    Read the article

  • use proxy in python to fetch a webpage

    - by carmao
    I am trying to write a function in Python to use a public anonymous proxy and fetch a webpage, but I got a rather strange error. The code (I have Python 2.4): import urllib2 def get_source_html_proxy(url, pip, timeout): # timeout in seconds (maximum number of seconds willing for the code to wait in # case there is a proxy that is not working, then it gives up) proxy_handler = urllib2.ProxyHandler({'http': pip}) opener = urllib2.build_opener(proxy_handler) opener.addheaders = [('User-agent', 'Mozilla/5.0')] urllib2.install_opener(opener) req=urllib2.Request(url) sock=urllib2.urlopen(req) timp=0 # a counter that is going to measure the time until the result (webpage) is # returned while 1: data = sock.read(1024) timp=timp+1 if len(data) < 1024: break timpLimita=50000000 * timeout if timp==timpLimita: # 5 millions is about 1 second break if timp==timpLimita: print IPul + ": Connection is working, but the webpage is fetched in more than 50 seconds. This proxy returns the following IP: " + str(data) return str(data) else: print "This proxy " + IPul + "= good proxy. " + "It returns the following IP: " + str(data) return str(data) # Now, I call the function to test it for one single proxy (IP:port) that does not support user and password (a public high anonymity proxy) #(I put a proxy that I know is working - slow, but is working) rez=get_source_html_proxy("http://www.whatismyip.com/automation/n09230945.asp", "93.84.221.248:3128", 50) print rez The error: Traceback (most recent call last): File "./public_html/cgi-bin/teste5.py", line 43, in ? rez=get_source_html_proxy("http://www.whatismyip.com/automation/n09230945.asp", "93.84.221.248:3128", 50) File "./public_html/cgi-bin/teste5.py", line 18, in get_source_html_proxy sock=urllib2.urlopen(req) File "/usr/lib64/python2.4/urllib2.py", line 130, in urlopen return _opener.open(url, data) File "/usr/lib64/python2.4/urllib2.py", line 358, in open response = self._open(req, data) File "/usr/lib64/python2.4/urllib2.py", line 376, in _open '_open', req) File "/usr/lib64/python2.4/urllib2.py", line 337, in _call_chain result = func(*args) File "/usr/lib64/python2.4/urllib2.py", line 573, in lambda r, proxy=url, type=type, meth=self.proxy_open: \ File "/usr/lib64/python2.4/urllib2.py", line 580, in proxy_open if '@' in host: TypeError: iterable argument required I do not know why the character "@" is an issue (I have no such in my code. Should I have?) Thanks in advance for your valuable help.

    Read the article

  • What's the standard convention for creating a new NSArray from an existing NSArray?

    - by Prairiedogg
    Let's say I have an NSArray of NSDictionaries that is 10 elements long. I want to create a second NSArray with the values for a single key on each dictionary. The best way I can figure to do this is: NSMutableArray *nameArray = [[NSMutableArray alloc] initWithCapacity:[array count]]; for (NSDictionary *p in array) { [nameArray addObject:[p objectForKey:@"name"]]; } self.my_new_array = array; [array release]; [nameArray release]; } But in theory, I should be able to get away with not using a mutable array and using a counter in conjunction with [nameArray addObjectAtIndex:count], because the new list should be exactly as long as the old list. Please note that I am NOT trying to filter for a subset of the original array, but make a new array with exactly the same number of elements, just with values dredged up from the some arbitrary attribute of each element in the array. In python one could solve this problem like this: new_list = [p['name'] for p in old_list] or if you were a masochist, like this: new_list = map(lambda p: p['name'], old_list) Having to be slightly more explicit in objective-c makes me wonder if there is an accepted common way of handling these situations.

    Read the article

  • Solving Naked Triples in Sudoku

    - by Kave
    Hello, I wished I paid more attention to the math classes back in Uni. :) How do I implement this math formula for naked triples? Naked Triples Take three cells C = {c1, c2, c3} that share a unit U. Take three numbers N = {n1, n2, n3}. If each cell in C has as its candidates ci ? N then we can remove all ni ? N from the other cells in U.** I have a method that takes a Unit (e.g. a Box, a row or a column) as parameter. The unit contains 9 cells, therefore I need to compare all combinations of 3 cells at a time that from the box, perhaps put them into a stack or collection for further calculation. Next step would be taking these 3-cell-combinations one by one and compare their candidates against 3 numbers. Again these 3 numbers can be any possible combination from 1 to 9. Thats all I need. But how would I do that? How many combinations would I get? Do I get 3 x 9 = 27 combinations for cells and then the same for numbers (N)? How would you solve this in classic C# loops? No Lambda expression please I am already confused enough :) Many Thanks for any help,

    Read the article

< Previous Page | 30 31 32 33 34 35 36 37 38 39  | Next Page >