Search Results

Search found 2562 results on 103 pages for 'vector'.

Page 92/103 | < Previous Page | 88 89 90 91 92 93 94 95 96 97 98 99  | Next Page >

  • Algorithm for scoring user activity

    - by ManBugra
    I have an application where users can: Write reviews about products Add comments to products Up / Down vote reviews Up / Down vote comments Every Up/Down vote is recorded in a db table. What i want to do now is to create a ranking of the most active users in the last 4 weeks. Of course good reviews should be weighted more than good comments. But also e.g. 10 good comments should be weighted more than just one good review. Example: // reviews created in recent 4 weeks //format: [ upVoteCount, downVoteCount ] var reviews = [ [120,23], [32,12], [12,0], [23,45] ]; // comments created in recent 4 weeks // format: [ upVoteCount, downVoteCount ] var comments = [ [1,2], [322,1], [0,0], [0,45] ]; // create weight vector // format: [ reviewWeight, commentsWeight ] var weight = [0.60, 0.40]; // signature: activties..., activityWeight var userActivityScore = score(reviews, comments, weight); ... update user table ... List<Users> users = "from users u order by u.userActivityScore desc"; How would a fair scoring function look like? How could an implementation of the score() function look like? How to add a weight g to the function so that reviews are weighted heavier? How would such a function look like if, for example, votes for pictures would be added?

    Read the article

  • How can I store an inventory-like list of numbers?

    - by Rachel
    I've got a list of number that I need to keep track of. The numbers are loosely related, but represent distinctly different items. I'd like to keep a list of the numbers but be able to refer to them by name so that I can call them and use them where needed easily. Kind of like an inventory listing, where the numbers all refer to a part ID and I'd like to call them idPart1, idPart2, idPart3 so their purpose is easily identifiable when they are used. What would be the best way to do this? 1)Define a structure. Say, PartIds. A number of int members will be included, part1, part2 etc. To use, an instance of the structure will be created, values assigned to the members, and the numbers will be used by saying struct.member as needed. 2)Define an enumeration. Use part1, part2 as the enum literals. Store the actual values in a vector or list, each one at the index corresponding to the value of the number's name within the enum. Use the enum literals to retrieve the values, list[enumLit]. 3)Something completely different There's nothing else I need to do with the numbers - just look them up every once in a while. Since there's no processing, I kind of think a new class for them is overkill, but I'm willing to be convinced otherwise. Any suggestions?

    Read the article

  • Collapsing data frame by selecing one row per group

    - by jkebinger
    I'm trying to collapse a data frame by removing all but one row from each group of rows with identical values in a particular column. In other words, the first row from each group. For example, I'd like to convert this > d = data.frame(x=c(1,1,2,4),y=c(10,11,12,13),z=c(20,19,18,17)) > d x y z 1 1 10 20 2 1 11 19 3 2 12 18 4 4 13 17 Into this: x y z 1 1 11 19 2 2 12 18 3 4 13 17 I'm using aggregate to do this currently, but the performance is unacceptable with more data: > d.ordered = d[order(-d$y),] > aggregate(d.ordered,by=list(key=d.ordered$x),FUN=function(x){x[1]}) I've tried split/unsplit with the same function argument as here, but unsplit complains about duplicate row numbers. Is rle a possibility? Is there an R idiom to convert rle's length vector into the indices of the rows that start each run, which I can then use to pluck those rows out of the data frame?

    Read the article

  • Moving inserted container element if possible

    - by doublep
    I'm trying to achieve the following optimization in my container library: when inserting an lvalue-referenced element, copy it to internal storage; but when inserting rvalue-referenced element, move it if supported. The optimization is supposed to be useful e.g. if contained element type is something like std::vector, where moving if possible would give substantial speedup. However, so far I was unable to devise any working scheme for this. My container is quite complicated, so I can't just duplicate insert() code several times: it is large. I want to keep all "real" code in some inner helper, say do_insert() (may be templated) and various insert()-like functions would just call that with different arguments. My best bet code for this (a prototype, of course, without doing anything real): #include <iostream> #include <utility> struct element { element () { }; element (element&&) { std::cerr << "moving\n"; } }; struct container { void insert (const element& value) { do_insert (value); } void insert (element&& value) { do_insert (std::move (value)); } private: template <typename Arg> void do_insert (Arg arg) { element x (arg); } }; int main () { { // Shouldn't move. container c; element x; c.insert (x); } { // Should move. container c; c.insert (element ()); } } However, this doesn't work at least with GCC 4.4 and 4.5: it never prints "moving" on stderr. Or is what I want impossible to achieve and that's why emplace()-like functions exist in the first place?

    Read the article

  • 500 Worker Threads, what kind of thread pool?

    - by Submerged
    I am wondering if this is the best way to do this. I have about 500 threads that run indefinitely, but Thread.sleep for a minute when done one cycle of processing. ExecutorService es = Executors.newFixedThreadPool(list.size()+1); for (int i = 0; i < list.size(); i++) { es.execute(coreAppVector.elementAt(i)); //coreAppVector is a vector of extends thread objects } The code that is executing is really simple and basically just this class aThread extends Thread { public void run(){ while(true){ Thread.sleep(ONE_MINUTE); //Lots of computation every minute } } } I do need a separate threads for each running task, so changing the architecture isn't an option. I tried making my threadPool size equal to Runtime.getRuntime().availableProcessors() which attempted to run all 500 threads, but only let 8 (4xhyperthreading) of them execute. The other threads wouldn't surrender and let other threads have their turn. I tried putting in a wait() and notify(), but still no luck. If anyone has a simple example or some tips, I would be grateful! Well, the design is arguably flawed. The threads implement Genetic-Programming or GP, a type of learning algorithm. Each thread analyzes advanced trends makes predictions. If the thread ever completes, the learning is lost. That said, I was hoping that sleep() would allow me to share some of the resources while one thread isn't "learning"

    Read the article

  • Elegant way of parsing Data files for Simulation

    - by sc_ray
    I am working on this project where I need to read in a lot of data from .dat files and use the data to perform simulations. The data in my .dat file looks as follows: DeviceID InteractingDeviceID InteractionStartTime InteractionEndTime 1 2 1101 1105 1,2 1101 and 1105 are tab delimited and it means Device 1 interacted with Device 2 at 1101 ms and ended the interaction at 1105ms. I have a trace data sets that compile thousands of such interactions and my job is to analyze these interactions. The first step is to parse the file. The language of choice is C++. The approach I was thinking of taking was to read the file, for every line that's read create a Device Object. This Device object will contain the property DeviceId and an array/vector of structs, that will contain a list of all the devices the given DeviceId interacted with over the course of the simulation.The struct will contain the Interacting Device Id, Interaction Start Time and Interaction End Time. I have a two fold question here: Is my approach correct? If I am on the right track, how do I rapidly parse these tab delimited data files and create Device objects without excessive memory overhead using C++? A push in the right direction will be much appreciated. Thanks

    Read the article

  • How do I improve my performance with this singly linked list struct within my program?

    - by Jesus
    Hey guys, I have a program that does operations of sets of strings. We have to implement functions such as addition and subtraction of two sets of strings. We are suppose to get it down to the point where performance if of O(N+M), where N,M are sets of strings. Right now, I believe my performance is at O(N*M), since I for each element of N, I go through every element of M. I'm particularly focused on getting the subtraction to the proper performance, as if I can get that down to proper performance, I believe I can carry that knowledge over to the rest of things I have to implement. The '-' operator is suppose to work like this, for example. Declare set1 to be an empty set. Declare set2 to be a set with { a b c } elements Declare set3 to be a set with ( b c d } elements set1 = set2 - set3 And now set1 is suppose to equal { a }. So basically, just remove any element from set3, that is also in set2. For the addition implementation (overloaded '+' operator), I also do the sorting of the strings (since we have to). All the functions work right now btw. So I was wondering if anyone could a) Confirm that currently I'm doing O(N*M) performance b) Give me some ideas/implementations on how to improve the performance to O(N+M) Note: I cannot add any member variables or functions to the class strSet or to the node structure. The implementation of the main program isn't very important, but I will post the code for my class definition and the implementation of the member functions: strSet2.h (Implementation of my class and struct) // Class to implement sets of strings // Implements operators for union, intersection, subtraction, // etc. for sets of strings // V1.1 15 Feb 2011 Added guard (#ifndef), deleted using namespace RCH #ifndef _STRSET_ #define _STRSET_ #include <iostream> #include <vector> #include <string> // Deleted: using namespace std; 15 Feb 2011 RCH struct node { std::string s1; node * next; }; class strSet { private: node * first; public: strSet (); // Create empty set strSet (std::string s); // Create singleton set strSet (const strSet &copy); // Copy constructor ~strSet (); // Destructor int SIZE() const; bool isMember (std::string s) const; strSet operator + (const strSet& rtSide); // Union strSet operator - (const strSet& rtSide); // Set subtraction strSet& operator = (const strSet& rtSide); // Assignment }; // End of strSet class #endif // _STRSET_ strSet2.cpp (implementation of member functions) #include <iostream> #include <vector> #include <string> #include "strset2.h" using namespace std; strSet::strSet() { first = NULL; } strSet::strSet(string s) { node *temp; temp = new node; temp->s1 = s; temp->next = NULL; first = temp; } strSet::strSet(const strSet& copy) { if(copy.first == NULL) { first = NULL; } else { node *n = copy.first; node *prev = NULL; while (n) { node *newNode = new node; newNode->s1 = n->s1; newNode->next = NULL; if (prev) { prev->next = newNode; } else { first = newNode; } prev = newNode; n = n->next; } } } strSet::~strSet() { if(first != NULL) { while(first->next != NULL) { node *nextNode = first->next; first->next = nextNode->next; delete nextNode; } } } int strSet::SIZE() const { int size = 0; node *temp = first; while(temp!=NULL) { size++; temp=temp->next; } return size; } bool strSet::isMember(string s) const { node *temp = first; while(temp != NULL) { if(temp->s1 == s) { return true; } temp = temp->next; } return false; } strSet strSet::operator + (const strSet& rtSide) { strSet newSet; newSet = *this; node *temp = rtSide.first; while(temp != NULL) { string newEle = temp->s1; if(!isMember(newEle)) { if(newSet.first==NULL) { node *newNode; newNode = new node; newNode->s1 = newEle; newNode->next = NULL; newSet.first = newNode; } else if(newSet.SIZE() == 1) { if(newEle < newSet.first->s1) { node *tempNext = newSet.first; node *newNode; newNode = new node; newNode->s1 = newEle; newNode->next = tempNext; newSet.first = newNode; } else { node *newNode; newNode = new node; newNode->s1 = newEle; newNode->next = NULL; newSet.first->next = newNode; } } else { node *prev = NULL; node *curr = newSet.first; while(curr != NULL) { if(newEle < curr->s1) { if(prev == NULL) { node *newNode; newNode = new node; newNode->s1 = newEle; newNode->next = curr; newSet.first = newNode; break; } else { node *newNode; newNode = new node; newNode->s1 = newEle; newNode->next = curr; prev->next = newNode; break; } } if(curr->next == NULL) { node *newNode; newNode = new node; newNode->s1 = newEle; newNode->next = NULL; curr->next = newNode; break; } prev = curr; curr = curr->next; } } } temp = temp->next; } return newSet; } strSet strSet::operator - (const strSet& rtSide) { strSet newSet; newSet = *this; node *temp = rtSide.first; while(temp != NULL) { string element = temp->s1; node *prev = NULL; node *curr = newSet.first; while(curr != NULL) { if( element < curr->s1 ) break; if( curr->s1 == element ) { if( prev == NULL) { node *duplicate = curr; newSet.first = newSet.first->next; delete duplicate; break; } else { node *duplicate = curr; prev->next = curr->next; delete duplicate; break; } } prev = curr; curr = curr->next; } temp = temp->next; } return newSet; } strSet& strSet::operator = (const strSet& rtSide) { if(this != &rtSide) { if(first != NULL) { while(first->next != NULL) { node *nextNode = first->next; first->next = nextNode->next; delete nextNode; } } if(rtSide.first == NULL) { first = NULL; } else { node *n = rtSide.first; node *prev = NULL; while (n) { node *newNode = new node; newNode->s1 = n->s1; newNode->next = NULL; if (prev) { prev->next = newNode; } else { first = newNode; } prev = newNode; n = n->next; } } } return *this; }

    Read the article

  • Trouble with applying a nested loop on a list

    - by user1665355
    I have a list consisting of 3 elements: datalist=list(a=datanew1,b=datanew2,c=datanew3) datalist$a : Inv_ret Firm size leverage Risk Liquidity Equity 17 0.04555968 17.34834 0.1323199 0.011292273 0.02471489 0 48 0.01405835 15.86315 0.6931730 0.002491093 0.12054914 0 109 0.04556252 16.91602 0.1714068 0.006235836 0.01194579 0 159 0.04753472 14.77039 0.3885720 0.007126830 0.06373028 0 301 0.03941040 16.94377 0.1805346 0.005450653 0.01723319 0 datalist$b : Inv_ret Firm size leverage Risk Liquidity Equity 31 0.04020832 18.13300 0.09326265 0.015235240 0.01579559 0.005025379 62 0.04439078 17.84086 0.11016402 0.005486982 0.01266566 0.006559096 123 0.04543250 18.00517 0.12215307 0.011154742 0.01531451 0.002282790 173 0.03960613 16.45457 0.10828643 0.011506857 0.02385191 0.009003780 180 0.03139643 17.57671 0.40063094 0.003447233 0.04530395 0.000000000 datalist$c : Inv_ret Firm size leverage Risk Liquidity Equity 92 0.03081029 19.25359 0.10513159 0.01635201 0.025760806 0.000119744 153 0.03280746 19.90229 0.11731517 0.01443786 0.006769735 0.011999005 210 0.04655847 20.12543 0.11622403 0.01418010 0.003125632 0.003802365 250 0.03301018 20.67197 0.13208234 0.01262499 0.009418828 0.021400052 282 0.04355975 20.03012 0.08588316 0.01918129 0.004213846 0.023657440 I am trying to create a cor.test on the datalist above : Cor.tests=sapply(datalist,function(x){ for(h in 1:length(names(x))){ for(i in 1:length(names(x$h[i]))){ for(j in 1:length(names(x$h[j]))){ cor.test(x$h[,i],x$h[,j])$p.value }}}}) But I get an error : Error in cor.test.default(x$h[, i], x$h[, j]) : 'x' must be a numeric vector Any suggestions about what I am doing wrong? P.S. If I simply have one dataframe, datanew1 : Inv_ret Firm size leverage Risk Liquidity Equity 17 0.04555968 17.34834 0.1323199 0.011292273 0.02471489 0 48 0.01405835 15.86315 0.6931730 0.002491093 0.12054914 0 109 0.04556252 16.91602 0.1714068 0.006235836 0.01194579 0 159 0.04753472 14.77039 0.3885720 0.007126830 0.06373028 0 301 0.03941040 16.94377 0.1805346 0.005450653 0.01723319 0 I use this loop : results=matrix(NA,nrow=6,ncol=6) for(i in 1:length(names(datanew1))){ for(j in 1:length(names(datanew1))){ results[i,j]<-cor.test(datanew1[,i],datanew1[,j])$p.value }} And the output is: results : [,1] [,2] [,3] [,4] [,5] [,6] [1,] 0.000000e+00 7.085663e-09 3.128975e-10 3.018239e-02 4.806400e-10 0.475139526 [2,] 7.085663e-09 0.000000e+00 2.141581e-21 0.000000e+00 2.247825e-20 0.454032499 [3,] 3.128975e-10 2.141581e-21 0.000000e+00 2.485924e-25 2.220446e-16 0.108643838 [4,] 3.018239e-02 0.000000e+00 2.485924e-25 0.000000e+00 5.870007e-15 0.006783324 [5,] 4.806400e-10 2.247825e-20 2.220446e-16 5.870007e-15 0.000000e+00 0.558827862 [6,] 4.751395e-01 4.540325e-01 1.086438e-01 6.783324e-03 5.588279e-01 0.000000000 Which is exactly what I want. But I want to get 3 matrices, one for each element of the datalist above.

    Read the article

  • How to asynchronously read to std::string using Boost::asio?

    - by SpyBot
    Hello. I'm learning Boost::asio and all that async stuff. How can I asynchronously read to variable user_ of type std::string? Boost::asio::buffer(user_) works only with async_write(), but not with async_read(). It works with vector, so what is the reason for it not to work with string? Is there another way to do that besides declaring char user_[max_len] and using Boost::asio::buffer(user_, max_len)? Also, what's the point of inheriting from boost::enable_shared_from_this<Connection> and using shared_from_this() instead of this in async_read() and async_write()? I've seen that a lot in the examples. Here is a part of my code: class Connection { public: Connection(tcp::acceptor &acceptor) : acceptor_(acceptor), socket_(acceptor.get_io_service(), tcp::v4()) { } void start() { acceptor_.get_io_service().post( boost::bind(&Connection::start_accept, this)); } private: void start_accept() { acceptor_.async_accept(socket_, boost::bind(&Connection::handle_accept, this, placeholders::error)); } void handle_accept(const boost::system::error_code& err) { if (err) { disconnect(); } else { async_read(socket_, boost::asio::buffer(user_), boost::bind(&Connection::handle_user_read, this, placeholders::error, placeholders::bytes_transferred)); } } void handle_user_read(const boost::system::error_code& err, std::size_t bytes_transferred) { if ( err or (bytes_transferred != sizeof(user_)) ) { disconnect(); } else { ... } } ... void disconnect() { socket_.shutdown(tcp::socket::shutdown_both); socket_.close(); socket_.open(tcp::v4()); start_accept(); } tcp::acceptor &acceptor_; tcp::socket socket_; std::string user_; std::string pass_; ... };

    Read the article

  • how to create a changing variable for fsolve

    - by Shun Miyamoto
    i want fsolve to calculate the output for different uc each time (increasing uc by 0.001 each time). each output from fsolve should be sent to a simulink model seperatly. so i set a loop to do so, but i believe that at the currenty constellation (if it will work)will just calculate 1000 different values? is there a way to send out the values seperately? if not, how can i create a parameter uc. that goes from 0 to say 1000? i tried uc=0:0.001:1000, but again, the demension doen't seem to fit. how do i create a function that takes the next element of a vector/matrix each time the function is called? uc=0; for i=0:1000 x0=[1,1,1]; y=x0(1); u=x0(2); yc=x0(3); options=optimset('Display','off'); x= fsolve(@myfun,x0,options,uc,d,spacing_amplitude,spacing_width); end best regards

    Read the article

  • Bilinear interpolation - DirectX vs. GDI+

    - by holtavolt
    I have a C# app for which I've written GDI+ code that uses Bitmap/TextureBrush rendering to present 2D images, which can have various image processing functions applied. This code is a new path in an application that mimics existing DX9 code, and they share a common library to perform all vector and matrix (e.g. ViewToWorld/WorldToView) operations. My test bed consists of DX9 output images that I compare against the output of the new GDI+ code. A simple test case that renders to a viewport that matches the Bitmap dimensions (i.e. no zoom or pan) does match pixel-perfect (no binary diff) - but as soon as the image is zoomed up (magnified), I get very minor differences in 5-10% of the pixels. The magnitude of the difference is 1 (occasionally 2)/256. I suspect this is due to interpolation differences. Question: For a DX9 ortho projection (and identity world space), with a camera perpendicular and centered on a textured quad, is it reasonable to expect DirectX.Direct3D.TextureFilter.Linear to generate identical output to a GDI+ TextureBrush filled rectangle/polygon when using the System.Drawing.Drawing2D.InterpolationMode.Bilinear setting? For this (magnification) case, the DX9 code is using this (MinFilter,MipFilter set similarly): Device.SetSamplerState(0, SamplerStageStates.MagFilter, (int)TextureFilter.Linear); and the GDI+ path is using: g.InterpolationMode = InterpolationMode.Bilinear; I thought that "Bilinear Interpolation" was a fairly specific filter definition, but then I noticed that there is another option in GDI+ for "HighQualityBilinear" (which I've tried, with no difference - which makes sense given the description of "added prefiltering for shrinking") Followup Question: Is it reasonable to expect pixel-perfect output matching between DirectX and GDI+ (assuming all external coordinates passed in are equal)? If not, why not? Finally, there are a number of other APIs I could be using (Direct2D, WPF, GDI, etc.) - and this question generally applies to comparing the output of "equivalent" bilinear interpolated output images across any two of these. Thanks!

    Read the article

  • R: manipulating data.frames containing strings and booleans.

    - by Mike Dewar
    Hello. I have a data.frame in R; it's called p. Each element in the data.frame is either True or False. My variable p has, say, m rows and n columns. For every row there is strictly only one TRUE element. It also has column names, which are strings. What I would like to do is the following: For every row in p I see a TRUE I would like to replace with the name of the corresponding column I would then like to collapse the data.frame, which now contains FALSEs and column names, to a single vector, which will have m elements. I would like to do this in an R-thonic manner, so as to continue my enlightenment in R and contribute to a world without for-loops. I can do step 1 using the following for loop: for (i in seq(length(colnames(p)))) { p[p[,i]==TRUE,i]=colnames(p)[i] } but theres's no beauty here and I have totally subscribed to this for-loops-in-R-are-probably-wrong mentality. Maybe wrong is too strong but they're certainly not great. I don't really know how to do step 2. I kind of hoped that the sum of a string and FALSE would return the string but it doesn't. I kind of hoped I could use an OR operator of some kind but can't quite figure that out (Python responds to False or 'bob' with 'bob'). Hence, yet again, I appeal to you beautiful Rstats people for help!

    Read the article

  • What makes this "declarator invalid"? C++

    - by nieldw
    I have Vertex template in vertex.h. From my graph.h: 20 template<class edgeDecor, class vertexDecor, bool dir> 21 class Vertex; which I use in my Graph template. I've used the Vertex template successfully throughout my Graph, return pointers to Vertices, etc. Now for the first time I am trying to declare and instantiate a Vertex object, and gcc is telling me that my 'declarator' is 'invalid'. How can this be? 81 template<class edgeDecor, class vertexDecor, bool dir> 82 Graph<edgeDecor,int,dir> Graph<edgeDecor,vertexDecor,dir>::Dijkstra(vertex s, bool print = false) const 83 { 84 /* Construct new Graph with apropriate decorators */ 85 Graph<edgeDecor,int,dir> span = new Graph<edgeDecor,int,dir>(); 86 span.E.reserve(this->E.size()); 87 88 typename Vertex<edgeDecor,int,dir> v = new Vertex(INT_MAX); 89 span.V = new vector<Vertex<edgeDecor,int,dir> >(this->V.size,v); 90 }; And gcc is saying: graph.h: In member function ‘Graph<edgeDecor, int, dir> Graph<edgeDecor, vertexDecor, dir>::Dijkstra(Vertex<edgeDecor, vertexDecor, dir>, bool) const’: graph.h:88: error: invalid declarator before ‘v’ graph.h:89: error: ‘v’ was not declared in this scope I know this is probably another noob question, but I'll appreciate any help.

    Read the article

  • Haskell: "how much" of a type should functions receive? and avoiding complete "reconstruction"

    - by L01man
    I've got these data types: data PointPlus = PointPlus { coords :: Point , velocity :: Vector } deriving (Eq) data BodyGeo = BodyGeo { pointPlus :: PointPlus , size :: Point } deriving (Eq) data Body = Body { geo :: BodyGeo , pict :: Color } deriving (Eq) It's the base datatype for characters, enemies, objects, etc. in my game (well, I just have two rectangles as the player and the ground right now :p). When a key, the characters moves right, left or jumps by changing its velocity. Moving is done by adding the velocity to the coords. Currently, it's written as follows: move (PointPlus (x, y) (xi, yi)) = PointPlus (x + xi, y + yi) (xi, yi) I'm just taking the PointPlus part of my Body and not the entire Body, otherwise it would be: move (Body (BodyGeo (PointPlus (x, y) (xi, yi)) wh) col) = (Body (BodyGeo (PointPlus (x + xi, y + yi) (xi, yi)) wh) col) Is the first version of move better? Anyway, if move only changes PointPlus, there must be another function that calls it inside a new Body. I explain: there's a function update which is called to update the game state; it is passed the current game state, a single Body for now, and returns the updated Body. update (Body (BodyGeo (PointPlus xy (xi, yi)) wh) pict) = (Body (BodyGeo (move (PointPlus xy (xi, yi))) wh) pict) That tickles me. Everything is kept the same within Body except the PointPlus. Is there a way to avoid this complete "reconstruction" by hand? Like in: update body = backInBody $ move $ pointPlus body Without having to define backInBody, of course.

    Read the article

  • Tips on designing a .NET API for future use with F#

    - by Drew Noakes
    I'm in the process of designing a .NET API to allow developers to create RoboCup agents for the 3D simulated soccer league. I'm pretty happy with how the API work with C# code, however I would like to use this project to improve my F# skill (which is currently based on reading rather than practice). So I would like to ask what kinds of things I should consider when designing an API that is to be consumed by both C# and F# code. Some points. I make fairly heavy use of matrix and vector math. These are currently immutable classes/structs. The API currently defines a few interfaces with the consumer implements (eg: IAgent), using instances of their implementations (eg: MyAgent) to construct other API classes (eg: new Client(myAgent)). The API fires events. The API exposes a few delegate types. The API includes several enums. I'd like to release a version of the API as soon as possible and don't want to make major changes to it later if I realise it's too difficult to work with from F#. Any advice is appreciated.

    Read the article

  • No output got after execution.

    - by wilson88
    I am still stuck with getting output for a copied vector. Probably something am not doing right. I get no output. void Auctioneer::accept_bids(const BidList& bid){ BidList list; BidList list2; BidList::const_iterator iter; copy (list.begin(),list.end(), back_inserter(list2)); for(iter=list2.begin(); iter != list2.end(); iter++) { const Bid& bid = *iter; // Get a reference to the Bid object that the iterator points to cout << "Bid id : " << bid.bidId << endl; cout << "Trd id : " << bid.trdId << endl; cout << "Quantity: " << bid.qty << endl; cout << "Price : " << bid.price << endl; cout << "Type : " << bid.type << endl; } }

    Read the article

  • C++ return a "NULL" object if search result not found

    - by aduric
    I'm pretty new to C++ so I tend to design with a lot of Java-isms while I'm learning. Anyway, in Java, if I had class with a 'search' method that would return an object T from a Collection< T that matched a specific parameter, I would return that object and if the object was not found in the collection, I would return a NULL. Then in my calling function I would just check if(T != NULL) { ... } In C++, I'm finding out that I can't return a NULL if the object doesn't exist. I just want to return an 'indicator' of type T that notifies the calling function that no object has been found. I don't want to throw an exception because it's not really an exceptional circumstance. class Node { .... Attr& getAttribute(const string& attribute_name) const { //search collection //if found at i return attributes[i]; //if not found return NULL; } private: vector<Attr> attributes; }

    Read the article

  • Saving "heavy" image to PDF in MATLAB - rendering problem

    - by yuk
    I generate a figure in MATLAB with lot amount of points (100000+) and want to save it into a PDF file. With zbuffer or painters renderer I've got very large and slowly opened file (over 4 Mb) - all points are in vector format. Using OpenGL renderer rasterize the figure in PDF, ok for the plot, but not good for text labels. The file size is about 150 Kb. Try this simplified code, for example: x=linspace(1,10,100000); y=sin(x)+randn(size(x)); plot(x,y,'.') set(gcf,'Renderer','zbuffer') print -dpdf -r300 testpdf_zb set(gcf,'Renderer','painters') print -dpdf -r300 testpdf_pa set(gcf,'Renderer','opengl') print -dpdf -r300 testpdf_op The actual figure is much more complex with several axes and different types of plots. Is there a way to rasterize the figure, but keep text labels as vectors? Another problem with OpenGL is that is does not work in terminal mode (-nosplash -nodesktop) under Mac OSX. Looks like OpenGL is not supported. I have to use terminal mode for automation. The MATLAB version I run is 2007b. Mac OSX server 10.4.

    Read the article

  • Stata Nearest neighbor of percentile

    - by Kyle Billings
    This has probably already been answered, but I must just be searching for the wrong terms. Suppose I am using the built in Stata data set auto: sysuse auto, clear and say for example I am working with 1 independent and 1 dependent variable and I want to essentially compress down to the IQR elements, min, p(25), median, p(75), max... so I use command, keep weight mpg sum weight, detail return list local min=r(min) local lqr=r(p25) local med = r(p50) local uqr = r(p75) local max = r(max) keep if weight==`min' | weight==`max' | weight==`med' | weight==`lqr' | weight==`uqr' Hence, I want to compress the data set down to only those 5 observations, and for example in this situation the median is not actually an element of the weight vector. there is an observation above and an observation below (due to the definition of median this is no surprise). is there a way that I can tell stata to look for the nearest neighbor above the percentile. ie. if r(p50) is not an element of weight then search above that value for the next observation? The end result is I am trying to get the data down to 2 vectors, say weight and mpg such that for each of the 5 elements of weight in the IQR have their matching response in mpg. Any thoughts?

    Read the article

  • C++ overide global operator comma gives error

    - by uray
    the second function gives error C2803 http://msdn.microsoft.com/en-us/library/zy7kx46x%28VS.80%29.aspx : 'operator ,' must have at least one formal parameter of class type. any clue? template<class T,class A = std::allocator<T>> class Sequence : public std::vector<T,A> { public: Sequence<T,A>& operator,(const T& a) { this->push_back(a); return *this; } Sequence<T,A>& operator,(const Sequence<T,A>& a) { for(Sequence<T,A>::size_type i=0 ; i<a.size() ; i++) { this->push_back(a.at(i)); } return *this; } }; //this works! template<typename T> Sequence<T> operator,(const T& a, const T&b) { Sequence<T> seq; seq.push_back(a); seq.push_back(b); return seq; } //this gives error C2803! Sequence<double> operator,(const double& a, const double& b) { Sequence<double> seq; seq.push_back(a); seq.push_back(b); return seq; }

    Read the article

  • Initializing objects on the fly

    - by pocoa
    I have a vector called players and a class called Player. And what I'm trying to do is to write: players.push_back(Player(name, Weapon(bullets))); So I want to be able to create players in a loop. But I see an error message says "no matching function for call Player::Player..." Then I've changed that to: Weapon w(bullets); Player p(name, w); players.push_back(p); Here is my Player definition: class Player { public: Player(string &name, Weapon &weapon); private string name; Weapon weapon; } I'm just trying to learn what is the difference between these definitions. And is this the right way to pass an object to an object constructor. Note: These are not my actual class definitions. I'm just trying to learn something about object oriented programming in C++ with coding it. I mean I know that Weapon should be initialized in Player :)

    Read the article

  • What is different about C++ math.h abs() compared to my abs()

    - by moka
    I am currently writing some glsl like vector math classes in c++, and I just implemented an abs() function like this: template<class T> static inline T abs(T _a) { return _a < 0 ? -_a : _a; } I compared its speed to the default c++ abs from math.h like this: clock_t begin = clock(); for(int i=0; i<10000000; ++i) { float a = abs(-1.25); }; clock_t end = clock(); unsigned long time1 = (unsigned long)((float)(end-begin) / ((float)CLOCKS_PER_SEC/1000.0)); begin = clock(); for(int i=0; i<10000000; ++i) { float a = myMath::abs(-1.25); }; end = clock(); unsigned long time2 = (unsigned long)((float)(end-begin) / ((float)CLOCKS_PER_SEC/1000.0)); std::cout<<time1<<std::endl; std::cout<<time2<<std::endl; Now the default abs takes about 25ms while mine takes 60. I guess there is some low level optimisation going on. Does anybody know how math.h abs works internally? The performance difference is nothing dramatic, but I am just curious!

    Read the article

  • passing data from a servlet to javascript code in an Ajax application ?

    - by A.S al-shammari
    I have a simple jsp/servlet application and I want to add AJAX feature to this app. I use JQuery , but it doesn't matter what javascript framework I use. This is my code: <script type="text/javascript"> function callbackFunction(data){ $('#content').html(data); } $('document').ready(function(){ $('#x').click(function() { $.post('/ajax_2/servlet',callbackFunction) }); }); </script> <body> <a href="#" id="x">Increase it</a> <div id="content"></div> </body> </html> Servlet HttpSession session = request.getSession(); Integer myInteger = (Integer)session.getAttribute("myInteger"); if(myInteger == null) myInteger = new Integer(0); else myInteger = new Integer(myInteger+1); session.setAttribute("myInteger", myInteger); response.getWriter().println(myInteger); The Question: I use out.print to transfer data from a servlet to javascript code (ajax code) , but If I have a complex structure such as Vector of Object or something like this , what is the best way to transfer the data? what about an XML file , JSON ? Is there any special jsp/servlets library to transfer data from a servlet to ajax application ? How can I parse this data in callbackFunction ?

    Read the article

  • OpenCL - incremental summation during compute

    - by user1721997
    I'm absolutelly novice in OpenCL programming. For my app. (molecular simulaton) I wrote a kernel for calculate intermolecular potential of lennard-jones liquid. In this kernel I need to compute cumulative value of the potential of all particles with one: __kernel void Molsim(__global const float* inmatrix, __global float* fi, const int c, const float r1, const float r2, const float r3, const float rc, const float epsilon, const float sigma, const float h1, const float h23) { float fi0; float fi1; float d; unsigned int i = get_global_id(0); //number of particles (typically 2000) if(c!=i) { // potential before particle movement d=sqrt(pow((0.5*h1-fabs(0.5*h1-fabs(inmatrix[c*3]-inmatrix[i*3]))),2.0)+pow((0.5*h23-fabs(0.5*h23-fabs(inmatrix[c*3+1]-inmatrix[i*3+1]))),2.0)+pow((0.5*h23-fabs(0.5*h23-fabs(inmatrix[c*3+2]-inmatrix[i*3+2]))),2.0)); if(d<rc) { fi0=4.0*epsilon*(pow(sigma/d,12.0)-pow(sigma/d,6.0)); } else { fi0=0; } // potential after particle movement d=sqrt(pow((0.5*h1-fabs(0.5*h1-fabs(r1-inmatrix[i*3]))),2.0)+pow((0.5*h23-fabs(0.5*h23-fabs(r2-inmatrix[i*3+1]))),2.0)+pow((0.5*h23-fabs(0.5*h23-fabs(r3-inmatrix[i*3+2]))),2.0)); if(d<rc) { fi1=4.0*epsilon*(pow(sigma/d,12.0)-pow(sigma/d,6.0)); } else { fi1=0; } // cumulative difference of potentials fi[0]+=fi1-fi0; } } My problem is in the line: fi[0]+=fi1-fi0;. In the one-element vector fi[0] are wrong results. I read something about sum reduction, but I do not know how to do it during the calculation. Exist any simple solution of my problem?

    Read the article

  • Impossible to be const-correct when combining data and it's lock?

    - by Graeme
    I've been looking at ways to combine a piece of data which will be accessed by multiple threads alongside the lock provisioned for thread-safety. I think I've got to a point where I don't think its possible to do this whilst maintaining const-correctness. Take the following class for example: template <typename TType, typename TMutex> class basic_lockable_type { public: typedef TMutex lock_type; public: template <typename... TArgs> explicit basic_lockable_type(TArgs&&... args) : TType(std::forward<TArgs...>(args)...) {} TType& data() { return data_; } const TType& data() const { return data_; } void lock() { mutex_.lock(); } void unlock() { mutex_.unlock(); } private: TType data_; mutable TMutex mutex_; }; typedef basic_lockable_type<std::vector<int>, std::mutex> vector_with_lock; In this I try to combine the data and lock, marking mutex_ as mutable. Unfortunately this isn't enough as I see it because when used, vector_with_lock would have to be marked as mutable in order for a read operation to be performed from a const function which isn't entirely correct (data_ should be mutable from a const). void print_values() const { std::lock_guard<vector_with_lock>(values_); for(const int val : values_) { std::cout << val << std::endl; } } vector_with_lock values_; Can anyone see anyway around this such that const-correctness is maintained whilst combining data and lock? Also, have I made any incorrect assumptions here?

    Read the article

< Previous Page | 88 89 90 91 92 93 94 95 96 97 98 99  | Next Page >