w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Simple Python - Error in Programming
Trying to give just a pointer - Your loop is in the wrong place. Think carefully about what code you want to keep repeating, and what code should execute once for each loop. Try to see what happens if your first input is OVER the speed limit :)

Categories : Python

Socket error - with simple socket programming using python
The problem with windows sockets is that they don't actually die when you close them unless you tell them to. Try adding the following code after you initialise the socket and see what happens. l_onoff = 1 l_linger = 0 s.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack('ii', l_onoff, l_linger)) The documentation for Lingering can be found at MSDN. also change your shutdown to: s.shutdown(socket.SHUT_RDWR) This should close all connections immediately if windows behaves itself. Which will prevent the buffer error caused by too many sockets lingering.

Categories : Python

Simple constraint programming solver
It depends on what are you trying to do. 1- If you want to get started with Constraint Programming (CP) tools, you need first to understand modelling in this approach. For that, you have be able to define a given problem as a set of constraints then you post your model to a solver (that already knows how to deal with these constraints). I personally find the G12_MiniZinc_Distribution (available via http://www.minizinc.org/) and its latest tutorial a very good way to start (the latest distribution cames with a lot of models). There is also online models if you want to see how a CP model looks like (w.r.t minizinc syntax) : http://www.hakank.org/minizinc. 2- If you have an advanced theoretical understanding of CP, you may directly see the implementation of some techniques (e.g. propaga

Categories : Java

need a simple programming logic solution..
I don't think you can do this on the database level. You would have to do something like this: Create an array of all country codes (including + sign) Fetch all the numbers from the database Use array_map() and in the callback run strpos() against each element in the country code array and if a match is made remove the country code from the number Finally after step 4 is finished run the number array through array_unique() CODE: $country_codes = array('+91', '+61'); $numbers_from_db = array('33445322453', '+913232', '3232', '+614343', '024343'); $sanitized_numbers = array_map(function($number) use ($country_codes){ if(substr($number, 0, 1) === "0") { $number = substr($number, 1); return $number; } foreach($country_codes as $country_code) {

Categories : PHP

Explanation for this simple looking haskell program (dynamic programming)
y = f y is equivalent to infinite chain of applications: `y = f ( f ( f ( f (... so c = a ++ (zipWith (+) b c) is equivalent to c = a ++ (zipWith (+) b (a ++ (zipWith (+) b (...)))

Categories : Haskell

node.js and asynchronous programming palindrome
You can put every callback call inside a timeout with one milisecond, that way they will be executed first when there are a thread free and all synchron tasks are done, then will the processor work through the stack of timeouts that want to be executet.

Categories : Javascript

Python Simple Sever and Client script (Socket programming)
while True: client_socket, address =server_socket.accept() print "Connection from ", address data = client_socket.recv(512) print "RECIEVED:" , data This should be: client_socket, address =server_socket.accept() print "Connection from ", address while True: data = client_socket.recv(512) print "RECIEVED:" , data server_socket.accept() will wait indefinitely until a new client is connected. Actually your loop is like : "accept a client and receive one time the data he sent".

Categories : Python

Clojure Functional reactive programming (FRP) with Lamina: Simple clock code?
I found a good article: http://adambard.com/blog/why-clojure-part-2-async-magic/ -LAMINA: ADVANCED ASYNCHRONOUS PROCESSING (ns example.helloperiodically (:require [lamina.core :as lamina])) (def ch (lamina/periodically 1000 (fn [] "Hello World!"))) (def loop-forever (comp doall repeatedly)) (defn consumer [] (loop-forever (fn [] (println @(lamina/read-channel ch))))) (defn main [] (-> (Thread. consumer) .start))

Categories : Clojure

Does asynchronous programming in node.js speed up CPU-bound tasks?
It depends on how the module is implemented. If the module is implemented without any support for threading then yes, CPU bound processing cannot be done asynchronously. Some functions provide callbacks and my look asynchronous but they're really not. They actually run synchronously and blocks the event loop. Examples of this in javascript is Array.forEach(). But, modules may be implemented to do the processing in background threads. In which case it truly is asynchronous and can speed up CPU bound tasks. At the very least it frees up the event loop to handle incoming requests while the background thread is busy computing results. An example of this is the crypto.pbkdf2() function in node's own Crypto module. But, how can modules execute code in other threads when node.js runs in a sin

Categories : Javascript

Get number of descendants at each node in tree in linear time without dynamic programming?
Your solution does what you ask for. It is linear: you only access each node once, and do a constant amount of work for each one. It does not use dynamic programming: dynamic programming requires a problem to exhibit overlapping subproblems and optimal substructure. This problem does not exhibit overlapping subproblems. Your subproblems, for a set node, consist of the answers for the subtrees rooted at that node. These subtrees do no overlap. If you want to set the results in each node, simply do something like this: void setNumberDescendants(Node root) { for(Node child:root.children){ setNumberDescendants(child); root.descendants += 1+child.descendants; } } class Node{ int key; int descendants; Lis

Categories : Java

Very simple websocket in node.js
I too have a small nit-picking issue with the ws module. They do not delete the socket object data after closing and it becomes a nuisance because all of data is then pushed into memory and it becomes a memory leak UNTIL the V8 Garbage Collector deletes the unused data. It's fine in 1 sense, but if you have a gameserver, or a VERY active game where people are refreshing/joining channels/games/etc, that extra overhead adds quite a bit of unnecessary memory usage. I believe the ws module would work best if they could delete the temporary socket object properties upon closing instead of waiting for the V8 GC to. With that said, it's a minimal amount of data and the average user won't even notice it unless they have a very active server. In any event, take a look at this gem that I found l

Categories : Node Js

Simple Q Promises Node Example
So basically you want to return the dfd.promise and then resolve or reject it after connecting to the DB. Q = require 'q' connect: () -> # Create deferred object dfd = Q.defer() # Attempt to connect try @mongoose.connect(...) # Resolve deferred object dfd.resolve('Database connected') catch e # Reject deferred with error object dfd.reject(e) # Return promise immediately dfd.promise Now when you run the connect method, you will get a promise object that you can bind to the .then and .fail methods db.connect() .then(msg) -> .fail(e) ->

Categories : Javascript

Simple include file to node.js
There's really no reason why you would need something like this. Node has the built-in module vm, which can help you in your problem, but there will be a lot of more problems envolving using it. For example: you'll need to pass a common context to your file, so it'll be able to require things at their own. This is very problematic, just write something that uses the standard module.exports from Node and forget this PHP thoughts :)

Categories : Node Js

Simple form node js application
This example does not quite complete your task. But it is a self contained node.js program that displays a form and a different page upon form receipt. Copy it into a file and then run node filename.js and then go to http://localhost:3000 in a browser. Take note of the asynchronous code structure. I define a handler function but don't execute it immediately. We instead pass the function to http.createServer and then call .listen(3000). Now when an HTTP request comes in, the http server will pass a req, res pair to the handler function. req is the request object (this will contain the form data; see this question for some hints on how to get that data out. (I suggest that you jump right in and build a small Express app. It's a really nice framework.) //app.js // Load the built in 'http'

Categories : Node Js

How to retrieve node with same name in XML simple in perl
XML::Simple is anything but simple. Its own documentation discourages further use of that module. The data structure you might be getting (who knows?) is on my system: { entry => { 13 => {}, 37 => {} }, name => "path:ko00010", number => "00010", org => "ko", reaction => { id => 13, name => "rn:R01070", product => { "cpd:C00111" => { id => 89 }, "cpd:C00118" => { id => 132 } }, substrate => { id => 105, name => "cpd:C05378" }, type => "reversible", }, } It is always good to inpect a data structure when you are not sure if you are accessing it correctly. One way to do so is use Data::Dumper; print Dumper $data. You mi

Categories : Xml

How to create a simple socket in node.js?
I don't think the server is put into listening state. This what I use.. // server require('net').createServer(function (socket) { console.log("connected"); socket.on('data', function (data) { console.log(data.toString()); }); }) .listen(8080); // client var s = require('net').Socket(); s.connect(8080); s.write('Hello'); s.end(); Client only.. var s = require('net').Socket(); s.connect(80, 'google.com'); s.write('GET http://www.google.com/ HTTP/1.1 '); s.on('data', function(d){ console.log(d.toString()); }); s.end();

Categories : Node Js

Request to the simple node js web server
It all depends on your client (browser). There are plugins/extensions in browsers that might create extra requests, Chrome will try to load favicon all the time, while Firefox for example will try once and in case with failure - will not retry. Add this into your callback to see what is exactly is requested: console.log(request.url, request.method)

Categories : Node Js

Error while writing a Google CCS server in node using node-xmpp
The important part is to send the message in the required format : <message id=""> <gcm xmlns="google:mobile:data"> { "to":"REGISTRATION_ID", // "to" replaces "registration_ids" "message_id":"m-1366082849205" // new required field "data": { "hello":"world", } "time_to_live":"600", "delay_while_idle": true/false } </gcm> </message> It doesn't matter if you use a template or not. I don't know python nor javascript, but the purpose of the template in the python example seems to be simply to avoid the need to write the xml tags that wrap the JSON every time you send a message. You can append them to the JSON when you send the message.

Categories : Javascript

How do you deserialize a simple xml node value into a composite type?
You must implement IXmlSerializable in one (or both) of these classes to support what you want. http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.aspx

Categories : C#

Building a simple Node.js scraper function
Your data will be undefined, because scrape function does not return a value, additionaly it asynchronous. You need change logic to something like this: function scrape(url, oncomplete) { console.log("Scraping: " + url); request(url, function(err, resp, body) { if (err) { throw err; } var html = cheerio.load(body); oncomplete(html); }); } scrape('http://www.stackoverflow.com', function(data) { /* do work here*/ });

Categories : Javascript

Simple way to write sync functions in node.js
You can use node-sync for that purpose https://github.com/0ctave/node-sync But in general I'd recommend you don't. The mocha test framework for example allows you to do async tests. Also async waterfall https://github.com/caolan/async#waterfall is a nice way to pseudo synchronize your code. I'd say stay in the async mind frame. Even when testing.

Categories : Javascript

Using an HTTP connection as a simple duplex socket in Node
HTTP in its very nature is uni-directional. The best you can get would be two uni-directional channels, without realtime communication. You can use Server-Sent events(EventSource), which is a part of HTML5 standard. It uses HTTP to transport messages. You should also look at websockets which are similar to tcp sockets. They offer full-duplex realtime communication. They use a different websocket protocol, but can use same ports as http. If websocket is not blocked, you should use it. Here is a comparison between the two : WebSockets vs. Server-Sent events/EventSource

Categories : Node Js

Is there a simple JS xhr library (for node.js) that uses Q promises for get/post actions?
There you go, built by Kris Kowal itself: https://github.com/kriskowal/q-io#http Usage: var http = require("q-io/http"); http.request("http://my.server.com/path").then(function() { ... }); http.read("http://my.server.com/path").then(function() { ... }); I haven't used this yet, and the docs are somewhat poor right now - so I can't tell you what are the args passed. But if you already know how to work with Q, than that's going to be so easy. Note that Q-IO has many other useful functions also. Hope it helps.

Categories : Ajax

How to sign Amazon Simple Pay button in node.js / Javascript
For posterity, here is the solution: 1) Don't mess with Simple Pay Buttons - use FPS instead 2) Of the myriad overlapping documents, I found this to be the simplest and clearest: http://docs.aws.amazon.com/AmazonFPS/latest/FPSBasicGuide/SendingaCBUIRequest.html 3) Use encodeURIComponent not encodeURI - this was my biggest most frustrating mistake This code will correctly sign an Amazon FPS request (assumes crypto for hmac and nconf for configuration) var crypto = require('crypto'); var _ = require('underscore'); var nconf = require('nconf').argv().env().file({ file: "./config.json" }); exports.azPayRequest=function (amount, desc,ref) { var params={ "returnUrl": nconf.get("awsPayments:returnURL"), //callback "callerKey" : nconf.get("awsPayments:callerKey"), //aws id "

Categories : Node Js

What is this error message in C# programming?
You changed ballSpeedXAxis to an array, yet in your OnUpdate you are trying to access it as if it were a normal integer: private void OnUpdate(object sender, object e) { Canvas.SetLeft(this.ball1, this.ballSpeedXAxis + Canvas.GetLeft(this.ball1)); } You must specify the index of the int in the array you whish to use this.ballSpeedXAxis[0] for example. Now you say the error is: 'MoveBall.Game' does not contain a definition for 'ballSpeedAxis1 If you're using VisualStudio, MonoDevelop or Xamarin Studio clicking the error item in the Errors Window should take you right to the point in the code where you are still refering to ballSpeedAxis1. You could even try to hit CTRL+F and enter 'ballSpeedAxis1' in the search box and search through the entire solution. If you cannot find

Categories : C#

A good programming language is a conceptual universe for thinking about programming
The meaning of this quote is: What we need is not just another programming language but a conceptual universe for thinking about software development, embodied in a kind of language that is new to computer science -- a language that will bridge the gap between programming and software development at large.

Categories : Misc

Is it good programming practice to use shell scripts in systems programming
You're running the shell script from within code in another language? In that case using a shell script is almost certainly unnecessary. Virtually all languages allow you to run an arbitrary command and capture the output. For example, C and friends have popen() and Perl, Ruby and such have backticks (`lpstat -a` returns the output of that command as a string). This kind of approach makes it unnecessary to have an extra shell script or a temporary file.

Categories : Bash

Error in Stroustrup's The C++ Programming Language?
Per § 8.5/7: To default-initialize an object of type T means: — if T is a (possibly cv-qualified) class type (Clause 9), the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor); — if T is an array type, each element is default-initialized; — otherwise, no initialization is performed. int falls in the last point, so it is left uninitialized. If your member had the type, say, std::string, it would call the default constructor of std::string and you'd have an empty string.

Categories : C++

Binding error - Socket programming
10014 is WSAEFAULT, which bind() returns when: The system detected an invalid pointer address in attempting to use a pointer argument in a call. This error is returned if the name parameter is NULL, the name or namelen parameter is not a valid part of the user address space, the namelen parameter is too small, the name parameter contains an incorrect address format for the associated address family, or the first two bytes of the memory block specified by name do not match the address family associated with the socket descriptor s. You are creating an IPv6 socket (AF_INET6), but you are trying to bind it to an IPv4 (AF_INET) address. That will not work. You need to either create an IPv4 socket, or bind to an IPv6 address, depending on what you are trying to accomplish. Lastly,

Categories : C

recv() error C/C++ socket programming
recv may return -1 with errno set to EINTR when a signal arrives. This is a transient failure and doesn't indicate any problem with your socket connection. You probably want to ignore this error and try calling recv again. The easiest way to do this on Linux is to use the TEMP_FAILURE_RETRY macro nbytes = TEMP_FAILURE_RETRY(recv(fileDesc, buffer, READ_MSG_SIZE,0)); This will call recv repeatedly until it returns something other than nbytes==-1 && errno==EINTR

Categories : C

Programming error - brought me out from the program
Try this: Segments mysegments; Segments::const_iterator itr; vector<Segments> segments_per_obj; for (itr= mysegments.begin(); itr!= mysegments.end(); itr++) { int index = itr->Label(); for (int i = segments_per_obj.size(); i <= index; ++i) { segments_per_obj.push_back(<create a new segment>); } segments_per_obj[index].push_back(*itr); } Or as suggested use a map, looks more suitable for this case.

Categories : C++

Python programming language login error
You need a colon at the end: if username[usrindex] == usrnm: Course, that only fixes the SyntaxError. You're also gonna get a ton of NameErrors because your code isn't really Python. It will blow up saying that Else and Then aren't defined. Python if-statements are composed like this: if condition: ... elif condition: ... else: ... Here is what I think you actually need: http://docs.python.org/2/tutorial/ This goes over all the basics in detail.

Categories : Python

Linear programming (lpSolve) error using Big Data in R
That's a tiny machine by modern standards, and a non-tiny problem. Short answer is that you should run on a machine with a lot more RAM. Note that the problem isn't that R can't allocate 130 MB vectors in general -- it can -- it's that it's run out of memory on your specific machine. I'd suggest running on a 64-bit instance of R 3.0 on a machine with 16 GB of RAM, and see if that helps. You may want to look into spinning up a machine on the cloud, and using RStudio remotely, which will be a lot cheaper than buying a new computer.

Categories : R

A Simple approach to implementing a multi level library with only one parent node, especially with MVC3/EF
I would go with a PARENT_ID column in the LibraryItem table, allowing for NULLS and a FK back to the PK of the same table. For your cascading delete issue, I would use a INSTEAD OF DELETE trigger on that table that; Deletes all reocrds where the PARENT_ID is the PK of the row being deleted Then delete the record of the parent itself.

Categories : Asp Net Mvc

SQL logic error or missing database in Blackberry programming
Try dropping the quotes around the third column value. INSERT INTO contactos VALUES (null,"a", 1); It's defined as an INTEGER. numero_conta INTEGER EDIT : System.out.println(uri); // check if null, or different if (uri == null) { uri = URI.create( "file:///SDCard/Databases/MBA.db"); } sqliteDB = DatabaseFactory.openOrCreate(uri); sqliteDB = DatabaseFactory.open(uri); // open again Statement st = sqliteDB.createStatement(query);

Categories : Java

FadeIn / FadeOut custom slideshow programming error
I think you need something like this: $(function () { var imgsrc = ''; $('ul.slideshow-menu').find('a').hover(function () { imgsrc = $('.pikachoose').css('background-image'); var newImg = $(this).attr('src'); $('.pikachoose').stop().fadeOut('slow', function () { $(this).css({ 'background-image': 'url(' + newImg + ')' }).fadeIn('slow'); }); }, function () { $('.pikachoose').stop().fadeOut('slow', function () { $(this).css({ 'background-image': imgsrc }).fadeIn('slow'); }); }); });

Categories : Javascript

Syntax error on token ";", , expected Java Programming
You have an extra } in the middle of your code so your onCreate and onCreateOptionsMenu are not actually inside your MainActivity class // your other code mega.setOnClickListener(checkedListener); } //<---- End of MainActivity class @Override protected void onCreate(Bundle savedInstanceState) { ... } @Override public boolean onCreateOptionsMenu(Menu menu) { ... } }// <--- should be actual end?

Categories : Java

Natural Language Programming vs. Literate Programming
Natural language programming is a system for expressing instructions to a computer in a form approximating a language humans write or speak. NLP syntax structure usually resembles human-language sentence structure, in a form that might sound stilted to a native speaker, but which tends to read almost like the real language. Many NLP implementations are focused on querying data stores rather than writing programs, but actual programming implementations also exist. Literate programming is a system for simultaneously writing programs and writing about programs. Unlike NLP, the code portions of a literate program are written in traditional programming languages. The classic examples, for which the name was coined, are Donald Knuth's writings on the TeX typesetting system. Published as h

Categories : Misc

What is the difference between the C programming language and C programming under linux?
The C language is governed by the ISO approved C standard and it does not take in to account the underlying platform on which you use C. So from the perspective of the language standard there is no difference, and a standard compliant program shall work correctly on both. However in practical usage one needs to do platform specific things for ex: IPC mechanisms, multithreading, file access and so on which are specific to the platform, such functionality will vary from platform to platform because each will provide functionality specific to itself. Note that such functionality is not covered by the C language standard, so using it makes the program non portable across other platforms.

Categories : C

Java Programming : Dynamic Programming on stairs example
why and how she employs the function map here? The book shows a dynamic programming technique called memoization. It is used to avoid calculating the same number again: if the element is not -1, then it has been computed again, and re-calculating it would mean wasting lots of CPU cycles. DP computes the value once, and then returns it every time the value is needed. map here is array right? Correct, map is of an array type. I do not see any line to save an input to the map array but how would it return something? That would be the assignment on the third line from the bottom: map[n] = countDP(n-1, map) + countDP(n-2, map) + countDP(n-3, map); Anybody has an idea of C++ or C version of this code? It is hard to understand this code. Maybe not because of the JAVA gramma

Categories : Java



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