Search Results

Search found 5784 results on 232 pages for 'points'.

Page 60/232 | < Previous Page | 56 57 58 59 60 61 62 63 64 65 66 67  | Next Page >

  • Combining two data sets and plotting in matlab

    - by bautrey
    I am doing experiments with different operational amplifier circuits and I need to plot my measured results onto a graph. I have two data sets: freq1 = [.1 .2 .5 .7 1 3 4 6 10 20 35 45 60 75 90 100]; %kHz Vo1 = [1.2 1.6 1.2 2 2 2.4 14.8 20.4 26.4 30.4 53.6 68.8 90 114 140 152]; %mV V1 = 19.6; Acm = Vo1/(1000*V1); And: freq2 = [.1 .5 1 30 60 70 85 100]; %kHz Vo1 = [3.96 3.96 3.96 3.84 3.86 3.88 3.88 3.88]; %V V1 = .96; Ad = Vo1/(2*V1); (I would show my plots but apparently I need more reps for that) I need to plot the equation, CMRR vs freq: CMRR = 20*log10(abs(Ad/Acm)); The size of Ad and Acm are different and the frequency points do not match up, but the boundaries of both of these is the same, 100Hz to 100kHz (x-axis). On the line of CMRR, Matlab says that Ad and Acm matrix dimensions do not agree. How I think I would solve this is using freq1 as the x-axis for CMRR and then taking approximated points from Ad according to the value on freq1. Or I could do function approximations of Ad and Acm and then do the divide operator on those. I do not know how I would code up this two ideas. Any other ideas would helpful, especially simpler ones. Thanks

    Read the article

  • How do I grep for entire, possibly wrapped, lines of code?

    - by NXT
    When searching code for strings, I constantly run into the problem that I get meaningless, context-less results. For example, if a function call is split across 3 lines, and I search for the name of a parameter, I get the parameter on a line by itself and not the name of the function. For example, in a file containing ... someFunctionCall ("test", MY_CONSTANT, (some *really) - long / expression); grepping for MY_CONSTANT would return a line that looked like this: MY_CONSTANT, Likewise, in a comment block: ///////////////////////////////////////// // FIXMESOON, do..while is the wrong choice here, because // it makes the wrong thing happen ///////////////////////////////////////// Grepping for FIXMESOON gives the very frustrating answer: // FIXMESOON, do..while is the wrong choice here, because When there are thousands of hits, single line results are a little meaningless. What I would like to do is have grep be aware of the start and stop points of source code lines, something as simple as having it consider ";" as the line separator would be a good start. Bonus points if you can make it return the entire comment block if the hit is inside a comment. I know you can't do this with grep alone. I also am aware of the option to have grep return a certain number of lines of content. Any suggestions on how to accomplish under Linux? FYI my preferred languages are C and Perl. I'm sure I could write something, but I know that somebody must have already done this. Thanks!

    Read the article

  • Which is the best license for my Open Source project?

    - by coderex
    I am a web developer, and I don't have enough knowledge about software licenses. I wish to publish some of my works, and I need to select licenses for them. My software product is free of cost. But I have some restrictions on the distribution/modification of the code. It's free of cost (but donations are acceptable ;-)). The source code is freely available. You can use, customize or edit/remove code (as long as the basic nature of the software is not changed). You don't have any permission to change the product name. There are some libraries and classes which are in a folder caller "myname". You don't have the permission to rename "myname". You can contribute any additions or modifications to my project, to the original source repository (the contributors name/email/site link will be listed on the credit file). You can't remove the original author's name from the license. You can put the license file or license code anywhere in the project file or folder. You can redistribute this code as free or commercial software. :) Do you think all these restrictions are valid? Given these restrictions, which license should I use? Edit 1:- My main intention is to make the product more popular with free source code while ensuring the original author is not ignored. The product is open. Edit 2:- Thank you all, the above points are because of my lack of knowledge of license terms. You can help me to correct or remove some of the above points. What I'm basically looking for is in my Edit 1.

    Read the article

  • summing functions handles in matlab

    - by user552231
    Hi I am trying to sum two function handles, but it doesn't work. for example: y1=@(x)(x*x); y2=@(x)(x*x+3*x); y3=y1+y2 The error I receive is "??? Undefined function or method 'plus' for input arguments of type 'function_handle'." This is just a small example, in reality I actually need to iteratively sum about 500 functions that are dependent on each other. EDIT The solution by Clement J. indeed works but I couldn't manage to generalize this into a loop and ran into a problem. I have the function s=@(x,y,z)((1-exp(-x*y)-z)*exp(-x*y)); And I have a vector v that contains 536 data points and another vector w that also contains 536 data points. My goal is to sum up s(v(i),y,w(i)) for i=1...536 Thus getting one function in the variable y which is the sum of 536 functions. The syntax I tried in order to do this is: sum=@(y)(s(v(1),y,z2(1))); for i=2:536 sum=@(y)(sum+s(v(i),y,z2(i))) end

    Read the article

  • Is this an acceptable use of "ASCII arithmetic"?

    - by jmgant
    I've got a string value of the form 10123X123456 where 10 is the year, 123 is the day number within the year, and the rest is unique system-generated stuff. Under certain circumstances, I need to add 400 to the day number, so that the number above, for example, would become 10523X123456. My first idea was to substring those three characters, convert them to an integer, add 400 to it, convert them back to a string and then call replace on the original string. That works. But then it occurred to me that the only character I actually need to change is the third one, and that the original value would always be 0-3, so there would never be any "carrying" problems. It further occurred to me that the ASCII code points for the numbers are consecutive, so adding the number 4 to the character "0", for example, would result in "4", and so forth. So that's what I ended up doing. My question is, is there any reason that won't always work? I generally avoid "ASCII arithmetic" on the grounds that it's not cross-platform or internationalization friendly. But it seems reasonable to assume that the code points for numbers will always be sequential, i.e., "4" will always be 1 more than "3". Anybody see any problem with this reasoning? Here's the code. string input = "10123X123456"; input[2] += 4; //Output should be 10523X123456

    Read the article

  • What is a mantainable way of saving "star rating" in a database?

    - by Montecristo
    I'll use the jQuery plugin for presenting the user with a nice interface The request is to display 5 stars, up to a total score of 10 (2 points per star). By now I thought about using 7/10 as a format for that value, but what if at some point in the future I'll receive a request like We would like to give users more choice, let's increase the total score to 20 (so that each star contributes with a maximum of 4 points) I'll end up with a table with mixed values for the "star rating" column: some will be like 7/10 while others will be like 14/20. Is it ok for you to have this difference in the database and deal with it in the logic layer to have it consistent? Or is preferred another way so that querying the table will not result in inconsistent results outside the application? Maybe floating point values could help me, is it better to store that value as a number less than or equal to one? So in each of the two examples the resulting value stored in the database would be 0,7, as a number, not a varchar, which can be queried also outside the application. What do you think?

    Read the article

  • Java/Android get array from xml

    - by Ashley
    I have a list of longitude and longitude points in an xml file that is used throughout my application. I find my self repeating this code to get points often and think there must be a better way? String[] mTempArray = getResources().getStringArray(R.array.stations); int len = mTempArray.length; mStationArray = new ArrayList<Station>(); for(int i = 0; i < len; i++){ Station s = new Station(); String[] fields = mTempArray[i].split("[\t ]"); s.setValuesFromArray(fields); Log.i("ADD STATION", ""+s); mStationArray.add(s); } XML is in the format of: <?xml version="1.0" encoding="utf-8"?> <resources> <array name="stations"> <item> <name>Station name</name> <longitude>1111111</longitude> <latitude>11111</latitude> <code>1</code> </item> And another (possible) problem is that to get just one station I have to get all of them and pull the one I want from the array. Is this going to be considerably slower? Can I make this array consistent throughout the app? (But keeping the separate Intent methodology)

    Read the article

  • Point covering problem

    - by Sean
    I recently had this problem on a test: given a set of points m (all on the x-axis) and a set n of lines with endpoints [l, r] (again on the x-axis), find the minimum subset of n such that all points are covered by a line. Prove that your solution always finds the minimum subset. The algorithm I wrote for it was something to the effect of: (say lines are stored as arrays with the left endpoint in position 0 and the right in position 1) algorithm coverPoints(set[] m, set[][] n): chosenLines = [] while m is not empty: minX = min(m) bestLine = n[0] for i=1 to length of n: if n[i][0] <= m and n[i][1] > bestLine[1] then bestLine = n[i] add bestLine to chosenLines for i=0 to length of m: if m <= bestLine[1] then delete m[i] from m return chosenLines I'm just not sure if this always finds the minimum solution. It's a simple greedy algorithm so my gut tells me it won't, but one of my friends who is much better than me at this says that for this problem a greedy algorithm like this always finds the minimal solution. For proving mine always finds the minimal solution I did a very hand wavy proof by contradiction where I made an assumption that probably isn't true at all. I forget exactly what I did. If this isn't a minimal solution, is there a way to do it in less than something like O(n!) time? Thanks

    Read the article

  • Need help/suggestions for creating fantasy sports scoring databases and queries

    - by MGumbel
    I'm trying to create a website for my friends and I to keep track of fantasy sports scoring. So far, I've been doing the calculations and storage in Excel, which is very tedious. I'm trying to make it more simplified and automated through a SQL database that I can then wrap a web app around to enter daily stat updates. It's premised on our participation in another commercial site where we trade virtual shares of athletes, and thus acquire an "ownership percentage" in each athlete. For instance, if there are 100 shares of AROD, and I own 10 shares, then I own 10%. It then applies this to traditional baseball rotisserie scoring. So, for instance, if AROD has 1 HR today, then his adjusted HR stat would be 1.10. If he also has 2 RBI's, then his adjusted RBI stat today would be 2.20, based on (2 x 1.10)(1 to normalize the stat, and the .10 to represent the ownership percentage). All the stats for my team would then be summed each day and added to my stat history to come to an aggregated total. After that, points are allocated based on the ranking of each participant in each category at the end of the day. E.g. if there are 10 participants, and I have the highest total aggregate number of Adjusted HR's, then I get 10 pts. The points are then summed across the different stat categories to come up with a total point ranking for that day. An added difficulty is that ownership %'s can change on a daily basis. So far, in playing around with different schema, I don't know that having a separate table for each athlete's stats and each player's ownership %'s is the wisest choice. It seems to me that simply having two tables, one that contains the daily stat information for each athlete, and another that shows the ownership % of each player. My friend suggested using a start and end date for each ownership % to represent the potential daily changes in this category. I'm admittedly new to database development, so any suggestions on query code would be appreciated.

    Read the article

  • In Java, is there a performance gain in using interfaces for complex models?

    - by Gnoupi
    The title is hardly understandable, but I'm not sure how to summarize that another way. Any edit to clarify is welcome. I have been told, and recommended to use interfaces to improve performances, even in a case which doesn't especially call for the regular "interface" role. In this case, the objects are big models (in a MVC meaning), with many methods and fields. The "good use" that has been recommended to me is to create an interface, with its unique implementation. There won't be any other class implementing this interface, for sure. I have been told that this is better to do so, because it "exposes less" (or something close) to the other classes which will use methods from this class, as these objects are referring to the object from its interface (all public methods from the implementation being reproduced in the interface). This seems quite strange to me, as it seems like a C++ use to me (with header files). There I see the point, but in Java? Is there really a point in making an interface for such unique implementation? I would really appreciate some clarifications on the topic, so I could justify not following such kind of behavior, and the hassle it creates from duplicating all declarations. Edit: Plenty of valid points in most answers, I'm wondering if I won't switch this question for a community wiki, so we can regroup these points in more structured answers.

    Read the article

  • Find if a user is facing a certain Location using Digital Compass by constructing a triangle and usi

    - by Aidan
    Hi Guys, I'm constructing a geolocation based application and I'm trying to figure out a way to make my application realise when a user is facing the direction of the given location (a particular long / lat co-ord). I've done some Googling and checked the SDK but can't really find anything for such a thing. Does anyone know of a way? To clarify Android knows my location, the second location and my orientation. What I want is a way for Android to recognise when my orientation is "facing" the second location (e.g within 90 Degrees or so). We're also assuming that the user is stationary and needs updates every second or so therefore getBearing(); is useless. Alright so we get it has to be math, there appears to be no simple SDK stuff we can use. I did some searching of my own and found Barycentric Co-ords http://www.blackpawn.com/texts/pointinpoly/default.html . So what I'm trying to do now is map the camera's field of view. For Example if the person is facing a certain direction the program should construct a triangle around that field of view, e.g it should make one vertices the phone's position and then go out either side for a set distance making the 2 end points vertices constructing a triangle. If I had this I could then apply Barycentric co-ords to see if the point lay within the newly constructed triangle. Idea's anyone? Example. I could get my current orientation, add 45 to it and go up X distance one side and subtact 45 and go up X distance the other side to find my 2 other points. Though, how would I make android know which way it should go "up" I guess? It would know its baring as this stage so I need it to recognise it's bearing and go out that direction.

    Read the article

  • Linear Interpolation. How to implement this algorithm in C ? (Python version is given)

    - by psihodelia
    There exists one very good linear interpolation method. It performs linear interpolation requiring at most one multiply per output sample. I found its description in a third edition of Understanding DSP by Lyons. This method involves a special hold buffer. Given a number of samples to be inserted between any two input samples, it produces output points using linear interpolation. Here, I have rewritten this algorithm using Python: temp1, temp2 = 0, 0 iL = 1.0 / L for i in x: hold = [i-temp1] * L temp1 = i for j in hold: temp2 += j y.append(temp2 *iL) where x contains input samples, L is a number of points to be inserted, y will contain output samples. My question is how to implement such algorithm in ANSI C in a most effective way, e.g. is it possible to avoid the second loop? NOTE: presented Python code is just to understand how this algorithm works. UPDATE: here is an example how it works in Python: x=[] y=[] hold=[] num_points=20 points_inbetween = 2 temp1,temp2=0,0 for i in range(num_points): x.append( sin(i*2.0*pi * 0.1) ) L = points_inbetween iL = 1.0/L for i in x: hold = [i-temp1] * L temp1 = i for j in hold: temp2 += j y.append(temp2 * iL) Let's say x=[.... 10, 20, 30 ....]. Then, if L=1, it will produce [... 10, 15, 20, 25, 30 ...]

    Read the article

  • C++ Conceptual problem with (Pointer) Pointers

    - by Ptr
    I have a structure usually containing a pointer to an int. However, in some special cases, it is necessary that this int pointer points to another pointer which then points to an int. Wow: I mentioned the word pointer 5 times so far! Is this even possible? I thought about it that way: Instead of using a second int pointer, which is most likely not possible as my main int pointer can only point to an int and not to another int pointer, I could make it a reference like this: int intA = 1; int intB = 2; int& intC = intB; int* myPointers[ 123 ]; myPointers[ 0 ] = &intA; myPointers[ 1 ] = &intB; myPointers[ 3 ] = &intC; So the above would do what I want: The reference to intB (intC) behaves quite like I want it to (If it gets changed it also changes intB) The problem: I can't change references once they are set, right? Or is there a way? Everything in short: How do I get a value to work with * (pointers) and ** (pointers to pointers)?

    Read the article

  • Using a CNAME with Shared Windows Azure Website

    - by user1679021
    I've been following instructions on the Azure site to add a CNAME to point to my Azure website. I have had some problems getting it to work and there seems to be some contradictory information in some of the posts. I have my website running in "Shared" mode, which according to the Azure instructions supports custom domains and indeed it seems to allow me to manage domains. But some posts seem to indicate that I have to run in reserved mode. Can anyone confirm this? Also, some posts seem to indicate that I need to add the CNAME in the Azure management portal, but I cannot find where this is. Any help appreciated? I don't really understand A records and CNAME that well. My DNS provider allows me to add both. Do I need to change both? Currently my A record points the "root" to the IP address that Azure gives me and the CNAME points www.mydomain to the Azure website host mysite.azurewebsites.net. I have left them for a while to propogate and nothing seem to happen.

    Read the article

  • Graph search problem with route restrictions

    - by Darcara
    I want to calculate the most profitable route and I think this is a type of traveling salesman problem. I have a set of nodes that I can visit and a function to calculate cost for traveling between nodes and points for reaching the nodes. The goal is to reach a fixed known score while minimizing the cost. This cost and rewards are not fixed and depend on the nodes visited before. The starting node is fixed. There are some restrictions on how nodes can be visited. Some simplified examples include: Node B can only be visited after A After node C has been visited, D or E can be visited. Visiting at least one is required, visiting both is permissible. Z can only be visited after at least 5 other nodes have been visited Once 50 nodes have been visited, the nodes A-M will no longer reward points Certain nodes can (and probably must) be visited multiple times Currently I can think of only two ways to solve this: a) Genetic Algorithms, with the fitness function calculating the cost/benefit of the generated route b) Dijkstra search through the graph, since the starting node is fixed, although the large number of nodes will probably make that not feasible memory wise. Are there any other ways to determine the best route through the graph? It doesn't need to be perfect, an approximated path is perfectly fine, as long as it's error acceptable. Would TSP-solvers be an option here?

    Read the article

  • Heap Algorithmic Issue

    - by OberynMarDELL
    I am having this algorithmic problem that I want to discuss about. Its not about find a solution but about optimization in terms of runtime. So here it is: Suppose we have a race court of Length L and a total of N cars that participate on the race. The race rules are simple. Once a car overtakes an other car the second car is eliminated from the race. The race ends when no more overtakes are possible to happen. The tricky part is that the k'th car has a starting point x[k] and a velocity v[k]. The points are given in an ascending order, but the velocities may differ. What I've done so far: Given that a car can get overtaken only by its previous, I calculated the time that it takes for each car to reach its next one t = (x[i] - x[i+1])/(v[i] - v[i+1]) and I insert these times onto a min heap in O(n log n). So in theory I have to pop the first element in O(logn), find its previous, pop it as well , update its time and insert it in the heap once more, much like a priority queue. My main problem is how I can access specific points of a heap in O(log n) or faster in order to keep the complexity in O(n log n) levels. This program should be written on Haskell so I would like to keep things simple as far as possible EDIT: I Forgot to write the actual point of the race. The goal is to find the order in which cars exit the game

    Read the article

  • C++ reinterpret cast ?

    - by Ian
    I would like to cast one object of the class PointsList to another object Points3DList (and vice versa) where: template <class T> class PointsList { protected: std::vector <Point <T> *> points; //Only illustration, not possible with templaes }; and template <class T> class Points3DList { protected: std::vector <Point3D<T> *> points; //Only illustration, not possible with templaes }; Between Point and Point3D there is no relationship (inheritance nor composition)... template <class T> class Point { protected: T x; T y; }; template <class T> class Point3D { protected: T x; T y; T z; }; What do you think about conversion Points3DList <T> *pl3D = new Points3DList <T> (); ... PointsList <T> *pl = reinterpret_cast < PointList <T> * > ( pl3D ); where pl3D represents pointer to Points3DList object.. Can reinterpret_cast be used in this case or it is better to create a conversion function? Data model in this case can not be changed...

    Read the article

  • direction line color google map v2

    - by user1328645
    I'm using this code to change direction line color in google map v2, but still it won't work even after using getpolyine? How can I change it? ` function direction() { var txtAddress = document.getElementById("<%=txtAddress.ClientID %>"); var address = txtAddress.value; var TextBox1 = document.getElementById("<%=TextBox1.ClientID %>"); var address1 = TextBox1.value; directions = new GDirections(map, directionsPanel); directions.load("from: " + address1 + " to: " + address + "", { getPolyline: true }); setTimeout(handle, 1000); // var address =txtAddress.value + " " + TextBox3.value; } function handle() { var points = []; var poly = direction.getPolyline(); for (var i = o; i < poly.getVertexCount(); i++) { points[i] = poly.getVertex(i); } var mypoly = new GPolyline(point, "#ff627", 3, 1) map.addOverlay(mypoly); } `

    Read the article

  • Clarification on ZVals

    - by Beachhouse
    I was reading this: http://www.dereleased.com/2011/04/27/the-importance-of-zvals-and-circular-references/ And there's an example that lost me a bit. $foo = &$bar; $bar = &$foo; $baz = 'baz'; $foo = &$baz; var_dump($foo, $bar); /* string(3) "baz" NULL */ If you’ve been following along, this should make perfect sense. $foo is created, and pointed at a ZVal location identified by $bar; when $bar is created, it points at the same place $foo was pointed. That location, of course, is null. When $foo is reassigned, the only thing that changes is to which ZVal $foo points; if we had assigned a different value to $foo first, then $bar would still retain that value. I learned to program in C. I understand that PHP is different and it uses ZVals instead of memory locations as references. But when you run this code: $foo = &$bar; $bar = &$foo; It seems to me that there would be two ZVals. In C there would be two memory locations (and the values would be of the opposite memory location). Can someone explain?

    Read the article

  • Convert JSON into array dataType

    - by Myhome Stories
    I have the following JSON string var json = {"result":[{"address":" Ardenham Court, Oxford Road ,AYLESBURY, BUCKINGHAMSHIRE ,UNITED KINGDOM","picture":"1.jpg","uniqueid":"8b54275a60088547d473d462763b4738","story":"I love my home. I feel safe, I am comfortable and I am loved. A home can't be a home without our parents and our loved ones. But sad to say, some are experiencing that eventhough their loved ones are in their houses, they are not loving each other. There is a big war. You can't call it a home."}]} I want to get address ,picture,story separately for accomplish this. I tried recent answers in stackoverflow, but I was not able to achieve it. Below is what I have tried, $.each(json.result.address, function (index, value) { // Get the items var items = this.address; // Here 'this' points to a 'group' in 'groups' // Iterate through items. $.each(items, function () { console.log(this.text); // Here 'this' points to an 'item' in 'items' }); });

    Read the article

  • Set all nonzero matrix elements to 1 (while keeping the others 0)

    - by Tomas Lycken
    I have a mesh grid defined as [X, Y, Z] = meshgrid(-100:100, -100:100, 25); % z will have more values later and two shapes (ovals, in this case): x_offset_1 = 40; x_offset_2 = -x_offset_1; o1 = ((X-x_offset_1).^2./(2*Z).^2+Y.^2./Z.^2 <= 1); o2 = ((X-x_offset_2).^2./(2*Z).^2+Y.^2./Z.^2 <= 1); Now, I want to find all points that are nonzero in either oval. I tried union = o1+o2; but since I simply add them, the overlapping region will have a value of 2 instead of the desired 1. How can I set all nonzero entries in the matrix to 1, regardless of their previous value? (I tried normalized_union = union./union;, but then I end up with NaN in all 0 elements because I'm dividing by zero...) Follow-up question: I got a perfect answer to my original question, but now I have a follow-up question on the same problem. I'm going to define a filled disc, c = (X.^2+Y.^2<R^2) that will also overlap with the two ovals. How do I find all the points that are inside the circle, but not inside any of the ovals?

    Read the article

  • Find existence of number in a sorted list in constant time? (Interview question)

    - by Rich
    I'm studying for upcoming interviews and have encountered this question several times (written verbatim) Find or determine non existence of a number in a sorted list of N numbers where the numbers range over M, M N and N large enough to span multiple disks. Algorithm to beat O(log n); bonus points for constant time algorithm. First of all, I'm not sure if this is a question with a real solution. My colleagues and I have mused over this problem for weeks and it seems ill formed (of course, just because we can't think of a solution doesn't mean there isn't one). A few questions I would have asked the interviewer are: Are there repeats in the sorted list? What's the relationship to the number of disks and N? One approach I considered was to binary search the min/max of each disk to determine the disk that should hold that number, if it exists, then binary search on the disk itself. Of course this is only an order of magnitude speedup if the number of disks is large and you also have a sorted list of disks. I think this would yield some sort of O(log log n) time. As for the M N hint, perhaps if you know how many numbers are on a disk and what the range is, you could use the pigeonhole principle to rule out some cases some of the time, but I can't figure out an order of magnitude improvement. Also, "bonus points for constant time algorithm" makes me a bit suspicious. Any thoughts, solutions, or relevant history of this problem?

    Read the article

  • method works fine, until it is called in a function, then UnboundLocalError

    - by user1776100
    I define a method called dist, to calculate the distance between two points which I does it correctly when directly using the method. However, when I get a function to call it to calculate the distance between two points, I get UnboundLocalError: local variable 'minkowski_distance' referenced before assignment edit sorry, I just realised, this function does work. However I have another method calling it that doesn't. I put the last method at the bottom This is the method: class MinkowskiDistance(Distance): def __init__(self, dist_funct_name_str = 'Minkowski distance', p=2): self.p = p def dist(self, obj_a, obj_b): distance_to_power_p=0 p=self.p for i in range(len(obj_a)): distance_to_power_p += abs((obj_a[i]-obj_b[i]))**(p) minkowski_distance = (distance_to_power_p)**(1/p) return minkowski_distance and this is the function: (it basically splits the tuples x and y into their number and string components and calculates the distance between the numeric part of x and y and then the distance between the string parts, then adds them. def total_dist(x, y, p=2, q=2): jacard = QGramDistance(q=q) minkowski = MinkowskiDistance(p=p) x_num = [] x_str = [] y_num = [] y_str = [] #I am spliting each vector into its numerical parts and its string parts so that the distances #of each part can be found, then summed together. for i in range(len(x)): if type(x[i]) == float or type(x[i]) == int: x_num.append(x[i]) y_num.append(y[i]) else: x_str.append(x[i]) y_str.append(y[i]) num_dist = minkowski.dist(x_num,y_num) str_dist = I find using some more steps #I am simply adding the two types of distance to get the total distance: return num_dist + str_dist class NearestNeighbourClustering(Clustering): def __init__(self, data_file, clust_algo_name_str='', strip_header = "no", remove = -1): self.data_file= data_file self.header_strip = strip_header self.remove_column = remove def run_clustering(self, max_dist, p=2, q=2): K = {} #dictionary of clusters data_points = self.read_data_file() K[0]=[data_points[0]] k=0 #I added the first point in the data to the 0th cluster #k = number of clusters minus 1 n = len(data_points) for i in range(1,n): data_point_in_a_cluster = "no" for c in range(k+1): distances_from_i = [total_dist(data_points[i],K[c][j], p=p, q=q) for j in range(len(K[c]))] d = min(distances_from_i) if d <= max_dist: K[c].append(data_points[i]) data_point_in_a_cluster = "yes" if data_point_in_a_cluster == "no": k += 1 K[k]=[data_points[i]] return K

    Read the article

  • How do I improve this linear regression function?

    - by user558383
    I have the following PHP function that I'm using to draw a trend line. However, it sometimes plots the line below all the points in the scatter graph. Is there an error in my function or is there a better way to do it. I think it might be something to do with that with the line it produces, it treats all the residuals (the distances from the scatter points to the line) as positive regardless of them being above or below the line. function linear_regression($x, $y) { $n = count($x); $x_sum = array_sum($x); $y_sum = array_sum($y); $xx_sum = 0; $xy_sum = 0; for($i = 0; $i < $n; $i++) { $xy_sum+=($x[$i]*$y[$i]); $xx_sum+=($x[$i]*$x[$i]); } $m = (($n * $xy_sum) - ($x_sum * $y_sum)) / (($n * $xx_sum) - ($x_sum * $x_sum)); $b = ($y_sum - ($m * $x_sum)) / $n; return array("m"=>$m, "b"=>$b); }

    Read the article

  • TFS API Change WorkItem CreatedDate And ChangedDate To Historic Dates

    - by Tarun Arora
    There may be times when you need to modify the value of the fields “System.CreatedDate” and “System.ChangedDate” on a work item. Richard Hundhausen has a great blog with ample of reason why or why not you should need to set the values of these fields to historic dates. In this blog post I’ll show you, Create a PBI WorkItem linked to a Task work item by pre-setting the value of the field ‘System.ChangedDate’ to a historic date Change the value of the field ‘System.Created’ to a historic date Simulate the historic burn down of a task type work item in a sprint Explain the impact of updating values of the fields CreatedDate and ChangedDate on the Sprint burn down chart Rules of Play      1. You need to be a member of the Project Collection Service Accounts              2. You need to use ‘WorkItemStoreFlags.BypassRules’ when you instantiate the WorkItemStore service // Instanciate Work Item Store with the ByPassRules flag _wis = new WorkItemStore(_tfs, WorkItemStoreFlags.BypassRules);      3. You cannot set the ChangedDate         - Less than the changed date of previous revision         - Greater than current date Walkthrough The walkthrough contains 5 parts 00 – Required References 01 – Connect to TFS Programmatically 02 – Create a Work Item Programmatically 03 – Set the values of fields ‘System.ChangedDate’ and ‘System.CreatedDate’ to historic dates 04 – Results of our experiment Lets get started………………………………………………… 00 – Required References Microsoft.TeamFoundation.dll Microsoft.TeamFoundation.Client.dll Microsoft.TeamFoundation.Common.dll Microsoft.TeamFoundation.WorkItemTracking.Client.dll 01 – Connect to TFS Programmatically I have a in depth blog post on how to connect to TFS programmatically in case you are interested. However, the code snippet below will enable you to connect to TFS using the Team Project Picker. // Services I need access to globally private static TfsTeamProjectCollection _tfs; private static ProjectInfo _selectedTeamProject; private static WorkItemStore _wis; // Connect to TFS Using Team Project Picker public static bool ConnectToTfs() { var isSelected = false; // The user is allowed to select only one project var tfsPp = new TeamProjectPicker(TeamProjectPickerMode.SingleProject, false); tfsPp.ShowDialog(); // The TFS project collection _tfs = tfsPp.SelectedTeamProjectCollection; if (tfsPp.SelectedProjects.Any()) { // The selected Team Project _selectedTeamProject = tfsPp.SelectedProjects[0]; isSelected = true; } return isSelected; } 02 – Create a Work Item Programmatically In the below code snippet I have create a Product Backlog Item and a Task type work item and then link them together as parent and child. Note – You will have to set the ChangedDate to a historic date when you created the work item. Remember, If you try and set the ChangedDate to a value earlier than last assigned you will receive the following exception… TF26212: Team Foundation Server could not save your changes. There may be problems with the work item type definition. Try again or contact your Team Foundation Server administrator. If you notice below I have added a few seconds each time I have modified the ‘ChangedDate’ just to avoid running into the exception listed above. // Create Linked Work Items and return Ids private static List<int> CreateWorkItemsProgrammatically() { // Instantiate Work Item Store with the ByPassRules flag _wis = new WorkItemStore(_tfs, WorkItemStoreFlags.BypassRules); // List of work items to return var listOfWorkItems = new List<int>(); // Create a new Product Backlog Item var p = new WorkItem(_wis.Projects[_selectedTeamProject.Name].WorkItemTypes["Product Backlog Item"]); p.Title = "This is a new PBI"; p.Description = "Description"; p.IterationPath = string.Format("{0}\\Release 1\\Sprint 1", _selectedTeamProject.Name); p.AreaPath = _selectedTeamProject.Name; p["Effort"] = 10; // Just double checking that ByPassRules is set to true if (_wis.BypassRules) { p.Fields["System.ChangedDate"].Value = Convert.ToDateTime("2012-01-01"); } if (p.Validate().Count == 0) { p.Save(); listOfWorkItems.Add(p.Id); } else { Console.WriteLine(">> Following exception(s) encountered during work item save: "); foreach (var e in p.Validate()) { Console.WriteLine(" - '{0}' ", e); } } var t = new WorkItem(_wis.Projects[_selectedTeamProject.Name].WorkItemTypes["Task"]); t.Title = "This is a task"; t.Description = "Task Description"; t.IterationPath = string.Format("{0}\\Release 1\\Sprint 1", _selectedTeamProject.Name); t.AreaPath = _selectedTeamProject.Name; t["Remaining Work"] = 10; if (_wis.BypassRules) { t.Fields["System.ChangedDate"].Value = Convert.ToDateTime("2012-01-01"); } if (t.Validate().Count == 0) { t.Save(); listOfWorkItems.Add(t.Id); } else { Console.WriteLine(">> Following exception(s) encountered during work item save: "); foreach (var e in t.Validate()) { Console.WriteLine(" - '{0}' ", e); } } var linkTypEnd = _wis.WorkItemLinkTypes.LinkTypeEnds["Child"]; p.Links.Add(new WorkItemLink(linkTypEnd, t.Id) {ChangedDate = Convert.ToDateTime("2012-01-01").AddSeconds(20)}); if (_wis.BypassRules) { p.Fields["System.ChangedDate"].Value = Convert.ToDateTime("2012-01-01").AddSeconds(20); } if (p.Validate().Count == 0) { p.Save(); } else { Console.WriteLine(">> Following exception(s) encountered during work item save: "); foreach (var e in p.Validate()) { Console.WriteLine(" - '{0}' ", e); } } return listOfWorkItems; } 03 – Set the value of “Created Date” and Change the value of “Changed Date” to Historic Dates The CreatedDate can only be changed after a work item has been created. If you try and set the CreatedDate to a historic date at the time of creation of a work item, it will not work. // Lets do a work item effort burn down simulation by updating the ChangedDate & CreatedDate to historic Values private static void WorkItemChangeSimulation(IEnumerable<int> listOfWorkItems) { foreach (var id in listOfWorkItems) { var wi = _wis.GetWorkItem(id); switch (wi.Type.Name) { case "ProductBacklogItem": if (wi.State.ToLower() == "new") wi.State = "Approved"; // Advance the changed date by few seconds wi.Fields["System.ChangedDate"].Value = Convert.ToDateTime(wi.Fields["System.ChangedDate"].Value).AddSeconds(10); // Set the CreatedDate to Changed Date wi.Fields["System.CreatedDate"].Value = Convert.ToDateTime(wi.Fields["System.ChangedDate"].Value).AddSeconds(10); wi.Save(); break; case "Task": // Advance the changed date by few seconds wi.Fields["System.ChangedDate"].Value = Convert.ToDateTime(wi.Fields["System.ChangedDate"].Value).AddSeconds(10); // Set the CreatedDate to Changed date wi.Fields["System.CreatedDate"].Value = Convert.ToDateTime(wi.Fields["System.ChangedDate"].Value).AddSeconds(10); wi.Save(); break; } } // A mock sprint start date var sprintStart = DateTime.Today.AddDays(-5); // A mock sprint end date var sprintEnd = DateTime.Today.AddDays(5); // What is the total Sprint duration var totalSprintDuration = (sprintEnd - sprintStart).Days; // How much of the sprint have we already covered var noOfDaysIntoSprint = (DateTime.Today - sprintStart).Days; // Get the effort assigned to our tasks var totalEffortRemaining = QueryTaskTotalEfforRemaining(listOfWorkItems); // Defining how much effort to burn every day decimal dailyBurnRate = totalEffortRemaining / totalSprintDuration < 1 ? 1 : totalEffortRemaining / totalSprintDuration; // we have just created one task var totalNoOfTasks = 1; var simulation = sprintStart; var currentDate = DateTime.Today.Date; // Carry on till effort has been burned down from sprint start to today while (simulation.Date != currentDate.Date) { var dailyBurnRate1 = dailyBurnRate; // A fixed amount needs to be burned down each day while (dailyBurnRate1 > 0) { // burn down bit by bit from all unfinished task type work items foreach (var id in listOfWorkItems) { var wi = _wis.GetWorkItem(id); var isDirty = false; // Set the status to in progress if (wi.State.ToLower() == "to do") { wi.State = "In Progress"; isDirty = true; } // Ensure that there is enough effort remaining in tasks to burn down the daily burn rate if (QueryTaskTotalEfforRemaining(listOfWorkItems) > dailyBurnRate1) { // If there is less than 1 unit of effort left in the task, burn it all if (Convert.ToDecimal(wi["Remaining Work"]) <= 1) { wi["Remaining Work"] = 0; dailyBurnRate1 = dailyBurnRate1 - Convert.ToDecimal(wi["Remaining Work"]); isDirty = true; } else { // How much to burn from each task? var toBurn = (dailyBurnRate / totalNoOfTasks) < 1 ? 1 : (dailyBurnRate / totalNoOfTasks); // Check that the task has enough effort to allow burnForTask effort if (Convert.ToDecimal(wi["Remaining Work"]) >= toBurn) { wi["Remaining Work"] = Convert.ToDecimal(wi["Remaining Work"]) - toBurn; dailyBurnRate1 = dailyBurnRate1 - toBurn; isDirty = true; } else { wi["Remaining Work"] = 0; dailyBurnRate1 = dailyBurnRate1 - Convert.ToDecimal(wi["Remaining Work"]); isDirty = true; } } } else { dailyBurnRate1 = 0; } if (isDirty) { if (Convert.ToDateTime(wi.Fields["System.ChangedDate"].Value).Date == simulation.Date) { wi.Fields["System.ChangedDate"].Value = Convert.ToDateTime(wi.Fields["System.ChangedDate"].Value).AddSeconds(20); } else { wi.Fields["System.ChangedDate"].Value = simulation.AddSeconds(20); } wi.Save(); } } } // Increase date by 1 to perform daily burn down by day simulation = Convert.ToDateTime(simulation).AddDays(1); } } // Get the Total effort remaining in the current sprint private static decimal QueryTaskTotalEfforRemaining(List<int> listOfWorkItems) { var unfinishedWorkInCurrentSprint = _wis.GetQueryDefinition( new Guid(QueryAndGuid.FirstOrDefault(c => c.Key == "Unfinished Work").Value)); var parameters = new Dictionary<string, object> { { "project", _selectedTeamProject.Name } }; var q = new Query(_wis, unfinishedWorkInCurrentSprint.QueryText, parameters); var results = q.RunLinkQuery(); var wis = new List<WorkItem>(); foreach (var result in results) { var _wi = _wis.GetWorkItem(result.TargetId); if (_wi.Type.Name == "Task" && listOfWorkItems.Contains(_wi.Id)) wis.Add(_wi); } return wis.Sum(r => Convert.ToDecimal(r["Remaining Work"])); }   04 – The Results If you are still reading, the results are beautiful! Image 1 – Create work item with Changed Date pre-set to historic date Image 2 – Set the CreatedDate to historic date (Same as the ChangedDate) Image 3 – Simulate of effort burn down on a task via the TFS API   Image 4 – The history of changes on the Task. So, essentially this task has burned 1 hour per day Sprint Burn Down Chart – What’s not possible? The Sprint burn down chart is calculated from the System.AuthorizedDate and not the System.ChangedDate/System.CreatedDate. So, though you can change the System.ChangedDate and System.CreatedDate to historic dates you will not be able to synthesize the sprint burn down chart. Image 1 – By changing the Created Date and Changed Date to ‘18/Oct/2012’ you would have expected the burn down to have been impacted, but it won’t be, because the sprint burn down chart uses the value of field ‘System.AuthorizedDate’ to calculate the unfinished work points. The AsOf queries that are used to calculate the unfinished work points use the value of the field ‘System.AuthorizedDate’. Image 2 – Using the above code I burned down 1 hour effort per day over 5 days from the task work item, I would have expected the sprint burn down to show a constant burn down, instead the burn down shows the effort exhausted on the 24th itself. Simply because the burn down is calculated using the ‘System.AuthorizedDate’. Now you would ask… “Can I change the value of the field System.AuthorizedDate to a historic date” Unfortunately that’s not possible! You will run into the exception ValidationException –  “TF26194: The value for field ‘Authorized Date’ cannot be changed.” Conclusion - You need to be a member of the Project Collection Service account group in order to set the fields ‘System.ChangedDate’ and ‘System.CreatedDate’ to historic dates - You need to instantiate the WorkItemStore using the flag ByPassValidation - The System.ChangedDate needs to be set to a historic date at the time of work item creation. You cannot reset the ChangedDate to a date earlier than the existing ChangedDate and you cannot reset the ChangedDate to a date greater than the current date time. - The System.CreatedDate can only be reset after a work item has been created. You cannot set the CreatedDate at the time of work item creation. The CreatedDate cannot be greater than the current date. You can however reset the CreatedDate to a date earlier than the existing value. - You will not be able to synthesize the Sprint burn down chart by changing the value of System.ChangedDate and System.CreatedDate to historic dates, since the burn down chart uses AsOf queries to calculate the unfinished work points which internally uses the System.AuthorizedDate and NOT the System.ChangedDate & System.CreatedDate - System.AuthorizedDate cannot be set to a historic date using the TFS API Read other posts on using the TFS API here… Enjoy!

    Read the article

< Previous Page | 56 57 58 59 60 61 62 63 64 65 66 67  | Next Page >