Menu
  • HOME
  • TAGS

Void function (c++)

c++,function,void,equation,quadratic

When you declare a function like void add_nmbr(int a, int b, int c) you are passing parameters by value which means you pass a copy of value into the function. You can change the value inside add_nmbr for a but that value stays inside the function. In you case, the...

How to perform a statement inside a query to check existence of a file that has the query id as name with less resources in laravel

php,function,laravel,laravel-4,eloquent

Do you have good reason to believe that scandir on a directory with a large number of folders will actually slow you down? You can do your query like this: if(Input::has('field')){ $filenames = scandir('img/folders'); $query = Model::whereIn('id', $filenames)->get(); } Edit 1 You may find these links useful: PHP: scandir() is...

Object Oriented Python - rectangle using classes and functions

python,function,class,oop,methods

Not sure I got your question right, but you may want to try: def getStats(self): return "width: %s\nheight: %s\narea: %s\nperimeter: %s" % (self.width, self.height, self.area(), self.perimeter()) To satisfy requirements 4 and 6, I would suggest something like: class Shape(object): def area(self): raise NotImplementedError def perimeter(self): raise NotImplementedError class Rectangle(Shape): def...

C++ need help figuring out word count in function. (Ex. Hello World = 2)

c++,function

int wordCounter(char usStr[]) { int index= sizeof(usStr); int result = 0; for (int i=0; i<index; i++){ if(usStr[index]== ' ') result++; }//end of the loop return result+1; } //try this one. ...

Infix operator with missing argument

function,haskell,infix-notation

Not really, no. On the other hand, you could perfectly well define a different operation that provides the default argument, e.g. withDef data2 = {- your default value -} <*> data2 If you really want to use a name that would otherwise be an operator, you can still name this...

How to produce legend in ggplot by mapping aes_string from different data frames in ggplot?

r,function,ggplot2

You can use shQuote to quote the string and scale_fill_manual to map the strings to appropriate colors x_var <- "Score" ggplot(met1, aes_string(x_var)) + geom_density(data=met1, aes_string(x=x_var, fill=shQuote("b"))) + geom_density(data=met1[met1$Group=="Group1",], aes_string(x=x_var, fill=shQuote("r")), alpha=0.50) + scale_fill_manual(name='Groups', guide='legend', values=c("b"="black", "r"="red"), labels=c('All Groups', 'Group1')) ...

R function that calculate correlation between two elements of a data frame if condition is meet

function,r

Try this: corr <- function(directory, threshold = 0) { files <- list.files(directory, full.names = T) dat2 <- lapply(files, function(x) na.omit(read.csv(x))) size <- unlist(lapply(dat2, nrow)) cors <- lapply(dat2[size > threshold], function(x) cor(x['nitrate'], x['sulfate'])) res <- unname(unlist(cors)) } ...

Replace paragraph in HTML with new paragraph using Javascript

javascript,function,onload,getelementbyid,appendchild

You can just replace the text content of the #two element: var two = document.getElementById("two"); window.onload = function () { var t = "I am the superior text"; two.textContent = t; }; <p id="two">Lorem ipsum dolor sit amet.</p> If you use createTextNode, then you'll need to use two.textContent = t.textContent...

Why can we use undefined object in Javascript function declaration?

javascript,function

The 2nd argument of cr.define() is an anonymous function expression, it is parsed and executed, the returned value is an object, which is then passed to cr.define() as argument. In fact it's not. It's just passed as a function to cr.define, without being called. It's executed from within there:...

Can anyone improve on the below Fuzzyfind function for VBA?

algorithm,vba,function,find,fuzzy-search

Try this out, I think it will find the best match Function FuzzyFind2(lookup_value As String, tbl_array As Range) As String Dim i As Integer, str As String, Value As String Dim a As Integer, b As Integer, cell As Variant Dim Found As Boolean b = 0 For Each cell...

Casting a String Into a Function in R

r,function,casting

You can use parse() and eval(): foo <- eval(parse(text = function_code)) > foo function(x) { as.dist(1-cor(t(x))) } Just wrap that in a function: parseEval <- function(text) { eval(parse(text = text)) } If you need an actual something() rather than a direct call. Here's an example: set.seed(1) x <- matrix(runif(20), ncol...

sum of Digits through Recursion

java,function,recursion,sum,digit

You aren't actually recursing. You've setup your base case, but when solving a problem recursively you should have code within the function that calls the function itself. So you're missing a line that calls sumDigits, with a smaller argument. Consider two important parts of a recursive soutlion: The base case....

JavaScript recursive function breaks when () included in call

javascript,jquery,function

If you write down setTimeout(countdown(), 1000);, basically when that block of code gets evaluated, JS will call countdown() inmediatelly. By doing setTimeout(countdown, 1000);, you are passing a reference to the function countdown as the first argumant, thus, it won't be executed until 1 second later as per the second argument...

Count neighboring cells

java,function,for-loop

Your upper limit in your for statements should by checking for <= not just less-than. By testing for less-than you stop before getting to x+1 or y+1. It should look like this: for (int i = Math.max(0, x - 1); i <= Math.min(grid.getWidth()-1, x + 1); i++) { for (int...

Function Returning Square Brackets When Using Array Methods

javascript,arrays,function

You are passing the range indexes in the wrong order. You cant go from 5 to 2, you need to go from 2 to 5 range(2,5) ...

How to condense this into a single function?

javascript,jquery,function,dry

You can use a loop to do that. An anonymous function inside the loop is used to prevent breakage jQuery events, try: for(var i = 1; i <= 3; i++){ (function(num){ $('.box' + num).hover(function() { $('.img_hover_effect' + (num == 1 ? "" : num)).fadeIn(500) }, function(){ $('.img_hover_effect' + (num ==...

Once again: JS functions and objects

javascript,function,object

How does JS know the difference between an object with a function property and a constructor to which properties have been added? There are different terminologies: Functions are objects which are Function instances. Callable objects are objects with an internal [[Call]] method. Constructors are objects with an internal [[Construct]]...

How do I return a value from a second function in PHP?

php,function,return,value

Your code is mostly working, you simply misplaced some quotes and concatenation. Adding quotes where they shouldn't be or forgetting to add them where needed will cause PHP to misinterpret your code. You might consider using a code editor or IDE to avoid this in the future. They will highlight...

Selecting and removing a html select option without selecting by index or ID, using vanilla JavaScript

javascript,function,select,options

Something like this? (function (){ var parent = document.getElementById("MediaCategory"); for(var i=0; i< parent.children.length; i++){ var child = parent.children[i]; if(child.text === "Archive") { parent.removeChild(child); } } })(); ...

Find out the biggest odd number from three arguments in a function [Python]

python,function

A few changes would be needed: def oddn(x,y,z): odd_number_keeper = [] for item in [x,y,z]: if item % 2==1: odd_number_keeper.append(item) if not odd_number_keeper: print 'No odd number is found' return return max(odd_number_keeper) Iterate over the values x, y and z and add the odd numbers to odd_number_keeper. If there are...

need help to search element from vector of struct

c++,function,c++11,std

A lambda is just a convenience functor that was introduced so that you can write these algorithms simpler. But it's just a convenience. If you can't use them in this case, it's not the end of the world. After all, we couldn't for many many years. The solution is to...

Call known function (with parameters) in class whose name is defined by string variable

java,function,class,variables

Your can use Reflection Object action = ???; // perhaps you need .newInstance() for action class // Hopefully you have a interface with performLogic String methodName = "performLogic"; try { Method method = action.getClass().getMethod(methodName, param1.class, param2.class); method.invoke(action, param1, param2); } catch (SecurityException | NoSuchMethodException e) { // Error by get...

Reversing the output of a function in python that is not a list

python,function,reversing

Your method func is missing a return statement (and thus returns None). Without returning a value, you can't apply the index operator on it.

Counting bytes received by posix read()

c,function,serial-port,posix

Yes, temp_uart_count will contain the actual number of bytes read, and obviously that number will be smaller or equal to the number of elements of temp_uart_data. If you get 0, it means that the end of file (or an equivalent condition) has been reached and there is nothing else to...

Functions with pointer arguments in C++

c++,function,pointers,constructor,ampersand

Item i2(i1); This works because it is not calling your user-defined constructor which takes a pointer, it is calling the implicitly generated copy-constructor which has the signature: Item (const Item &); If you don't want this to be valid, you can delete it (requires C++11): Item (const Item &) =...

Excel Function Error

excel,function,text

From what I understand that you are trying to achieve, the logic is wrong. I would suggest =IF(H4<50;"Sigur";IF(H4<100;"Probabil";"Da")) Note I removed the "text" function - the double quotes are enough.

Swift func - Does not conform to protocol “Boolean Type”

function,swift,dictionary

You don't need to add parameters into return like this (isGot: Bool, dictLocations: Dictionary <String, Double>). you just need to tell compiler that what type this function will return. Here is the correct way to achieve that: func getRecordNumber(recordNumber: Int32) -> (Bool, Dictionary <String, Double>) { let isGot = Bool()...

Read blank as missing(NA) in R data table

r,function,data.table

You can use the fast nzchar like this : is.na(x) | !nzchar(x) For example : x <- c(NA,'','a') is.na(x) | !nzchar(x) ## [1] TRUE TRUE FALSE apply this to OP example: I wrap this in a function with ifelse : tt <- data.table(x=c('an','ax','','az'),y=c('bn','','bz','bx')) tt[, lapply(.SD, function(x) ifelse(is.na(x) | !nzchar(x),'some value',x))...

Array of constant pointers to functions

c,function,pointers,constants,ansi

The const is misplaced. As it stands, the functions are supposed to return const int (which makes little sense). What you want is: int (*const x[])(int) This way it reads: array of "const pointers to function"....

How to skip a function

function,python-2.7

If I you're asking what I think you're asking, then yes. In fact, that's the whole point. Functions are sections of reusable code that you define first (they don't run when they're defined!) and then you call that function later. For example, you can define a function, helloworld like this:...

How can I minimize this function in R?

r,function,optimization,mathematical-optimization

I think you want to minimize the square of a-fptotal ... ff <- function(x) myfun(x)^2 > optimize(ff,lower=0,upper=30000) $minimum [1] 28356.39 $objective [1] 1.323489e-23 Or find the root (i.e. where myfun(x)==0): uniroot(myfun,interval=c(0,30000)) $root [1] 28356.39 $f.root [1] 1.482476e-08 $iter [1] 4 $init.it [1] NA $estim.prec [1] 6.103517e-05 ...

Pick subset of functions as string & evaluate

javascript,jquery,arrays,string,function

I could see two things wrong: Your functions were not assigned to the window Your "effect" variable contained leading whitespace I have corrected the above points here: http://jsfiddle.net/ftaq8q4m/1/ This appears to have resolved the issue you described. Example: window.func1 = function() { $('html').append('func1'); } And: window[effect.trim()](); Update As a bonus...

Stuck on Structs(c++)

c++,function,struct

You have declared coordinate startPt, endPt; in main() and you are trying to access them Readcoordinate(). To resolve error you should declarecoordinate startPt, endPt;inReadcoordinate()` or pass them as argument. coordinate Readcoordinate() { coordinate startPt; cout << "Enter Longitude(in degrees)" << endl; cin >> startPt.latitude >> startPt.longitude >> startPt.city; return startPt;...

sql server function does not allow return statement

sql-server,function,return

Take a look at this example... You still need to add your logic to it. But it should give you a hint. CREATE FUNCTION dbo.fnGetToInvoiceLoads (@TruckID int, @ClientID int, @OpdrachtID int, @OpcID int, @VertrekIDs varchar(max), @BestemmingIDs varchar(max), @CarIDs varchar(max)) RETURNS @result TABLE (RitChecked bit, RitID int, ClientID int) AS BEGIN...

How can I simulate a nested function without lambda expressions in C++11?

c++,function,c++11,lambda,allegro

Simply put the image inside the visual_plot function and make it static: void visual_plot() { static Image img("sample.png"); x.draw(); // Problem. } This will initialize img the first time visual_plot is called, and only then. This will solve both the performance problem and the "it must be initialized after app.run()"...

xslt condition output one by one

xml,function,xslt,if-statement,xpath

Try: <xsl:template match="blabla"> <all> <xsl:for-each select="a"> <a n="{@n}"> <xsl:copy-of select="../b[@n >= current()/@n]"/> </a> </xsl:for-each> </all> </xsl:template> ...

How to have multiple variable function work with vectors

function,vector,scilab

Scilab doesn't have a direct analogue of Python's fcn(*v) function call that would interpret the entries of v as multiple arguments. If you want to be able to call your function as either fcn(1,2,3,4,5,6) or as v = 1:6; fcn(v), then you'll need to add this clause to its beginning:...

How do I fix function compilation error?

oracle,function,plsql,sql-update

I would try not to use a function at all. Using straight SQL is usually a better solution. Based on the information you gave we have the following tables. (Your function does compile with these tables.) CREATE TABLE emp_task (emp_id NUMBER PRIMARY KEY ,grade_id NUMBER ,sal NUMBER); CREATE TABLE sal_inc...

Waiting without Sleeping? (C#)

c#,function,wait

Use Task.Delay: Task.Delay(1000).ContinueWith((t) => Console.WriteLine("I'm done")); or await Task.Delay(1000); Console.WriteLine("I'm done"); For the older frameworks you can use the following: var timer = new System.Timers.Timer(1000); timer.Elapsed += delegate { Console.WriteLine("I'm done"); }; timer.AutoReset = false; timer.Start(); Example according to the description in the question: class SimpleClass { public bool Flag...

Python avoid item = None in a request of multiple items

python,function,request,urllib,nonetype

You can use a try/except block around the code that's causing the issue. If the list is empty, run the next iteration of the outer for loop (untested): def searchGoFromDico(dictionary): dicoGoForEachGroup = {} for groupName in dico: taxonAndGene = dico[groupName] listeAllGoForOneGroup = [] for taxon in taxonAndGene: geneIds = taxonAndGene[taxon]...

Decremented value called in the recursion in Haskell

string,function,haskell,recursion,parameters

Yes, once you call again f with a new value of n, it has no way to reference the old value of n unless you pass it explicitly. One way to do it is to have an internal recursive function with its width parameter, as you have, but that can...

How does ((a++,b)) work? [duplicate]

c,function,recursion,comma

In your first code, Case 1: return reverse(i++); will cause stack overflow as the value of unchanged i will be used as the function argument (as the effect of post increment will be sequenced after the function call), and then i will be increased. So, it is basically calling the...

passing arguments via reference and pointer C++

c++,function,pointers,reference

Yes. There's no copy anywhere as you're either using pointers or references when you “pass” the variable from one place to another, so you're actually using the same variable everywhere. In g(), you return a reference to z, then in f() you keep this reference to z. Moreover, when you...

set time interval for javascript function in “microseconds”

javascript,jquery,function

4 ms is the minimum timeout in standard HTML5 according to the spec See this reference: https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout#Minimum_delay_and_timeout_nesting You may think you can assign any amount of duration in millisecond which is as small as you want in JavaScript, however, it is limited by the HTML5 spec that the minimum delay...

accessing a variable from outside a function and returning the variable. In a module pattern

javascript,function,module,scope

When you module first gets executed (e.g. when you script is first parsed), addAmount is assigned the return value of getAmount() which, when you don't pass in an argument, is undefined. Now when you return the object from the module and assign returnAmount to addAmount - you are setting returnAmount...

Interpret formulae/operators as functions

r,function,variable-assignment,formula,evaluation

You can do this: `*` <- intersect `+` <- c Be aware that if you do that in the global environment (not a function) it will probably make the rest of your script fail unless you intend for * and + to always do sum and intercept. Other options would...

PHP: How to use function to either echo result or to save it in a variable (partially working)

php,function,variables,echo

Just return the value in the function instead of echoing it: function fetchTransMain($trans, $itemID){ foreach($trans as $key => $val){ if($val["ID"] == $itemID){ return $val["trans"]; } } } Then, when you want to print it you do: echo fetchTransMain($trans, someID); Otherwise you do: $someVariable = fetchTransMain($trans, someID); ...

Toggle text + also call method with argument?

jquery,function,toggle

Why not just: document.addEventListener("keydown", function(e) { if (e.keyCode == "32") { e.preventDefault(); $(".spacebar_left").text(function(i, v) { if (v === 'PUSH ME') { custommethod("start") return 'DON"T PUSH ME' } else { custommethod("end") return "PUSH ME" } }) } }); p.s.: in your example custommethod() is never called as it goes after return...

Global scope for array of structs inside function - Swift

arrays,function,swift,struct,shuffle

"...that doesn`t seem to work..." is a variation on perhaps the least helpful thing you can say when asking for help. What do you mean it "doesn't seem to work"?!?!? How doesn't it work? Explain what it's doing that doesn't meet your needs. Is it crashing? Is the shuffledQuestions array...

Get array output of one function in another function php

php,function,codeigniter

Simply pass that value within that function as public function add_attachments($openid) { $config = array( 'upload_path' => './uploads/attachments/', 'allowed_types' => 'gif|jpg|png|jpeg|doc|pdf', 'max_size' => '1024000000', 'multi' => 'all' ); $this->load->library('upload', $config); if (!$this->upload->do_upload()) { $error = array('error' => $this->upload->display_errors()); } else { $data = $this->upload->data(); } $new_array = array_column($data, 'full_path'); $this->getback($new_array);...

what does php's header function do?

php,function,http,header,content-type

why this code is sending "header('HTTP/1.1 200 OK');"? i know this code means that the page is Good, but why are we sending this code??_ This tells your browser that the requested script was found. The broswer can then assume it will be getting some other data as well....

Why doesn't this swift function work?

string,function,swift

In the inner loop for y in 0..<loc_except.count { if loc[x] != loc_except[y] { loc[x] = "-" } } loc[x] is replaced by the dash "-" if it is different from any characters in loc_except. This will always be the case if the exception string has at least two different...

Functions and pointers in C

c,function,pointers

That's not the correct way to a pointer from a function. Also r is local variable whose lifetime is limited to the function. Allocate memory using malloc and return it instead: int* randn(int n, int l){ int *r=malloc(n * sizeof *r); if(!r) { */ error */} int i; for (...

in jquery can i add a readonly attribute to a input that the only property i can touch is a function?

jquery,function,readonly

Yes, you can, using an attribute equals selector: $('input[onkeydown="return scriptReadonly();"]').prop("readonly", true); Live Example: function scriptReadonly() { } $('input[onkeydown="return scriptReadonly();"]').prop("readonly", true); <INPUT id="ctl00_ContentPlaceHolder_txtSOPurchaserSapID" onkeydown="return scriptReadonly();" style="WIDTH: 150px" name=ctl00$ContentPlaceHolder$txtSOPurchaserSapID> <INPUT id="ctl01_ContentPlaceHolder_txtSOPurchaserSapID" onkeydown="return scriptReadonly();" style="WIDTH: 150px"...

How to return an array with unhappy numbers removed?

matlab,function

I've written a small function (which might be further improved) to test the "happines" of a number. Current version only works with scalar and one dim. array. Input: the scalar or array to be tested Output: 1) an index: happy (1) unhappy(0) 2) the list of happy number within the...

How to call a data.frame inside an R Function by name

r,function,data.frame,call

There are number of ways of doing this. Your "native" way would be mydata <- ls(pattern = "set") for (dataCount in mydata) { print(summary(lm(x~y, data=get(dataCount)))) } or you could collate your data.frames into a list and work on that. mylist <- list(set1, set2) lapply(mylist, FUN = function(yourdata) { print(summary(lm(x ~...

function pointer is not a function or function pointer

c++,function,pointers

funcy is a pointer to a member function, so you need to call it on an instance of the class, like this: (this->*funcy)(items,i); ...

C# add to list not working

c#,function

Because that's not the way to show a list in the console. Try this: for(int i=0;i<slope.Count;i++) { Console.WriteLine(slope[i]); } ...

Generic method to perform a map-reduce operation. (Java-8)

java,function,generics,java-8,overloading

The example you present in your question has got nothing to do with Java 8 and everything to do with how generics work in Java. Function<T, Integer> function and Function<T, Double> function will go through type-erasure when compiled and will be transformed to Function. The rule of thumb for method...

JS: Is it possible “something(arg)” and “something.my_method(arg)” at same time

javascript,function,oop,methods

Well, this is javacript, and there are many ways to do it. edit: I actually thought about this, and tried to imagine other way to do the same thing, and actually I cannot find any. There's @elcodedocle which I thought about but is close but not what you ask, or...

How to allow variable parameters passed to function

c,function,parameter-passing

What you want is called Variadic function. It can accept variable number of arguments. **Famous examples: printf()/scanf() These functions contain an ellipsis (…) notation in the argument list, and uses special macros to access the variable arguments. The most basic idea is to write a function that accepts a variable...

is return main(); a valid syntax?

c,function,return,language-lawyer,return-type

I didn't know that the return statement accepts any parameter that can be evaluated to the expected return data type, Well, a return statement can have an expression. Quoting C11 standard, chapter 6.8.6.4, The return statement. If a return statement with an expression is executed, the value of the...

My function will log a value to the console, but it won't return the same value - why? [duplicate]

javascript,arrays,function,recursion

You're missing a return when calling steamroller recursively. Fixed code: function steamroller(arr) { arr = arr.reduce(function(a, b, i){ return a.concat(b); },[]); if (!Array.isArray(arr[arr.length-1])) {console.log(arr); return arr;} return steamroller(arr); } steamroller([1, [2], [3, [[4]]]]); ...

When calling a recursive function to order values, it misses one. How do I fix this?

python,algorithm,function,recursion

Just sort on the last column: sorted(f,key=lambda x: int(x.split(",")[-1])) You can use bisect to find where to put the new data to keep the data ordered after it is sorted once: from bisect import bisect import csv with open("foo.txt") as f: r = list(csv.reader(f)) keys = [int(row[-1]) for row in...

My is_prime function fails on 9, and I don't know why?

python,function

That is because the function does not check all eligible divisors until it returns. Instead, it exits early with True if x is not divisible by 2, which is not what you want for odd numbers (e.g. 9 is not divisible by 2, yet it's not prime). Instead, you want...

Return type of list front (C++)

c++,function,reference,linked-list,return-type

There are two types of constructors added automatically to any class you declare: The default constructor, which default-initializes all members of that class §12.1.4 and the copy constructor §12.8.7. In your case, we have to take a look at the copy constructor: The declaration of the copy constructor looks like...

Scope in javascript acting weird

javascript,function,scope,pass-by-reference

If you added another line you can get a clearer picture of what is happening: function change(a,b) { a.x = 'added'; a = b; a.x = 'added as well'; }; a={}; b={}; change(a,b); console.log(a); //{x:'added'} console.log(b); //{x:'added as well'} When you're doing a = b you're assigning the local variable...

Fetch a function definition without rights on source files

php,function,source,server-side,definition

If you can call the function that means you can include its file to load it which means you can inspect the file contents. If you didn't have permissions to include (read) the file then you couldn't load the function and you couldn't call it and for all intents and...

XQuery - Doing math on elements within a sequence and aggregating results

function,operators,xquery,sequence,aggregation

The error is occurring because you're using operations (like multiplication) that take exactly two arguments, and passing a sequence on one side or both. To illustrate the meaning of the error -- you get the exact same thing running: (1,2,3) * 2 Since your goal is to multiply values together...

How to execute JavaScript function in an Ajax() Response

javascript,jquery,ajax,function,eval

You should delegate event: $(".allShopping-deals").on('click', '.products', function(){ alert($(this).find('.pid').text()); }); ...

Passing a vector as argument to function

c++,function,stl

Use the referenced type void Foo(std::vector<bool> &Visited, int actual element); Otherwise the function deals with a copy of the original vector. Here is a dempnstrative program #include <iostream> #include <vector> void f( std::vector<int> &v ) { v.assign( { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 } );...

How to have parameters to a button command in tkinter python3 [duplicate]

python,function,python-3.x,tkinter

You are looking for the lambda keyword: from tkinter import * index={'Food':['apple', 'orange'], 'Drink':['juice', 'water', 'soda']} Names=['Food', 'Drink'] def display(list): for item in list: print(item) mon=Tk() app=Frame(mon) app.grid() for item in Names: Button(mon, text=item, command= lambda name = item: display(index[name])).grid() mon.mainloop() You have to use name = item so that...

How do I set up a bash alias for a common working folder?

bash,function,alias

Two workarounds: Add this to your .bashrc: CDPATH="$CDPATH:$HOME/some/deep/working" then you can use cd folder/bob from everywhere. Use a variable: myfolder="$HOME/some/deep/working/folder" cd "$myfolder/bob" ...

Why is the button.setText() shows error

java,android,function

You cannot touch UI from background thread. use AsyncTask http://developer.android.com/reference/android/os/AsyncTask.html

call function after “loop” function for multiple elements is finished in jQuery

jquery,function,loops,animation

I didn't want to rewrite it all but you have some necessary stuff. It illustrates the use of the fadeIn callback. https://jsfiddle.net/c633f5w8/4/ var v = $(".box"); var cur = 0; var len = v.length; console.log(len); var first = function () { function fadeInNextLI() { if(cur+1 == len){ v.eq(cur++).fadeIn(200,'swing',finish); } else...

Trying to include an array using a function to require the files with the array

php,arrays,function

functions in php create scope. this means any variable defined inside a function is not visible outside of it's body function foo() { $bar = 1; } // Here $bar is undefined foo(); // Still undefined In you case, you initialize the $lang variable inside the lang_files function, so it's...

Stopping condition on a recursive function - Haskell

string,function,haskell,if-statement,recursion

Your code doesn't handle the case where a line is shorter than the maximum length. This is somewhat obscured by another bug: n is decremented until a whitespace is found, and then f is called recursively passing this decremented value of n, effectively limiting all subsequent lines to the length...

Calling function and passing arguments multiple times

python,function,loops

a,b,c = 1,2,3 while i<n: a,b,c = myfunction(a,b,c) i +=1 ...

Passing Pointers through a Function Then Getting Giberish

c++,function,pointers

x is the address of arr and arr is a stack variable so you cannot pass it as a return value. If you want check to return a pointer to an array you need to allocate it with new: arr = new int[r]. Note that you will need to eventually...

Genetic Algorithm - convergence

java,algorithm,function,genetic-programming,convergence

I don't have the time to dig into your code but I'll try to answer from what I remember on GAs: Sometimes I will give it points that will never produce a function, or will sometimes produce a function. It can even depend on how deep the initial trees are....

JS Browser with pause function, help please

javascript,function,browser

Add a variable for your timeout period, instead of using the value 4000. Note that it must have global scope. I've added a variable calleddelay here: var wnd; var curIndex = 0; // a var to hold the current index of the current url var delay; Then, use the new...

What makes the object.prototype to the constructor function if he has no name? [duplicate]

javascript,function,class,inheritance,prototype

after constructorFunction.prototype there is no propertie or method name That's not true. The prototype of the constructor is set using triangle object. The prototype has 3 properties. prototype is an object. Consider these examples: var obj = { 'baz': 'bar' }; obj = { 'foo': 'bash' } // obj...

Is it possible to use $(this) in a function called from another function?

jquery,function,this

Always be careful when using the this as you may end up using an unexpected value depending on the context your function was called. Instead, you should consider using a parameter: $('.member-div a').on("click",function(f){ f.preventDefault(); newfunc($(this)); }); function newfunc(item){ var x = item.parent('div').attr('id').slice(-1); $('.member-div').hide(); if(item.hasClass('next')){ var y = parseInt(x)+1; }; if(item.hasClass('back')){...

SQL average age comparison function returns null

mysql,sql,function,datetime

While you declared the variable averMen, you have not initialized it. The query which should be calculating averMen is calculating averWomen instead. Try changing ... SELECT AVG(DATEDIFF(BIRTH_DATE,CURDATE())) INTO averWomen FROM PLAYERS WHERE sex = 'M'; into SELECT AVG(DATEDIFF(BIRTH_DATE,CURDATE())) INTO averMen FROM PLAYERS WHERE sex = 'M'; ...

strip_tags() on MySQLi Query and PHP Function [closed]

php,mysql,string,function,mysqli

strilp_tags() is definitely somewhere in your code to throw the error. Try posting all the codes involved so we can find out where your problem is coming from.

A function to calculate cumulative maximum for a double matrix in MATLAB

matlab,function,matrix,max

If cummax isn't working then I came up with this little function function m = cummax2(x) [X, ~] = meshgrid(x, ones(size(x))); %replace elements above diagonal with -inf X(logical(triu(ones(size(X)),1))) = -inf; %get cumulative maximum m = reshape(max(X'), size(x)); end ...

Delete file after “x” second after creation

vb.net,function

You must handle the timed event in a handler for the Timer's Tick Event (or Elapsed if using System.Timers.Timer): Private m_strTest As String = String.Empty Private Sub Form1_Click(sender As Object, e As EventArgs) Handles Me.Click m_strTest = Application.StartupPath & "\" + tte4 Timer1.Enabled = True End Sub If using System.Forms.Timer...

MySQL function with parameters syntax error

mysql,regex,function

You must be getting an error on the SET @dd line. You can't set values to any variable by assigning a statement. You have to use SELECT .... INTO ... syntax to set value for a variable. There are several other errors in your code. Change them as suggested below:...

session value in javascript cannot be set

javascript,function,session

Javascript is a client-side language. Session are server-side component. If you want to update session when user does something on your page, you should create a ajax request to the server. Or maybe use some client side variables that, for some aspects, are similar to session (they will be forever...

Python 3 random.randint() only returning 1's and 2's

function,python-3.x,random,dice

this line if die == 'a' or 'A': will always return True. That is because the way the items are grouped, it is the same as if (die == 'a') or ('A'): and 'A' (along with any string except "") is always True. Try changing all those lines to if...

Update input number variable onclick

javascript,jquery,html,function

You need to put all the calculations into the calc() function: function calc() { // Get Years var years = (document.getElementById('years').value); // Variables var years; var gallons = 1100 * 365; var grain = 45 * 365; var forest = 30 * 365; var co2 = 20 * 365; var...

jQuery - Value in Function

jquery,arrays,function

You need to use brackets notation to access property by variable: function myFunc( array, fieldToCompare, valueToCompare ) { if( array[fieldToCompare] == "Thiago" ) alert(true); } And wrap name in quotes: myFunc( myArray, 'name', "Thiago" ); ...

Can't understand this Javascript function (function overloading)

javascript,function,methods,overloading

fn.length will return the number of parameters defined in fn. Will arguments.length return the number of which arguments? The already existing function's? No. arguments is an array-like local variable that's available inside of a function. It contains the number of arguments passed to the function. The rest of your...

How to pass pointer to struct to a function?

c,function,pointers,struct

Inside your doStuff() function, myCoords is already a pointer. You can simply pass that pointer itself to calculateCoords() and calculateMotorSpeeds() function. Also, with a function prototype like void calculateCoords(struct coords* myCoords) calling calculateCoords(&myCoords); from doStuff() is wrong, as it is passing struct coords**. Solution: Keep your function signature for calculateCoords()...

JSLint won't recognize getElementById

javascript,function,getelementbyid,jslint

You missed document prefix. As getElementById is defined on document object you've to call it using document object as follow: document.getElementById("player").play(); // ^^^^^^ Docs...

PercentOfSum(fld, condfld) SSRS Equivalent

function,reporting-services,crystal-reports,ssrs-2008,ssrs-2008-r2

It's a tricky question because grouping in SSRS is handled outside of functions, so the equivalent to condfld is explained here. The short answer is the cell will generally obey the grouping that you have applied to the row. So onto the percent, you'll need an expression (right click on...