w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
How do I handle a variable number of arguments passed to a function in Racket?
There's nothing improper about the list received as a variadic argument list (meaning: variable number of arguments). For example: (define test-list (lambda xs (length xs))) ; xs is a normal list, use it like any other list (test-list 1 2 3 4) => 4 In the above example, the xs parameter is a normal, plain, vanilla list, there's nothing improper about it. You can iterate over it as you would over any other list. There's no need to car it, it's already a list! Also, notice that the same function can be written like this: (define (test-list . xs) (length xs)) ; xs is a normal list, use it like any other list Just for reference: an improper list is one that does not end with the null list. For example: '(1 2 3 . 4). Again, that's not how a variadic argument list looks.

Categories : List

Best way of calling a function with different arguments passed by reference when you only need one of these arguments
Acknowledge to Mats Petersson: you can't pass nullptr as the function requires references. If the function has no warranty attached to it, then you should create temporary variables and pass them all in. It would be unsafe to pass the same variable; in case it's used in internal computation. Even if the function works with the same variable passed, there is no guarantee that someone won't change the implementation of that function in a way that causes your code to break. You could be opening yourself up to nasty bugs in the future.

Categories : C++

checking number of arguments bash script
Just like any other simple command, [ ... ] or test requires spaces between its arguments. if [ "$#" -ne 1 ]; then echo "Illegal number of parameters" fi Or if test "$#" -ne 1; then echo "Illegal number of parameters" fi When in Bash, prefer using [[ ]] instead as it doesn't do word splitting and pathname expansion to its variables that quoting may not be necessary unless it's part of an expression. [[ $# -ne 1 ]] It also has some other features like unquoted condition grouping, pattern matching (extended pattern matching with extglob) and regex matching. The following example checks if arguments are valid. It allows a single argument or two. [[ ($# -eq 1 || ($# -eq 2 && $2 == <glob pattern>)) && $1 =~ <regex pattern> ]] For pure arithmetic

Categories : Bash

WinDBG View Passed Arguments to Any Function
If you have private symbols, dv will show you locals and arguments. There is also a "Locals" window that can be opened with Alt+3 if you prefer to use the GUI. If symbols are not available, it is not quite so easy. You can start with kv to see raw arguments and calling convention. Once you know the calling convention, you know where arguments are stored (stack and/or registers), and it is a matter of deciphering their layout in memory.

Categories : Debugging

Can arguments be passed just by reference to function in javascript
When you add an event listener the function you add gets passed an event object depending on what type of event it is (click, scroll, etc). http://www.w3schools.com/jsref/dom_obj_event.asp window.addEventListener("click", function(event) { alert(event.pageX + ", " + event.pageY); }, false); // same as window.addEventListener("click", function(e) { alert(e.pageX + ", " + e.pageY); }, false); The parameter name can be anything it still represents the event object. EDIT List all of the properties and functions of an event object window.addEventListener("click", function(event) { var all = ""; for(var prop in event) { all += prop + " : " + event[prop] + " "; } alert(all); }, false);

Categories : Javascript

Extracting array as list of arguments passed to function
I assume you know how your array is built. So, why do not you just pass an array as a parameter and then use it in your function ? If you do something like this you can access to your array's values : echo $array['something_else']; And build your function like this : $array = array('id' => '5', 'something_else' => 'hi'); function some_function($an_array) { echo $an_array['something_else']; // value for something_else } some_function($array); Or if you don't want to change function's parameters, call it like this : some_function($array['id'], $array['something_else']);

Categories : PHP

Evaluating ddply within a function when passed ggplot2 aesthetic mappings as arguments
You'll find life easier if you "render" the aesthetics early on. Then you don't need any special ddply calls: library(ggplot2) library(plyr) ggbean <- function(data, mapping, ...) { df <- quickdf(eval.quoted(mapping, data)) ddply(df, "x", summarise, med = median(y, na.rm = TRUE)) } single_df <- data.frame( dv = c(rnorm(100), rnorm(100, 12, 3)), iv = sample(LETTERS[1:4], size = 200, replace = TRUE) ) res3 <- ggbean(data = single_df, aes(x = iv, y = dv))

Categories : R

Find the nearest even number to passed one in MongoDB
The linked related question describes two approaches in finding the "nearest" value. One is to run two queries: to find nearest value higher than given number, and to find nearest lower value. The other approach is to use geospatial index (which would require changing your schema). If you don't mind two queries then the only modification you need to make on the query is to add a constraint that you only want to consider even numbers: db.collection.find ( { "num" : { "$mod" : [ 2, 0 ] } } ) is a way to query for only numbers which are even (see $mod operator docs). Your two queries then become: a=db.collection.find({"num":{"$mod":[2,0], $gte:INPUTNUM }}).sort({"num":1}).limit(-1) b=db.collection.find({"num":{"$mod":[2,0], $lte:INPUTNUM }}).sort({"num":-1}).limit(-1) where you ke

Categories : Performance

Is it possible use column name instead of number as in a function passed to apply?
apply coerces things to a matrix. See Details in ?apply: If X is not an array but an object of a class with a non-null dim value (such as a data frame), apply attempts to coerce it to an array via as.matrix if it is two-dimensional (e.g., a data frame) or via as.array. So $ indexing isn't appropriate.

Categories : R

ArgumentError (wrong number of arguments (2 for 1)) - `find' and `create' for RoR app
A couple of points to note here. The Masterlocation.all returns an Array and when you do Array.find() then that in turn returns Enumerator. You can check these by testing the following in your rails console: @masterlocation.class => Array @masterlocation.find().class => Enumerator So the #find method method only takes in one parameter(Ref doc: http://rdoc.info/stdlib/core/1.9.3/Enumerable#find-instance_method) and you are trying to supply two, hence the error. The fix for this would be to do: @masterlocation.find{|ml| ml.id == params[:id] and ml.nickname == params[:startthere]} But then the question is why do you want to retrieve all the Masterlocations and then use find on the ruby side instead of in the database via ActiveRecords as follows? Masterlocation.find(:all,

Categories : Mysql

Find no. of parameters passed in jQuery function
You can use the arguments object ex var len = arguments.length alert(len) Demo: Fiddle Then you can access the values using the index like arguments[0] will give the first parameter

Categories : Javascript

Undefined function 'time' for input arguments of type 'double'. How do i find a function that others didn't seem to have defined in their code?
As pm89 already suspected, time in this case is a variable. Type: > help mpretrack in your command window. Amongst other information, it will say: Also, the program looks for the files "fov#times.mat" for the "time" variable and the images files "fov#fov#####.tif" from the basepath. If you don't have the specified .mat file, the variable time is unknown, which causes the error you see.

Categories : Matlab

Get total number of arguments a function can take
The number of arguments are virtually endless. Limitations depends not on the language itself, but on hardware/os limitations like memory usage and stuff like that. So you'll probably will not encounter a situation where it will really cause any problems. You could also instead of and endless list of arguments just pass an array as an argument, which in itself can also hold virtually an endless list of key/value pairs. Will not make a big difference in terms of resource usage, but personally I find it easier to handle when the argument list is possibly really really long. -- EDIT If I understand correctly what you want to do (but please explain yourself more clearly if I don't), this is what you want: function my_function($arg1, $arg2) { if(func_num_args() > 2) { throw n

Categories : PHP

Wrong number of arguments for a simple function
See (doc reduce): [...] If coll contains no items, f must accept no arguments as well, and reduce returns the result of calling f with no arguments. [...] Here coll is nil, which is effectively being treated as a collection containing no items (as it usually is in similar contexts), and f is #(%1). Thus #(%1) is being called with no arguments and ends up throwing the exception you see.

Categories : Clojure

How can I determine number of arguments to a function in Clojure?
If you have access to the var that holds the function you can get the argument count by accessing its metadata in the following way: (defn arities [v] (->> v meta :arglists (map count))) (defn a []) (defn b [_ _]) (map arities [#'a #'b]) ;= ((0) (2)) arities will return a seq with all the arities for the function. This has the disadvantage that for a variadic argument vector ([_ _ & _]) it will return (4). (defn c [_ _ & _]) (arities #'c) ;= (4) This could be fixed by removing the & symbol from all the argument lists. (defn arities [v] (->> v meta :arglists (map #(remove #{'&} %)) (map count))) (arities #'c) ;= (3) If you don't have access to the var, the following is a little function that I've used to detect the argument coun

Categories : Clojure

Can you write a c# decorator function that can take any number of arguments?
No, you can'd do exactly this in C# with strongly typed results. It is mainly due to return type - you can relatively easy construct calling of the function with arbitrary number of parameters (i.e. Emit or reflection), but to have strongly typed result you'll have to have multiple functions. Usual approach is to have multiple functions for each of 0-n (often 0-3 is enough) number of arguments. public Func<TReturn> EnableP4<TReturn>(Func<T1, TReturn> function)... public Func<T1, TReturn> EnableP4<TReturn, T1>(Func<T1, TReturn> function).... public Func<T1, T2, TReturn> EnableP4<TReturn, T1, T2>(Func<T1, T2, TReturn> function)... Notes: you may experiment with dynamic to see if you get close to what you want also Dependenc

Categories : C#

PHP function - Call self with same (variable number) arguments
Use call_user_func_array. Example: class TestClass { private $ting = FALSE; public function test() { $args = func_get_args(); if ($this->ting) { var_dump($args); } else { $this->ting = TRUE; call_user_func_array(array($this, 'test'),$args); } } } $test = new TestClass(); //Outputs array(3) { [0]=> string(6) "apples" [1]=> string(7) "oranges" [2]=> string(5) "pears" } $test->test("apples","oranges","pears");

Categories : PHP

Is there a standard Python function that takes any number of arguments and does nothing?
Create your own: def noop(*args, **kw): pass This takes any number of positional and keyword arguments and does nothing at all. pass signifies an empty python block; it works anywhere Python expects a block, including loops, if statements and try statements. Python callables always return something (it is a language requirement); if no explicit return value is given None is returned. The * and ** indicate arbitrary length parameters; you can pass in 0 or more positional parameters and the args name will represent a tuple of them, and 0 or more keyword arguments, and they are captured in the kw dictionary. From the function definition documentation: If the form “*identifier” is present, it is initialized to a tuple receiving any excess positional parameters, defaulting to the

Categories : Python

How to pass arguments to a function of arbitrary number of parameters via macro?
How about something like this: case class Action(f: Function, ts: List[TypeName]) { def render(ruleName: String): Expr[Unit] = { val argNames = (1 to ts.size).map(i => newTermName(s"value$i")) val args = argNames.map(name => Ident(name)) val valDefs = (ts zip argNames).map { case (tn, argName) => q"val $argName = p.valueStack.pop().asInstanceOf[$tn]" } c.Expr[Unit]( q""" val p = ${c.prefix} ..$valDefs p.valueStack.push($f(..$args)) """) } } This compiles (in Scala 2.10.2 with Macro Paradise plugin), but I didn't test whether it works.

Categories : Scala

How can I create a Python function dynamically which takes a specified number of arguments?
A function can be defined as taking any (minimum) number of arguments by preceding one with a *, which will then result in the name being bound to a tuple containing the appropriate arguments. def foo(a, b, *c): print a, b, c foo(1, 2, 3, 4, 5) You will need to limit/check the number of values passed this way yourself though.

Categories : Python

Function class accepting variable number of arguments from a container at runtime
#include <functional> #include <boost/any.hpp> template<class ValueType> struct Function { template <typename ...Args> Function(const std::function<ValueType(Args...)>& f) : fn(f) {} template <typename ...Args> ValueType operator () (Args... args) { auto f = boost::any_cast<const std::function<ValueType(Args...)>&>(fn); return f(args...); } boost::any fn; }; int a(int) { return 1; } int b(int, double) { return 2; } int main(int argc, char** argv) { typedef std::vector<Function<int>> Functions; Functions functions { std::function<int(int)>(a), std::function<int(int, double)>(b) }; std::cout << functions[0](1) << f

Categories : C++

Invalid number of arguments when calling static method through function reference
Okay, found the issue. I was linking some of this swfs library with another, that other swf used the ProductInfoManager, so instead of compiling the newer version of ProductInfoManager with changes, flash was pulling the old version from the other swf. Quite frustrating behaviour if you don't know what's going on.

Categories : Actionscript

R - parApply cannot evaluate function/find arguments with optim or optimx
One problem in your code is that variables such as "strike", "yield_avg" and "census" are not in the scope of VB04, since they are local variables in the worker function. You could fix that by defining VB04 inside that function, also. That will solve the scoping problem, and you also won't have to export VB04. Here's a ridiculously stripped down version of your code that demonstrates this: library(parallel) cl <- makePSOCKcluster(3) test <- matrix(1:4, 2) tempres <- parApply(cl, test, 1, function(x) { VB04 <- function() { strike * yield_avg } strike <- x[1] yield_avg <- x[2] VB04() }) optim and optimx provide a way to pass additional arguments to the function, which may be a better solution.

Categories : R

ggplot in function using variables -- geom_density: arguments imply differing number of rows
You should research more into ggplot(), specifically geom_line and geom_point. I don't think geom_density is what you were looking for here. Below is an example of one way you could approach this task, but there are literally thousands of different approaches you could take, that's why I recommend looking into the documentation more, some links that may help: http://www.cookbook-r.com/Graphs/Bar_and_line_graphs_%28ggplot2%29/. http://sape.inf.usi.ch/quick-reference/ggplot2/geom_text Note: I didn't factorize dt$Thread library(plyr) dd.mean <- ddply(dt, 'Thread', summarize, TPS = round(mean(TPS), 2), RT = round(mean(RT), 2)) ggplot(dd.mean, aes(x = Thread, y = RT)) + geom_line(size = 1, alpha = 0.3, colour = "red") + geom_point(size = 3, alpha = 1, colour = "red"

Categories : R

bash: Using param in find function filling an array
Try using readarray instead: RANGE=$1 readarray -t ARR < <(find /net/nas3/mediadata/xmlprodpictures/tui ! -iname "* *" -iregex ".*/big/[${RANGE}]/.*"'(jpg|gif|png|jpeg)' -type f | sort) printf "Value: %s " "${ARR[@]}"

Categories : Arrays

How to save variable number of arguments using variadic template arguments?
Here is how I tried to solve it: The parametr pack can be recursivle expanded and each parametr saved. Function store is supposed to do it. It uses one (two times overloaded) helper function. template<typename T> void storeHelperFunction(void*& memory, T last) { *((T*)memory) = last; memory = (void*)((char*)memory + sizeof(T)); } template<typename T, typename... Params> void storeHelperFunction(void*& memory, T first, Params... rest) { storeHelperFunction(memory, first); storeHelperFunction(memory, rest...); } template<typename... Params> void store(void* memory, Params... args) { // Copy of pointer to memory was done when passing it to this function storeHelperFunction(memory, args...); } Function store takes a pointer to memory wher

Categories : C++

wrong arguments are passed to .ksh
Give it a try with ${10} rather than $10. The ksh man page states under Parameter expansion: A positional parameter of more than one digit must be enclosed in braces. However, a better way to do it may be to use the entire array: /usr/java/jdk1.7.0_25/bin/java -Xmx256M "$@" You can actually see what's going wrong in the following transcript: pax> cat tst.ksh #!/usr/bin/ksh echo " 1 = [$1]" echo " 2 = [$2]" echo " :" echo " 9 = [$9]" echo "10a = [$10]" echo "11a = [$11]" echo "10b = [${10}]" echo "11b = [${11}]" pax> tst.ksh a b c d e f g h i j k 1 = [a] 2 = [b] : 9 = [i] 10a = [a0] 11a = [a1] 10b = [j] 11b = [k] The multi-digit positional parameters without braces are being treated as single-digit ones with a trailing digit constant. In other words, $10 is bei

Categories : Java

How to use the passed arguments in OOP perl?
and how do i access the hash inside the constructor? Your hashref inside the constructor ($point) is the object. When you bless a reference you make it into an object. So you can now do this: print $point->{year}; # from inside constructor ... print $object->{year}; # after construction But accessing the private parts of the object isn't safe. I would suggest that you create accessors for it rather than manipulating the hash directly. E.g. sub year { my $self = shift; # this is now the object if (@_) { $self->{year} = $_[0]; } return $self->{year}; } ... print $object->year(1984); print $object->year; What's the use of that overriden values inside the constructor? Can anyone site a good example wherein the default values inside the

Categories : Perl

Python arguments passed with quotes
Hard without seeing what you're using or any code. Your shell may be interfering, you may need to escape the spaces with . Example: python script.py -o a -f "file1.txt" "file 2.csv"

Categories : Python

What are the differences between -m, -s and -X arguments passed to git rebase?
These arguments don't do different things but rather modify how the rebase will apply the changes. http://linux.die.net/man/1/git-rebase -m, --merge Use merging strategies to rebase. When the recursive (default) merge strategy is used, this allows rebase to be aware of renames on the upstream side. Note that a rebase merge works by replaying each commit from the working branch on top of the <upstream> branch. Because of this, when a merge conflict happens, the side reported as ours is the so-far rebased series, starting with <upstream>, and theirs is the working branch. In other words, the sides are swapped. In other words, rather than just applying the changes with each commit perform merge the changes into the branch. For example, if a file was renamed, git will make yo

Categories : GIT

In prepareforsegue how datas are passed by using arguments
Set your custom properties on the destination view controller,Use this method to pass the property in all of your view controllers ASEventDetail *vc = [segue destinationViewController]; vc.someobject=[eventArr objectAtIndex:self.view.tag]; for reference you can refer Pass Data Between View Controllers

Categories : IOS

What arguments are passed to msiexec on uninstall
You can type the following from a command window to see all the options: msiexec.exe /? Then to find out which of these is passed for a particular application, go to the following key in the registry and look for the sub-key for the application you're interested in HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionUninstall For example, on my system, the Microsoft Visio Viewer 2013 entry shows the following command line under the UninstallString key: MsiExec.exe /I{95150000-0052-0409-1000-0000000FF1CE}

Categories : Windows

Why do events commonly use EventHandler, even when no arguments need to be passed?
Because you can write a generic event handler and use it for many different kind of events (like a logging facility) taking advantage of contravariance in delegates. Here's an example from the msdn: // Event hander that accepts a parameter of the EventArgs type. private void MultiHandler(object sender, System.EventArgs e) { label1.Text = System.DateTime.Now.ToString(); } public Form1() { InitializeComponent(); // You can use a method that has an EventArgs parameter, // although the event expects the KeyEventArgs parameter. this.button1.KeyDown += this.MultiHandler; // You can use the same method // for an event that expects the MouseEventArgs parameter. this.button1.MouseClick += this.MultiHandler; } Other than this, it is only a design guide

Categories : C#

How are primitives passed into functions as arguments in JavaScript?
From what I know when primitive types are passed in an argument of a function then they are passed by value and a copy of the primitive value is passed in the function. Which means that if within the function you change the value of the argument then the 'original' value of the variable is intact. var pvalue = 'foo'; //primitive function changeMe(prim) { prim = 'bar'; } changeMe(pvalue); console.log(pvalue); // pvalue remains foo (unchanged) However if you try the same with an object it will change the 'original' object since it's new variable in the function will point also to the original object. But that doesn't mean that it was passed in by reference. Check this out. function changeMe(obj) { obj.foo = "foo"; obj = new Object(); obj.foo = "bar"; } var ovalue = {

Categories : Javascript

Confusion about how arguments are passed through Python decorators
def this_is_a_decorator(fn): def decorated_fn(*args,**kwargs): result = fn(*args,**kwargs) #notice we are calling the original function return "%s decorated"%result return decorated_fn @this_is_a_decorator def reverse_string(msg=""): return msg[::-1] print reverse_string("Hello!") for the decorator for you def init_cart(fn): def decorated_fn(*args,**kwargs): cart = Cart() fn(cart) return cart return decorated_fn @init_cart def add_item(shopping_cart=None): shopping_cart.add(request.params)

Categories : Python

Find a random number generator using a given random number generating function
You need to use rejection sampling. That is, reject results that don't fit your target distribution. In your case you could use the lower three bits of two successive calls to your rand15 function (− 1 if necessary), concatenate them and reject those results that are outside your target interval and retry until you find a number that's inside.

Categories : Algorithm

SQL COUNT Function to find number of a particular ddata
If some columns can contain APPLE more than one time, please put it in your question. If not, you can use the following: SELECT COUNT(*) FROM Fruits WHERE Your_Column='APPLE' If Apple can show up with some other text, you can use this one: SELECT COUNT(*) FROM Fruits WHERE LEN(Your_Column)!=LEN(REPLACE(Your_Column,'APPLE','')) I wrote for MSSQL, I don't know which sql server you are using.

Categories : SQL

getting the type of parameters passed in a variable arguments list
I'd rather consider passing tuple or array or a vector. As std::array is template with N, it is possible to make your function a template with N too, and implement in a generic way. Variadic template is also viable if your complier is good for it. The ... is something we try to get rid of. It's undefined behavior to pass anything non-POD, and no type check is possible. What makes it way too prone to errors. For your case it is not very helpful either.

Categories : C++

Code Igniter Pagination and URL passed method arguments
As I understand, you want not to see page number in url, but CI Pagination class always add number to link. For more details see Pagination class. Also you can use jquery datatable for client or server pagination.

Categories : PHP

How to obtain arguments passed to setup.py from pip with '--install-option'?
I was having this problem installing pyside. I needed to specify the --qmake option. This is the form you need: pip install --install-option="--qmake=/usr/lib64/qt4/bin/qmake" PySide

Categories : Python



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.