Search Results

Search found 4969 results on 199 pages for 'def'.

Page 19/199 | < Previous Page | 15 16 17 18 19 20 21 22 23 24 25 26  | Next Page >

  • How to understand the output of gcc -S *.cpp?

    - by user198729
    A sample one as follows: .file "hw.cpp" .section .rdata,"dr" LC0: .ascii "Oh shit really bad~!\15\12\0" .text .align 2 .globl __Z3badv .def __Z3badv; .scl 2; .type 32; .endef __Z3badv: pushl %ebp movl %esp, %ebp subl $8, %esp movl $LC0, (%esp) call _printf leave ret .section .rdata,"dr" LC1: .ascii "WOW\0" .text .align 2 .globl __Z3foov .def __Z3foov; .scl 2; .type 32; .endef __Z3foov: pushl %ebp movl %esp, %ebp subl $4, %esp movl LC1, %eax movl %eax, -4(%ebp) movl $__Z3badv, 4(%ebp) leave ret .def ___main; .scl 2; .type 32; .endef .align 2 .globl _main .def _main; .scl 2; .type 32; .endef _main: pushl %ebp movl %esp, %ebp subl $8, %esp andl $-16, %esp movl $0, %eax addl $15, %eax addl $15, %eax shrl $4, %eax sall $4, %eax movl %eax, -4(%ebp) movl -4(%ebp), %eax call __alloca call ___main call __Z3foov movl $0, %eax leave ret .def _printf; .scl 2; .type 32; .endef Has anyone tried to understand it?

    Read the article

  • Does C# have an equivalent to Scala's structural typing?

    - by Tom Morris
    In Scala, I can define structural types as follows: type Pressable { def press(): Unit } This means that I can define a function or method which takes as an argument something that is Pressable, like this: def foo(i: Pressable) { // etc. The object which I pass to this function must have defined for it a method called press() that matches the type signature defined in the type - takes no arguments, returns Unit (Scala's version of void). I can even use the structural type inline: def foo(i: { def press(): Unit }) { // etc. It basically allows the programmer to have all the benefits of duck typing while still having the benefit of compile-time type checking. Does C# have something similar? I've Googled but can't find anything, but I'm not familiar with C# in any depth. If there aren't, are there any plans to add this?

    Read the article

  • Is there a Django template tag that lets me set a context variable?

    - by hekevintran
    I want to be able to set variables in a template to string values. I wrote a tag, but it doesn't seem to change the context. The intended use is: {% define my_var as "a string" %} class DefineNode(Node): def __init__(self, value, variable_name, nodelist): self.value = value self.variable_name = variable_name self.nodelist = nodelist def __repr__(self): return "<DefineNode>" def render(self, context): context[self.variable_name] = self.value return '' @register.tag def define(parser, token): bits = list(token.split_contents()) if len(bits) != 4: raise TemplateSyntaxError("%r expected format is 'value as variable'" % bits[0]) if bits[1][0] in ('"', "'") and bits[1][-1] == bits[1][0]: value = bits[1][1:-1] nodelist = parser.parse(('enddefine',)) parser.delete_first_token() return DefineNode(value, bits[3], nodelist) I

    Read the article

  • getting last insert id .sqlalchemy orm

    - by gummmibear
    Hi i use sqlalchemy, i need some help. import hashlib import sqlalchemy as sa from sqlalchemy import orm from allsun.model import meta t_user = sa.Table("users",meta.metadata,autoload=True) class Duplicat(Exception): pass class LoginExistsException(Exception): pass class EmailExistsException(Exception): pass class User(object): """ def __setattr__(self, key, value): if key=='password' : value=unicode(hashlib.sha512(value).hexdigset()) object.__setattr__(self,key,value) """ def loginExists(self): try: meta.Session.query(User).filter(User.login==self.login).one() except orm.exc.NoResultFound: pass else: raise LoginExistsException() def emailExists(self): try: meta.Session.query(User).filter(User.email==self.email).one() except orm.exc.NoResultFound: pass else: raise EmailExistsException() def save(self): meta.Session.begin() meta.Session.save(self) try: meta.Session.commit() except sa.exc.IntegrityError: raise Duplicat() How can i get inserted id when i call? user = User() user.login = request.params['login'] user.password = hashlib.sha512(request.params['password']).hexdigest() user.email = request.params['email'] user.save()

    Read the article

  • question regarding rails framework code

    - by Joseph Misiti
    I noticed that the code in the rails framework is using the following convention all over the place: class SomeClass class << self def some function end end end rather than class SomeClass end def SomeClass.function end and class SomeClass def self.somefunction end end What is the reason for this design choice? They all seem to accomplish them same thing

    Read the article

  • Bypassing confirmation prompt of an external process

    - by Alidad
    How can I convert this Perl code to Groovy? How to bypass confirmation prompts of an external process? I am trying to convert a Perl script to Groovy. The program is loading/delete maestro (job scheduling) jobs automatically. The problem is the delete command will prompt for confirmation (Y/N) on every single job that it finds. I tried the process execute in groovy but will stop at the prompts. The Perl script is writing bunch of Ys to the stream and print it to the handler( if I understood it correctly) to avoid stopping. I am wondering how to do the same thing in Groovy ? Or any other approach to execute a command and somehow write Y on every confirmation prompt. Perl Script: $maestrostring=""; while ($x < 1500) { $maestrostring .= "y\n"; $x++; } # delete the jobs open(MAESTRO_CMD, "|ssh mserver /bin/composer delete job=pserver#APPA@") print MAESTRO_CMD $maestrostring; close(MAESTRO_CMD); This is my groovy code so far: def deleteMaestroJobs (){ ... def commandSched ="ssh $maestro_server /bin/composer delete sched=$primary_server#$app_acronym$app_level@" def commandJobs ="ssh $maestro_server /bin/composer delete job=$primary_server#$app_acronym$app_level@" try { executeCommand commandJobs } catch (Exception ex ){ throw new Exception("Error executing the Maestro Composer [DELETE]") } try { executeCommand commandSched } catch (Exception ex ){ throw new Exception("Error executing the Maestro Composer [DELETE]") } } def executeCommand(command){ def process = command.execute() process.withWriter { writer -> 1500.times {writer.println 'Y' } } process.consumeProcessOutput(System.out, System.err) process.waitFor() }

    Read the article

  • Iterating through nested dictionaries

    - by Framester
    I want to write an iterator for my 'toy' Trie implementation. Adding already works like this: class Trie: def __init__(self): self.root = dict() pass def add(self, string, value): global nops current_dict = self.root for letter in s: nops += 1 current_dict = current_dict.setdefault(letter, {}) current_dict = current_dict.setdefault('value', value) pass The output of the adding looks like that: trie = Trie() trie.add("hello",1) trie.add("world",2) trie.add("worlds",12) print trie.root {'h': {'e': {'l': {'l': {'o': {'value': 1}}}}}, 'w': {'o': {'r': {'l': {'d': {'s': {'value': 2}, 'value': 2}}}}}} I know, that I need a __iter__ and next method. def __iter__(self): self.root.__iter__() pass def next(self): print self.root.next() But AttributeError: 'dict' object has no attribute 'next'. How should I do it? [Update] In the perfect world I would like the output to be one dict with all the words/entries with their corresponding values.

    Read the article

  • weakref list in python

    - by Dan
    I'm in need of a list of weak references that deletes items when they die. Currently the only way I have of doing this is to keep flushing the list (removing dead references manually). I'm aware there's a WeakKeyDictionary and a WeakValueDictionary, but I'm really after a WeakList, is there a way of doing this? Here's an example: import weakref class A(object): def __init__(self): pass class B(object): def __init__(self): self._references = [] def addReference(self, obj): self._references.append(weakref.ref(obj)) def flush(self): toRemove = [] for ref in self._references: if ref() is None: toRemove.append(ref) for item in toRemove: self._references.remove(item) b = B() a1 = A() b.addReference(a1) a2 = A() b.addReference(a2) del a1 b.flush() del a2 b.flush()

    Read the article

  • XmlSlurper/NekoHTML document fragment parsing - No HTML or BODY tags wanted

    - by Misha Koshelev
    Dear All, I am trying to parse the following HTML fragment, and I would like to get the same fragment as output (without HTML and BODY tags). Is this possible? If so, how? Thank you Misha p.s. I am reading here: http://nekohtml.sourceforge.net/faq.html#fragments and I believe I have added the correct options below. However, the output is still incorrect :( Thank you Misha import groovy.xml.MarkupBuilder import groovy.xml.StreamingMarkupBuilder import groovy.util.XmlNodePrinter import groovy.util.slurpersupport.NodeChild def text=""" <div><h2>Test</h2> <div>Hi</div> </div> """ // Parse def config=new org.cyberneko.html.HTMLConfiguration() config.setFeature("http://cyberneko.org/html/features/balance-tags/document-fragment",true) def html=new XmlSlurper(new org.cyberneko.html.parsers.SAXParser()).parseText(text) // Output def printNode(NodeChild node) { def writer = new StringWriter() writer << new StreamingMarkupBuilder().bind { mkp.declareNamespace('':node[0].namespaceURI()) mkp.yield node } new XmlNodePrinter().print(new XmlParser().parseText(writer.toString())) } printNode(html) Output: <HTML> <tag0:HEAD xmlns:tag0="http://www.w3.org/1999/xhtml"/> <BODY> <DIV> <H2> Test </H2> <DIV> Hi </DIV> </DIV> </BODY> </HTML>

    Read the article

  • How to make Excel strip ALL quotes from CSV text fields

    - by Klay
    When importing a CSV file into Excel, it only strips the double-quotes from the FIRST field on the line, but leaves them on all other fields. How can I force Excel to strip the quotes from ALL strings? For instance, I have a CSV file: "text1", "text2", "numeric1", "numeric 2" "abc", "def", 123, 456 "abc", "def", 123, 456 "abc", "def", 123, 456 "abc", "def", 123, 456 I import it into Excel using Data Import External Data Import Data. I specify that the fields are delimited by commas, and that the text delimiter is the double-quote character. Both the data preview and the actual Excel spreadsheet columns only strip the double-quotes from the first text field. All other text fields still have quotes around them. What's really strange is that Access is able to import this data correctly (i.e. strips quotes from every text field. Note that this is NOT a matter of internal commas or quotes or escape characters. This happens in Excel 2003 and Excel 2007.

    Read the article

  • How to control respond_to based on variable in Rails controller?

    - by smotchkkiss
    The dilemma I'm using a before_filter in my controller that restricts access to admins. However, I want to allow access public access to some methods based on request format. See the index method to understand what I'm talking about. items_controller.rb class ItemsController < ApplicationController before_filter :superuser_required layout 'superuser' def index @items = Item.all respond_to do |format| format.html format.js # I want public to have access to this end end def show @item = Item.find(params[:id]) respond_to do |format| format.html end end def new @item = Item.new respond_to do |format| format.html end end # remaining controller methods # ... def superuser_required redirect_to login_path unless current_user.superuser? end end

    Read the article

  • Quick help refactoring Ruby Class

    - by mplacona
    I've written this class that returns feed updates, but am thinking it can be further improved. It's not glitchy or anything, but as a new ruby developer, I reckon it's always good to improve :-) class FeedManager attr_accessor :feed_object, :update, :new_entries require 'feedtosis' def initialize(feed_url) @feed_object = Feedtosis::Client.new(feed_url) fetch end def fetch @feed_object.fetch end def update @updates = fetch end def updated? @updates.new_entries.count > 0 ? true : false end def new_entries @updates.new_entries end end As you can see, it's quite simple, but the things I'm seeing that aren't quite right are: Whenever I call fetch via terminal, it prints a list with the updates, when it's really supposed return an object. So as an example, in the terminal if I do something like: client = Feedtosis::Client.new('http://stackoverflow.com/feeds') result = client.fetch I then get: <Curl::Easy http://stackoverflow.com/feeds> Which is exactly what I'd expect. However, when doing the same thing with "inniting" class with: FeedManager.new("http://stackoverflow.com/feeds") I'm getting the object returning as an array with all the items on the feed. Sure I'm doing something wrong, so any help refactoring this class will he greatly appreciated. Also, I'd like to see comments about my implementation, as well as any sort of comment to make it better would be welcome. Thanks in advance

    Read the article

  • JW Player - How can I add an event listener for fullscreen toggling?

    - by Charles
    I'm using JW Player 4.5 on my site and I need to add an event listener for when fullscreen is toggled. The reason for this is to switch between a low-def version and high-def version. The default video will be the low-def version and when they switch to a fullscreen display, it will change to the high-def version. According to http://developer.longtailvideo.com/trac/wiki/Player5Events, the ViewEvent.JWPLAYER_VIEW_FULLSCREEN1 event can only be called from Actionscript. I need it to be from Javascript... Is there any way to achieve this? Can you recommend a better solution?

    Read the article

  • How to use will_paginate with a nested resource in Rails?

    - by Sue Petersen
    I'm new to Rails, and I'm having major trouble getting will_paginate to work with a nested resource. I have two models, Statement and Invoice. will_paginate is working on Statement, but I can't get it to work on Invoice. I know I'd doing something silly, but I can't figure it out and the examples I've found on google won't work for me. statement.rb class Statement < ActiveRecord::Base has_many :invoices def self.search(search, page) paginate :per_page => 19, :page => page, :conditions => ['company like ?', "%#{search}%"], :order => 'date_due DESC, company, supplier' end end statements_controller.rb <irrelevant code clipped for readability> def index #taken from the RAILSCAST 51, will_paginate podcast @statements = Statement.search(params[:search], params[:page]) end I call this in the view like so, and it works: <%= will_paginate @statements %> But I can't figure out how to get it to work for Invoices: invoice.rb class Invoice < ActiveRecord::Base belongs_to :statement def self.search(search, page) paginate :per_page => 19, :page => page, :conditions => ['company like ?', "%#{search}%"], :order => 'employee' end end invoices_controller.rb class InvoicesController < ApplicationController before_filter :find_statement #TODO I can't get will_paginate to work w a nested resource def index #taken from the RAILSCAST 51, will_paginate podcast @invoices = Invoice.search(params[:search], params[:page]) end def find_statement @statement_id = params[:statement_id] return(redirect_to(statements_url)) unless @statement_id @statement = Statement.find(@statement_id) end end And I try to call it like this: <%= will_paginate (@invoices) % The most common error message, as I play with this, is: "The @statements variable appears to be empty. Did you forget to pass the collection object for will_paginate?" I don't have a clue what the problem is, or how to fix it. Thanks for any help and guidance!

    Read the article

  • Python: Can subclasses overload inherited methods?

    - by Rosarch
    I'm making a shopping cart app in Google App Engine. I have many classes that derive from a base handler: class BaseHandler(webapp.RequestHandler): def get(self, CSIN=None): self.body(CSIN) Does this mean that the body() method of every descendant class needs to have the same argument? This is cumbersome. Only one descendant actually uses that argument. And what about when I add new args? Do I need to go through and change every class? class Detail(BaseHandler): def body(self, CSIN): class MainPage(BaseHandler): def body(self, CSIN=None): #@UnusedVariable class Cart(BaseHandler): def body(self, CSIN): #@UnusedVariable

    Read the article

  • Can someone here explain constructors and destructors in python - simple explanation required - new

    - by rgolwalkar
    i will try to see if it makes sense :- class Person: '''Represnts a person ''' population = 0 def __init__(self,name): //some statements and population += 1 def __del__(self): //some statements and population -= 1 def sayHi(self): '''grettings from person''' print 'Hi My name is %s' % self.name def howMany(self): '''Prints the current population''' if Person.population == 1: print 'i am the only one here' else: print 'There are still %d guyz left ' % Person.population rohan = Person('Rohan') rohan.sayHi() rohan.howMany() sanju = Person('Sanjivi') sanju.howMany() del rohan # am i doing this correctly --- ? i need to get an explanation for this del - destructor O/P:- Initializing person data ****************************************** Initializing Rohan ****************************************** Population now is: 1 Hi My name is Rohan i am the only one here Initializing person data ****************************************** Initializing Sanjivi ****************************************** Population now is: 2 In case Person dies: ****************************************** Sanjivi Bye Bye world there are still 1 people left i am the only one here In case Person dies: ****************************************** Rohan Bye Bye world i am the last person on earth Population now is: 0 If required i can paste the whole lesson as well --- learning from :- http://www.ibiblio.org/swaroopch/byteofpython/read/

    Read the article

  • Python Socket Getting Connection Reset

    - by Ian
    I created a threaded socket listener that stores newly accepted connections in a queue. The socket threads then read from the queue and respond. For some reason, when doing benchmarking with 'ab' (apache benchmark) using a concurrency of 2 or more, I always get a connection reset before it's able to complete the benchmark (this is taking place locally, so there's no external connection issue). class server: _ip = '' _port = 8888 def __init__(self, ip=None, port=None): if ip is not None: self._ip = ip if port is not None: self._port = port self.server_listener(self._ip, self._port) def now(self): return time.ctime(time.time()) def http_responder(self, conn, addr): httpobj = http_builder() httpobj.header('HTTP/1.1 200 OK') httpobj.header('Content-Type: text/html; charset=UTF-8') httpobj.header('Connection: close') httpobj.body("Everything looks good") data = httpobj.generate() sent = conn.sendall(data) def http_thread(self, id): self.log("THREAD %d: Starting Up..." % id) while True: conn, addr = self.q.get() ip, port = addr self.log("THREAD %d: responding to request: %s:%s - %s" % (id, ip, port, self.now())) self.http_responder(conn, addr) self.q.task_done() conn.close() def server_listener(self, host, port): self.q = Queue.Queue(0) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind( (host, port) ) sock.listen(5) for i in xrange(4): #thread count thread.start_new(self.http_thread, (i+1, )) while True: self.q.put(sock.accept()) sock.close() server('', 9999) When running the benchmark, I get totally random numbers of good requests before it errors out, usually between 4 and 500. Edit: Took me a while to figure it out, but the problem was in sock.listen(5). Because I was using apache benchmark with a higher concurrency (5 and up) it was causing the backlog of connections to pile up, at which point the connections started getting dropped by the socket.

    Read the article

  • Groovy 1.7 changes "final"?

    - by Aaron L. Carlow
    Just started learning Groovy, got the PragProg book "Programming Groovy" and had a problem compiling one of the sample scripts: class GCar2 { final miles = 0 def getMiles() { println "getMiles called" miles } def drive(dist) { if (dist > 0) { miles += dist } } } def car = new GCar2() println "Miles: $car.miles" println 'Driving' car.drive(10) println "Miles: $car.miles" try { print 'Can I see the miles? ' car.miles = 12 } catch (groovy.lang.ReadOnlyPropertyException ex) { println ex.message GroovyCar2.groovy: 20: cannnot access final field or property outside of constructor. @ line 20, column 35. def drive(dist) { if (dist > 0) miles += dist } ^ Groovy versions prior to 1.7 do not give an error. I looked through whatever documentation I could find and did not see the issue discussed. What is going on here? Aaron

    Read the article

  • net/http.rb:560:in `initialize': getaddrinfo: Name or service not known (SocketError)

    - by Sid
    ` @@timestamp = nil def generate_oauth_url @@timestamp = timestamp url = CONNECT_URL + REQUEST_TOKEN_PATH + "&oauth_callback=#{OAUTH_CALLBACK}&oauth_consumer_key=#{OAUTH_CONSUMER_KEY}&oauth_nonce=#{NONCE} &oauth_signature_method=#{OAUTH_SIGNATURE_METHOD}&oauth_timestamp=#{@@timestamp}&oauth_version=#{OAUTH_VERSION}" puts url url end def sign(url) Base64.encode64(HMAC::SHA1.digest((NONCE + url), OAUTH_CONSUMER_SECRET)).strip end def get_request_token url = generate_oauth_url signed_url = sign(url) request = Net::HTTP.new((CONNECT_URL + REQUEST_TOKEN_PATH),80) puts request.inspect headers = { "Authorization" => "Authorization: OAuth oauth_nonce = #{NONCE}, oauth_callback = #{OAUTH_CALLBACK}, oauth_signature_meth od = #{OAUTH_SIGNATURE_METHOD}, oauth_timestamp=#{@@timestamp}, oauth_consumer_key = #{OAUTH_CONSUMER_KEY}, oauth_signature = #{signed_url}, oauth_versio n = #{OAUTH_VERSION}" } request.post(url, nil,headers) end def timestamp Time.now.to_i end ` I am trying to do what oauth does in an attempt to understand how to use the Authorization headers. I am also getting the following error. I am trying to connect to the linkedin API. /usr/lib/ruby/1.8/net/http.rb:560:in 'initialize': getaddrinfo: Name or service not known (SocketError) I would really appreciate it if someone could nudge me in the right direction.

    Read the article

  • Help me understand Inorder Traversal without using recursion

    - by vito
    I am able to understand preorder traversal without using recursion, but I'm having a hard time with inorder traversal. I just don't seem to get it, perhaps, because I haven't understood the inner working of recursion. This is what I've tried so far: def traverseInorder(node): lifo = Lifo() lifo.push(node) while True: if node is None: break if node.left is not None: lifo.push(node.left) node = node.left continue prev = node while True: if node is None: break print node.value prev = node node = lifo.pop() node = prev if node.right is not None: lifo.push(node.right) node = node.right else: break The inner while-loop just doesn't feel right. Also, some of the elements are getting printed twice; may be I can solve this by checking if that node has been printed before, but that requires another variable, which, again, doesn't feel right. Where am I going wrong? I haven't tried postorder traversal, but I guess it's similar and I will face the same conceptual blockage there, too. Thanks for your time! P.S.: Definitions of Lifo and Node: class Node: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right class Lifo: def __init__(self): self.lifo = () def push(self, data): self.lifo = (data, self.lifo) def pop(self): if len(self.lifo) == 0: return None ret, self.lifo = self.lifo return ret

    Read the article

  • Optimizing Haskell code

    - by Masse
    I'm trying to learn Haskell and after an article in reddit about Markov text chains, I decided to implement Markov text generation first in Python and now in Haskell. However I noticed that my python implementation is way faster than the Haskell version, even Haskell is compiled to native code. I am wondering what I should do to make the Haskell code run faster and for now I believe it's so much slower because of using Data.Map instead of hashmaps, but I'm not sure I'll post the Python code and Haskell as well. With the same data, Python takes around 3 seconds and Haskell is closer to 16 seconds. It comes without saying that I'll take any constructive criticism :). import random import re import cPickle class Markov: def __init__(self, filenames): self.filenames = filenames self.cache = self.train(self.readfiles()) picklefd = open("dump", "w") cPickle.dump(self.cache, picklefd) picklefd.close() def train(self, text): splitted = re.findall(r"(\w+|[.!?',])", text) print "Total of %d splitted words" % (len(splitted)) cache = {} for i in xrange(len(splitted)-2): pair = (splitted[i], splitted[i+1]) followup = splitted[i+2] if pair in cache: if followup not in cache[pair]: cache[pair][followup] = 1 else: cache[pair][followup] += 1 else: cache[pair] = {followup: 1} return cache def readfiles(self): data = "" for filename in self.filenames: fd = open(filename) data += fd.read() fd.close() return data def concat(self, words): sentence = "" for word in words: if word in "'\",?!:;.": sentence = sentence[0:-1] + word + " " else: sentence += word + " " return sentence def pickword(self, words): temp = [(k, words[k]) for k in words] results = [] for (word, n) in temp: results.append(word) if n > 1: for i in xrange(n-1): results.append(word) return random.choice(results) def gentext(self, words): allwords = [k for k in self.cache] (first, second) = random.choice(filter(lambda (a,b): a.istitle(), [k for k in self.cache])) sentence = [first, second] while len(sentence) < words or sentence[-1] is not ".": current = (sentence[-2], sentence[-1]) if current in self.cache: followup = self.pickword(self.cache[current]) sentence.append(followup) else: print "Wasn't able to. Breaking" break print self.concat(sentence) Markov(["76.txt"]) -- module Markov ( train , fox ) where import Debug.Trace import qualified Data.Map as M import qualified System.Random as R import qualified Data.ByteString.Char8 as B type Database = M.Map (B.ByteString, B.ByteString) (M.Map B.ByteString Int) train :: [B.ByteString] -> Database train (x:y:[]) = M.empty train (x:y:z:xs) = let l = train (y:z:xs) in M.insertWith' (\new old -> M.insertWith' (+) z 1 old) (x, y) (M.singleton z 1) `seq` l main = do contents <- B.readFile "76.txt" print $ train $ B.words contents fox="The quick brown fox jumps over the brown fox who is slow jumps over the brown fox who is dead."

    Read the article

  • By-Name-Parameters for Constructors

    - by hotzen
    Hello, coming from my other question is there a way to get by-name-parameters for constructors working? I need a way to provide a code-block which is executed on-demand/lazy/by-name inside an object and this code-block must be able to access the class-methods as if the code-block were part of the class. Following Testcase fails: package test class ByNameCons(code: => Unit) { def exec() = { println("pre-code") code println("post-code") } def meth() = println("method") def exec2(code2: => Unit) = { println("pre-code") code2 println("post-code") } } object ByNameCons { def main(args: Array[String]): Unit = { val tst = new ByNameCons { println("foo") meth() // knows meth() as code is part of ByNameCons } tst.exec() // ByName fails (executed right as constructor) println("--------") tst.exec2 { // ByName works println("foo") //meth() // does not know meth() as code is NOT part of ByNameCons } } } Output: foo method pre-code post-code -------- pre-code foo post-code

    Read the article

  • Convert cookies from HTMLUnit to HTTPBuilder?

    - by Misha Koshelev
    Dear All: I am doing this (in Groovy): def cookies=webClient.cookieManager.cookies def http=new HTTPBuilder("myurl") http.request(POST) { def headersCookie='' cookies.eachWithIndex() { cookie,i-> if (i>0) { headersCookie+='; ' } headersCookie+=cookie.getName()+"="+cookie.getValue() } headers.'Cookie'=headersCookie ... } Is there a better/less hacky way? Thank you Misha

    Read the article

  • Copy call signature to decorator

    - by Morgoth
    If I do the following def mydecorator(f): def wrapper(*args, **kwargs): f(*args, **kwargs) wrapper.__doc__ = f.__doc__ wrapper.__name__ = f.__name__ return wrapper @mydecorator def myfunction(a,b,c): '''My docstring''' pass And then type help myfunction, I get: Help on function myfunction in module __main__: myfunction(*args, **kwargs) My docstring So the name and docstring are correctly copied over. Is there a way to also copy over the actual call signature, in this case (a, b, c)?

    Read the article

< Previous Page | 15 16 17 18 19 20 21 22 23 24 25 26  | Next Page >