Search Results

Search found 31989 results on 1280 pages for 'method'.

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

  • method implementation for this case in Java

    - by Thomas
    Hello, I just saw a code snippet like this: private static class DefaultErrorHandler<RT> implements ErrorHandler<RT> { public RT handle(Object[] params, Throwable e) { return Exceptions.throwUncheckedException(e); } Now I am wondering what the static method "throwUncheckedException (Throwable e)" would return exactly and how it might be implemented regarding the generics. Can anybody give me an example ?

    Read the article

  • When is a parameterized method call useful?

    - by johann-christoph-jacob
    A Java method call may be parameterized like in the following code: class Test { <T> void test() { } public static void main(String[] args) { new Test().<Object>test(); // ^^^^^^^^ } } I found out this is possible from the Eclipse Java Formatter settings dialog and wondered if there are any cases where this is useful or required.

    Read the article

  • How to use method hiding (new) with generic constrained class

    - by ongle
    I have a container class that has a generic parameter which is constrained to some base class. The type supplied to the generic is a sub of the base class constraint. The sub class uses method hiding (new) to change the behavior of a method from the base class (no, I can't make it virtual as it is not my code). My problem is that the 'new' methods do not get called, the compiler seems to consider the supplied type to be the base class, not the sub, as if I had upcast it to the base. Clearly I am misunderstanding something fundamental here. I thought that the generic where T: xxx was a constraint, not an upcast type. This sample code basically demonstrates what I'm talking about. using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace GenericPartialTest { class ContextBase { public string GetValue() { return "I am Context Base: " + this.GetType().Name; } public string GetOtherValue() { return "I am Context Base: " + this.GetType().Name; } } partial class ContextSub : ContextBase { public new string GetValue() { return "I am Context Sub: " + this.GetType().Name; } } partial class ContextSub { public new string GetOtherValue() { return "I am Context Sub: " + this.GetType().Name; } } class Container<T> where T: ContextBase, new() { private T _context = new T(); public string GetValue() { return this._context.GetValue(); } public string GetOtherValue() { return this._context.GetOtherValue(); } } class Program { static void Main(string[] args) { Console.WriteLine("Simple"); ContextBase myBase = new ContextBase(); ContextSub mySub = new ContextSub(); Console.WriteLine(myBase.GetValue()); Console.WriteLine(myBase.GetOtherValue()); Console.WriteLine(mySub.GetValue()); Console.WriteLine(mySub.GetOtherValue()); Console.WriteLine("Generic Container"); Container<ContextBase> myContainerBase = new Container<ContextBase>(); Container<ContextSub> myContainerSub = new Container<ContextSub>(); Console.WriteLine(myContainerBase.GetValue()); Console.WriteLine(myContainerBase.GetOtherValue()); Console.WriteLine(myContainerSub.GetValue()); Console.WriteLine(myContainerSub.GetOtherValue()); Console.ReadKey(); } } }

    Read the article

  • How to invoke a method of js object after invoking another method?

    - by Unitpage
    I often saw this code in jQuery. $('div').action1().delay(miliseconds).action2(); I could realize it in one level action in the following code. function $(id) { var $ = document.getElementById(id); $.action1 = function() { }; return $; } How to write the method delay() and action2() so that I could use them this way? $('div').action1().delay(miliseconds).action2();

    Read the article

  • Rhino Mocks verify a private method is called from a public method

    - by slowcelica
    I have been trying to figure this one out, how do i test that a private method is called with rhino mocks with in the class that I am testing. So my class would be something like this. Public class Foo { public bool DoSomething() { if(somevalue) { //DoSomething; } else { ReportFailure("Failure"); } } private void ReportFailure(string message) { //DoSomeStuff; } } So my unit test is on class Foo and method DoSomething() I want to check and make sure that a certain message is passed to ReportFailure if somevalue is false, using rhino mocks.

    Read the article

  • Overload method (specifically drawRect:) without subclassing.

    - by SooDesuNe
    I'm using a container UIView to house a UIImageView and do some custom drawing. At this point I'd like to do some drawing on top of my subview. So overriding drawRect: in my container UIView will only draw below the subviews. Is there a way to overload drawRect: in my subview without subclassing it? I think method swizzling may be the answer, but I'm hoping not. (NOTE: yes, it would have been smarter to have the UIView be the subview of the UIImageView, but unfortunately I'm committed to my mistake now.)

    Read the article

  • Qt undocumented method setSharable

    - by soxs060389
    I stumbled about a method which seems to be present in all DataObjects like QList, QQueue, QHash... I even investigated so far i can see the source code of it, which is inline void setSharable(bool sharable) { if (!sharable) detach(); d->sharable = sharable; } in qlist.h (lines 117) but what effect does it have on the QList, QQueue, QHash... ? And is it in any way related to threading? (which sounds reasonable) Thanks for any answer, and please only answer if you got actual knowledge.

    Read the article

  • Ruby delete method (string manipulation)

    - by brianheys
    I'm new to Ruby, and have been working my way through Mr Neighborly's Humble Little Ruby Guide. There have been a few typos in the code examples along the way, but I've always managed to work out what's wrong and subsequently fix it - until now! This is really basic, but I can't get the following example to work on Mac OS X (Snow Leopard): gone = "Got gone fool!" puts "Original: " + gone gone.delete!("o", "r-v") puts "deleted: " + gone Output I'm expecting is: Original: Got gone fool! deleted: G gne fl! Output I actually get is: Original: Got gone fool! deleted: Got gone fool! The delete! method doesn't seem to have had any effect. Can anyone shed any light on what's going wrong here? :-\

    Read the article

  • Why C# calls different overloaded method for different values of same type?

    - by Fabio Veronez
    Hello all, I have one doubt concerning c# method overloading call resolution. Let's suppose I have the following C# code: enum MyEnum { Value1, Value2 } public void test() { method(0); // this calls method(MyEnum) method(1); // this calls method(object) } public void method(object o) { } public void method(MyEnum e) { } Note that I know how to make it work but I would like to know why for one value of int (0) it calls one method and for another (1) it calls another. It sounds awkward since both values have the same type (int) but they are "linked" for different methods. Ps.: This is my first question here, i'm sorry if I made something wrong. =P

    Read the article

  • Naming Suggestions For A Function Providing 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

  • Define Instance Variable Outside of Method Defenition (ruby)

    - by Ell
    Hi all, I am developing (well, trying to at least) a Game framework for the Ruby Gosu library. I have made a basic event system wherebye each Blocks::Event has a list of handlers and when the event is fired the methods are called. At the moment the way to implement an event is as follows: class TestClass attr_accessor :on_close def initialize @on_close = Blocks::Event.new end def close @on_close.fire(self, Blocks::OnCloseArgs.new) end end But this method of implementing events seems rather long, my question is, how can I make a way so that when one wants an event in a class, they can just do this class TestClass event :on_close def close @on_close.fire(self, Blocks::OnCloseArgs.new) end end Thanks in advance, ell.

    Read the article

  • c# Generic overloaded method dispatching ambiguous

    - by sebgod
    Hello, I just hit a situation where a method dispatch was ambiguous and wondered if anyone could explain on what basis the compiler (.NET 4.0.30319) chooses what overload to call interface IfaceA { } interface IfaceB<T> { void Add(IfaceA a); T Add(T t); } class ConcreteA : IfaceA { } class abstract BaseClassB<T> : IfaceB<T> { public virtual T Add(T t) { ... } public virtual void Add(IfaceA a) { ... } } class ConcreteB : BaseClassB<IfaceA> { // does not override one of the relevant methods } void code() { var concreteB = new ConcreteB(); // it will call void Add(IfaceA a) concreteB.Add(new ConcreteA()); } In any case, why does the compiler not warn me or even why does it compile? Thank you very much for any answers.

    Read the article

  • how do I send stuff to method using the JQuery Ajax method

    - by nisardotnet
    $.ajax({ type: "POST", url: "WebService.asmx/AddVisitor", data: "{'fname':'dave', 'lname':'ward'}", contentType: "application/json; charset=utf-8", dataType: "json" }); I have an Asp.Net WebMethod that takes a firstName, lastName.....as a parameter, how do I send that stuff to that method using the JQuery Ajax method. if i hardcode the above it works without any problem but if i pass dynamic it fails var firstName = $("[id$='txtFirstName']"); var lastName = $("[id$='txtLastName']"); //data: "{'firstName':'Chris','lastName':'Brandsma'}"<br> data: "{'firstname':'" + escape(firstName.val()) + "','lastName':'" + escape(lastName.val()) + "'}", my WebMethod looks like this [WebMethod] public bool AddVisitor(string firstName, string lastName) { return true; } what wrong here? i have tried with eval and escape none of that works. Thanks for any help.

    Read the article

  • Segfault when calling a method c++

    - by shuttle87
    I am fairly new to c++ and I am a bit stumped by this problem. I am trying to assign a variable from a call to a method in another class but it always segfaults. My code compiles with no warnings and I have checked that all variables are correct in gdb but the function call itself seems to cause a segfault. The code I am using is roughly like the following: class History{ public: bool test_history(); }; bool History::test_history(){ std::cout<<"test"; //this line never gets executed //more code goes in here return true; } class Game{ private: bool some_function(); public: History game_actions_history; bool local_variable; }; bool Game::some_function(){ local_variable = game_actions_history.test_history(); if (local_variable == true){ return true; } else{ return false; } } Any tips or advice is greatly appreciated!

    Read the article

  • How to replace a codebehind method with an aspx method using ternary operator

    - by user466663
    I have an asp:hyperlink control as part of a gridview template. The code in the aspx page is given below: asp:HyperLink runat="server" ID="lnkEdit" ToolTip="Edit article" NavigateUrl='<%# GetUrl(Eval("ID").ToString(), Eval("CategoryID").ToString()) %' ImageUrl="~/Images/Edit.gif" The NavigateUrl value is obtained from the codebehind method GetUrl(string, string). The code works fine and is as follows: protected string GetUrl(string id, string categoryID) { var CategoryID = string.Empty; if (!String.IsNullOrEmpty(Request.QueryString["CatID"])) { CategoryID = Request.QueryString["CatID"].ToString(); } else if (!String.IsNullOrEmpty(categoryID)) { CategoryID = categoryID; } return "~/TBSArticles/WriteOrEditArticle.aspx?ID=" + id + "&CatID=" + CategoryID; } I want to replace the code behind method by using a ternary operator within the aspx page. I tried something like below, but didn't work: asp:HyperLink runat="server" ID="lnkEdit" ToolTip="Edit article" NavigateUrl='<%# "~/TBSArticles/WriteOrEditArticle.aspx?ID=" + Eval("ID") + "&CatID=" + Eval(this.Request.QueryString["CatID"].ToString()) != ""? this.Request.QueryString["CatID"] : Eval("CategoryID")) %' ImageUrl="~/Images/Edit.gif" Any help will be greatly appreciated. Thanks

    Read the article

  • Method overloading in groovy

    - by slojo
    I am trying to take advantage of the convenience of groovy's scripting syntax to assign properties, but having trouble with a specific case. I must be missing something simple here. I define class A, B, C as so: class A { A() { println "Constructed class A!" } } class B { B() { println "Constructed class B!" } } class C { private member C() { println "Constructed class C!" } def setMember(A a) { println "Called setMember(A)!" member = a } def setMember(B b) { println "Called setMember(B)!" member = b } } And then try the following calls in a script: c = new C() c.setMember(new A()) // works c.member = new A() // works c.setMember(new B()) // works c.member = new B() // doesn't work! The last assignment results in an error: 'Cannot cast object of class B to class A". Why doesn't it call the proper setMember method for class B like it does for class A?

    Read the article

  • Reference to an instance method of a particular object

    - by Andrey
    In the following code, if i try to pass method reference using the class name, works. But passing the reference variable compiler gives an error, i do not understand why? public class User { private String name; public User(String name) { this.name = name; } public void printName() { System.out.println(name); } } public class Main { public static void main(String[] args) { User u1 = new User("AAA"); User u2 = new User("BBB"); User u3 = new User("ZZZ"); List<User> userList = Arrays.asList(u1, u2, u3); userList.forEach(User::printName); // works userList.forEach(u1::printName); // compile error } } Thanks,

    Read the article

  • Why doesn't this method print its text? (java)

    - by David
    here's the method: public static int chooseStrat () { String[] strats = new String[1] ; strats[0] = "0 - Blob" ; int n ; boolean a = false ; while (a == false) ; { System.out.println ("Which strategy should the AI use?(#)") ; printArrayS (strats) ; n = getInt () ; System.out.println ("you selected "+n+"."+" are you sure you want the computer to use the "+ strats[n]+ " ?(Y/N)") ; String c = getIns () ; while ((((!( (c.equals ("y")) || (c.equals ("Y")) )) && (!( (c.equals ("n")) || (c.equals ("N")) ) ) ))) ; { System.out.println ("try again") ; c = getIns () ; } if ( (c.equals ("Y")) || (c.equals ("y")) ) a = true ; } return n ; } When i run this it never prints "Which strategy should the AI use?(#)" it just tries to get an entry from the keyboard. why does it do this?

    Read the article

  • Factory Method Implementation

    - by cedar715
    I was going through the 'Factory method' pages in SO and had come across this link. And this comment. The example looked as a variant and thought to implement in its original way: to defer instantiation to subclasses... Here is my attempt. Does the following code implements the Factory pattern of the example specified in the link? Please validate and suggest if this has to undergo any re-factoring. public class ScheduleTypeFactoryImpl implements ScheduleTypeFactory { @Override public IScheduleItem createLinearScheduleItem() { return new LinearScheduleItem(); } @Override public IScheduleItem createVODScheduleItem() { return new VODScheduleItem(); } } public class UseScheduleTypeFactory { public enum ScheduleTypeEnum { CableOnDemandScheduleTypeID, BroadbandScheduleTypeID, LinearCableScheduleTypeID, MobileLinearScheduleTypeID } public static IScheduleItem getScheduleItem(ScheduleTypeEnum scheduleType) { IScheduleItem scheduleItem = null; ScheduleTypeFactory scheduleTypeFactory = new ScheduleTypeFactoryImpl(); switch (scheduleType) { case CableOnDemandScheduleTypeID: scheduleItem = scheduleTypeFactory.createVODScheduleItem(); break; case BroadbandScheduleTypeID: scheduleItem = scheduleTypeFactory.createVODScheduleItem(); break; case LinearCableScheduleTypeID: scheduleItem = scheduleTypeFactory.createLinearScheduleItem(); break; case MobileLinearScheduleTypeID: scheduleItem = scheduleTypeFactory.createLinearScheduleItem(); break; default: break; } return scheduleItem; } }

    Read the article

  • By using " editingStyleForRowAtIndexPath " method , " didSelectRowAtIndexPath " method is not calle

    - by Madan Mohan
    Hi, the delegate method not called -(void)viewWillAppear:(BOOL)animated { [theTableView setEditing:TRUE animated:TRUE]; } -(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath { return UITableViewCellEditingStyleDelete; } by calling the above the methods i will get minus component before each cell in table view. But the below method didSelectRowAtIndexPath is not called and disclouser indicator is not in visible. (void )tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [theTableView deselectRowAtIndexPath:indexPath animated:YES]; ContactEditViewCotroller *contactEditViewCotroller=[[ContactEditViewCotroller alloc]init]; contactEditViewCotroller.isEdit=isEdit; if(isEdit == YES) { for(int i=0; i<=[editObject.contactList count]-1;i++) { if(indexPath.section == i) { appDelegate.isAddInEdit=NO; editcontacts = [editObject.contactList objectAtIndex:i]; contactEditViewCotroller.editcontacts=editcontacts; indexRow=i; } } } else { for(int i=0; i<=[addContactList count]-1;i++) { if(indexPath.section == i) { appDelegate.isAddInEdit=NO; Contacts *obj = [addContactList objectAtIndex:i]; contactEditViewCotroller.addcontacts=obj; } } } [[self navigationController] pushViewController:contactEditViewCotroller animated:YES]; [contactEditViewCotroller release]; }

    Read the article

  • java Finalize method call

    - by Rajesh Kumar J
    The following is my Class code import java.net.*; import java.util.*; import java.sql.*; import org.apache.log4j.*; class Database { private Connection conn; private org.apache.log4j.Logger log ; private static Database dd=new Database(); private Database(){ try{ log= Logger.getLogger(Database.class); Class.forName("com.mysql.jdbc.Driver"); conn=DriverManager.getConnection("jdbc:mysql://localhost/bc","root","root"); conn.setReadOnly(false); conn.setAutoCommit(false); log.info("Datbase created"); /*Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); conn=DriverManager.getConnection("jdbc:odbc:rmldsn"); conn.setReadOnly(false); conn.setAutoCommit(false);*/ } catch(Exception e){ log.info("Cant Create Connection"); } } public static Database getDatabase(){ return dd; } public Connection getConnection(){ return conn; } @Override protected void finalize()throws Throwable { try{ conn.close(); Runtime.getRuntime().gc(); log.info("Database Close"); } catch(Exception e){ log.info("Cannot be closed Database"); } finally{ super.finalize(); } } } This can able to Initialize Database Object only through getDatabase() method. The below is the program which uses the single Database connection for the 4 threads. public class Main extends Thread { public static int c=0; public static int start,end; private int lstart,lend; public static Connection conn; public static Database dbase; public Statement stmt,stmtEXE; public ResultSet rst; /** * @param args the command line arguments */ static{ dbase=Database.getDatabase(); conn=dbase.getConnection(); } Main(String s){ super(s); try{ stmt=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); start=end; lstart=start; end=end+5; lend=end; System.out.println("Start -" +lstart +" End-"+lend); } catch(Exception e){ e.printStackTrace(); } } @Override public void run(){ try{ URL url=new URL("http://localhost:8084/TestWeb/"); rst=stmt.executeQuery("SELECT * FROM bc.cdr_calltimestamp limit "+lstart+","+lend); while(rst.next()){ try{ rst.updateInt(2, 1); rst.updateRow(); conn.commit(); HttpURLConnection httpconn=(HttpURLConnection) url.openConnection(); httpconn.setDoInput(true); httpconn.setDoOutput(true); httpconn.setRequestProperty("Content-Type", "text/xml"); //httpconn.connect(); String reqstring="<?xml version=\"1.0\" encoding=\"US-ASCII\"?>"+ "<message><sms type=\"mt\"><destination messageid=\"PS0\"><address><number" + "type=\"international\">"+ rst.getString(1) +"</number></address></destination><source><address>" + "<number type=\"unknown\"/></address></source><rsr type=\"success_failure\"/><ud" + "type=\"text\">Hello World</ud></sms></message>"; httpconn.getOutputStream().write(reqstring.getBytes(), 0, reqstring.length()); byte b[]=new byte[httpconn.getInputStream().available()]; //System.out.println(httpconn.getContentType()); httpconn.getInputStream().read(b); System.out.println(Thread.currentThread().getName()+new String(" Request"+rst.getString(1))); //System.out.println(new String(b)); httpconn.disconnect(); Thread.sleep(100); } catch(Exception e){ e.printStackTrace(); } } System.out.println(Thread.currentThread().getName()+" "+new java.util.Date()); } catch(Exception e){ e.printStackTrace(); } } public static void main(String[] args) throws Exception{ System.out.println(new java.util.Date()); System.out.println("Memory-before "+Runtime.getRuntime().freeMemory()); Thread t1=new Main("T1-"); Thread t2=new Main("T2-"); Thread t3=new Main("T3-"); Thread t4=new Main("T4-"); t1.start(); t2.start(); t3.start(); t4.start(); System.out.println("Memory-after "+Runtime.getRuntime().freeMemory()); } } I need to Close the connection after all the threads gets executed. Is there any good idea to do so. Kindly help me out in getting this work.

    Read the article

  • Should main method be only consists of object creations and method calls?

    - by crucified soul
    A friend of mine told me that, the best practice is class containing main method should be named Main and only contains main method. Also main method should only parse inputs, create other objects and call other methods. The Main class and main method shouldn't do anything else. Basically what he is saying that class containing main method should be like: public class Main { public static void main(String[] args) { //parse inputs //create other objects //call methods } } Is it the best practice?

    Read the article

  • No Method Error Undefined method 'save' for nil:NilClass

    - by BennyB
    I'm getting this error when i try to create a "Lecture" via my Lecture controller's create method. This used to work but i went on to work on other parts of the app & then of course i come back & something is now throwing this error when a user tries to create a Lecture in my app. I'm sure its something small i'm just overlooking (been at it a while & probably need to take a break)...but I'd appreciate if someone could let me know why this is happening...let me know if i need to post anything else...thx! The error I get NoMethodError in LecturesController#create undefined method `save' for nil:NilClass Rails.root: /Users/name/Sites/rails_projects/app_name Application Trace | Framework Trace | Full Trace app/controllers/lectures_controller.rb:13:in `create' My view to create a new Lecture views/lectures/new.html.erb <% provide(:title, 'Start a Lecture') %> <div class="container"> <div class="content-wrapper"> <h1>Create a Lecture</h1> <div class="row"> <div class="span 6 offset3"> <%= form_for(@lecture) do |f| %> <%= render 'shared/error_messages', :object => f.object %> <div class="field"> <%= f.text_field :title, :placeholder => "What will this Lecture be named?" %> <%= f.text_area :content, :placeholder => "Describe this Lecture & what will be learned..." %> </div> <%= f.submit "Create this Lecture", :class => "btn btn-large btn-primary" %> <% end %> </div> </div> </div> </div> Then my controller where its saying the error is coming from controllers/lectures_controller.rb class LecturesController < ApplicationController before_filter :signed_in_user, :only => [:create, :destroy] before_filter :correct_user, :only => :destroy def index end def new @lecture = current_user.lectures.build if signed_in? end def create if @lecture.save flash[:success] = "Lecture created!" redirect_to @lecture else @activity_items = [ ] render 'new' end end def show @lecture = Lecture.find(params[:id]) end def destroy @lecture.destroy redirect_to root_path end private def correct_user @lecture = current_user.lectures.find_by_id(params[:id]) redirect_to root_path if @lecture.nil? end

    Read the article

  • Question regarding the method local innerclasses accesing the local variables of the method

    - by flash
    Hi I was going through the SCJP book about the innerclasses, and found this statement, it goes something like this. "A method local class can only refer to the local variables which are marked final" and in the explanation the reason specified is about the scope and lifetime of the local class object and the local variables on the heap, But I am unable to understand that.am I missing anything here about 'final'??

    Read the article

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