Search Results

Search found 32130 results on 1286 pages for 'method chaining'.

Page 18/1286 | < Previous Page | 14 15 16 17 18 19 20 21 22 23 24 25  | Next Page >

  • Oracle HRMS API – Create Employee Payment Method

    - by PRajkumar
    API --  hr_personal_pay_method_api.create_personal_pay_method   Example -- DECLARE   ln_method_id  PAY_PERSONAL_PAYMENT_METHODS_F.PERSONAL_PAYMENT_METHOD_ID%TYPE; ln_ext_acc_id        PAY_EXTERNAL_ACCOUNTS.EXTERNAL_ACCOUNT_ID%TYPE; ln_obj_ver_num    PAY_PERSONAL_PAYMENT_METHODS_F.OBJECT_VERSION_NUMBER%TYPE; ld_eff_start_date   DATE;   ld_eff_end_date    DATE; ln_comment_id     NUMBER; BEGIN      -- Create Employee Payment Method      -- --------------------------------------------------       hr_personal_pay_method_api.create_personal_pay_method       (   -- Input data elements           -- ------------------------------           p_effective_date                                     => TO_DATE('21-JUN-2011'),           p_assignment_id                                   => 33561,           p_org_payment_method_id               => 2,           p_priority                                                 => 50,           p_percentage                                           => 100,           p_territory_code                                     => 'US',           p_segment1                                              => 'PRAJKUMAR',           p_segment2                                              => 'S',           p_segment3                                              => '100200300',           p_segment4                                              => '567',           p_segment5                                              => 'HDFC',           p_segment6                                              => 'INDIA',           -- Output data elements           -- --------------------------------           p_personal_payment_method_id   => ln_method_id,           p_external_account_id                       => ln_ext_acc_id,           p_object_version_number                  => ln_obj_ver_num,           p_effective_start_date                          => ld_eff_start_date,           p_effective_end_date                           => ld_eff_end_date,          p_comment_id                                        => ln_comment_id      );    COMMIT; EXCEPTION           WHEN OTHERS THEN                           ROLLBACK;                            dbms_output.put_line(SQLERRM); END; / SHOW ERR;    

    Read the article

  • Struct Method for Loops Problem

    - by Annalyne
    I have tried numerous times how to make a do-while loop using the float constructor for my code but it seems it does not work properly as I wanted. For summary, I am making a TBRPG in C++ and I encountered few problems. But before that, let me post my code. #include <iostream> #include <string> #include <ctime> #include <cstdlib> using namespace std; int char_level = 1; //the starting level of the character. string town; //town string town_name; //the name of the town the character is in. string charname; //holds the character's name upon the start of the game int gems = 0; //holds the value of the games the character has. const int MAX_ITEMS = 15; //max items the character can carry string inventory [MAX_ITEMS]; //the inventory of the character in game int itemnum = 0; //number of items that the character has. bool GameOver = false; //boolean intended for the game over scr. string monsterTroop [] = {"Slime", "Zombie", "Imp", "Sahaguin, Hounds, Vampire"}; //monster name float monsterTroopHealth [] = {5.0f, 10.0f, 15.0f, 20.0f, 25.0f}; // the health of the monsters int monLifeBox; //life carrier of the game's enemy troops int enemNumber; //enemy number //inventory[itemnum++] = "Sword"; class RPG_Game_Enemy { public: void enemyAppear () { srand(time(0)); enemNumber = 1+(rand()%3); if (enemNumber == 1) cout << monsterTroop[1]; //monster troop 1 else if (enemNumber == 2) cout << monsterTroop[2]; //monster troop 2 else if (enemNumber == 3) cout << monsterTroop[3]; //monster troop 3 else if (enemNumber == 4) cout << monsterTroop[4]; //monster troop 4 } void enemDefeat () { cout << "The foe has been defeated. You are victorious." << endl; } void enemyDies() { //if the enemy dies: //collapse declaration cout << "The foe vanished and you are victorious!" << endl; } }; class RPG_Scene_Battle { public: RPG_Scene_Battle(float ini_health) : health (ini_health){}; float getHealth() { return health; } void setHealth(float rpg_val){ health = rpg_val;}; private: float health; }; //---------------------------------------------------------------// // Conduct Damage for the Scene Battle's Damage //---------------------------------------------------------------// float conductDamage(RPG_Scene_Battle rpg_tr, float damage) { rpg_tr.setHealth(rpg_tr.getHealth() - damage); return rpg_tr.getHealth(); }; // ------------------------------------------------------------- // void RPG_Scene_DisplayItem () { cout << "Items: \n"; for (int i=0; i < itemnum; ++i) cout << inventory[i] <<endl; }; In this code I have so far, the problem I have is the battle scene. For example, the player battles a Ghost with 10 HP, when I use a do while loop to subtract the HP of the character and the enemy, it only deducts once in the do while. Some people said I should use a struct, but I have no idea how to make it. Is there a way someone can display a code how to implement it on my game? Edit: I made the do-while by far like this: do RPG_Scene_Battle (player, 20.0f); RPG_Scene_Battle (enemy, 10.0f); cout << "Battle starts!" <<endl; cout << "You used a blade skill and deducted 2 hit points to the enemy!" conductDamage (enemy, 2.0f); while (enemy!=0) also, I made something like this: #include <iostream> using namespace std; int gems = 0; class Entity { public: Entity(float startingHealth) : health(startingHealth){}; // initialize health float getHealth(){return health;} void setHealth(float value){ health = value;}; private: float health; }; float subtractHealthFrom(Entity& ent, float damage) { ent.setHealth(ent.getHealth() - damage); return ent.getHealth(); }; int main () { Entity character(10.0f); Entity enemy(10.0f); cout << "Hero Life: "; cout << subtractHealthFrom(character, 2.0f) <<endl; cout << "Monster Life: "; cout << subtractHealthFrom(enemy, 2.0f) <<endl; cout << "Hero Life: "; cout << subtractHealthFrom(character, 2.0f) <<endl; cout << "Monster Life: "; cout << subtractHealthFrom(enemy, 2.0f) <<endl; }; Struct method, they say, should solve this problem. How can I continously deduct hp from the enemy? Whenever I deduct something, it would return to its original value -_-

    Read the article

  • Invoking callhierarchy for a method

    - by Steven
    hi, I have an object of type IMethod which represents a method .I want to get the Call Hierarchy of this method . Which methods should i call to get the call hierarchy of a method? Is there any method by which i can do it? I know that i can get it by ctrl+alt+H but i want the code or method for invoking it. Thanks

    Read the article

  • Method-Object pairs in Java

    - by John Manak
    I'd like to create a list of method-object pairs. Each method is a function returning a boolean. Then: foreach(pair) { if method evaluates to true { do something with the object } } One way of modelling this that I can think of is to have a class Constraint with a method isValid() and for each constraint produce an anonymous class (overriding the isValid() method). I feel like there could be a nicer way. Can you think of any?

    Read the article

  • Removing SCIM input method as default from gnome terminal

    - by Mark
    Hello - I am recently back into the Linux world after about a 10 year absence. While I can find my way around most things, terminals and desktop managers are different than I remember. One of the biggest problems that I am encountering today is that when running a gnome terminal (this is Suse 10.0 enterprise), I'm getting behavior in the window that I don't want. Specifically, when I type, my typing is underlined as if something is trying to spell check my window. Further, it seems as if when running vi or less, my keystrokes are only processed by these apps when I hit 'return'. I.e. if I'm running less and want to go back a page, I'll hit b, but nothing happens until I hit 'return'. I seem to have tracked this down to the 'input method". Right clicking in the Gnome terminal allows me to set my input method to one of a dozen values. It seems that currently, it's set to "SCIM Input Method". If I then select 'default' or 'X Input Method', apps (i.e. things like less, vi, and even the bash shell) behave as I would expect. Can someone tell me a) what is this SCIM input method b) how can I make it so that it is not the default? I've poked around various configuration files in my home directory as well as in /etc, but I can't see to find how this is set. I guess as a final question, can I just get rid of SCIM? Or is that tied into the window manager somehow? I do appreciate any clarifications that I can get. Thanks.

    Read the article

  • Enumerable Interleave Extension Method

    - by João Angelo
    A recent stackoverflow question, which I didn’t bookmark and now I’m unable to find, inspired me to implement an extension method for Enumerable that allows to insert a constant element between each pair of elements in a sequence. Kind of what String.Join does for strings, but maintaining an enumerable as the return value. Having done the single element part I got a bit carried away and ended up expanding it adding overloads to support interleaving elements of another sequence and support for a predicate to control when interleaving takes place. I have to confess that I did this for fun and now I can’t think of any real usage scenario, nonetheless, it may prove useful for someone. First a simple example: var target = new string[] { "(", ")", "(", ")" }; var result = target.Interleave(".", (f, s) => f == "("); // Prints: (.)(.) Console.WriteLine(String.Join(string.Empty, result)); And now the untested but documented implementation: using System; using System.Collections; using System.Collections.Generic; using System.Linq; public static class EnumerableExtensions { /// <summary> /// Iterates infinitely over a constant element. /// </summary> /// <typeparam name="T"> /// The type of element in the sequence. /// </typeparam> private class InfiniteSequence<T> : IEnumerable<T>, IEnumerator<T> { public InfiniteSequence(T element) { this.Element = element; } public T Element { get; private set; } public IEnumerator<T> GetEnumerator() { return this; } IEnumerator IEnumerable.GetEnumerator() { return this; } T IEnumerator<T>.Current { get { return this.Element; } } void IDisposable.Dispose() { } object IEnumerator.Current { get { return this.Element; } } bool IEnumerator.MoveNext() { return true; } void IEnumerator.Reset() { } } /// <summary> /// Interleaves the specified <paramref name="element"/> between each pair of elements in the <paramref name="target"/> sequence. /// </summary> /// <typeparam name="T"> /// The type of elements in the sequence. /// </typeparam> /// <param name="target"> /// The target sequence to be interleaved. /// </param> /// <param name="element"> /// The element used to perform the interleave operation. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="target"/> or <paramref name="element"/> is a null reference. /// </exception> /// <returns> /// The <paramref name="target"/> sequence interleaved with the specified <paramref name="element"/>. /// </returns> public static IEnumerable<T> Interleave<T>( this IEnumerable<T> target, T element) { if (target == null) throw new ArgumentNullException("target"); if (element == null) throw new ArgumentNullException("element"); return InterleaveInternal(target, new InfiniteSequence<T>(element), (f, s) => true); } /// <summary> /// Interleaves the specified <paramref name="element"/> between each pair of elements in the <paramref name="target"/> sequence. /// </summary> /// <remarks> /// The interleave operation is interrupted as soon as the <paramref name="target"/> sequence is exhausted; If the number of <paramref name="elements"/> to be interleaved are not enough to completely interleave the <paramref name="target"/> sequence then the remainder of the sequence is returned without being interleaved. /// </remarks> /// <typeparam name="T"> /// The type of elements in the sequence. /// </typeparam> /// <param name="target"> /// The target sequence to be interleaved. /// </param> /// <param name="elements"> /// The elements used to perform the interleave operation. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="target"/> or <paramref name="element"/> is a null reference. /// </exception> /// <returns> /// The <paramref name="target"/> sequence interleaved with the specified <paramref name="elements"/>. /// </returns> public static IEnumerable<T> Interleave<T>( this IEnumerable<T> target, IEnumerable<T> elements) { if (target == null) throw new ArgumentNullException("target"); if (elements == null) throw new ArgumentNullException("elements"); return InterleaveInternal(target, elements, (f, s) => true); } /// <summary> /// Interleaves the specified <paramref name="element"/> between each pair of elements in the <paramref name="target"/> sequence that satisfy <paramref name="predicate"/>. /// </summary> /// <typeparam name="T"> /// The type of elements in the sequence. /// </typeparam> /// <param name="target"> /// The target sequence to be interleaved. /// </param> /// <param name="element"> /// The element used to perform the interleave operation. /// </param> /// <param name="predicate"> /// A predicate used to assert if interleaving should occur between two target elements. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="target"/> or <paramref name="element"/> or <paramref name="predicate"/> is a null reference. /// </exception> /// <returns> /// The <paramref name="target"/> sequence interleaved with the specified <paramref name="element"/>. /// </returns> public static IEnumerable<T> Interleave<T>( this IEnumerable<T> target, T element, Func<T, T, bool> predicate) { if (target == null) throw new ArgumentNullException("target"); if (element == null) throw new ArgumentNullException("element"); if (predicate == null) throw new ArgumentNullException("predicate"); return InterleaveInternal(target, new InfiniteSequence<T>(element), predicate); } /// <summary> /// Interleaves the specified <paramref name="element"/> between each pair of elements in the <paramref name="target"/> sequence that satisfy <paramref name="predicate"/>. /// </summary> /// <remarks> /// The interleave operation is interrupted as soon as the <paramref name="target"/> sequence is exhausted; If the number of <paramref name="elements"/> to be interleaved are not enough to completely interleave the <paramref name="target"/> sequence then the remainder of the sequence is returned without being interleaved. /// </remarks> /// <typeparam name="T"> /// The type of elements in the sequence. /// </typeparam> /// <param name="target"> /// The target sequence to be interleaved. /// </param> /// <param name="elements"> /// The elements used to perform the interleave operation. /// </param> /// <param name="predicate"> /// A predicate used to assert if interleaving should occur between two target elements. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="target"/> or <paramref name="element"/> or <paramref name="predicate"/> is a null reference. /// </exception> /// <returns> /// The <paramref name="target"/> sequence interleaved with the specified <paramref name="elements"/>. /// </returns> public static IEnumerable<T> Interleave<T>( this IEnumerable<T> target, IEnumerable<T> elements, Func<T, T, bool> predicate) { if (target == null) throw new ArgumentNullException("target"); if (elements == null) throw new ArgumentNullException("elements"); if (predicate == null) throw new ArgumentNullException("predicate"); return InterleaveInternal(target, elements, predicate); } private static IEnumerable<T> InterleaveInternal<T>( this IEnumerable<T> target, IEnumerable<T> elements, Func<T, T, bool> predicate) { var targetEnumerator = target.GetEnumerator(); if (targetEnumerator.MoveNext()) { var elementsEnumerator = elements.GetEnumerator(); while (true) { T first = targetEnumerator.Current; yield return first; if (!targetEnumerator.MoveNext()) yield break; T second = targetEnumerator.Current; bool interleave = true && predicate(first, second) && elementsEnumerator.MoveNext(); if (interleave) yield return elementsEnumerator.Current; } } } }

    Read the article

  • Writing a method to 'transform' an immutable object: how should I approach this?

    - by Prog
    (While this question has to do with a concrete coding dilemma, it's mostly about what's the best way to design a function.) I'm writing a method that should take two Color objects, and gradually transform the first Color into the second one, creating an animation. The method will be in a utility class. My problem is that Color is an immutable object. That means that I can't do color.setRGB or color.setBlue inside a loop in the method. What I can do, is instantiate a new Color and return it from the method. But then I won't be able to gradually change the color. So I thought of three possible solutions: 1- The client code includes the method call inside a loop. For example: int duration = 1500; // duration of the animation in milliseconds int steps = 20; // how many 'cycles' the animation will take for(int i=0; i<steps; i++) color = transformColor(color, targetColor, duration, steps); And the method would look like this: Color transformColor(Color original, Color target, int duration, int steps){ int redDiff = target.getRed() - original.getRed(); int redAddition = redDiff / steps; int newRed = original.getRed() + redAddition; // same for green and blue .. Thread.sleep(duration / STEPS); // exception handling omitted return new Color(newRed, newGreen, newBlue); } The disadvantage of this approach is that the client code has to "do part of the method's job" and include a for loop. The method doesn't do it's work entirely on it's own, which I don't like. 2- Make a mutable Color subclass with methods such as setRed, and pass objects of this class into transformColor. Then it could look something like this: void transformColor(MutableColor original, Color target, int duration){ final int STEPS = 20; int redDiff = target.getRed() - original.getRed(); int redAddition = redDiff / steps; int newRed = original.getRed() + redAddition; // same for green and blue .. for(int i=0; i<STEPS; i++){ original.setRed(original.getRed() + redAddition); // same for green and blue .. Thread.sleep(duration / STEPS); // exception handling omitted } } Then the calling code would usually look something like this: // The method will usually transform colors of JComponents JComponent someComponent = ... ; // setting the Color in JComponent to be a MutableColor Color mutableColor = new MutableColor(someComponent.getForeground()); someComponent.setForeground(mutableColor); // later, transforming the Color in the JComponent transformColor((MutableColor)someComponent.getForeground(), new Color(200,100,150), 2000); The disadvantage is - the need to create a new class MutableColor, and also the need to do casting. 3- Pass into the method the actual mutable object that holds the color. Then the method could do object.setColor or similar every iteration of the loop. Two disadvantages: A- Not so elegant. Passing in the object that holds the color just to transform the color feels unnatural. B- While most of the time this method will be used to transform colors inside JComponent objects, other kinds of objects may have colors too. So the method would need to be overloaded to receive other types, or receive Objects and have instanceof checks inside.. Not optimal. Right now I think I like solution #2 the most, than solution #1 and solution #3 the least. However I'd like to hear your opinions and suggestions regarding this.

    Read the article

  • Factory Method Pattern clarification

    - by nettguy
    My understanding of Factory Method Pattern is (Correct me if i am wrong) Factory Method Pattern "Factory Method allow the client to delegates the product creation (Instance Creation) to the subclass". There are two situation in which we can go for creating Factory Method pattern. (i) When the client is restricted to the product (Instance) creation. (ii) There are multiple products available.But a decision to be made which product instance need to be returned. If you want to create Abstract Method pattern You need to have abstract product Concrete Product Factory Method to return the appropriate product. Example : public enum ORMChoice { L2SQL, EFM, LS, Sonic } //Abstract Product public interface IProduct { void ProductTaken(); } //Concrete Product public class LinqtoSql : IProduct { public void ProductTaken() { Console.WriteLine("OR Mapping Taken:LinqtoSql"); } } //concrete product public class Subsonic : IProduct { public void ProductTaken() { Console.WriteLine("OR Mapping Taken:Subsonic"); } } //concrete product public class EntityFramework : IProduct { public void ProductTaken() { Console.WriteLine("OR Mapping Taken:EntityFramework"); } } //concrete product public class LightSpeed : IProduct { public void ProductTaken() { Console.WriteLine("OR Mapping Taken :LightSpeed"); } } public class Creator { //Factory Method public IProduct ReturnORTool(ORMChoice choice) { switch (choice) { case ORMChoice.EFM:return new EntityFramework(); break; case ORMChoice.L2SQL:return new LinqtoSql(); break; case ORMChoice.LS:return new LightSpeed(); break; case ORMChoice.Sonic:return new Subsonic(); break; default: return null; } } } **Client** Button_Click() { Creator c = new Creator(); IProduct p = c.ReturnORTool(ORMChoice.L2SQL); p.ProductTaken(); } Is my understanding of Factory Method is correct?

    Read the article

  • algorithm || method to write prog

    - by fatai
    I am one of the computer science student. My wonder is everyone solve problem with different or same method, but actually I dont know whether they use method or I dont know whether there are such common method to approach problem. All teacher give us problem which in simple form sometimes, but they dont introduce any approach or method(s) so that we can first choose method then apply that one to problem , afterward find solution then write code. I have found one method when I failed the course, More accurately, When I counter problem in language , I will get more paper and then ; first, input/ output step ; my prog will take this / these there argument(s) and return namely X , ex : in c, input length is not known and at same type , so I must use pointer desired output is in form of package , so use structure second, execution part ; in that step , I am writing all step which are goes to final output ex : in python ; 1.) [ + , [- , 4 , [ * , 1 , 2 ]], 5] 2.) [ + , [- , 4 , 2 ],5 ] 3.) [ + , 2 , 5] 4.) 7 ==> return 7 third, I will write test code ex : in c++ input : append 3 4 5 6 vector_x remove 0 1 desired output vector_x holds : 5 6 But now, I wonder other method ; used to construct class :::: for c++ , python, java used to communicate classes / computers used for solving embedded system problem ::::: for c Why I wonder , because I learn if you dont costruct algorithm on paper, you may achieve your goal. Like no money no lunch , I can say no algorithm no prog therefore , feel free when you write your own method , a way which is introduced by someone else but you are using and you find it is so efficient

    Read the article

  • Most awkward/misleading method in Java Base API ?

    - by JG
    I was recently trying to convert a string literal into a boolean, when the method "boolean Boolean.getBoolean(String name)" popped out of the auto-complete window. There was also another method ("boolean Boolean.parseBoolean(String s)") appearing right after, which lead me to search to find out what were the differences between these two, as they both seemed to do the same. It turns out that what Boolean.getBoolean(String name) really does is to check if there exists a System property (!) of the given name and if its value is true. I think this is very misleading, as I'm definitely not expecting that a method of Boolean is actually making a call to System.getProperty, and just by looking at the method signature, it sure looks (at least to me) like it should be used to parse a String as a boolean. Sure, the javadoc states it clearly, but I still think the method has a misleading name and is not in the right place. Other primitive type wrappers, such as Integer also have a similar method. Also, it doesn't seem to be a very useful method to belong in the base API, as I think it's not very common to have something like -Darg=true. Maybe it's a good question for a Java position interview: "What is the output of Boolean.getBoolean("true")?". I believe a more appropriate place for those methods would be in the System class, e.g., getPropertyAsBoolean; but again, I still think it's unnecessary to have these methods in the base API. It'd make sense to have these in something like the Properties class, where it's very common to do this kind of type conversions. What do you think of all this ? Also, if there's another "awkward" method that you're aware of, please post it. N.B. I know I can use Boolean.valueOf or Boolean.parseBoolean to convert a string literal into a boolean, but I'm just looking to discuss the API design.

    Read the article

  • What are Bridge and Synthetic methods in Java?

    - by kunjaan
    Returns : true if and only if this method is a bridge method as defined by the Java Language Specification. Since: 1.5 Returns: true if and only if this method is a synthetic method as defined by the Java Language Specification. Since: 1.5 I saw these in my Reflection doc. I saw couple of docs but I couldn't fully understand the usage of them. Could Somebody expalin these methods for a layperson?

    Read the article

  • C# Is it possible to wire up an event to a method when it is finished?

    - by Martijn
    I have a .dll file and in there, there's a method called A. When I call that method I'd like to call a method of my own, method B. So my question is, is it possible to call method B immediately when method A is finished? Offcourse I can call method A and after that call method B manually. But I was wondering is there a manner to do this automatically, maybe with an event? So when method A is finished the event gets fired somehow and method A is called.

    Read the article

  • Java overloading and overriding

    - by Padmanabh
    We always say that method overloading is static polymorphism and overriding is runtime polymorphism. What exactly do we mean by static here? Is the call to a method resolved on compiling the code? So whats the difference between normal method call and calling a final method? Which one is linked at compile time?

    Read the article

  • How to generalize a method call in Java (to avoid code duplication)

    - by dln385
    I have a process that needs to call a method and return its value. However, there are several different methods that this process may need to call, depending on the situation. If I could pass the method and its arguments to the process (like in Python), then this would be no problem. However, I don't know of any way to do this in Java. Here's a concrete example. (This example uses Apache ZooKeeper, but you don't need to know anything about ZooKeeper to understand the example.) The ZooKeeper object has several methods that will fail if the network goes down. In this case, I always want to retry the method. To make this easy, I made a "BetterZooKeeper" class that inherits the ZooKeeper class, and all of its methods automatically retry on failure. This is what the code looked like: public class BetterZooKeeper extends ZooKeeper { private void waitForReconnect() { // logic } @Override public Stat exists(String path, Watcher watcher) { while (true) { try { return super.exists(path, watcher); } catch (KeeperException e) { // We will retry. } waitForReconnect(); } } @Override public byte[] getData(String path, boolean watch, Stat stat) { while (true) { try { return super.getData(path, watch, stat); } catch (KeeperException e) { // We will retry. } waitForReconnect(); } } @Override public void delete(String path, int version) { while (true) { try { super.delete(path, version); return; } catch (KeeperException e) { // We will retry. } waitForReconnect(); } } } (In the actual program there is much more logic and many more methods that I took out of the example for simplicity.) We can see that I'm using the same retry logic, but the arguments, method call, and return type are all different for each of the methods. Here's what I did to eliminate the duplication of code: public class BetterZooKeeper extends ZooKeeper { private void waitForReconnect() { // logic } @Override public Stat exists(final String path, final Watcher watcher) { return new RetryableZooKeeperAction<Stat>() { @Override public Stat action() { return BetterZooKeeper.super.exists(path, watcher); } }.run(); } @Override public byte[] getData(final String path, final boolean watch, final Stat stat) { return new RetryableZooKeeperAction<byte[]>() { @Override public byte[] action() { return BetterZooKeeper.super.getData(path, watch, stat); } }.run(); } @Override public void delete(final String path, final int version) { new RetryableZooKeeperAction<Object>() { @Override public Object action() { BetterZooKeeper.super.delete(path, version); return null; } }.run(); return; } private abstract class RetryableZooKeeperAction<T> { public abstract T action(); public final T run() { while (true) { try { return action(); } catch (KeeperException e) { // We will retry. } waitForReconnect(); } } } } The RetryableZooKeeperAction is parameterized with the return type of the function. The run() method holds the retry logic, and the action() method is a placeholder for whichever ZooKeeper method needs to be run. Each of the public methods of BetterZooKeeper instantiates an anonymous inner class that is a subclass of the RetryableZooKeeperAction inner class, and it overrides the action() method. The local variables are (strangely enough) implicitly passed to the action() method, which is possible because they are final. In the end, this approach does work and it does eliminate the duplication of the retry logic. However, it has two major drawbacks: (1) it creates a new object every time a method is called, and (2) it's ugly and hardly readable. Also I had to workaround the 'delete' method which has a void return value. So, here is my question: is there a better way to do this in Java? This can't be a totally uncommon task, and other languages (like Python) make it easier by allowing methods to be passed. I suspect there might be a way to do this through reflection, but I haven't been able to wrap my head around it.

    Read the article

  • Revisiting ANTS Performance Profiler 7.4

    - by James Michael Hare
    Last year, I did a small review on the ANTS Performance Profiler 6.3, now that it’s a year later and a major version number higher, I thought I’d revisit the review and revise my last post. This post will take the same examples as the original post and update them to show what’s new in version 7.4 of the profiler. Background A performance profiler’s main job is to keep track of how much time is typically spent in each unit of code. This helps when we have a program that is not running at the performance we expect, and we want to know where the program is experiencing issues. There are many profilers out there of varying capabilities. Red Gate’s typically seem to be the very easy to “jump in” and get started with very little training required. So let’s dig into the Performance Profiler. I’ve constructed a very crude program with some obvious inefficiencies. It’s a simple program that generates random order numbers (or really could be any unique identifier), adds it to a list, sorts the list, then finds the max and min number in the list. Ignore the fact it’s very contrived and obviously inefficient, we just want to use it as an example to show off the tool: 1: // our test program 2: public static class Program 3: { 4: // the number of iterations to perform 5: private static int _iterations = 1000000; 6: 7: // The main method that controls it all 8: public static void Main() 9: { 10: var list = new List<string>(); 11: 12: for (int i = 0; i < _iterations; i++) 13: { 14: var x = GetNextId(); 15: 16: AddToList(list, x); 17: 18: var highLow = GetHighLow(list); 19: 20: if ((i % 1000) == 0) 21: { 22: Console.WriteLine("{0} - High: {1}, Low: {2}", i, highLow.Item1, highLow.Item2); 23: Console.Out.Flush(); 24: } 25: } 26: } 27: 28: // gets the next order id to process (random for us) 29: public static string GetNextId() 30: { 31: var random = new Random(); 32: var num = random.Next(1000000, 9999999); 33: return num.ToString(); 34: } 35: 36: // add it to our list - very inefficiently! 37: public static void AddToList(List<string> list, string item) 38: { 39: list.Add(item); 40: list.Sort(); 41: } 42: 43: // get high and low of order id range - very inefficiently! 44: public static Tuple<int,int> GetHighLow(List<string> list) 45: { 46: return Tuple.Create(list.Max(s => Convert.ToInt32(s)), list.Min(s => Convert.ToInt32(s))); 47: } 48: } So let’s run it through the profiler and see what happens! Visual Studio Integration First, let’s look at how the ANTS profilers integrate with Visual Studio’s menu system. Once you install the ANTS profilers, you will get an ANTS menu item with several options: Notice that you can either Profile Performance or Launch ANTS Performance Profiler. These sound similar but achieve two slightly different actions: Profile Performance: this immediately launches the profiler with all defaults selected to profile the active project in Visual Studio. Launch ANTS Performance Profiler: this launches the profiler much the same way as starting it from the Start Menu. The profiler will pre-populate the application and path information, but allow you to change the settings before beginning the profile run. So really, the main difference is that Profile Performance immediately begins profiling with the default selections, where Launch ANTS Performance Profiler allows you to change the defaults and attach to an already-running application. Let’s Fire it Up! So when you fire up ANTS either via Start Menu or Launch ANTS Performance Profiler menu in Visual Studio, you are presented with a very simple dialog to get you started: Notice you can choose from many different options for application type. You can profile executables, services, web applications, or just attach to a running process. In fact, in version 7.4 we see two new options added: ASP.NET Web Application (IIS Express) SharePoint web application (IIS) So this gives us an additional way to profile ASP.NET applications and the ability to profile SharePoint applications as well. You can also choose your level of detail in the Profiling Mode drop down. If you choose Line-Level and method-level timings detail, you will get a lot more detail on the method durations, but this will also slow down profiling somewhat. If you really need the profiler to be as unintrusive as possible, you can change it to Sample method-level timings. This is performing very light profiling, where basically the profiler collects timings of a method by examining the call-stack at given intervals. Which method you choose depends a lot on how much detail you need to find the issue and how sensitive your program issues are to timing. So for our example, let’s just go with the line and method timing detail. So, we check that all the options are correct (if you launch from VS2010, the executable and path are filled in already), and fire it up by clicking the [Start Profiling] button. Profiling the Application Once you start profiling the application, you will see a real-time graph of CPU usage that will indicate how much your application is using the CPU(s) on your system. During this time, you can select segments of the graph and bookmark them, giving them mnemonic names. This can be useful if you want to compare performance in one part of the run to another part of the run. Notice that once you select a block, it will give you the call tree breakdown for that selection only, and the relative performance of those calls. Once you feel you have collected enough information, you can click [Stop Profiling] to stop the application run and information collection and begin a more thorough analysis. Analyzing Method Timings So now that we’ve halted the run, we can look around the GUI and see what we can see. By default, the times are shown in terms of percentage of time of the total run of the application, though you can change it in the View menu item to milliseconds, ticks, or seconds as well. This won’t affect the percentages of methods, it only affects what units the times are shown. Notice also that the major hotspot seems to be in a method without source, ANTS Profiler will filter these out by default, but you can right-click on the line and remove the filter to see more detail. This proves especially handy when a bottleneck is due to a method in the BCL. So now that we’ve removed the filter, we see a bit more detail: In addition, ANTS Performance Profiler gives you the ability to decompile the methods without source so that you can dive even deeper, though typically this isn’t necessary for our purposes. When looking at timings, there are generally two types of timings for each method call: Time: This is the time spent ONLY in this method, not including calls this method makes to other methods. Time With Children: This is the total of time spent in both this method AND including calls this method makes to other methods. In other words, the Time tells you how much work is being done exclusively in this method, and the Time With Children tells you how much work is being done inclusively in this method and everything it calls. You can also choose to display the methods in a tree or in a grid. The tree view is the default and it shows the method calls arranged in terms of the tree representing all method calls and the parent method that called them, etc. This is useful for when you find a hot-spot method, you can see who is calling it to determine if the problem is the method itself, or if it is being called too many times. The grid method represents each method only once with its totals and is useful for quickly seeing what method is the trouble spot. In addition, you can choose to display Methods with source which are generally the methods you wrote (as opposed to native or BCL code), or Any Method which shows not only your methods, but also native calls, JIT overhead, synchronization waits, etc. So these are just two ways of viewing the same data, and you’re free to choose the organization that best suits what information you are after. Analyzing Method Source If we look at the timings above, we see that our AddToList() method (and in particular, it’s call to the List<T>.Sort() method in the BCL) is the hot-spot in this analysis. If ANTS sees a method that is consuming the most time, it will flag it as a hot-spot to help call out potential areas of concern. This doesn’t mean the other statistics aren’t meaningful, but that the hot-spot is most likely going to be your biggest bang-for-the-buck to concentrate on. So let’s select the AddToList() method, and see what it shows in the source window below: Notice the source breakout in the bottom pane when you select a method (from either tree or grid view). This shows you the timings in this method per line of code. This gives you a major indicator of where the trouble-spot in this method is. So in this case, we see that performing a Sort() on the List<T> after every Add() is killing our performance! Of course, this was a very contrived, duh moment, but you’d be surprised how many performance issues become duh moments. Note that this one line is taking up 86% of the execution time of this application! If we eliminate this bottleneck, we should see drastic improvement in the performance. So to fix this, if we still wanted to maintain the List<T> we’d have many options, including: delay Sort() until after all Add() methods, using a SortedSet, SortedList, or SortedDictionary depending on which is most appropriate, or forgoing the sorting all together and using a Dictionary. Rinse, Repeat! So let’s just change all instances of List<string> to SortedSet<string> and run this again through the profiler: Now we see the AddToList() method is no longer our hot-spot, but now the Max() and Min() calls are! This is good because we’ve eliminated one hot-spot and now we can try to correct this one as well. As before, we can then optimize this part of the code (possibly by taking advantage of the fact the list is now sorted and returning the first and last elements). We can then rinse and repeat this process until we have eliminated as many bottlenecks as possible. Calls by Web Request Another feature that was added recently is the ability to view .NET methods grouped by the HTTP requests that caused them to run. This can be helpful in determining which pages, web services, etc. are causing hot spots in your web applications. Summary If you like the other ANTS tools, you’ll like the ANTS Performance Profiler as well. It is extremely easy to use with very little product knowledge required to get up and running. There are profilers built into the higher product lines of Visual Studio, of course, which are also powerful and easy to use. But for quickly jumping in and finding hot spots rapidly, Red Gate’s Performance Profiler 7.4 is an excellent choice. Technorati Tags: Influencers,ANTS,Performance Profiler,Profiler

    Read the article

  • replacing a method of a Moose object at runtime

    - by xxxxxxx
    Hi, is it possible to replace a method of a Moose object at runtime ? By looking at the source code of Class::MOP::Method(which Moose::Meta::Method inherits from) I concluded that by doing $method->{body} = sub{ my stuff } I would be able to replace at runtime a method of an object. I can get the method using $object->meta->find_method_by_name(<method_name>); However.. this didn't quite work out. Is it conceivable to modify methods at runtime ? and what is the way to do it with Moose ? Thanks

    Read the article

  • Silverlight WCF method calls fails if WCF service is not running initially

    - by Craig
    Quite simply I have a generic Silverlight 3.0 web page that is calling a Ping method on a WCF service. I do not have the WCF service running initially when I navigate to this Silverlight page. As expected I get a communication exception when I press the Silverlight button to call the Ping method, which I catch. Now if I start the WCF service and press the Ping button I still get the communication exception. How come? The other scenario is the WCF is running when I navigate to the SL page and the Ping method call works. I turn off the WCF service, ping method fails. Turn it back on and the ping method succeeds. How come if it's not running initially the ping method fails always? I could include some sample code if you'd like but this is just a real simple Hello World example using basichttpbinding, straight out the book. Thanks, Craig

    Read the article

  • Recommended method for XML level loading in XNA

    - by David Saltares Márquez
    I want to use Blender as my level designer tool for an XNA game. Using an existing plugin, I can export my levels to DotScene format which is basically an xml file like this one: <scene formatVersion="1.0.0"> <nodes> <node name="scene-staircase.001"> <position x="10.500000" y="1.400000" z="-9.600000"/> <quaternion x="0.000000" y="0.000000" z="-0.000000" w="1.000000"/> <scale x="1.000000" y="1.000000" z="1.000000"/> <entity name="scene-staircase.001" meshFile="staircase.mesh"/> </node> <node name="Lamp.003"> <position x="11.024290" y="5.903862" z="9.658987"/> <quaternion x="-0.284166" y="0.726942" z="0.342034" w="0.523275"/> <scale x="1.000000" y="1.000000" z="1.000000"/> <light name="Spot.003" type="point"> <colourDiffuse r="0.400000" g="0.154618" b="0.145180"/> <colourSpecular r="0.400000" g="0.154618" b="0.145180"/> <lightAttenuation range="5000.0" constant="1.000000" linear="0.033333" quadratic="0.000000"/> </light> </node> ... </nodes> </scene> Using naming conventions I could easily parse the file and load the correspondent in game content. I am new to XNA and I have seen that there are several methods to load XML files into a game like serializing and deserializing. Which one would you recommend?

    Read the article

  • Alternative printing method(s) for an unsupported printer

    - by B. Roland
    Hello! I have in my office, a Konica Minolta bizhub 211 multifunction printer, it works well with windows workstations... It has a lot of good features, like duplex... I haven't found any drivers for UNIX, so I'm looking for alternative methods, how can we make it useable in Ubuntu. I'm thinking on some windows based server, or what I know... I wrote here requesting for drivers: ubuntu.hu, linuxforums.org, forums.debian.net, ubuntuforums.org; and also to the manufacturer, but they said only, that "the first PostScript supported printer is only bizhub 223", so they don't care that thing. Please suggest working methods, Thanks, B. Roland

    Read the article

  • how do I know when/where to invoke the overridden method of the super class

    - by Henry
    Hi, This question occured to me while programming a Android application, but it seems to be a general programming question more. The situation is, I am extending (subclass-ing) an class from a library, and overriding a method. how do I know if I should invoke the method of super-class? and when? (in the beginning of the overridden method or in the end?) For example, I am overriding the method "public boolean onCreateOptionsMenu(Menu menu)" from class "Activity" in Android platform. And I saw someone write "return super.onCreateOptionsMenu(menu)" in the end of the method, in an example. But how do I know it should be done this way? and it is correct or not? what's the difference if I begin my method with "super.onCreateOptionsMenu(menu)"? BR, Henry

    Read the article

< Previous Page | 14 15 16 17 18 19 20 21 22 23 24 25  | Next Page >