Search Results

Search found 9134 results on 366 pages for 'variadic functions'.

Page 38/366 | < Previous Page | 34 35 36 37 38 39 40 41 42 43 44 45  | Next Page >

  • varargs in lambda functions in Python

    - by brain_damage
    Is it possible a lambda function to have variable number of arguments? For example, I want to write a metaclass, which creates a method for every method of some other class and this newly created method returns the opposite value of the original method and has the same number of arguments. And I want to do this with lambda function. How to pass the arguments? Is it possible? class Negate(type): def __new__(mcs, name, bases, _dict): extended_dict = _dict.copy() for (k, v) in _dict.items(): if hasattr(v, '__call__'): extended_dict["not_" + k] = lambda s, *args, **kw: not v(s, *args, **kw) return type.__new__(mcs, name, bases, extended_dict) class P(metaclass=Negate): def __init__(self, a): self.a = a def yes(self): return True def maybe(self, you_can_chose): return you_can_chose But the result is totally wrong: >>>p = P(0) >>>p.yes() True >>>p.not_yes() # should be False Traceback (most recent call last): File "<pyshell#150>", line 1, in <module> p.not_yes() File "C:\Users\Nona\Desktop\p10.py", line 51, in <lambda> extended_dict["not_" + k] = lambda s, *args, **kw: not v(s, *args, **kw) TypeError: __init__() takes exactly 2 positional arguments (1 given) >>>p.maybe(True) True >>>p.not_maybe(True) #should be False True

    Read the article

  • C++: Templates for static functions?

    - by Rosarch
    I have a static Utils class. I want certain methods to be templated, but not the entire class. How do I do this? This fails: #pragma once #include <string> using std::string; class Utils { private: template<class InputIterator, class Predicate> static set<char> findAll_if_rec(InputIterator begin, InputIterator end, Predicate pred, set<char> result); public: static void PrintLine(const string& line, int tabLevel = 0); static string getTabs(int tabLevel); template<class InputIterator, class Predicate> static set<char> Utils::findAll_if(InputIterator begin, InputIterator end, Predicate pred); }; Error: utils.h(10): error C2143: syntax error : missing ';' before '<' utils.h(10): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int utils.h(10): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int utils.h(10): error C2238: unexpected token(s) preceding ';' utils.h(10): error C2988: unrecognizable template declaration/definition utils.h(10): error C2059: syntax error : '<' What am I doing wrong? What is the correct syntax for this? Incidentally, I'd like to templatize the return value, too. So instead of: template<class InputIterator, class Predicate> static set<char> findAll_if_rec(InputIterator begin, InputIterator end, Predicate pred, set<char> result); I'd have: template<class return_t, class InputIterator, class Predicate> static return_t findAll_if_rec(InputIterator begin, InputIterator end, Predicate pred, set<char> result); How would I specify that: 1) return_t must be a set of some sort 2) InputIterator must be an iterator 3) InputIterator's type must work with return_t's type. Thanks.

    Read the article

  • What is the scope of JS variables in anonymous functions

    - by smorhaim
    Why does this code returns $products empty? If I test for $products inside the function it does show data... but once it finishes I can't seem to get the data. var $products = new Array(); connection.query($sql, function(err, rows, fields) { if (err) throw err; for(i=0; i< rows.length; i++) { $products[rows[i].source_identifier] = "xyz"; } }); connection.end(); console.log($products); // Shows empty.

    Read the article

  • problem with prototype.js Ajax functions

    - by Maksim Burnin
    my code(prototype 1.6.1) Event.observe(window, 'load', function() { new Ajax.Request('/modal/order_same/', { parameters: {}, onComplete: function(){alert('err0');}, onSuccess:function(){alert('err1');}, onCreate:function(){alert('err2');}, onFailure:function(){alert('err3');}, onException:function(){alert('err4');}, onLoaded:function(){alert('err5');} }); }); or Event.observe(window, 'load', function() { new Ajax.Updater(somelement,'/modal/order_same/', { parameters: {}, onComplete: function(){alert('err0');}, onSuccess:function(){alert('err1');}, onCreate:function(){alert('err2');}, onFailure:function(){alert('err3');}, onException:function(){alert('err4');}, onLoaded:function(){alert('err5');} }); }); all i get in ff3.7prea5 is "err2". my client says he has ff3.6.3 and same error firebug console says he's get the response and the status code is 200 works fine in opera, ie 6-8, ff on some computers any suggestions?

    Read the article

  • C#: Preferred pattern for functions requiring arguments that implement two interfaces

    - by JS Bangs
    The argument to my function f() must implement two different interfaces that are not related to each other by inheritance, IFoo and IBar. I know of two different ways of doing this. The first is to declare an empty interface that inherits from both: public interface IFooBar : IFoo, IBar { // nothing to see here } public int f(IFooBar arg) { // etc. } This, of course, requires that the classes declare themselves as implementing IFooBar rather than IFoo and IBar separately. The second way is to make f() generic with a constraint: public int f<T>(T arg) where T : IFoo, IBar { // etc. } Which of these do you prefer, and why? Are there any non-obvious advantages or disadvantages to each?

    Read the article

  • Access Codeigniter database functions from file

    - by Manny Calavera
    Hello. I am using a SWFupload script and I can't make a request from flash with mod_rewrite, I don't know why... I just need to point the Flash request to that file directly. This file runs an upload script that works ok but now I need to save some info to the database and I would like to know what should I write to have access from that file that is not called from the controller and does not extend the model in order to run a mysql query. Thanks.

    Read the article

  • Using callback functions for error handling in C

    - by Earlz
    Hi, I have been thinking about the difficulty incurred with C error handling.. like who actually does if(printf("hello world")==-1){exit(1);} But you break common standards by not doing such verbose, and usually useless coding. Well what if you had a wrapper around the libc? like so you could do something like.. //main... error_catchall(my_errors); printf("hello world"); //this will automatically call my_errors on an error of printf ignore=1; //this makes it so the function will return like normal and we can check error values ourself if(fopen.... //we want to know if the file opened or not and handle it ourself. } int my_errors(){ if(ignore==0){ _exit(1); //exit if we aren't handling this error by flagging ignore } return 0; //this is called when there is an error anywhere in the libc } ... I am considering making such a wrapper as I am synthesizing my own BSD licensed libc(so I already have to touch the untouchable..), but I would like to know what people think about it.. would this actually work in real life and be more useful than returning -1?

    Read the article

  • String Vector program exits before input

    - by kylepayne
    So, I have a project that must add, delete, and print the contents of a vector... the problem is that, when run the program exits before I can type in the string to add to the vector. I commented the function that that portion is in. Thanks! #include <iostream> #include <cstdlib> #include <vector> #include <string> using namespace std; void menu(); void addvector(vector<string>& vec); void subvector(vector<string>& vec); void vectorsize(const vector<string>& vec); void printvec(const vector<string>& vec); void printvec_bw(const vector<string>& vec); int main() { vector<string> svector; menu(); return 0; } //functions definitions void menu() { vector<string> svector; int choice = 0; cout << "Thanks for using this program! \n" << "Enter 1 to add a string to the vector \n" << "Enter 2 to remove the last string from the vector \n" << "Enter 3 to print the vector size \n" << "Enter 4 to print the contents of the vector \n" << "Enter 5 ----------------------------------- backwards \n" << "Enter 6 to end the program \n"; cin >> choice; switch(choice) { case 1: addvector(svector); break; case 2: subvector(svector); break; case 3: vectorsize(svector); break; case 4: printvec(svector); break; case 5: printvec_bw(svector); break; case 6: exit(1); default: cout << "not a valid choice \n"; // menu is structured so that all other functions are called from it. } } void addvector(vector<string>& vec) { string line; int i = 0; cout << "Enter the string please \n"; getline(cin, line); // doesn't prompt for input! vec.push_back(line); } void subvector(vector<string>& vec) { vec.pop_back(); return; } void vectorsize(const vector<string>& vec) { if (vec.empty()) { cout << "vector is empty"; } else { cout << vec.size() << endl; } return; } void printvec(const vector<string>& vec) { for(int i = 0; i < vec.size(); i++) { cout << vec[i] << endl; } return; } void printvec_bw(const vector<string>& vec) { for(int i = vec.size(); i > 0; i--) { cout << vec[i] << endl; } return; }

    Read the article

  • Passing variables to functions in Python

    - by brno792
    Im writing test scripts in python for selenium web testing. How do I pass parameters through a python function to call in a later function? I first have a login test function. Then I have a new user registration function. Im trying to pass the Username and Password I use in the registration function to the testLogin function that I call inside the testRegister function. This is my python code: userName = "admin" password = "admin" #pass username and password variables to this function def testLogin(userName,password): browser = webdriver.Firefox() browser.get("http://url/login") element = browser.find_element_by_name("userName") element.send_keys(userName) element = browser.find_element_by_name("userPassword") element.send_keys(password) element.send_keys(Keys.RETURN) browser.close() # test registration def testRegister(): browser = webdriver.Firefox() browser.get("http://url/register") #new username variable newUserName = "test" element = browser.find_element_by_name("regUser") element.send_keys(newUserName) #new password variable newUserPassword = "test" element = browser.find_element_by_name("regPassword") element.send_keys(newUserPassword) # #now test if user is registered, I want to call testLogin with the test user name and pw. testLogin(newUserName,newUserPassword) browser.close()

    Read the article

  • jquery callback functions failing to finish execution

    - by calumbrodie
    I'm testing a jquery app i've written and have come across some unexpected behaviour $('button.clickme').live('click',function(){ //do x (takes 2 seconds) //do y (takes 4 seconds) //do z (takes 0.5 seconds) }) The event can be triggered by a number of buttons. What I'm finding is that when I click each button slowly (allowing 10 seconds between clicks) - my callback function executes correctly (actions x, y & z complete). However If I rapidly click buttons on my page it appears that the function sometimes only completes up to step x or y before terminating. My question: Is it the case that if this function is fired by a clicking second DOM element, while the first callback function is completing - will jQuery terminate the first callback and start over again? Do I have to write my callback function explicitly outside the event handler and then call it?? function doStuff() { //do x //do y //do z ( } $('button.clickme).live('click',doStuff()) If this is the case can someone explain why this is happening or give me a link to some advice on best practice on closures etc - I'd like to know the BEST way to write jQuery to improve performance etc. Thanks

    Read the article

  • scope of variables in JavaScript callback functions

    - by Ethan
    I expected the code below to alert "0" and "1", but it alert "2" twice. I don't the reason. Don't know if it is a problem of jQuery. Also, please help me to edit title and tags of this post if they are inaccurate. <html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript"> $(function() { for (var i=0; i<2; i++) { $.get('http://www.google.com/', function() { alert(i); }); } }); </script> </head> <body> </body> </html>

    Read the article

  • Associative Array / Object can't be read in functions

    - by Matrym
    At the very beginning of the javascript file, I have: var lbp = {}; lbp.defaults = { minLength: 40 }; I can successfully alert it afterwards, with: alert(lbp.defaults.minLength); But as soon as I put it inside a function, when I alert, I get "Undefined". What gives, and how do I avoid this? Is it absolutely necessary to pass this variable into each function, for example, by doing: function(lbp) { alert(lbp.defaults.minLength); } I would have thought that defining it first, it would attain global scope and not be required to be passed in? Thanks in advance for enlightening me :) ==================================== EDIT: The problem seems like it might be my initialize function is itself defined within lbp. Is there any way to use this function var, and still use lbp vars inside it? lbp.initialize = function() { alert(lbp.defaults.minLength); }; The full bit of code looks like this: <script type="text/javascript"> var lbp = { defaults: { minLength: 40 } }; lbp.initialize = function() { alert(lbp.defaults.minLength); }; window.onload = lbp.initialize; </script>

    Read the article

  • MATLAB: Automatic detection of relations between workspace variables through functions

    - by Peterstone
    Hi all, I´m trying to write a function what detect this relation between the variables I have got in the workspace: v1 - fft(v2) = 0 Where v1, v2 are variables of my workspace. Sometimes I need to know which variables have a certain numerical relation. If I have thirty, I don´t want to be looking for this relation in "manual way", just itroducing a sentence for each pair of different variables. I would like a function in which I introuce (or I modify this function every time I need it) the sentence (for instance what I wrote before) and the function show me the pair of variables a I am looking for. Does anyone know how to do it? Thank you so much!

    Read the article

  • C++ Beginner - 'friend' functions and << operator overloading: What is the proper way to overload an

    - by Francisco P.
    Hello, everyone! In a project I'm working on, I have a Score class, defined below in score.h. I am trying to overload it so, when a << operation is performed on it, _points + " " + _name is returned. Here's what I tried to do: ostream & Score::operator<< (ostream & os, Score right) { os << right.getPoints() << " " << right.scoreGetName(); return os; } Here are the errors returned: 1>c:\users\francisco\documents\feup\1a2s\prog\projecto3\projecto3\score.h(30) : error C2804: binary 'operator <<' has too many parameters (This error appears 4 times, actually) I managed to get it working by declaring the overload as a friend function: friend ostream & operator<< (ostream & os, Score right); And removing the Score:: from the function declaration in score.cpp (effectively not declaring it as a member). Why does this work, yet the code describe above doesn't? Thanks for your time! Below is the full score.h /////////////////////////////////////////////////////////// // Score.h // Implementation of the Class Score // Created on: 10-Mai-2010 11:43:56 // Original author: Francisco /////////////////////////////////////////////////////////// #ifndef SCORE_H_ #define SCORE_H_ #include <string> #include <iostream> #include <iostream> using std::string; using std::ostream; class Score { public: Score(string name); Score(); virtual ~Score(); void addPoints(int n); string scoreGetName() const; int getPoints() const; void scoreSetName(string name); bool operator>(const Score right) const; ostream & operator<< (ostream & os, Score right); private: string _name; int _points; }; #endif

    Read the article

  • Javascript parent and child window functions

    - by Mike Thornley
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE>Lab 9-3</TITLE> <SCRIPT LANGUAGE="JavaScript"> <!-- function myFunction(){ myWin = open("","","width=200,height=200"); with(myWin.document){ open(); write("<HTML><HEAD><TITLE>Child Window</TITLE>"); write("<SCRIPT>function myTest(){"); write("alert('This function is defined in the child window "); write("and is called from the parent window.'); this.focus();}"); write("</SCRIPT></HEAD><BODY><H3>Child Window</H3><HR>"); write("<FORM><INPUT TYPE='button' VALUE='parent window function' "); // Use opener property write("onClick='opener.winFunction();'>"); write("<P><INPUT TYPE='button' VALUE='close window' "); write("onClick='window.close();'>"); write("</FORM></BODY></HTML>"); close(); } } function winFunction(){ alert("This function is defined in the parent window\n" + "and is called from the child window."); myWin.focus(); } //--> </SCRIPT> </HEAD> <BODY> <H3>CIW Web Languages</H3> <HR> <FORM NAME="myForm"> <INPUT TYPE="button" VALUE="open new window" onClick="myFunction();"> <!-- Invoke child window function --> <input type="button" value="Click to open child window" onclick="javascript:void(myWin.myTest());"/> </FORM> <P> </BODY> </HTML> To explain further what my initial query was, the code above, should open the child window (myWin) with the second button, the 'Open child window' button without the need to open the window with the first button or do anything else. It should simply call the myWin.myTest()function The child window will open when the second button is pressed but needs to have the child window open first (first button push) before it'll work. This is not the intended purpose, the 'Open child window' button should work without anything else needing to be done. For some reason the parent window isn't communicating with the myWin window and myTest fucntion. It's not homework, it's part of a certification course lab and is coded in the manner I have been shown to understand as correct. DTD isn't included as the focus is the JavaScript. I code correctly with regards to that and other W3C requirements.

    Read the article

  • Visitor Pattern can be replaced with Callback functions?

    - by getit
    Is there any significant benefit to using either technique? In case there are variations, the Visitor Pattern I mean is this: http://en.wikipedia.org/wiki/Visitor_pattern And below is an example of using a delegate to achieve the same effect (at least I think it is the same) Say there is a collection of nested elements: Schools contain Departments which contain Students Instead of using the Visitor pattern to perform something on each collection item, why not use a simple callback (Action delegate in C#) Say something like this class Department { List Students; } class School { List Departments; VisitStudents(Action<Student> actionDelegate) { foreach(var dep in this.Departments) { foreach(var stu in dep.Students) { actionDelegate(stu); } } } } School A = new School(); ...//populate collections A.Visit((student)=> { ...Do Something with student... }); *EDIT Example with delegate accepting multiple params Say I wanted to pass both the student and department, I could modify the Action definition like so: Action class School { List Departments; VisitStudents(Action<Student, Department> actionDelegate, Action<Department> d2) { foreach(var dep in this.Departments) { d2(dep); //This performs a different process. //Using Visitor pattern would avoid having to keep adding new delegates. //This looks like the main benefit so far foreach(var stu in dep.Students) { actionDelegate(stu, dep); } } } }

    Read the article

  • How cast in XML for aggregate functions

    - by renegm
    In SQL Server 2008. I need execute a query like that: DECLARE @x AS xml SET @x=N'<r><c>First Text</c></r><r><c>Other Text</c></r>' SELECT @x.query('fn:max(r/c)') But return nothing (apparently because convert xdt:untypedAtomic to numeric) How to "cast" r/c to varchar? Something like SELECT @x.query('fn:max(«CAST(r/c «AS varchar(20))»)') Edit: Using Nodes the function MAX is from T-SQL no fn:max function In this code: DECLARE @x xml; SET @x = ''; SELECT @x.query('fn:max((1, 2))'); SELECT @x.query('fn:max(("First Text", "Other Text"))'); both query return expected: 2 and "Other Text" fn:max can evaluate string expression ad hoc. But the first query dont work. How to force string arguments to fn:max?

    Read the article

  • prevent using functions before initialization, constructors-like in C

    - by Hernán Eche
    This is the way I get to prevent funA,funB,funC, etc.. for being used before init #define INIT_KEY 0xC0DE //any number except 0, is ok static int initialized=0; int Init() { //many init task initialized=INIT_KEY; } int funA() { if (initialized!=INIT_KEY) return 1 //.. } int funB() { if (initialized!=INIT_KEY) return 1 //.. } int funC() { if (initialized!=INIT_KEY) return 1 //.. } The problem with this approach is that if some of those function is called within a loop so "if (initialized!=INIT_KEY)" is called again, and again, although it's not necessary. It's a good example of why constructors are useful haha, If it were an object I would be sure that when was created initialization was called, but in C, I don't know how to do it. Any other ideas are welcome!

    Read the article

  • Using functions like formulas in Excel

    - by Arlen Beiler
    I am trying to use a formula to get a letter of the alphabet. Formula: =Keytable(RANDOM,ROW()) Function: Function KeyTable(seed As Long, position As Long) As String Dim i As Long Stop Dim calpha(1 To 26) As String Dim alpha(1 To 26) As String For i = 1 To 26 alpha(i) = Chr(i + UPPER_CASE - 1) Next i For i = 1 To 26 calpha(i) = alpha(seed Mod 27 - i) Next i Stop KeyTable = calpha(position) End Function Result: #Value! When I step through the function, it never gets to the second stop.

    Read the article

  • jquery live() method on custom functions

    - by user271619
    I have a custom event handler, or I suppose some call it a custom jquery function. My problem is I'm trying to apply the live() method to it. But I'm not too successful. Here's a simple custom jquery function: $.fn.myFunction = function() { return $(this).addClass('changed'); } And here I use it: $('.changePlease').myFunction(); Ok, simple enough. But how do I apply the live() method to it?? I actually have no idea if that's even possible. But I do use live() for other things, like: $(".changePlease").live("click",function(){ alert("hello"); }); Any thoughts on this?

    Read the article

  • a question of javascript DOM functions in IE 6

    - by CunruiLi
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Test</title> </head> <body> <div id="test"> </div> <script type="text/javascript"> var check = function(){ alert(document.examsys); } var _form = document.createElement("form"); _form.name = "examsys"; _form.action="javascript:;" for(var i=0 ; i<5; i++){ _form.innerHTML += "<input type='radio' name='answer' value='ccc' />&nbsp;abc<br />"; } var submit = document.createElement("input"); submit.type = "image"; submit.src = "tijiao.gif"; submit.alt = "Submit"; if(submit.attachEvent){ submit.attachEvent("onclick",check); } else if(submit.addEventListener){ submit.addEventListener("click",check,false); } _form.appendChild(submit); document.getElementById("test").appendChild(_form); </script> </body> </html> why in IE6 the document.examsys returns "undefined".

    Read the article

< Previous Page | 34 35 36 37 38 39 40 41 42 43 44 45  | Next Page >