Search Results

Search found 1626 results on 66 pages for 'age'.

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

  • Use reflection to get the value of a property by name in a class instance

    - by TheMoot
    Lets say I have class Person { public Person(int age, string name) { Age = age; Name = name; } public int Age{get;set} public string Name{get;set} } and I would like to create a method that accepts a string that contains either "age" or "name" and returns an object with the value of that property. Like the following pseudo code: public object GetVal(string propName) { return <propName>.value; } How can I do this using reflection? I am coding using asp.net 3.5, c# 3.5

    Read the article

  • How to iterate a list inside a list in java?

    - by user2142786
    Hi i have two value object classes . package org.array; import java.util.List; public class Father { private String name; private int age ; private List<Children> Childrens; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public List<Children> getChildrens() { return Childrens; } public void setChildrens(List<Children> childrens) { Childrens = childrens; } } second is for children package org.array; public class Children { private String name; private int age ; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } and i want to print there value i nested a list inside a list here i am putting only a single value inside the objects while in real i have many values . so i am nesting list of children inside father list. how can i print or get the value of child and father both. here is my logic. package org.array; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class ArrayDemo { public static void main(String[] args) { List <Father> fatherList = new ArrayList<Father>(); Father father = new Father(); father.setName("john"); father.setAge(25); fatherList.add(father); List <Children> childrens = new ArrayList<Children>(); Children children = new Children(); children.setName("david"); children.setAge(2); childrens.add(children); father.setChildrens(childrens); fatherList.add(father); Iterator<Father> iterator = fatherList.iterator(); while (iterator.hasNext()) { System.out.println(iterator.toString()); } } }

    Read the article

  • What parts of a motherboard age, and how can I choose one with the longest possible life?

    - by Robert Harvey
    I have a home-built computer that's probably about four years old. I realize this probably seems ancient to some folks, but computers have no moving parts (except the fans), so theoretically they should last a long time, if I still have software to run on them. A few weeks ago, it began blue-screening and freezing up, with various error messages. It almost always happened about five minutes after startup. I assumed that the video card was overheating, since the cheap little fan on the heatsink died, so I replaced it. Long story short, after upgrading the video drivers a couple of times and performing some other troubleshooting, I remembered that the last time this happened, I took out the memory SIMS and cleaned the contacts with a gum eraser, so I did that again (noting that the SATA cables were very close to the chips on the SIMS). I re-routed the cables and reinstalled the SIMS. So far, so good; the machine has been trouble-free since. But blue-screens are distressing; I never know what bits are being chewed up in my OS installation when something like this happens. So I'm wondering if I'm choosing my components properly. If it matters, it's an Intel D915GAG motherboard and Corsair memory, but what I'm wondering is, should I be looking for certain characteristics when I choose these parts for my next computer, so that I can avoid this problem in my next build?

    Read the article

  • How can I accurately determine the age of a hard drive?

    - by Todd Stout
    Yes, if it's large, heavy, and only 65 Meg in capacity, you can assume it's ancient. An RLL controller would positively indicate the drive is from antiquity. What about drives that are only 3 or 4 years old? If I know the serial number, make and model is there a public database that indicates a manufacturing date? Update: As trite as this question might seem to some, the hard drive I was looking at that precipitated this question had no obvious manufacturing date stamped on it. I realize that most do. I think the answers given are very useful to myself and others.

    Read the article

  • Which LINQ expression is faster

    - by Vlad Bezden
    Hi All In following code public class Person { public string Name { get; set; } public uint Age { get; set; } public Person(string name, uint age) { Name = name; Age = age; } } void Main() { var data = new List<Person>{ new Person("Bill Gates", 55), new Person("Steve Ballmer", 54), new Person("Steve Jobs", 55), new Person("Scott Gu", 35)}; // 1st approach data.Where (x => x.Age > 40).ToList().ForEach(x => x.Age++); // 2nd approach data.ForEach(x => { if (x.Age > 40) x.Age++; }); data.ForEach(x => Console.WriteLine(x)); } in my understanding 2nd approach should be faster since it iterates through each item once and first approach is running 2 times: Where clause ForEach on subset of items from where clause. However internally it might be that compiler translates 1st approach to the 2nd approach anyway and they will have the same performance. Any suggestions or ideas? I could do profiling like suggested, but I want to understand what is going on compiler level if those to lines of code are the same to the compiler, or compiler will treat it literally. Thanks in advance for your help.

    Read the article

  • org.hibernate.PropertyNotFoundException

    - by niru
    hi i am new to hibernate, i m using the following code and getting the following error public class OperProfile { private String empId; private long age; private String name; public long getAge() { return age; } public void setAge(long age) { this.age = age; } public String getEmpId() { return empId; } public void setEmpId(String empId) { this.empId = empId; } public String getName() { return name; } public void setName(String name) { this.name = name; } } i am getting this error org.hibernate.PropertyNotFoundException: Could not find a getter for age in class com.fmr.OperProfile my hbm.xml file is <hibernate-mapping> <class name="com.fmr.OperProfile" table="EMPLOYEE" dynamic-update="true"> <id name="empId" type="java.lang.String" column="EMP_ID"> <generator class="assigned" /> </id> <property name="name" type="java.lang.String" column="NAME"/> <property name=" age" type="java.lang.Long" column="AGE" not-null="true" /> <property name="address1" type="java.lang.String" column="ADDRESS1" /> <property name="address2" type="java.lang.String" column="ADDRESS2" /> <property name="city" type="java.lang.String" column="CITY" /> <property name="state" type="java.lang.String" column="STATE" /> <property name="pincode" type="java.lang.Long" column="PINCODE" /> </class> </hibernate-mapping> please can anyone help me

    Read the article

  • How to get the age from a birthdate using PHP & MySQL?

    - by TaG
    I ask my users for their birthdate and store it in my database in the following way $month $day $year output May 6 1901 but I was wondering how can I get the age from the stored birthdate using PHP & MySQL? Here is the PHP code. if (isset($_POST['submitted'])) { $mysqli = mysqli_connect("localhost", "root", "", "sitename"); $dbc = mysqli_query($mysqli,"SELECT users.* FROM users WHERE user_id=3"); $month_options = array("Month", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"); $day_options = array("Day", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"); $month = mysqli_real_escape_string($mysqli, htmlentities(strip_tags($_POST['month']))); $day = mysqli_real_escape_string($mysqli, htmlentities(strip_tags($_POST['day']))); $year = mysqli_real_escape_string($mysqli, htmlentities(strip_tags($_POST['year']))); if (mysqli_num_rows($dbc) == 0) { $mysqli = mysqli_connect("localhost", "root", "", "sitename"); $dbc = mysqli_query($mysqli,"INSERT INTO users (user_id, month, day, year) VALUES ('$user_id', '$month', '$day', '$year')"); } if ($dbc == TRUE) { $dbc = mysqli_query($mysqli,"UPDATE users SET month = '$month', day = '$day', year = '$year' WHERE user_id = '$user_id'"); echo '<p class="changes-saved">Your changes have been saved!</p>'; } if (!$dbc) { print mysqli_error($mysqli); return; } } Here is the html. <form method="post" action="index.php"> <fieldset> <ul> <li><label>Date of Birth: </label> <label for="month" class="hide">Month: </label> <?php // month options echo '<select name="month" id="month">' . "\n"; foreach($month_options as $option) { if ($option == $month) { echo '<option value="' . stripslashes(htmlentities(strip_tags($option))) . '" selected="selected">' . stripslashes(htmlentities(strip_tags($option))) . '</option>' . "\n"; } else { echo '<option value="'. stripslashes(htmlentities(strip_tags($option))) . '">' . stripslashes(htmlentities(strip_tags($option))) . '</option>'."\n"; } } echo '</select>'; ?> <label for="day" class="hide">Day: </label> <?php // day options echo '<select id="day" name="day">' . "\n"; foreach($day_options as $option) { if ($option == $day) { echo '<option value="' . stripslashes(htmlentities(strip_tags($option))) . '" selected="selected">' . stripslashes(htmlentities(strip_tags($option))) . '</option>' . "\n"; } else { echo '<option value="'. stripslashes(htmlentities(strip_tags($option))) . '">' . stripslashes(htmlentities(strip_tags($option))) . '</option>'."\n"; } } echo '</select>'; ?> <label for="year" class="hide">Year: </label><input type="text" name="year" id="year" size="4" maxlength="4" value="<?php if (isset($_POST['year'])) { echo stripslashes(htmlentities(strip_tags($_POST['year']))); } else if(!empty($year)) { echo stripslashes(htmlentities(strip_tags($year))); } ?>" /></li> <li><input type="submit" name="submit" value="Save Changes" class="save-button" /> <input type="hidden" name="submitted" value="true" /> <input type="submit" name="submit" value="Preview Changes" class="preview-changes-button" /></li> </ul> </fieldset> </form>

    Read the article

  • How to pass object from one activity to another in android

    - by kaibuki
    Hi I am trying to work on sending an object of my "Customer" class from one activity and display on other activity. the code for the customer class : `package com.kaibuki; public class Customer { private String firstName, lastName, Address; int Age; public Customer(String fname, String lname, int age, String address) { firstName = fname; lastName = lname; Age = age; Address = address; } public String printValues() { String data = null; data = "First Name :" + firstName + " Last Name :" + lastName + " Age : " + Age + " Address : " + Address; return data; } } I want to send its object from one activity to another and then display the data on the other activity. Please need urgent help. Thanks alot Kai`

    Read the article

  • How to override equals method in java

    - by Subash Adhikari
    I am trying to override equals method in java. I have a class People which basically has 2 data fields name and age. Now I want to override equals method so that I can check between 2 People objects. My code is as follows public boolean equals(People other){ boolean result; if((other == null) || (getClass() != other.getClass())){ result = false; } // end if else{ People otherPeople = (People)other; result = name.equals(other.name) && age.equals(other.age); } // end else return result; } // end equals But when I write age.equals(other.age) it gives me error as equals method can only compare String and age is Integer. Please help me fix this. Thanks is Advance.

    Read the article

  • Making CSV from PHP - Carriage return won't work

    - by DMin
    Seems like a fairly simple issue but can't get it to work. I am getting the user to download a csv file(which works fine). Basically I can't get the carriage return to work. header("Content-type: text/x-csv"); header("Content-Disposition: attachment; filename=search_results.csv"); echo '"Name","Age"\n"Chuck Norris","70"'; exit; Result : Name     Age\n"Chuck Norris"    70 Tried : echo '"Name","Age",\n,"Chuck Norris","70"'; Result : Name     Age    \n    Chuck Norris    70 And echo '"Name","Age",\n\r,"Chuck Norris","70"'; Result : Name     Age    \n\r    Chuck Norris    70 Know what's going wrong?

    Read the article

  • How to give an error when no options are given with optparse

    - by Acorn
    I'm try to work out how to use optparse, but I've come to a problem. My script (represented by this simplified example) takes a file, and does different things to it depending on options that are parsed to it. If no options are parsed nothing is done. It makes sense to me that because of this, an error should be given if no options are given by the user. I can't work out how to do this. Am I using options in the wrong way? If so, how should I be doing it instead? #!/usr/bin/python from optparse import OptionParser dict = {'name': foo, 'age': bar} parser = OptionParser() parser.add_option("-n", "--name", dest="name") parser.add_option("-a", "--age", dest="age") (options, args) = parser.parse_args() if options.name: dict['name'] = options.name if options.age: dict['age'] = options.age print dict #END

    Read the article

  • Hibernate error: cannot resolve table

    - by Roman
    I'm trying to make work the example from hibernate reference. I've got simple table Pupil with id, name and age fields. I've created correct (as I think) java-class for it according to all java-beans rules. I've created configuration file - hibernate.cfg.xml, just like in the example from reference. I've created hibernate mapping for one class Pupil, and here is the error occured. <hibernate-mapping> <class name="Pupil" table="pupils"> ... </class> </hibernate-mapping> table="pupils" is red in my IDE and I see message "cannot resolve table pupils". I've also founded very strange note in reference which says that most users fail with the same problem trying to run the example. Ah.. I'm very angry with this example.. IMHO if authors know that there is such problem they should add some information about it. But, how should I fix it? I don't want to deal with Ant here and with other instruments used in example. I'm using MySql 5.0, but I think it doesn't matter. UPD: source code Pupil.java - my persistent class package domain; public class Pupil { private Integer id; private String name; private Integer age; protected Pupil () { } public Pupil (String name, int age) { this.age = age; this.name = name; } public Integer getId () { return id; } public void setId (Integer id) { this.id = id; } public String getName () { return name; } public void setName (String name) { this.name = name; } public Integer getAge () { return age; } public void setAge (Integer age) { this.age = age; } public String toString () { return "Pupil [ name = " + name + ", age = " + age + " ]"; } } Pupil.hbm.xml is mapping for this class <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="domain" > <class name="Pupil" table="pupils"> <id name="id"> <generator class="native" /> </id> <property name="name" not-null="true"/> <property name="age"/> </class> </hibernate-mapping> hibernate.cfg.xml - configuration for hibernate <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost/hbm_test</property> <property name="connection.username">root</property> <property name="connection.password">root</property> <property name="connection.pool_size">1</property> <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property> <property name="current_session_context_class">thread</property> <property name="show_sql">true</property> <mapping resource="domain/Pupil.hbm.xml"/> </session-factory> </hibernate-configuration> HibernateUtils.java package utils; import org.hibernate.SessionFactory; import org.hibernate.HibernateException; import org.hibernate.cfg.Configuration; public class HibernateUtils { private static final SessionFactory sessionFactory; static { try { sessionFactory = new Configuration ().configure ().buildSessionFactory (); } catch (HibernateException he) { System.err.println (he); throw new ExceptionInInitializerError (he); } } public static SessionFactory getSessionFactory () { return sessionFactory; } } Runner.java - class for testing hibernate import org.hibernate.Session; import java.util.*; import utils.HibernateUtils; import domain.Pupil; public class Runner { public static void main (String[] args) { Session s = HibernateUtils.getSessionFactory ().getCurrentSession (); s.beginTransaction (); List pups = s.createQuery ("from Pupil").list (); for (Object obj : pups) { System.out.println (obj); } s.getTransaction ().commit (); HibernateUtils.getSessionFactory ().close (); } } My libs: antlr-2.7.6.jar, asm.jar, asm-attrs.jar, cglib-2.1.3.jar, commons-collections-2.1.1.jar, commons-logging-1.0.4.jar, dom4j-1.6.1.jar, hibernate3.jar, jta.jar, log4j-1.2.11.jar, mysql-connector-java-5.1.7-bin.jar Compile error: cannot resolve table pupils

    Read the article

  • Making a textfile into a list in matlab?

    - by Ben Fossen
    I have a textfile and would like to import it onto Matlab and make it a list Person1 name = steven grade = 11 age= 17 Person2 name = mike grade = 9 age= 15 Person3 name = taylor grade = 11 age= 17 There are a few hundred entries like these above. Each are seperated by a blank line I was thinking I could scan the text and make the information between each blank line into an item in the list. I also would like to be able to look up each person by name once I have a list like the one below. I want something like x = [Person1 Person2 Person3 name = steven name = mike name = taylor grade = 11 grade = 9 grade = 11 age = 17 age = 15 age = 17] This seems very straight forward but I have been having trouble with this so far, I may be overlooking something. anyone have any ideas or advice?

    Read the article

  • how to solve the errors of this program

    - by hussein abdullah
    include using std::cout; using std::cin; using std::endl; include void initialize(char[],int*); void input(const char[] ,int&); void print ( const char*,const int); void growOlder (const char [], int* ); bool comparePeople(const char* ,const int*,const char*,const int*); int main(){ char name1[25]; char name2[25]; int age1; int age2; initialize (name1,&age1); initialize (name2,&age2); print(name1,*age1); print(name2,*age2); input(name1,age1); input(name2,age2); print(&name1,&age1); print(&name2,&age2); growOlder(name2,age2); if(comparePeople(name1,&age1,name2,&age2)) cout<<"Both People have the same name and age "<<endl; return 0; } void input(const char name[],int &age) { cout<<"Enter a name :"; cinname ; cout<<"Enter an age:"; cin>>age; cout<<endl; } void initialize ( char name[],int *age) { name=""; age=0; } void print ( const char name[],const int age ) { cout<<"The Value stored in variable name is :" < void growOlder(const char name[],int *age) { cout<< name <<" has grown one year older\n\n"; *age++; } bool comparePeople (const char *name1,const int *age1, const char *name2,const int *age2) { return(age1==age2 &&strcmp(name1,name2)); }

    Read the article

  • Get the first and second objects from a list using LINQ

    - by Vahid
    I have a list of Person objects. How can I get the first and second Person objects that meet a certain criteria from List<Person> People using LINQ? Let's say here is the list I've got. How can I get the first and second persons that are over 18 that is James and Jodie. public class Person { public string Name; public int age; } var People = new List<Person> { new Person {Name = "Jack", Age = 15}, new Person {Name = "James" , Age = 19}, new Person {Name = "John" , Age = 14}, new Person {Name = "Jodie" , Age = 21}, new Person {Name = "Jessie" , Age = 19} }

    Read the article

  • json returning string instead of object

    - by peter
    i have $age = implode(',', $wage); // which is object return: [1,4],[7,11],[15,11] $ww = json_encode($age); and then i retrieve it here var age = JSON.parse(<?php echo json_encode($ww); ?>); so if i make alert(typeof(<?php echo $age; ?>)) // object alert(typeof(age)) //string in my case JSON.parse retuned as string. how can i let json return as object? EDIT: var age = JSON.parse(<?php echo $ww; ?>); // didnt work , its something syntax error

    Read the article

  • Update someones birthday with javascript

    - by user2768038
    So far the only mathematical way I can think of doing it is this: var age = 18 var today = new Date(); var myDate = new Date(); myDate.setFullYear(2013,3,13); /* My birthday is april 13th */ var y = (today - myDate); var days = ( y / (1000*60*60*24)); if(days >= 360){ var age = age +1; } if(days >= 720){ var age = age +1; } //etc...... document.write(age); Is there a better way of doing the if statements? so that I don't have to write one out for every year? I can't think!

    Read the article

  • How to stable_sort without copying?

    - by Mehrdad
    Why does stable_sort need a copy constructor? (swap should suffice, right?) Or rather, how do I stable_sort a range without copying any elements? #include <algorithm> class Person { Person(Person const &); // Disable copying public: Person() : age(0) { } int age; void swap(Person &other) { using std::swap; swap(this->age, other.age); } friend void swap(Person &a, Person &b) { a.swap(b); } bool operator <(Person const &other) const { return this->age < other.age; } }; int main() { static size_t const n = 10; Person people[n]; std::stable_sort(people, people + n); }

    Read the article

  • Taking advantage of Windows Azure CDN and Dynamic Pages in ASP.NET - Caching content from hosted services

    - by Shawn Cicoria
    With the updates to Windows Azure CDN announced this week [1] I wanted to help illustrate the capability with a working sample that will serve up dynamic content from an ASP.NET site hosted in a WebRole. First, to get a good overview of the capability you can read the Overview of the Windows Azure CDN [2] content on MSDN. When you setup the ability to cache content from a hosted service, the requirement is to provide a path to your role’s DNS endpoint that ends in the path “/cdn”.  Additionally, you then map CDN to that service. What WAZ CDN does, is allow you to then map that through the CDN to your host.  The CDN will then make a request to your host on your client’s behalf. The requirement is still that your client, and any Url’s that are to be serviced through the CDN and this capability have to use the CDN DNS name and not your host – no different than what CDN does for Blog storage. The following 2 URL’s are samples of how the client needs to issue the requests. Windows Azure hosted service URL: http: //myHostedService.cloudapp.net/cdn/music.aspx   - for regular “dynamic” content Windows Azure CDN URL: http: //<identifier>.vo.msecnd.net/music.aspx   - for CDN “cachable” content. The first URL path’s the request direct to your host into the Azure datacenter.  The 2nd URL paths the request through the CDN infrastructure, where CDN will make the determination to request the content on behalf of the client to the Azure datacenter and your host on the /cdn path. The big advantage here is you can apply logic to your content creation.  What’s important is emitting the CDN friendly headers that allow CDN to request and re-request only when you designate based upon it’s rules of “staleness” as described in the overview page. With IIS7.5 there is an underlying issue when the Managed Module “OutputCache” is enabled that in order to emit a good header for your content, you’ll need to remove, and in my sample, helps provide CDN friendly headers.  You get IIS 7.5 when running under OS Family “2” in your service configuration. By default, and when the OutputCache managed module is loaded, if you use the HttpResponse.CachePolicy to set the Http Headers for “max-age” when the HttpCacheability is “Public”, you will NOT get the “max-age” emitted as part of the “Cache-control:” header.  Instead, the OutputCache module will remove “max-age” and just emit “public”.  It works ok when Cacheability is set to “private”. To work around the issue and ensure your code as follows emits the full max-age along with the public option, you need to remove as follows: <system.webServer>   <modules runAllManagedModulesForAllRequests="true">     <remove name="OutputCache"/>   </modules> </system.webServer>   Response.Cache.SetCacheability(HttpCacheability.Public); Response.Cache.SetMaxAge(TimeSpan.FromMinutes(rv));   In the attached solution, the way I approached it was to have a VirtualApplication under the root site that has it’s own web.config  - this VirtualApplication is the /cdn of the site and when deployed to Azure as a Web Role will surface as a distinct IIS Application – along with a separate AppDomain. The CDN Sample is a simple Web Forms site that the /default landing page contains 3 IFrames to host: 1. Content direct from the host @   http://xxxx.cloudapp.net/cdn 2. Content via the CDN @ http://azxxx.vo.msecnd.net  3. Simple list of recent requests – showing where the request came from.   When you run the sample the first time you hit the page, both the Host and the CDN will cause 2 initial requests to hit the host.  You won’t see the first requests in the list because of timing – but if you refresh, you’ll see that the list will show that you have 2 requests initially. 1. sourced direct from the Browser to the HOST 2. sourced via the CDN The picture above shows the call-outs of each of those requests – green rows showing requests coming direct to the HOST, yellow showing the CDN request.  The IP addresses of the green items are direct from the client, where the CDN is from the CDN data center. As you refresh the page (hit Ctrl+F5 to force a full refresh and avoid “304 – not changed”) you’ll see that the request to the HOST get’s processed direct; but the request to the CDN endpoint is serviced direct from the CDN and doesn’t incur any additional request back to the HOST. The following is the Headers from the CDN response (Status-Line) HTTP/1.1 200 OK Age 13 Cache-Control public, max-age=300 Connection keep-alive Content-Length 6212 Content-Type image/jpeg; charset=utf-8 Date Fri, 11 Mar 2011 20:47:14 GMT Expires Fri, 11 Mar 2011 20:52:01 GMT Last-Modified Fri, 11 Mar 2011 20:47:02 GMT Server Microsoft-IIS/7.5 X-AspNet-Version 4.0.30319 X-Powered-By ASP.NET   The following are the Headers from the HOST response (Status-Line) HTTP/1.1 200 OK Cache-Control public, max-age=300 Content-Length 6189 Content-Type image/jpeg; charset=utf-8 Date Fri, 11 Mar 2011 20:47:15 GMT Last-Modified Fri, 11 Mar 2011 20:47:02 GMT Server Microsoft-IIS/7.5 X-AspNet-Version 4.0.30319 X-Powered-By ASP.NET   You can see that with the CDN request, the countdown (age) starts for aging the content. The full sample is located here: CDNSampleSite.zip [1] http://blogs.msdn.com/b/windowsazure/archive/2011/03/09/now-available-updated-windows-azure-sdk-and-windows-azure-management-portal.aspx [2] http://msdn.microsoft.com/en-us/library/ff919703.aspx

    Read the article

  • readonly keyword

    - by nmarun
    This is something new that I learned about the readonly keyword. Have a look at the following class: 1: public class MyClass 2: { 3: public string Name { get; set; } 4: public int Age { get; set; } 5:  6: private readonly double Delta; 7:  8: public MyClass() 9: { 10: Initializer(); 11: } 12:  13: public MyClass(string name = "", int age = 0) 14: { 15: Name = name; 16: Age = age; 17: Initializer(); 18: } 19:  20: private void Initializer() 21: { 22: Delta = 0.2; 23: } 24: } I have a couple of public properties and a private readonly member. There are two constructors – one that doesn’t take any parameters and the other takes two parameters to initialize the public properties. I’m also calling the Initializer method in both constructors to initialize the readonly member. Now when I build this, the code breaks and the Error window says: “A readonly field cannot be assigned to (except in a constructor or a variable initializer)” Two things after I read this message: It’s such a negative statement. I’d prefer something like: “A readonly field can be assigned to (or initialized) only in a constructor or through a variable initializer” But in my defense, I AM assigning it in a constructor (only indirectly). All I’m doing is creating a method that does it and calling it in a constructor. Turns out, .net was not ‘frameworked’ this way. We need to have the member initialized directly in the constructor. If you have multiple constructors, you can just use the ‘this’ keyword on all except the default constructors to call the default constructor. This default constructor can then initialize your readonly members. This will ensure you’re not repeating the code in multiple places. A snippet of what I’m talking can be seen below: 1: public class Person 2: { 3: public int UniqueNumber { get; set; } 4: public string Name { get; set; } 5: public int Age { get; set; } 6: public DateTime DateOfBirth { get; set; } 7: public string InvoiceNumber { get; set; } 8:  9: private readonly string Alpha; 10: private readonly int Beta; 11: private readonly double Delta; 12: private readonly double Gamma; 13:  14: public Person() 15: { 16: Alpha = "FDSA"; 17: Beta = 2; 18: Delta = 3.0; 19: Gamma = 0.0989; 20: } 21:  22: public Person(int uniqueNumber) : this() 23: { 24: UniqueNumber = uniqueNumber; 25: } 26: } See the syntax in line 22 and you’ll know what I’m talking about. So the default constructor gets called before the one in line 22. These are known as constructor initializers and they allow one constructor to call another. The other ‘myth’ I had about readonly members is that you can set it’s value only once. This was busted as well (I recall Adam and Jamie’s show). Say you’ve initialized the readonly member through a variable initializer. You can over-write this value in any of the constructors any number of times. 1: public class Person 2: { 3: public int UniqueNumber { get; set; } 4: public string Name { get; set; } 5: public int Age { get; set; } 6: public DateTime DateOfBirth { get; set; } 7: public string InvoiceNumber { get; set; } 8:  9: private readonly string Alpha = "asdf"; 10: private readonly int Beta = 15; 11: private readonly double Delta = 0.077; 12: private readonly double Gamma = 1.0; 13:  14: public Person() 15: { 16: Alpha = "FDSA"; 17: Beta = 2; 18: Delta = 3.0; 19: Gamma = 0.0989; 20: } 21:  22: public Person(int uniqueNumber) : this() 23: { 24: UniqueNumber = uniqueNumber; 25: Beta = 3; 26: } 27:  28: public Person(string name, DateTime dob) : this() 29: { 30: Name = name; 31: DateOfBirth = dob; 32:  33: Alpha = ";LKJ"; 34: Gamma = 0.0898; 35: } 36:  37: public Person(int uniqueNumber, string name, int age, DateTime dob, string invoiceNumber) : this() 38: { 39: UniqueNumber = uniqueNumber; 40: Name = name; 41: Age = age; 42: DateOfBirth = dob; 43: InvoiceNumber = invoiceNumber; 44:  45: Alpha = "QWER"; 46: Beta = 5; 47: Delta = 1.0; 48: Gamma = 0.0; 49: } 50: } In the above example, every constructor over-writes the values for the readonly members. This is perfectly valid. There is a possibility that based on the way the object is instantiated, the readonly member will have a different value. Well, that’s all I have for today and read this as it’s on a related topic.

    Read the article

  • ASP.NET ViewState Tips and Tricks #2

    - by João Angelo
    If you need to store complex types in ViewState DO implement IStateManager to control view state persistence and reduce its size. By default a serializable object will be fully stored in view state using BinaryFormatter. A quick comparison for a complex type with two integers and one string property produces the following results measured using ASP.NET tracing: BinaryFormatter: 328 bytes in view state IStateManager: 28 bytes in view state BinaryFormatter sample code: // DO NOT [Serializable] public class Info { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } } public class ExampleControl : WebControl { protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (!this.Page.IsPostBack) { this.User = new Info { Id = 1, Name = "John Doe", Age = 27 }; } } public Info User { get { object o = this.ViewState["Example_User"]; if (o == null) return null; return (Info)o; } set { this.ViewState["Example_User"] = value; } } } IStateManager sample code: // DO public class Info : IStateManager { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } private bool isTrackingViewState; bool IStateManager.IsTrackingViewState { get { return this.isTrackingViewState; } } void IStateManager.LoadViewState(object state) { var triplet = (Triplet)state; this.Id = (int)triplet.First; this.Name = (string)triplet.Second; this.Age = (int)triplet.Third; } object IStateManager.SaveViewState() { return new Triplet(this.Id, this.Name, this.Age); } void IStateManager.TrackViewState() { this.isTrackingViewState = true; } } public class ExampleControl : WebControl { protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (!this.Page.IsPostBack) { this.User = new Info { Id = 1, Name = "John Doe", Age = 27 }; } } public Info User { get; set; } protected override object SaveViewState() { return new Pair( ((IStateManager)this.User).SaveViewState(), base.SaveViewState()); } protected override void LoadViewState(object savedState) { if (savedState != null) { var pair = (Pair)savedState; this.User = new Info(); ((IStateManager)this.User).LoadViewState(pair.First); base.LoadViewState(pair.Second); } } }

    Read the article

  • Social Targeting: Who Do You Think You’re Talking To?

    - by Mike Stiles
    Are you the kind of person that tries to sell Clay Aiken CD’s outside Warped Tour concert venues? Then you don’t think a lot about targeting your messages to the right audience. For your communication to pack the biggest punch it can, you need to know where to throw it. And a recent study on social demographics might help you see social targeting in a whole new light. Pingdom’s annual survey of social network demographics shows us first of all that there is no gender difference between Facebook and Twitter. Both are 40% male, 60% female. If you’re looking for locales that lean heavily male, that would be Slashdot, Hacker News and Stack Overflow. The women are dominating Pinterest, Goodreads and Blogger. So what about age? 55% of tweeters are 35 and up, compared with 63% at Pinterest, 65% at Facebook and 70% at LinkedIn. As you can tell, LinkedIn supports the oldest user base, with the average member being 44. The average age at Facebook is 51, and it’s 37 at Twitter. If you want to aim younger, have you met Orkut yet? 83% of its users are under 35. The next sites in order as great candidates for the young market are deviantART, Hacker News, Hi5, Github, and Reddit. I know, other than Reddit, many of you might be saying “who?” But the list could offer an opportunity to look at the vast social world beyond Facebook, Twitter and Google+ (which Pingdom did not include in the survey at all due to a lack of accessible data). As for the average age of social users overall: 26% are 25-34 25% are 35-44 19% are 45-54 16% are 18-24  6% are 55-64  5% are 0-17  and 2% are 65 Now you know where you stand on the “cutting edge” scale for a person your age. You’re welcome. Certainly such demographics are a moving target and need to be watched and reassessed on a regular basis to make sure you’re moving in step with the people you want to talk to. For instance, since Pingdom’s survey last year, the age of the average Facebook user has gone up 2 years, while the age of the average Twitter user has gone down 2 years. With the targeting and analytics tools available on today’s social management platforms, there’s little need to market in the dark. Otherwise, good luck with those Clay CD’s.

    Read the article

  • export web page data to excel using javascript [on hold]

    - by Sreevani sri
    I have created web page using html.When i clicked on submit button it will export to excel. using javascript i wnt to export thadt data to excel. my html code is 1. Please give your Name:<input type="text" name="Name" /><br /> 2. Area where you reside:<input type="text" name="Res" /><br /> 3. Specify your age group<br /> (a)15-25<input type="text" name="age" /> (b)26-35<input type="text" name="age" /> (c)36-45<input type="text" name="age" /> (d) Above 46<input type="text" name="age" /><br /> 4. Specify your occupation<br /> (a) Student<input type="checkbox" name="occ" value="student" /> (b) Home maker<input type="checkbox" name="occ" value="home" /> (c) Employee<input type="checkbox" name="occ" value="emp" /> (d) Businesswoman <input type="checkbox" name="occ" value="buss" /> (e) Retired<input type="checkbox" name="occ" value="retired" /> (f) others (please specify)<input type="text" name="others" /><br /> 5. Specify the nature of your family<br /> (a) Joint family<input type="checkbox" name="family" value="jfamily" /> (b) Nuclear family<input type="checkbox" name="family" value="nfamily" /><br /> 6. Please give the Number of female members in your family and their average age approximately<br /> Members Age 1 2 3 4 5<br /> 8. Please give your highest level of education (a)SSC or below<input type="checkbox" name="edu" value="ssc" /> (b) Intermediate<input type="checkbox" name="edu" value="int" /> (c) Diploma <input type="checkbox" name="edu" value="dip" /> (d)UG degree <input type="checkbox" name="edu" value="deg" /> (e) PG <input type="checkbox" name="edu" value="pg" /> (g) Doctorial degree<input type="checkbox" name="edu" value="doc" /><br /> 9. Specify your monthly income approximately in RS <input type="text" name="income" /><br /> 10. Specify your time spent in making a purchase decision at the outlet<br /> (a)0-15 min <input type="checkbox" name="dis" value="0-15 min" /> (b)16-30 min <input type="checkbox" name="dis" value="16-30 min" /> (c) 30-45 min<input type="checkbox" name="dis" value="30-45 min" /> (d) 46-60 min<input type="checkbox" name="dis" value="46-60 min" /><br /> <input type="submit" onclick="exportToExcel()" value="Submit" /> </div> </form>

    Read the article

  • How should I design a wizard for generating requirements and documentation

    - by user1777663
    I'm currently working in an industry where extensive documentation is required, but the apps I'm writing are all pretty much cookie cutter at a high level. What I'd like to do is build an app that asks a series of questions regarding business rules and marketing requirements to generate a requirements spec. For example, there might be a question set that asks "Does the user need to enter their age?" and a follow-up question of "What is the minimum age requirement?" If the inputs are "yes" and "18", then this app will generate requirements that look something like this: "The registration form shall include an age selector" "The registration form shall throw an error if the selected age is less than 18" Later on down the line, I'd like to extend this to do additional things like generate test cases and even code, but the idea is the same: generate some output based on rules determined by answering a set of questions. Are there any patterns I could research to better design the architecture of such an application? Is this something that I should be modeling as a finite state machine?

    Read the article

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