w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Design by Contract and Fail Fast
Similarities: Both can be implemented via assertions Both are intrinsic to the design of XML Differences: Design by Contract doesn't handle unexpected errors Fail fast doesn't handle redundant checks Design by Contract doesn't handle bad requirements Fail fast doesn't handle requirements mapping

Categories : Misc

AngularJs chaining an undefined ajax request and output progress (also if one request fail)
You can use $q.all to get all response and then process the response at the same time $q.all(promises).then(function (values) { //process all result together }); And you can also plugin a callback function to each promises to indicate the progress $q.all(promises[0].then(callback), promises[1].then(callback), ...).then(function (values) { //process all result together });

Categories : Angularjs

Transition function chaining after all transitions are complete
Given that you need to call this function only once and that you know exactly when the transition finishes, you can call it after that time using setTimeout. Chaining transitions is meant for exactly that and not really to call a single function once. To call any further functions after that, simply call them from the first function. I've modified your jsfiddle here with this solution. Alternatively, you could do something like in the answer to this question to make sure that the function is only called once.

Categories : Javascript

Assembling a function as needed and computing it fast
If you want something working right out of the box have a look at ExprTK. If you want to write an expression parser yourself check out Boost Spirit. An alternative would be to create C++ code on the fly, compile it as a shared library (plugin) and load it at runtime. This would probably be the fastest solution.

Categories : C++

Fast sine and cosine function in java
Since you don't care much about accuracy store it in a table that is precomputed or only computed once, this is what I do when I want to avoid calls to Math which can be expensive when done alot. Roughly public class CosSineTable { double[] cos = new double[361]; double[] sin = new double[361]; private static CosSineTable table = new CosSineTable(); private CosSineTable() { for (int i = 0; i <= 360; i++) { cos[i] = Math.cos(Math.toRadians(i)); sin[i] = Math.sin(Math.toRadians(i)); } } public double getSine(int angle) { int angleCircle = angle % 360; return sin[angleCircle]; } public double getCos(int angle) { int angleCircle = angle % 360; return cos[angleCircle]; } public static CosSineTable getTable() { return table; } } I leave the

Categories : Java

Fast hash function with unique hashes
if your hash is uniformly distributed then you can calculate the size of the hash (in bits) that you need from the approx number of files you expect to handle before a collision. basically, because of the birthday paradox, it's twice the number of bits. so, for example, if you are happy with a collision after a million files then you need a has that is about 40 bits log (2 * log2(1e6)). conversely, if a hash is N bits, then it's good for 2^(N/2) files without collision (more or less). there are many fast hashes. for example, xxhash is a 64 bit hash, so is good for about 4,000,000,000 files. google's fast-hash is another. if you want more than 64bits (more than ~4 billion files before a collision) then you can either use a hash with a larger output or join two 64bit hashes together (

Categories : Java

Move audio player 5 second fast-rewind & fast-forward
Put below methods for forward and rewind player time - (IBAction)btnForwardClicked:(id)sender { int currentTime = [player currentTime]; [player setCurrentTime:currentTime+5]; } - (IBAction)btnBackwardClicked:(id)sender { int currentTime = [player currentTime]; [player setCurrentTime:currentTime-5]; } here player is avaudio player's object AVAudioPlayer *player;

Categories : Iphone

Why does my img error function fail?
Though your explaination is not really clear, the most probable reason is that your <img> tag is not there at the time of calling function $('img').error(); try 1) create a dynamic image with some id. 2) call error function after putting the the img tag in DOM. The <img> tag is not bound with the error function, and that is the only reason I can see for not working of your code. now the working sample : html: <div id="myId"> h </div> jQuery Script: var jObject = $("<img src='helo.png' />"); $(jObject).error(function(){ $(this).attr("src", "http://rack.2.mshcdn.com/media/ZgkyMDEyLzEyLzAzL2U0L3NlZWhvd3lvdXJnLjlyMS5qcGcKcAl0aHVtYgk5NTB4NTM0IwplCWpwZw/8fec6ce4/e71/see-how-your-google-results-measure-up-with-google-grader-video--6b8bbb4b41.jpg");

Categories : Javascript

Why does “git push” to HP-UX fail on SSH URLs with “Function is not available”?
I know that git client does't source .profile files when pushing. Your environment variable is probably not set when you pushing. see Trying to set up remote git, pushing initial commit gives "git-receive-pack: not found"

Categories : GIT

Run a function whenever Karma tests fail
Typically this would be done by the Continuous Integration server, for instance Jenkins. If you don't use it, I would recommend so. If you really want to implement this in Karma, you can write a custom reporter, there is a method onSpecComplete.

Categories : Api

jquery hover function fast mouse in partial fire
You need to use the jQuery.finish() function so that you don't end up with a long queue of animations after fast mouse movement. So change the following lines to include the .finish() function before the animation: $('.backing').finish().fadeOut(); $('#'+gymlocation+'_back').finish().fadeIn(); $('.backing').finish().fadeOut(); $('#'+current_back).finish().fadeIn(); You then have the issue of your mouseover/out areas are restricted to the text & not the whole coloured area - which is kind of weird but might be what you want? So I haven't suggested a solution for that. You also have duplicate javascript functionality which might lead to unwanted animations. Remove the second to last section of code: $('#menu-wrapper').mouseleave(function() { ... and everything in-between ... });

Categories : Jquery

ActiveX OLE control not registered, MFC Create function fail
Your dialog instance is already created and shown with the DoModal call. Then you're trying to create it again - this will lead to all kinds of resource problems. You need to either show it with DoModal and then hide it from within the dialog code, or don't use DoModal at all. See similar questions: Hide an MFC dialog window and Hiding an MFC dialog box

Categories : Visual Studio

Huffman Encoder - Recursive, coding function fail
My suspicion is with your first function 'createTree' As my initial comment indicates, you should consider using a priority queue for various reasons. Here is a quick list of problems I am noticing You are sorting a vector of pointers. So the pointers will be sorted based on their address values and not the objects they point too. However, it is possible you are supplying a comparator. If this is the case, ignore this bullet. Resorting the vector each while loop iteration is O(nLog(n)) where inserting into a priority queue and maintaining sorted order is O(Log(n)) Since you are sorting on pointers, the index of 0 for the vector isn't guaranteed to be the root of the tree. Consider using a priority queue instead: In the header file #include <queue> // Comparator for priority q

Categories : C++

Why a upcase function made my rspec test to fail?
Why are you upcasing the email? Would you be equally surprised if .reverse made it fail? You're changing the email address. EXAMPLE@EMAIL.COM is not the same as example@email.com, strictly speaking. It might be equivalent for your application, but you need to make the application know that. Are you using devise? If so, the config/devise.rb file will have: # Configure which authentication keys should be case-insensitive. # These keys will be downcased upon creating or modifying a user and when used # to authenticate or find a user. Default is :email. config.case_insensitive_keys = [ :email ] Which should make what you're doing work. If you're not using it, whatever framework you're using will probably have a similar option, and if you're doing it yourself, you'll need to handle it

Categories : Ruby On Rails

Fail to detect and fail to prompt error for same data in the SQL server and textbox
In the row if (tbpid.Equals(dr["policeid"].ToString())) you forgot .Text: if (tbpid.Text.Equals(dr["policeid"].ToString())) the same in checking for NRIC And regarding However, when i type a different PoliceID but the same NRIC, the error msg did not appear but the insertion of the data succeeded. I suppose your table hase uniq constraint on policeid column, but not on nric

Categories : C#

How can I make a Grunt task fail if one of its sub tasks fail?
The default behavior in Grunt is to not run subsequent tasks if one fails. So you must be using the force option somewhere. You are either: 1 - passing --force on the command line 2 - calling grunt.option( 'force', true ); somewhere 3 - have the jshint force option set on your jshint task Note that in the case of calling grunt.option( 'force', true );, it remains true for the remainder of the batch, not just inside the task where it was set. see this question and this question for details.

Categories : Javascript

Can I remove the fast scroll overlay without creating an entire custom fast scroll view?
You do not have to implement SectionHeader in your adapter to enable fast scroll, you can enable fast scroll separately. Xml: <se.emilsjolander.stickylistheaders.StickyListHeadersListView android:id="@android:id/list" android:fastScrollEnabled="true" android:layout_width="match_parent" android:layout_height="wrap_content" /> Code: stickyListView.setFastScrollEnabled(true); This applies to the standard ListView as well.

Categories : Android

MySQL full-text search: need fast insert and fast search
Answer based on eggyal's comment. I ended up installing Sphinx. It's awesome. I'm using its real time indexing. Fast search and fast insert. Way faster than mysql free-text insert/search. Granted, my database is pretty small. They have tricks for fast real time indexing with large databases (split into 2 indexes, one with old data, one with newer data), but I have not needed that. BTW: I'm using Python/Django and did not not need to install any api or library, besides sphinx itself: import MySQLdb connection = MySQLdb.connect(host='', port = 9306) cursor = connection.cursor() cursor.execute("select id from my_index where match('stackoverflow')") results = cursor.fetchall() # I use my regular connection to insert the IDs into a table in my regular database and then join with th

Categories : Mysql

Rendering openGL texture: Class function causes rendering to fail
I did see your mistake within one second. So you didn't waste anyone's time (except your own ;) ). Anyway doing it like this: void CControl::RenderChildren() { for( int i = 0; i < Children.size(); i++ ) { Children[i]->X(Children[i]->X()+_X); //offset child _X with parent's _X Children[i]->Y(Children[i]->Y()+_Y); //offset child _Y with parent's _Y Children[i]->OnRender(); Children[i]->X(Children[i]->X()-_X); Children[i]->Y(Children[i]->Y()-_Y); } } is not optimal. In your case you're using integers where you're experiencing any problems. But say at one point you decide to use floats: The problem is, that every operation happening on floating point numbers creates round off error. Doing it iteratively (li

Categories : C++

Chaining sed statements
sed natively accepts a dozen of patterns (if you for some reason prefer sed): {:foo => foo, :bar => bar, :foobar => foobar, :fubar => fubar}.inject("") do |acc, k, v| acc += " -e 's/#{k}/#{v}'" end run "sed #{acc} file.ext"

Categories : Ruby

Chaining functions in Go?
This works: package main import ( "fmt" "strings" ) type String string func (s *String) tolower() *String { *s = String(strings.ToLower(string(*s))) return s } func (s *String) toupper() *String { *s = String(strings.ToUpper(string(*s))) return s } func main() { var s String = "ASDF" (s.tolower()).toupper() s.toupper(); s.tolower(); s.tolower().toupper() fmt.Println(s) } Your return type is of String, for functions defined on pointers to String. It wouldn't make sense to be able to chain them.

Categories : Go

Chaining deferreds
LoadFromURL will simplify as follows: function LoadFromURL(url) { return $.get(url).then(function(text) { return LoadFromText(text); }); } There may be issues you haven't considered ... Like your original version, the process will tend to recurse indefinitely until the server returns an HTTP error. You would have a slight challenge in writing the server resource appropriately, especially if, as is probable, you need to access the finally delivered text. With a little more thought, you could deliver all text in such a way that "continue" or "complete" is indicated in the text itself, or in an HTTP response code. For example, you could use response code 202 ("Accepted") to indicate that the process is incomplete. I think this will work (with jQuery 1.5+) : function L

Categories : Jquery

Dojo xhr chaining
Yes, exactly. You can call then infinite times on base: var d1 = base.then(fn1), d2 = base.then(fn2), … Notice that while it currently may work fine, your d1 does not represent any result - the chain is broken as you're not returning anything from the callback. You should return the promise for the second request actually: var base = xhr.get({ url: config.baseUrl + base_query, handleAs: "json" }); base.then(widget.set.bind(widget, 'value')); // or: dojo.hitch(widget, widget.set, 'value') if you like that better var d1 = base.then(function(result) { return xhr.get({ // ^^^^^^ url: config.baseUrl + result.id, handleAs: "json" }); }); d1.then(widget.set.bind(widget, 'visibility'));

Categories : Javascript

"Chaining" two controllers?
Why not just one controller with these request mappings? @RequestMapping("/rest/user") public class UserController { @RequestMapping("{keyType}/{key}/orders") public ModelAndView orders(@PathVariable String keyType, @PathVariable String key) { User u = findUser(keyType, key); // ... } @RequestMapping("{keyType}/{key}/profile") public ModelAndView profile(@PathVariable String keyType, @PathVariable String key) { User u = findUser(keyType, key); // ... } @RequestMapping("{keyType}/{key}/address") public ModelAndView address(@PathVariable String keyType, @PathVariable String key) { User u = findUser(keyType, key); // ... } private User findUser(String keyType, String key) { // ... } }

Categories : Java

Chaining Actions in C#
I'm not entirely sure what it is you're asking but I'm just going to address a couple of things in your post which are wrong. Firstly; Action is a Delegate it's just one that accepts a single parameter and does not return a value. If I have some Action call it A - Delegate d = A; will compile and run. Secondly, to pass args in a general manner (meaning to some arbitrary function) you can use DynamicInvoke and wrap your arguments in an object array. As long as the items in the array are of the right types and are in the right order the method will correctly execute. Otherwise it will throw. DynamicInvoke has a specific application but as an example if you provide me with an Object[] and a Delegate I can use DynamicInvoke to invoke the function without knowing what it's definition is. Li

Categories : C#

Chaining queries in MongoEngine
Since, mongoengine supports keyword arguments to the objects call, you can create a dictionary, with the keys as field_names, and values as field_values. And then use this dictionary while querying. For example: query = {} if 'name' in request.args: query['name'] = request.args['name'] if 'phone' in request.args: query['phone'] = request.args['phone'] if 'email' in request.args: query['email'] = request.args['email'] user = User.objects(**query) The above is just a sample, you might want to add security measures, and maybe have a default query, depending on your app.

Categories : Python

C++ Method chaining with classes
Your updated question is illegal because Bar::Options() returns a reference to a Bar and you don't provide a way to convert a Bar to a Foo object.

Categories : C++

Click chaining jquery
I think what you are looking for is to stop the propagation of the event. That can be done by adding the following code to the event handler evt.stopPropagation(). With this modification your click handler would be: ... $("li").on("click", function (evt) { $(this).siblings().find("*").css("display", "none"); $(this).children().css("display", "block"); $(this).children().children().css("display", "block"); console.log($(this).children()[0]); evt.stopPropagation(); }); ... Here's the fiddle for the modification.

Categories : Jquery

C++ Method chaining on constructor
The new expression returns a pointer so you just have to do : Wav* wave = new Wav("asf", DOUBLE)->Emphasize(); // ^^ Also your method Emphasize return a reference on a Signal object : Signal& Emphasize() { // ^ Reference return *this; } But you are trying to assign this reference to a pointer Wav*. You have two choices here : // ... Signal* Emphasize() { return this; } // ... Wav* wave = new Wav("asf", DOUBLE)->Emphasize(); Or you keep you initiale Emphasize method : // ... Signal& Emphasize() { return *this; } // ... Wav wave = new Wav("asf", DOUBLE)->Emphasize(); EDIT : Ok the real error is that you are trying to convert a Signal object into Wav object. There is no convertion from Signal to Wav object. A Wa

Categories : C++

Method chaining from namespace
Regarding your new function: In order to be able to call the process method below int* data = process(toArray<int>( vals.begin(), vals.end()) ); the parameter for the process method should match the return type of the toArray method. Perhaps you can templatize the process method too as below. template<typename T> T* process(T* t) { //more code here return t; } After adding the process method as above, the call to process will compile, but you will have to make the implementation of the process method generic enough to deal with different return types from other methods like toArray.

Categories : C++

Chaining Javascript Constructors
Javascript doesn't know that a function is a constructor. It's only treated as one when you call it using the new keyword. If you were to call it without new, it would behave differently. Parent.call(this, name) simply calls Parent as a regular function, using the newly constructed Child (because you used the new keyword when you constructed a Child) as its this. So all your function parent does in this case is assign the name to the object that it received. In this case, the Child that you just constructed. Compare your Child to this: var Child = function(name, toy) { var child = new Parent(name); child.toy = toy; return child; } Here, the child function is using Parent as a constructor.

Categories : Javascript

How to do method chaining with DOMDocument?
Do you have a definite requirement that transformToThis() has to modify the original object? I'd think it would be cleaner to do something like this: function trasform($xslfile) { $xsldom = new DOMDocument('1.0', 'UTF-8'); $xsldom->load($xslfile); $xproc = new XSLTProcessor(); $xproc->importStylesheet($xsldom); $xml = $xproc->transformToXML($this); $newDom = new DOMxx(); $newDom.loadXML($xml); return $newDom; } If you really want to modify the original object, I imagine this would work also (for that last part of the method): $xml = $xproc->transformToXML($this); $this.loadXML($xml); return $this;

Categories : PHP

Chaining Animations in jQuery
I modified your code: var menuShown = 0; // toggle the menu on clicking the control menu_toggle.click(function () { if(menuShown){ menu.slideUp(500, function(){ menu_li.animate({opacity: 0}, 500); menuShown = 0; }) }else{ menu.slideDown(500, function(){ menu_li.animate({ opacity: 1}, 500); menuShown = 1; }); } return false; }); Here is DEMO

Categories : Jquery

method chaining with polymorphism c++
Take a look at Curiously recurring template pattern. If Base is an abstract type (only instantiated in its subclasses) then make it a template taking type name. Your Derive will extend the template - e.g. Derived : public Base<Derived>. If Base is a concrete type - then you will need to introduce a new abstract class that would be a base type for Base and Derived. This way withFoo can be templated to return real type.

Categories : C++

Problems with Chaining in javascript
The console isn't lying. HTMLElement doesn't have a method named two, as that method belongs to window.de. Don't modify host objects like HTMLElement by adding to their prototype. They aren't implemented in JavaScript. Write a wrapper that contains your methods instead, sort of like jQuery: (function(window) { var de = function(thing) { return new de.prototype.init(thing); }; de.prototype = { constructor: de, init: function(thing) { this.thing = thing; }, one: function(other) { return de(other); } }; de.prototype.init.prototype = de.prototype; window.de = de; })(window); Now, you can do: de('foo').one('bar').one('bar').one('baz')

Categories : Javascript

Objective C chaining properties
Make sure that isFemale is properly synthesized. Beware, the is keyword is an objective-C standard convention (as in @property (nonatomic, getter=isFemale) BOOL female). If in doubt, try another property name, such as femaleGender. that the Office propery currentEmployee is of type Employee and that the calling class knows about the the Employee properties (`#include "Employee.h").

Categories : Objective C

hashing with chaining c code
hashTable is indeed a pointer to a structure. But, somewhere in the code (which you don't show) memory is allocated for an array of struct hash. The address of this memory is then assigned to hashTable. Then when you do hashTable[index]; you're simply accessing this allocated array. In C, when you write hashTable[index]; this is identical to *(hashTable + index). Then, adding index to this pointer result in an address that is index * sizeof(struct hash) further. This has the effect of 'jumping' to the index' element in the array. For more details read the appropriate section in the C FAQ.

Categories : C

Chaining parentNode calls
At the root of the question, yes you can chain Node.parentNode calls as each call is returning another Node with that same property exposed. Visually: <div id="baz"> <div id="bar"> <p id="foo">Hello, world!</p> </div> <div> var el = document.getElementById('foo'); // p#foo // traversing, route a: var bar = el.parentNode; var baz = bar.parentNode; // traversing, route b: var baz = el.parentNode.parentNode; // ^ #bar ^ // ^ #baz ^ However, it's (arguably) poor design to be changing the element's ID and, instead, I would look in to adding (or removing) a className instead.

Categories : Javascript

Django is this chaining tasks?
Short version, yes you're doing the right thing here. Long version: The thing is that you don't want something like this: @task def something(**kwargs): # do something here something_else.delay().get() @task def something_else(**kwargs): # do something else here pass Which will make something wait for the result from something_else. You could even consider moving the creating of the message to a task (so your loop only spawns tasks and doesn't connect to the database straight away). PS: if you want to keep track of all the results from the result of the ProcessRequests task you could execute these as subresults: http://docs.celeryproject.org/en/latest/userguide/canvas.html?highlight=asyncresult#subtasks It can help you group the results: http://docs.celeryproject.o

Categories : Django

Chaining validation in Scala
It's a case class, so why aren't you doing this with pattern matching? def validateConfig(config: Config): Try[Config] = config match { case Config(None, _, _, _) => Failure(new IllegalArgumentException("Email Address") case Config(_, None, _, _) => Failure(new IllegalArgumentException("First Name") case Config(_, _, None, _) => Failure(new IllegalArgumentException("Last Name") case Config(_, _, _, None) => Failure(new IllegalArgumentException("Password") case _ => Success(config) } In your simple example, my priority would be to forget monads and chaining, just get rid of that nasty if...else smell. However, while a case class works perfectly well for a short list, for a large number of configuration options, this becomes tedious and the risk of error increase

Categories : Scala

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