Search Results

Search found 42090 results on 1684 pages for 'mean square method'.

Page 1/1684 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Mean filter in MATLAB without loops or signal processing toolbox

    - by Doresoom
    I need to implement a mean filter on a data set, but I don't have access to the signal processing toolbox. Is there a way to do this without using a for loop? Here's the code I've got working: x=0:.1:10*pi; noise=0.5*(rand(1,length(x))-0.5); y=sin(x)+noise; %generate noisy signal a=10; %specify moving window size my=zeros(1,length(y)-a); for n=a/2+1:length(y)-a/2 my(n-a/2)=mean(y(n-a/2:n+a/2)); %calculate mean for each window end mx=x(a/2+1:end-a/2); %truncate x array to match plot(x,y) hold on plot(mx,my,'r')

    Read the article

  • Creating a dynamic proxy generator with c# – Part 4 – Calling the base method

    - by SeanMcAlinden
    Creating a dynamic proxy generator with c# – Part 1 – Creating the Assembly builder, Module builder and caching mechanism Creating a dynamic proxy generator with c# – Part 2 – Interceptor Design Creating a dynamic proxy generator with c# – Part 3 – Creating the constructors   The plan for calling the base methods from the proxy is to create a private method for each overridden proxy method, this will allow the proxy to use a delegate to simply invoke the private method when required. Quite a few helper classes have been created to make this possible so as usual I would suggest download or viewing the code at http://rapidioc.codeplex.com/. In this post I’m just going to cover the main points for when creating methods. Getting the methods to override The first two notable methods are for getting the methods. private static MethodInfo[] GetMethodsToOverride<TBase>() where TBase : class {     return typeof(TBase).GetMethods().Where(x =>         !methodsToIgnore.Contains(x.Name) &&                              (x.Attributes & MethodAttributes.Final) == 0)         .ToArray(); } private static StringCollection GetMethodsToIgnore() {     return new StringCollection()     {         "ToString",         "GetHashCode",         "Equals",         "GetType"     }; } The GetMethodsToIgnore method string collection contains an array of methods that I don’t want to override. In the GetMethodsToOverride method, you’ll notice a binary AND which is basically saying not to include any methods marked final i.e. not virtual. Creating the MethodInfo for calling the base method This method should hopefully be fairly easy to follow, it’s only function is to create a MethodInfo which points to the correct base method, and with the correct parameters. private static MethodInfo CreateCallBaseMethodInfo<TBase>(MethodInfo method) where TBase : class {     Type[] baseMethodParameterTypes = ParameterHelper.GetParameterTypes(method, method.GetParameters());       return typeof(TBase).GetMethod(        method.Name,        BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,        null,        baseMethodParameterTypes,        null     ); }   /// <summary> /// Get the parameter types. /// </summary> /// <param name="method">The method.</param> /// <param name="parameters">The parameters.</param> public static Type[] GetParameterTypes(MethodInfo method, ParameterInfo[] parameters) {     Type[] parameterTypesList = Type.EmptyTypes;       if (parameters.Length > 0)     {         parameterTypesList = CreateParametersList(parameters);     }     return parameterTypesList; }   Creating the new private methods for calling the base method The following method outline how I’ve created the private methods for calling the base class method. private static MethodBuilder CreateCallBaseMethodBuilder(TypeBuilder typeBuilder, MethodInfo method) {     string callBaseSuffix = "GetBaseMethod";       if (method.IsGenericMethod || method.IsGenericMethodDefinition)     {                         return MethodHelper.SetUpGenericMethod             (                 typeBuilder,                 method,                 method.Name + callBaseSuffix,                 MethodAttributes.Private | MethodAttributes.HideBySig             );     }     else     {         return MethodHelper.SetupNonGenericMethod             (                 typeBuilder,                 method,                 method.Name + callBaseSuffix,                 MethodAttributes.Private | MethodAttributes.HideBySig             );     } } The CreateCallBaseMethodBuilder is the entry point method for creating the call base method. I’ve added a suffix to the base classes method name to keep it unique. Non Generic Methods Creating a non generic method is fairly simple public static MethodBuilder SetupNonGenericMethod(     TypeBuilder typeBuilder,     MethodInfo method,     string methodName,     MethodAttributes methodAttributes) {     ParameterInfo[] parameters = method.GetParameters();       Type[] parameterTypes = ParameterHelper.GetParameterTypes(method, parameters);       Type returnType = method.ReturnType;       MethodBuilder methodBuilder = CreateMethodBuilder         (             typeBuilder,             method,             methodName,             methodAttributes,             parameterTypes,             returnType         );       ParameterHelper.SetUpParameters(parameterTypes, parameters, methodBuilder);       return methodBuilder; }   private static MethodBuilder CreateMethodBuilder (     TypeBuilder typeBuilder,     MethodInfo method,     string methodName,     MethodAttributes methodAttributes,     Type[] parameterTypes,     Type returnType ) { MethodBuilder methodBuilder = typeBuilder.DefineMethod(methodName, methodAttributes, returnType, parameterTypes); return methodBuilder; } As you can see, you simply have to declare a method builder, get the parameter types, and set the method attributes you want.   Generic Methods Creating generic methods takes a little bit more work. /// <summary> /// Sets up generic method. /// </summary> /// <param name="typeBuilder">The type builder.</param> /// <param name="method">The method.</param> /// <param name="methodName">Name of the method.</param> /// <param name="methodAttributes">The method attributes.</param> public static MethodBuilder SetUpGenericMethod     (         TypeBuilder typeBuilder,         MethodInfo method,         string methodName,         MethodAttributes methodAttributes     ) {     ParameterInfo[] parameters = method.GetParameters();       Type[] parameterTypes = ParameterHelper.GetParameterTypes(method, parameters);       MethodBuilder methodBuilder = typeBuilder.DefineMethod(methodName,         methodAttributes);       Type[] genericArguments = method.GetGenericArguments();       GenericTypeParameterBuilder[] genericTypeParameters =         GetGenericTypeParameters(methodBuilder, genericArguments);       ParameterHelper.SetUpParameterConstraints(parameterTypes, genericTypeParameters);       SetUpReturnType(method, methodBuilder, genericTypeParameters);       if (method.IsGenericMethod)     {         methodBuilder.MakeGenericMethod(genericArguments);     }       ParameterHelper.SetUpParameters(parameterTypes, parameters, methodBuilder);       return methodBuilder; }   private static GenericTypeParameterBuilder[] GetGenericTypeParameters     (         MethodBuilder methodBuilder,         Type[] genericArguments     ) {     return methodBuilder.DefineGenericParameters(GenericsHelper.GetArgumentNames(genericArguments)); }   private static void SetUpReturnType(MethodInfo method, MethodBuilder methodBuilder, GenericTypeParameterBuilder[] genericTypeParameters) {     if (method.IsGenericMethodDefinition)     {         SetUpGenericDefinitionReturnType(method, methodBuilder, genericTypeParameters);     }     else     {         methodBuilder.SetReturnType(method.ReturnType);     } }   private static void SetUpGenericDefinitionReturnType(MethodInfo method, MethodBuilder methodBuilder, GenericTypeParameterBuilder[] genericTypeParameters) {     if (method.ReturnType == null)     {         methodBuilder.SetReturnType(typeof(void));     }     else if (method.ReturnType.IsGenericType)     {         methodBuilder.SetReturnType(genericTypeParameters.Where             (x => x.Name == method.ReturnType.Name).First());     }     else     {         methodBuilder.SetReturnType(method.ReturnType);     }             } Ok, there are a few helper methods missing, basically there is way to much code to put in this post, take a look at the code at http://rapidioc.codeplex.com/ to follow it through completely. Basically though, when dealing with generics there is extra work to do in terms of getting the generic argument types setting up any generic parameter constraints setting up the return type setting up the method as a generic All of the information is easy to get via reflection from the MethodInfo.   Emitting the new private method Emitting the new private method is relatively simple as it’s only function is calling the base method and returning a result if the return type is not void. ILGenerator il = privateMethodBuilder.GetILGenerator();   EmitCallBaseMethod(method, callBaseMethod, il);   private static void EmitCallBaseMethod(MethodInfo method, MethodInfo callBaseMethod, ILGenerator il) {     int privateParameterCount = method.GetParameters().Length;       il.Emit(OpCodes.Ldarg_0);       if (privateParameterCount > 0)     {         for (int arg = 0; arg < privateParameterCount; arg++)         {             il.Emit(OpCodes.Ldarg_S, arg + 1);         }     }       il.Emit(OpCodes.Call, callBaseMethod);       il.Emit(OpCodes.Ret); } So in the main method building method, an ILGenerator is created from the method builder. The ILGenerator performs the following actions: Load the class (this) onto the stack using the hidden argument Ldarg_0. Create an argument on the stack for each of the method parameters (starting at 1 because 0 is the hidden argument) Call the base method using the Opcodes.Call code and the MethodInfo we created earlier. Call return on the method   Conclusion Now we have the private methods prepared for calling the base method, we have reached the last of the relatively easy part of the proxy building. Hopefully, it hasn’t been too hard to follow so far, there is a lot of code so I haven’t been able to post it all so please check it out at http://rapidioc.codeplex.com/. The next section should be up fairly soon, it’s going to cover creating the delegates for calling the private methods created in this post.   Kind Regards, Sean.

    Read the article

  • Detect if square in grid is within a diamond shape

    - by myrkos
    So I have a game in which basically everything is a square inside a big grid. It's easy to check if a square is inside a box whose center is another square: *** x *o* --> x is not in o's square *** **x *o* --> x IS in o's square *** This can be done by simply subtracting the coordinates of o and x, then taking the largest coordinate of that and comparing it with the half side length. Now I want to do the same thing but check if x is in o's diamond, like so: * **x **o** --> x IS in o's diamond *** * What would be the best way to check if a square is in another square's surrounding diamond-shaped area, given the diamond's half width/height?

    Read the article

  • what's the point of method overloading?

    - by David
    I am following a textbook in which I have just come across method overloading. It briefly described method overloading as: when the same method name is used with different parameters its called method overloading. From what I've learned so far in OOP is that if I want different behaviors from an object via methods, I should use different method names that best indicate the behavior, so why should I bother with method overloading in the first place?

    Read the article

  • Arrays- Square root of an Array and printing the result JAVA

    - by roger34
    Hello, The title says it all, really. I'm trying to get an array of (9) numbers squared then printed but I keep coming back with only one result - the number of numbers in the array squared- obviously not what I want. Thanks for any help. Ok, here is my terrible code so far. Trying to pass it to a method as well. public static void main ( String args[] ) { double[] nums = {126, 12.939, 795, 320.16, 110, 34.7676, 7773, 67, 567, 323}; System.out.println ("Square root is " +square); square(nums); } public static double square (double [] array) { double result; for( double i = 0; i < array.length ; i++ ) result = Math.sqrt(array[i]); return result; } }

    Read the article

  • XNA C# Rectangle Intersect Ball on a Square

    - by user2436057
    I made a Game like Peggle Deluxe using C# and XNA for lerning. I have 2 rectangles a ball and a square field. The ball gets shoot out with a cannon and if the Ball hits the Square the Square disapears and the Ball flys away.But the Ball doesent spring of realistically, it sometimes flys away in a different direction or gets stuck on the edge. Thads my Code at the moment: public void Update(Ball b, Deadline dl) { ArrayList listToDelete = new ArrayList(); foreach (Field aField in allFields) { if (aField.square.Intersects(b.ballhere)) { listToDelete.Add(aField); Punkte = Punkte + 100; float distanceX = Math.Abs(b.ballhere.X - aField.square.X); float distanceY = Math.Abs(b.ballhere.Y - aField.square.Y); if (distanceX < distanceY) { b.myMovement.X = -b.myMovement.X; } else { b.myMovement.Y = -b.myMovement.Y; } } } It changes the X or Y axis depending on how the ball hits the Square but not everytimes. What could cause the problem? Thanks for your answer. Greetings from Switzerland.

    Read the article

  • accessing array values without square brackets in php

    - by amb
    In php how can I access an array's values without using square brackets around the key? My particular problem is that I want to access the elements of an array returned by a function. Say function(args) returns an array. Why is $var = function(args)[0]; yelling at me about the square brackets? Can I do something like $var = function(args).value(0); or am I missing something very basic?

    Read the article

  • compute mean in python for a generator

    - by nmaxwell
    Hi, I'm doing some statistics work, I have a (large) collection of random numbers to compute the mean of, I'd like to work with generators, because I just need to compute the mean, so I don't need to store the numbers. The problem is that numpy.mean breaks if you pass it a generator. I can write a simple function to do what I want, but I'm wondering if there's a proper, built-in way to do this? It would be nice if I could say "sum(values)/len(values)", but len doesn't work for genetators, and sum already consumed values. here's an example: import numpy def my_mean(values): n = 0 Sum = 0.0 try: while True: Sum += next(values) n += 1 except StopIteration: pass return float(Sum)/n X = [k for k in range(1,7)] Y = (k for k in range(1,7)) print numpy.mean(X) print my_mean(Y) these both give the same, correct, answer, buy my_mean doesn't work for lists, and numpy.mean doesn't work for generators. I really like the idea of working with generators, but details like this seem to spoil things. thanks for any help -nick

    Read the article

  • Square Peg Web: Gets you the traffic to where it matters most: Your Website!

    - by demetriusalwyn
    Have you decided to start your business online or is your business not reaching the targeted audience? Come to Square Peg Web; where you will find what you want to make your business reach new heights. The team at Square Peg Web is professionals who understand what you want and make sure you get it right. Our confidence stems from the fact of thousands of satisfied clients who keep referring friends and business associates to us and we do not let our clients down. Many companies promise the sky but how far is does their work live up to the promises? We do not know about the others however, we are sure that we strive to put together all our ideas and thoughts to make your website rank among the top. Web hosting is something that needs to have a personal touch; Square Peg Web customizes everything to suit your requirements so that you do not have to look further. With Square Peg Web you have a host of features to make your Business go viral. Some of the product details that are offered with Square Peg Web are unlimited product options/ variants/ properties giving you an option on price modifiers. You get unlimited customized input fields for your products and you can also Customer-define the prices. Square Peg Web provides you an option of using multiple product images with zoom features and one can also list a particular product in several categories. There are other aspects which make Square Peg Web the best choice for your website needs; every sale of yours’ is important to you and to us. We make sure that each sale is tracked by the product and also the list of bestsellers that appeal to the audience. Other comprehensive statistics of Square Peg Web includes searchable order data, an interface for shipments and order fulfillments, export sales & customer data for usage in a spreadsheet and the ability to export orders to QuickBooks format. With Square Peg Web; Admin Panel is a lot simpler. Administrative access is completely password protected and any changes done are all in real-time. You can have absolute control on the cart from anywhere around the world using your web browser and the topping on the cake is the unlimited amount of admin accounts that can be created for you. Square Peg Web offers you a world of experience with the options of choosing from marketing websites to e-commerce and from customized applications to community oriented sites. Some of the projects which appear in the portfolio of Square Peg Web are Online Marketing Web Sites, E-Commerce Web Sites, customized web applications, Blog designing and programming, video sharing and the option of downloading web sites, online advertisements, flash animation, customer and product support web sites, web site re-designing and planning and complete information architecture.

    Read the article

  • constructor function's object literal returns toString() method but no other method

    - by JohnMerlino
    I'm very confused with javascript methods defined in objects and the "this" keyword. In the below example, the toString() method is invoked when Mammal object instantiated: function Mammal(name){ this.name=name; this.toString = function(){ return '[Mammal "'+this.name+'"]'; } } var someAnimal = new Mammal('Mr. Biggles'); alert('someAnimal is '+someAnimal); Despite the fact that the toString() method is not invoked on the object someAnimal like this: alert('someAnimal is '+someAnimal.toString()); It still returns 'someAnimal is [Mammal "Mr. Biggles"]' . That doesn't make sense to me because the toString() function is not being called anywhere. Then to add even more confusion, if I change the toString() method to a method I make up such as random(): function Mammal(name){ this.name=name; this.random = function(){ return Math.floor(Math.random() * 15); } } var someAnimal = new Mammal('Mr. Biggles'); alert(someAnimal); It completely ignores the random method (despite the fact that it is defined the same way was the toString() method was) and returns: [object object] Another issue I'm having trouble understanding with inheritance is the value of "this". For example, in the below example function person(w,h){ width.width = w; width.height = h; } function man(w,h,s) { person.call(this, w, h); this.sex = s; } "this" keyword is being send to the person object clearly. However, does "this" refer to the subclass (man) or the super class (person) when the person object receives it? Thanks for clearing up any of the confusion I have with inheritance and object literals in javascript.

    Read the article

  • Method chaining and exceptions in C#

    - by devoured elysium
    If I have a method chain like the following: var abc = new ABC(); abc.method1() .method2() .methodThrowsException() .method3() ; assuming I've defined method1(), method2() and method3() as public ABC method1() { return this; } and methodThrowsException() as public ABC method3() { throw new ArgumentException(); } When running the code, is it possible to know which specific line of code has thrown the Exception, or will it just consider all the method chaining as just one line? I've done a simple test and it seems it considers them all as just one line but Method Chaining says Putting methods on separate lines also makes debugging easier as error messages and debugger control is usually on a line by line basis. Am I missing something, or does that just not apply to C#? Thanks

    Read the article

  • alias_attribute and creating and method with the original attribute name causes a loop

    - by Tiago
    Im trying to dynamically create a method chain in one attribute in my model. By now I have this function: def create_filtered_attribute(attribute_name) alias_attribute "#{attribute_name}_without_filter", attribute_name define_method "#{attribute_name}" do filter_words(self.send("#{attribute_name}_without_filter")) end end so I receive a string with the attribute name, alias it for '*_without_filter*' (alias_method or alias_method_chain fails here, because the attribute isnt there when the class is created), and I create a new method with the attribute name, where I filter its contents. But somehow, when I call *"#{attribute_name}_without_filter"* it calls my new method (i think because the alias_attribute some how), and the program goes into a stack loop. Can someone please enlighten me on this.

    Read the article

  • Calculating the square of BigInteger

    - by brickner
    Hi, I'm using .NET 4's System.Numerics.BigInteger structure. I need to calculate the square (x^2) of very large numbers. If x is a BigInteger, What is the time complexity of: x*x; or BigInteger.Pow(x,2); ? If it's worse than O(n^2), do you have a better implementation? Maybe something like Schönhage–Strassen algorithm?

    Read the article

  • Can Eclipse generate method-chaining setters

    - by Chris R
    I'd like to generate method-chaining setters (setters that return the object being set), like so: public MyObject setField (Object value) { this.field = value; return this; } This makes it easier to do one-liner instantiations, which I find easier to read: myMethod (new MyObject ().setField (someValue).setOtherField (someOtherValue)); Can Eclipse's templates be modified to do this? I've changed the content to include return this; but the signature is not changed.

    Read the article

  • Drawing random smooth lines contained in a square [migrated]

    - by Doug Mercer
    I'm trying to write a matlab function that creates random, smooth trajectories in a square of finite side length. Here is my current attempt at such a procedure: function [] = drawroutes( SideLength, v, t) %DRAWROUTES Summary of this function goes here % Detailed explanation goes here %Some parameters intended to help help keep the particles in the box RandAccel=.01; ConservAccel=0; speedlimit=.1; G=10^(-8); % %Initialize Matrices Ax=zeros(v,10*t); Ay=Ax; vx=Ax; vy=Ax; x=Ax; y=Ax; sx=zeros(v,1); sy=zeros(v,1); % %Define initial position in square x(:,1)=SideLength*.15*ones(v,1)+(SideLength*.7)*rand(v,1); y(:,1)=SideLength*.15*ones(v,1)+(SideLength*.7)*rand(v,1); % for i=2:10*t %Measure minimum particle distance component wise from boundary %for each vehicle BorderGravX=[abs(SideLength*ones(v,1)-x(:,i-1)),abs(x(:,i-1))]'; BorderGravY=[abs(SideLength*ones(v,1)-y(:,i-1)),abs(y(:,i-1))]'; rx=min(BorderGravX)'; ry=min(BorderGravY)'; % %Set the sign of the repulsive force for k=1:v if x(k,i)<.5*SideLength sx(k)=1; else sx(k)=-1; end if y(k,i)<.5*SideLength sy(k)=1; else sy(k)=-1; end end % %Calculate Acceleration w/ random "nudge" and repulive force Ax(:,i)=ConservAccel*Ax(:,i-1)+RandAccel*(rand(v,1)-.5*ones(v,1))+sx*G./rx.^2; Ay(:,i)=ConservAccel*Ay(:,i-1)+RandAccel*(rand(v,1)-.5*ones(v,1))+sy*G./ry.^2; % %Ad hoc method of trying to slow down particles from jumping outside of %feasible region for h=1:v if abs(vx(h,i-1)+Ax(h,i))<speedlimit vx(h,i)=vx(h,i-1)+Ax(h,i); elseif (vx(h,i-1)+Ax(h,i))<-speedlimit vx(h,i)=-speedlimit; else vx(h,i)=speedlimit; end end for h=1:v if abs(vy(h,i-1)+Ay(h,i))<speedlimit vy(h,i)=vy(h,i-1)+Ay(h,i); elseif (vy(h,i-1)+Ay(h,i))<-speedlimit vy(h,i)=-speedlimit; else vy(h,i)=speedlimit; end end % %Update position x(:,i)=x(:,i-1)+(vx(:,i-1)+vx(:,i))/2; y(:,i)=y(:,i-1)+(vy(:,i-1)+vy(:,1))/2; % end %Plot position clf; hold on; axis([-100,SideLength+100,-100,SideLength+100]); cc=hsv(v); for j=1:v plot(x(j,1),y(j,1),'ko') plot(x(j,:),y(j,:),'color',cc(j,:)) end hold off; % end My original plan was to place particles within a square, and move them around by allowing their acceleration in the x and y direction to be governed by a uniformly distributed random variable. To keep the particles within the square, I tried to create a repulsive force that would push the particles away from the boundaries of the square. In practice, the particles tend to leave the desired "feasible" region after a relatively small number of time steps (say, 1000)." I'd love to hear your suggestions on either modifying my existing code or considering the problem from another perspective. When reading the code, please don't feel the need to get hung up on any of the ad hoc parameters at the very beginning of the script. They seem to help, but I don't believe any beside the "G" constant should truly be necessary to make this system work. Here is an example of the current output: Many of the vehicles have found their way outside of the desired square region, [0,400] X [0,400].

    Read the article

  • Override ActiveRecord#save, Method Alias? Trying to mixin functionality into save method...

    - by viatropos
    Here's the situation: I have a User model, and two modules for authentication: Oauth and Openid. Both of them override ActiveRecord#save, and have a fair share of implementation logic. Given that I can tell when the user is trying to login via Oauth vs. Openid, but that both of them have overridden save, how do "finally" override save such that I can conditionally call one of the modules' implementations of it? Here is the base structure of what I'm describing: module UsesOauth def self.included(base) base.class_eval do def save puts "Saving with Oauth!" end def save_with_oauth save end end end end module UsesOpenid def self.included(base) base.class_eval do def save puts "Saving with OpenID!" end def save_with_openid save end end end end module Sequencer def save if using_oauth? save_with_oauth elsif using_openid? save_with_openid else super end end end class User < ActiveRecord::Base include UsesOauth include UsesOpenid include Sequencer end I was thinking about using alias_method like so, but that got too complicated, because I might have 1 or 2 more similar modules. I also tried using those save_with_oauth methods (shown above), which almost works. The only thing that's missing is that I also need to call ActiveRecord::Base#save (the super method), so something like this: def save_with_oauth # do this and that super.save # the rest end But I'm not allowed to do that in ruby. Any ideas for a clever solution to this?

    Read the article

  • Move a 2D square on y axis on android GLES2

    - by Dan
    I am trying to create a simple game for android, to start i am trying to make the square move down the y axis but the way i am doing it dosent move the square at all and i cant find any tutorials for GLES20 The on draw frame function in the render class updates the users position based on accleration dew to gravity, gets the transform matrix from the user class which is used to move the square down, then the program draws it. All that happens is that the square is drawn, no motion happens public void onDrawFrame(GL10 gl) { user.update(0.0, phy.AccelerationDewToGravity); GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT); // Re draws black background GLES20.glVertexAttribPointer(maPositionHandle, 3, GLES20.GL_FLOAT, false, 12, user.SquareVB);//triangleVB); GLES20.glEnableVertexAttribArray(maPositionHandle); GLES20.glUniformMatrix4fv(maPositionHandle, 1, false, user.getTransformMatrix(), 0); GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4); } The update function in the player class is public void update(double vh, double vv) { Vh += vh; // Increase horrzontal Velosity Vv += vv; // Increase vertical velosity //Matrix.translateM(mMMatrix, 0, (int)Vh, (int)Vv, 0); Matrix.translateM(mMMatrix, 0, mMMatrix, 0, (float)Vh, (float)Vv, 0); }

    Read the article

  • Why does Java's invokevirtual need to resolve the called method's compile-time class?

    - by Chris
    Consider this simple Java class: class MyClass { public void bar(MyClass c) { c.foo(); } } I want to discuss what happens on the line c.foo(). At the bytecode level, the meat of c.foo() will be the invokevirtual opcode, and, according to the documentation for invokevirtual, more or less the following will happen: Look up the foo method defined in compile-time class MyClass. (This involves first resolving MyClass.) Do some checks, including: Verify that c is not an initialization method, and verify that calling MyClass.foo wouldn't violate any protected modifiers. Figure out which method to actually call. In particular, look up c's runtime type. If that type has foo(), call that method and return. If not, look up c's runtime type's superclass; if that type has foo, call that method and return. If not, look up c's runtime type's superclass's superclass; if that type has foo, call that method and return. Etc.. If no suitable method can be found, then error. Step #3 alone seems adequate for figuring out which method to call and verifying that said method has the correct argument/return types. So my question is why step #1 gets performed in the first place. Possible answers seem to be: You don't have enough information to perform step #3 until step #1 is complete. (This seems implausible at first glance, so please explain.) The linking or access modifier checks done in #1 and #2 are essential to prevent certain bad things from happening, and those checks must be performed based on the compile-time type, rather than the run-time type hierarchy. (Please explain.)

    Read the article

  • Naming Suggestions For A Function Providing Method Chaining In A Different Way

    - by sid3k
    I've coded an experimental function which makes passed objects chainable by using high order functions. It's name is "chain" for now, and here is a usage example; chain("Hello World") (print) // evaluates print function by passing "Hello World" object. (console.log,"Optional","Parameters") (returnfrom) // returns "Hello World" It looks lispy but behaves very different since it's coded in a C based language, I don't know if there is a name for this idiom and I couldn't any name more suitable than "chain". Any ideas, suggestions?

    Read the article

  • grouping objects to achieve a similar mean property for all groups

    - by cytochrome
    I have a collection of objects, each of which has a numerical 'weight'. I would like to create groups of these objects such that each group has approximately the same arithmetic mean of object weights. The groups won't necessarily have the same number of members, but the size of groups will be within one of each other. In terms of numbers, there will be between 50 and 100 objects and the maximum group size will be about 5. Is this a well-known type of problem? It seems a bit like a knapsack or partition problem. Are efficient algorithms known to solve it? As a first step, I created a python script that achieves very crude equivalence of mean weights by sorting the objects by weight, subgrouping these objects, and then distributing a member of each subgroup to one of the final groups. I am comfortable programming in python, so if existing packages or modules exist to achieve part of this functionality, I'd appreciate hearing about them. Thank you for your help and suggestions.

    Read the article

  • Square game map rendered as sphere

    - by Roflha
    For a hobby project of mine I have created a finite voxel world (similar to Minecraft), but as I said, mine is finite. When you reach the edge of it, you are sent to the other side. That is all working fine along with rendering the far side of the map, but I want to be able to render this grid as a sphere. Looking down from above, the world is a square. I basically want to be able to represent a portion of that square as a sphere, as if you were looking at a planet. Right now I am experimenting with taking a circular section of the map, and rendering that, but it look to flat (no curvature around the edges). My question then, is what would be the best way to add some curvature to the edges of a 2d circle to make it look like a hemisphere. However, I am not overly attached to this implementation so if somebody has some other idea for representing the square as a planet, I am all ears.

    Read the article

  • Static method , Abstract method , Interface method comparision ?

    - by programmerist
    When i choose these methods? i can not decide which one i must prefer or when will i use one of them?which one give best performance? First Type Usage public abstract class _AccessorForSQL { public virtual bool Save(string sp, ListDictionary ld, CommandType cmdType); public virtual bool Update(); public virtual bool Delete(); public virtual DataSet Select(); } class GenAccessor : _AccessorForSQL { DataSet ds; DataTable dt; public override bool Save(string sp, ListDictionary ld, CommandType cmdType) { } public override bool Update() { return true; } public override bool Delete() { return true; } public override DataSet Select() { DataSet dst = new DataSet(); return dst; } Second Type Usage Also i can write it below codes: public class GenAccessor { public Static bool Save() { } public Static bool Update() { } public Static bool Delete() { } } Third Type Usage Also i can write it below codes: public interface IAccessorForSQL { bool Delete(); bool Save(string sp, ListDictionary ld, CommandType cmdType); DataSet Select(); bool Update(); } public class _AccessorForSQL : IAccessorForSQL { private DataSet ds; private DataTable dt; public virtual bool Save(string sp, ListDictionary ld, CommandType cmdType) { } } } I can use first one below usage: GenAccessor gen = New GenAccessor(); gen.Save(); I can use second one below usage: GenAccessor.Save(); Which one do you prefer? When will i use them? which time i need override method ? which time i need static method?

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >