Search Results

Search found 21759 results on 871 pages for 'int'.

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

  • Should this immutable struct be a mutable class?

    - by ChaosPandion
    I showed this struct to a fellow programmer and they felt that it should be a mutable class. They felt it is inconvenient not to have null references and the ability to alter the object as required. I would really like to know if there are any other reasons to make this a mutable class. [Serializable] public struct PhoneNumber : ICloneable, IEquatable<PhoneNumber> { private const int AreaCodeShift = 54; private const int CentralOfficeCodeShift = 44; private const int SubscriberNumberShift = 30; private const int CentralOfficeCodeMask = 0x000003FF; private const int SubscriberNumberMask = 0x00003FFF; private const int ExtensionMask = 0x3FFFFFFF; private readonly ulong value; public int AreaCode { get { return UnmaskAreaCode(value); } } public int CentralOfficeCode { get { return UnmaskCentralOfficeCode(value); } } public int SubscriberNumber { get { return UnmaskSubscriberNumber(value); } } public int Extension { get { return UnmaskExtension(value); } } public PhoneNumber(ulong value) : this(UnmaskAreaCode(value), UnmaskCentralOfficeCode(value), UnmaskSubscriberNumber(value), UnmaskExtension(value), true) { } public PhoneNumber(int areaCode, int centralOfficeCode, int subscriberNumber) : this(areaCode, centralOfficeCode, subscriberNumber, 0, true) { } public PhoneNumber(int areaCode, int centralOfficeCode, int subscriberNumber, int extension) : this(areaCode, centralOfficeCode, subscriberNumber, extension, true) { } private PhoneNumber(int areaCode, int centralOfficeCode, int subscriberNumber, int extension, bool throwException) { value = 0; if (areaCode < 200 || areaCode > 989) { if (!throwException) return; throw new ArgumentOutOfRangeException("areaCode", areaCode, @"The area code portion must fall between 200 and 989."); } else if (centralOfficeCode < 200 || centralOfficeCode > 999) { if (!throwException) return; throw new ArgumentOutOfRangeException("centralOfficeCode", centralOfficeCode, @"The central office code portion must fall between 200 and 999."); } else if (subscriberNumber < 0 || subscriberNumber > 9999) { if (!throwException) return; throw new ArgumentOutOfRangeException("subscriberNumber", subscriberNumber, @"The subscriber number portion must fall between 0 and 9999."); } else if (extension < 0 || extension > 1073741824) { if (!throwException) return; throw new ArgumentOutOfRangeException("extension", extension, @"The extension portion must fall between 0 and 1073741824."); } else if (areaCode.ToString()[1] - 48 > 8) { if (!throwException) return; throw new ArgumentOutOfRangeException("areaCode", areaCode, @"The second digit of the area code cannot be greater than 8."); } else { value |= ((ulong)(uint)areaCode << AreaCodeShift); value |= ((ulong)(uint)centralOfficeCode << CentralOfficeCodeShift); value |= ((ulong)(uint)subscriberNumber << SubscriberNumberShift); value |= ((ulong)(uint)extension); } } public object Clone() { return this; } public override bool Equals(object obj) { return obj != null && obj.GetType() == typeof(PhoneNumber) && Equals((PhoneNumber)obj); } public bool Equals(PhoneNumber other) { return this.value == other.value; } public override int GetHashCode() { return value.GetHashCode(); } public override string ToString() { return ToString(PhoneNumberFormat.Separated); } public string ToString(PhoneNumberFormat format) { switch (format) { case PhoneNumberFormat.Plain: return string.Format(@"{0:D3}{1:D3}{2:D4} {3:#}", AreaCode, CentralOfficeCode, SubscriberNumber, Extension).Trim(); case PhoneNumberFormat.Separated: return string.Format(@"{0:D3}-{1:D3}-{2:D4} {3:#}", AreaCode, CentralOfficeCode, SubscriberNumber, Extension).Trim(); default: throw new ArgumentOutOfRangeException("format"); } } public ulong ToUInt64() { return value; } public static PhoneNumber Parse(string value) { var result = default(PhoneNumber); if (!TryParse(value, out result)) { throw new FormatException(string.Format(@"The string ""{0}"" could not be parsed as a phone number.", value)); } return result; } public static bool TryParse(string value, out PhoneNumber result) { result = default(PhoneNumber); if (string.IsNullOrEmpty(value)) { return false; } var index = 0; var numericPieces = new char[value.Length]; foreach (var c in value) { if (char.IsNumber(c)) { numericPieces[index++] = c; } } if (index < 9) { return false; } var numericString = new string(numericPieces); var areaCode = int.Parse(numericString.Substring(0, 3)); var centralOfficeCode = int.Parse(numericString.Substring(3, 3)); var subscriberNumber = int.Parse(numericString.Substring(6, 4)); var extension = 0; if (numericString.Length > 10) { extension = int.Parse(numericString.Substring(10)); } result = new PhoneNumber( areaCode, centralOfficeCode, subscriberNumber, extension, false ); return result.value == 0; } public static bool operator ==(PhoneNumber left, PhoneNumber right) { return left.Equals(right); } public static bool operator !=(PhoneNumber left, PhoneNumber right) { return !left.Equals(right); } private static int UnmaskAreaCode(ulong value) { return (int)(value >> AreaCodeShift); } private static int UnmaskCentralOfficeCode(ulong value) { return (int)((value >> CentralOfficeCodeShift) & CentralOfficeCodeMask); } private static int UnmaskSubscriberNumber(ulong value) { return (int)((value >> SubscriberNumberShift) & SubscriberNumberMask); } private static int UnmaskExtension(ulong value) { return (int)(value & ExtensionMask); } } public enum PhoneNumberFormat { Plain, Separated }

    Read the article

  • passing a fortran int array to C++ by calling C++ function in fortran

    - by cppb
    hi, I am trying to call a C++ function in FORTRAN subroutine. This C+ function is supposed to update an integer array. Here is a non-working code I wrote. Can someone please let me know what the issue is: ! FORTRAN function that calls a C++ function subroutine my_function() integer(4) ar(*) integer(4) get_filled_ar ! Need correct syntax here. ar = get_filled_ar() end // C++ function: extern "C" { void get_filled_ar(int *ar){ ar[0] = 1; ar[1] = 10; ar[3] = 100; } }

    Read the article

  • Typecast to an int in Octave/Matlab

    - by Leif Andersen
    I need to call the index of a matrix made using the linspace command, and based on somde data taken from an oscilloscope. Because of this, the data inputed is a double. However, I can't really call: Time[V0Found] where V0Found is something like 5.2 however, taking index 5 is close enough, so I need to drop the decimal. I used this equation to drop the decimal: V0FoundDec = V0Found - mod(V0Found,1) Time[V0FoundDec] However, eve though that drops the decimal, octave still complains about it. So, what can I do to typecast it to an int? Thank you.

    Read the article

  • Binding a nullable int to an asp:TextBox

    - by Slauma
    I have a property int? MyProperty as a member in my datasource (ObjectDataSource). Can I bind this to a TextBox, like <asp:TextBox ID="MyTextBox" runat="server" Text='<%# Bind("MyProperty") %>' /> Basically I want to get a null value displayed as blank "" in the TextBox, and a number as a number. If the TextBox is blank MyProperty shall be set to null. If the TextBox has a number in it, MyProperty should be set to this number. If I try it I get an exception: "Blank is not a valid Int32". But how can I do that? How to work with nullable properties and Bind? Thanks in advance!

    Read the article

  • Using STL/Boost to initialize a hard-coded set<vector<int> >

    - by Hooked
    Like this question already asked, I'd like to initialize a container using STL where the elements are hard-coded in the cleanest manner possible. In this case, the elements are a doubly nested container: set<vector<int> > A; And I'd like (for example) to put the following values in: A = [[0,0,1],[0,1,0],[1,0,0],[0,0,0]]; C++0x fine, using g++ 4.4.1. STL is preferable as I don't use Boost for any other parts of the code (though I wouldn't mind an example with it!).

    Read the article

  • Size of int in C on different architectures

    - by NawaMan
    I am aware that the specification of the C language does not dictate the exact size of each integer type (e.g., int). What I am wondering is: Is there a way in C (not C++) to define an integer type with a specific size that ensures it will be the same across different architectures? Like: typedef int8 <an integer with 8 bits> typedef int16 <an integer with 16 bits> Or any other way that will allow other parts of the program to be compiled on different architecture.

    Read the article

  • fastercsv parsing to int or other into ActiveRecord

    - by Schroedinger
    I'm currently importing a CSV into an activerecord element but can't choose to parse the elements as say ints or decimals on a case by case basis using fastercsv. I can either choose to parse everything as an int or the other, or all as strings. I need to parse some columns as ints, some as decimals and some as strings. Otherwise, is there a way after I've parsed everything as strings to convert and update individual elements in the activerecord to the new form? Say parse values in as strings then convert certain values to ints, others to decs, etc?

    Read the article

  • Explanation of casting/conversion int/double in C#

    - by cad
    I coded some calculation stuff (I copied below a really simplifed example of what I did) like CASE2 and got bad results. Refactored the code like CASE1 and worked fine. I know there is an implicit cast in CASE 2, but not sure of the full reason. Any one could explain me what´s exactly happening below? //CASE 1, result 5.5 double auxMedia = (5 + 6); auxMedia = auxMedia / 2; //CASE 2, result 5.0 double auxMedia1 = (5 + 6) / 2; //CASE 3, result 5.5 double auxMedia3 = (5.0 + 6.0) / 2.0; //CASE 4, result 5.5 double auxMedia4 = (5 + 6) / 2.0; My guess is that /2 in CASE2 is casting (5 + 6) to int and causing round of division to 5, then casted again to double and converted to 5.0. CASE3 and CASE 4 also fixes the problem.

    Read the article

  • migrate method Rand(int) Visual Fox Pro to C#.net

    - by ch2o
    I'm migrating a Visual Fox Pro code to C #. NET What makes the Visual Fox Pro: generates a string of 5 digits ("48963") based on a text string (captured in a textbox), if you always enter the same text string will get that string always 5 digits (no reverse), my code in C #. NET should generate the same string. I want to migrate the following code (Visual Fox Pro 6 to C#) gnLower = 1000 gnUpper = 100000 vcad = 1 For y=gnLower to gnUpper step 52 genClave = **Rand(vcad)** * y vRound = allt(str(int(genclave))) IF Len(vRound) = 3 vDec = Right(allt(str(genClave,10,2)), 2) finClave = vRound+vDec Thisform.txtPass.value = Rand(971); Exit Endif Next y outputs: vcad = 1 return: 99905 vcad = 2 return: 10077 vcad = thanks return: 17200 thks!

    Read the article

  • C# int to byte[]

    - by Petoj
    If I need to convert an int to byte[] I could use Bitconvert.GetBytes(). But if I should follow this: An XDR signed integer is a 32-bit datum that encodes an integer in the range [-2147483648,2147483647]. The integer is represented in two's complement notation. The most and least significant bytes are 0 and 3, respectively. Integers are declared as follows: Taken from RFC1014 3.2. What method should I use then if there is no method to do this? How would it look like if you write your own? I don't understand the text 100% so I can't implement it on my own.

    Read the article

  • Best way to store enum values in database - String or Int

    - by inutan
    Hello there, I have a number of enums in my application which are used as property type in some classes. What is the best way to store these values in database, as String or Int? FYI, I will also be mapping these attribute types using fluent Nhibernate. Sample code: public enum ReportOutputFormat { DOCX, PDF, HTML } public enum ReportOutputMethod { Save, Email, SaveAndEmail } public class ReportRequest { public Int32 TemplateId { get { return templateId; } set { templateId = value; } } public ReportOutputFormat OutputFormat { get { return outputFormat; } set { outputFormat = value; } } public ReportOutputMethod OutputMethod { get { return outputMethod; } set { outputMethod = value; } } }

    Read the article

  • Java Incompatible Types Boolean Int

    - by ikurtz
    i have the following class: public class NewGameContract { public boolean HomeNewGame = false; public boolean AwayNewGame = false; public boolean GameContract(){ if (HomeNewGame && AwayNewGame){ return true; } else { return false; } } } when i try to use it like so: if (networkConnection){ connect4GameModel.newGameContract.HomeNewGame = true; boolean status = connect4GameModel.newGameContract.GameContract(); switch (status){ case true: break; case false: break; } return; } i am getting the error: incompatible types found: boolean required: int on the following switch (status) code. what am i doing wrong please?

    Read the article

  • Timestamp as int field, query performance

    - by Kirzilla
    Hello, I'm storing timestamp as int field. And on large table it takes too long to get rows inserted at date because I'm using mysql function FROM_UNIXTIME. SELECT * FROM table WHERE FROM_UNIXTIME(timestamp_field, '%Y-%m-%d') = '2010-04-04' Is there any ways to speed this query? Maybe I should use query for rows using timestamp_field >= x AND timestamp_field < y? Thank you I've just tried this query... SELECT * FROM table WHERE timestamp_field >= UNIX_TIMESTAMP('2010-04-14 00:00:00') AND timestamp_field <= UNIX_TIMESTAMP('2010-04-14 23:59:59') but there is no any performance bonuses. :(

    Read the article

  • 'int' object is not callable

    - by Oscar Reyes
    I'm trying to define a simply Fraction class And I'm getting this error: python fraction.py Traceback (most recent call last): File "fraction.py", line 20, in <module> f.numerator(2) TypeError: 'int' object is not callable The code follows: class Fraction(object): def __init__( self, n=0, d=0 ): self.numerator = n self.denominator = d def get_numerator(self): return self.numerator def get_denominator(self): return self.denominator def numerator(self, n): self.numerator = n def denominator( self, d ): self.denominator = d def prints( self ): print "%d/%d" %(self.numerator, self.denominator) if __name__ == "__main__": f = Fraction() f.numerator(2) f.denominator(5) f.prints() I thought it was because I had numerator(self) and numerator(self, n) but now I know Python doesn't have method overloading ( function overloading ) so I renamed to get_numerator but that's not the problems. What could it be?

    Read the article

  • Whats the problem with int *p=23;

    - by piemesons
    Yesterday in my interview I was asked this question. (At that time I was highly pressurized by so many abrupt questions). int *p; *p=23; printf('%d',*p); Is there any problem with this code? I explained him that you are trying to assign value to a pointer to whom memory is not allocated. But the way he reacted, it was like I am wrong. Although I got the job but after that he said Mohit think about this question again. I don't know what he was trying to say. Please let me know is there any problem in my answer?

    Read the article

  • Lucene.NET - sorting by int

    - by Judah Himango
    In the latest version of Lucene (or Lucene.NET), what is the proper way to get the search results back in sorted order? I have a document like this: var document = new Lucene.Document(); document.AddField("Text", "foobar"); document.AddField("CreationDate", DateTime.Now.Ticks.ToString()); // store the date as an int lucene.AddDocument(document); Now I want do a search and get my results back in order of most recent. How can I do a search that orders results by CreationDate? All the documentation I see is for old Lucene versions that use now-deprecated APIs.

    Read the article

  • Java: charAt convert to int?

    - by sling
    Hi, I would like to key in my nirc number eg.S1234567I and then put 1234567 individualy as a integer as indiv1 as charAt(1), indiv2 as charAt(2), indiv as charAt(3), etc. However, when I do as the codes below, I cant seem to get even the first the number out? Any idea? Scanner console = new Scanner(System.in); System.out.println("Enter your NRIC number: "); String nric = console.nextLine(); int indiv1 = nric.charAt(1); System.out.println(indiv1);

    Read the article

  • Strange error: cannot convert from 'int' to 'ios_base::openmode'

    - by Dylan Klomparens
    I am using g++ to compile some code. I wrote the following snippet: bool WriteAccess = true; string Name = "my_file.txt"; ofstream File; ios_base::open_mode Mode = std::ios_base::in | std::ios_base::binary; if(WriteAccess) Mode |= std::ios_base::out | std::ios_base::trunc; File.open(Name.data(), Mode); And I receive these errors... any idea why? Error 1: invalid conversion from ‘int’ to ‘std::_Ios_Openmode’ Error 2: initializing argument 2 of ‘std::basic_filebuf<_CharT, _Traits* std::basic_filebuf<_CharT, _Traits::open(const char*, std::_Ios_Openmode) [with _CharT = char, _Traits = std::char_traits]’ As far as I could tell from a Google search, g++ is actually breaking the C++ standard here. Which I find quite astonishing, since they generally conform very strictly to the standard. Is this the case? Or am I doing something wrong. My reference for the standard: http://www.cplusplus.com/reference/iostream/ofstream/open/

    Read the article

  • Custom "Very Long Int" Division Issue

    - by befall
    Hey everyone, So, for a very silly project in C++, we are making our own long integer class, called VLI (Very Long Int). The way it works (they backboned it, blame them for stupidity) is this: User inputs up to 50 digits, which are input as string. String is stored in pre-made Sequence class, which stores the string in an array, in reverse order. That means, when "1234" is input, it gets stored as [4|3|2|1]. So, my question is this: How can I go about doing division using only these arrays of chars? If the input answer is over 32 digits, I can't use ints to check for stuff, and they basically saying using long ints here is cheating. Any input is welcome, and I can give more clarification if need be, thanks everyone.

    Read the article

  • Code crashing compiler: main() returning a struct instead of an int

    - by AndrejaKo
    Hi! I'm experimenting with a piece of C code. Can anyone tell me why is VC 9.0 with SP1 crashing for me? Oh, and the code is meant to be an example used in a discussion why something like void main (void) is evil. struct foo { int i; double d; } main (double argc, struct foo argv) { struct foo a; a.d=0; a.i=0; return a.i; } If I put return a; compiler doesn't crash.

    Read the article

  • PHP validating integers

    - by Mikk
    Hi, I was wondering, what would be the best way to validate an integer. I'd like this to work with strings as well, so I could to something like (string)+00003 - (int)3 (valid) (string)-027 - (int)-27 (valid) (int)33 - (int)33 (valid) (string)'33a' - (FALSE) (invalid) That is what i've go so far: function parseInt($int){ //If $int already is integer, return it if(is_int($int)){return $int;} //If not, convert it to string $int=(string)$int; //If we have '+' or '-' at the beginning of the string, remove them $validate = ($int[0] === '-' || $int[0] === '+')?substr($int, 1):$int; //If $validate matches pattern 0-9 convert $int to integer and return it //otherwise return false return preg_match('/^[0-9]+$/', $validate)?(int)$int:FALSE; } As far as I tested, this function works, but it looks like a clumsy workaround. Is there any better way to write this kind of function. I've also tried filter_var($foo, FILTER_VALIDATE_INT); but it won't accept values like '0003', '-0' etc.

    Read the article

  • Loss of precision - int -> float or double

    - by stan
    I have an exam question i am revising for and the question is for 4 marks "In java we can assign a int to a double or a float". Will this ever loose infromation and why? I have put that because ints are normally of fixed length or size - the precision for sotring data is finite, where storing information in floating point can be infinite, essentially we loose infromation because of this Now i am a little sketchy as to whetehr or not i am hitting the right areas here. I very sure it will loose precision but i cant exactly put my finger on why. Can i getsome help please Thanks

    Read the article

  • Java Switch Incompatible Types Boolean Int

    - by ikurtz
    i have the following class: public class NewGameContract { public boolean HomeNewGame = false; public boolean AwayNewGame = false; public boolean GameContract(){ if (HomeNewGame && AwayNewGame){ return true; } else { return false; } } } when i try to use it like so: if (networkConnection){ connect4GameModel.newGameContract.HomeNewGame = true; boolean status = connect4GameModel.newGameContract.GameContract(); switch (status){ case true: break; case false: break; } return; } i am getting the error: incompatible types found: boolean required: int on the following switch (status) code. what am i doing wrong please?

    Read the article

  • How can i convert a string into byte[] of unsigned int 32 C#

    - by Miroo
    i have string like "0x5D, 0x50, 0x68, 0xBE, 0xC9, 0xB3, 0x84, 0xFF" i wanna convert it into byte[] key= new byte[] { 0x5D, 0x50, 0x68, 0xBE, 0xC9, 0xB3, 0x84, 0xFF}; i thought about splitting the string by ',' then loop on it and setvalue into another byte[] in index of i string Key = "0x5D, 0x50, 0x68, 0xBE, 0xC9, 0xB3, 0x84, 0xFF"; string[] arr = Key.Split(','); byte[] keybyte= new byte[8]; for (int i = 0; i < arr.Length; i++) { keybyte.SetValue(Int32.Parse(arr[i].ToString()), i); } but seems like it doesn't work i get error in converting the string into unsigned int32 on the first beginning an help would be appreciated

    Read the article

  • Calling this[int index] via reflection

    - by tkutter
    I try to implement a reflection-based late-bound library to Microsoft Office. The properties and methods of the Offce COM objects are called the following way: Type type = Type.GetTypeFromProgID("Word.Application"); object comObject = Activator.CreateInstance(type); type.InvokeMember(<METHOD NAME>, <BINDING FLAGS>, null, comObject, new object[] { <PARAMS>}); InvokeMember is the only possible way because Type.GetMethod / GetProperty works improperly with the COM objects. Methods and properties can be called using InvokeMember but now I have to solve the following problem: Method in the office-interop wrapper: Excel.Workbooks wb = excel.Workbooks; Excel.Workbook firstWb = wb[0]; respectively foreach(Excel.Workbook w in excel.Workbooks) // doSmth. How can I call the this[int index] operator of Excel.Workbooks via reflection?

    Read the article

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