Search Results

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

Page 28/871 | < Previous Page | 24 25 26 27 28 29 30 31 32 33 34 35  | Next Page >

  • Why does this Quicksort work?

    - by IVlad
    I find this Quicksort partitioning approach confusing and wrong, yet it seems to work. I am referring to this pseudocode. Note: they also have a C implementation at the end of the article, but it's very different from their pseudocode, so I don't care about that. I have also written it in C like this, trying to stay true to the pseudocode as much as possible, even if that means doing some weird C stuff: #include <stdio.h> int partition(int a[], int p, int r) { int x = a[p]; int i = p - 1; int j = r + 1; while (1) { do j = j - 1; while (!(a[j] <= x)); do i = i + 1; while (!(a[i] >= x)); if (i < j) { int t = a[i]; a[i] = a[j]; a[j] = t; } else { for (i = 1; i <= a[0]; ++i) printf("%d ", a[i]); printf("- %d\n", j); return j; } } } int main() { int a[100] = //{8, 6,10,13,15,8,3,2,12}; {7, 7, 6, 2, 3, 8, 4, 1}; partition(a, 1, a[0]); return 0; } If you run this, you'll get the following output: 1 6 2 3 4 8 7 - 5 However, this is wrong, isn't it? Clearly a[5] does not have all the values before it lower than it, since a[2] = 6 > a[5] = 4. Not to mention that 7 is supposed to be the pivot (the initial a[p]) and yet its position is both incorrect and lost. The following partition algorithm is taken from wikipedia: int partition2(int a[], int p, int r) { int x = a[r]; int store = p; for (int i = p; i < r; ++i) { if (a[i] <= x) { int t = a[i]; a[i] = a[store]; a[store] = t; ++store; } } int t = a[r]; a[r] = a[store]; a[store] = t; for (int i = 1; i <= a[0]; ++i) printf("%d ", a[i]); printf("- %d\n", store); return store; } And produces this output: 1 6 2 3 8 4 7 - 1 Which is a correct result in my opinion: the pivot (a[r] = a[7]) has reached its final position. However, if I use the initial partitioning function in the following algorithm: void Quicksort(int a[], int p, int r) { if (p < r) { int q = partition(a, p, r); // initial partitioning function Quicksort(a, p, q); Quicksort(a, q + 1, r); // I'm pretty sure q + r was a typo, it doesn't work with q + r. } } ... it seems to be a correct sorting algorithm. I tested it out on a lot of random inputs, including all 0-1 arrays of length 20. I have also tried using this partition function for a selection algorithm, in which it failed to produce correct results. It seems to work and it's even very fast as part of the quicksort algorithm however. So my questions are: Can anyone post an example on which the algorithm DOESN'T work? If not, why does it work, since the partitioning part seems to be wrong? Is this another partitioning approach that I don't know about?

    Read the article

  • How to implement rank structure

    - by Luke101
    What is the best way to implement a rank system: here is the code i will use public class MyRank { private int LevelOneMaxPoints = 100; private int LevelTwoMinPoints = 200; private int LevelTwoMaxPoints = 299; private int LevelThreeMinPoints = 300; private int LevelThreeMaxPoints = 399; private int LevelFourMinPoints = 400; private int LevelFourMaxPoints = 599; private int LevelFourPlusMinPoints = 600; private int LevelFourPlusMaxPoints = 999; private int LevelFiveMinPoints = 1000; private int LevelFiveMaxPoints = 1299; private int LevelSixMinPoints = 1300; private int LevelSixMaxPoints = 2699; private int LevelSevenMinPoints = 2700; private int LevelSevenMaxPoints = 3999; private int LevelEightMinPoints = 4000; private int LevelEightMaxPoints = 5499; private int LevelEightPlusMinPoints = 5500; private int LevelEightPlusMaxPoints = 7499; private int LevelNineMinPoints = 7500; private int LevelNineMaxPoints = 9999; private int LevelTenMinPoints = 10000; private string LevelOneName = "Private"; private string LevelTwoName = "PV2"; private string LevelThreeName = "Private Fist Class"; private string LevelFourName = "Specialist"; private string LevelFourPlusName = "Corporal"; private string LevelFiveName = "Sergeant"; //private string LevelSixName = "Staff Sergeant"; private string LevelSevenName = "Sergeant First Class"; private string LevelEightName = "Master Sergeant"; private string LevelEightPlusName = "First Sergeant"; private string LevelNineName = "Sergeant Major"; //private string LevelTenName = "Sergeant Major of the Answers"; private int points = 0; public string RankName { get; private set; } public MyRank(int points) { this.points = points; RankName = GetRankName(); } private string GetRankName() { if (points >= Int32.MinValue && points <= LevelOneMaxPoints) return LevelOneName; else if (points >= LevelTwoMinPoints && points <= LevelTwoMaxPoints) return LevelTwoName; else if (points >= LevelThreeMinPoints && points <= LevelThreeMaxPoints) return LevelThreeName; else if (points >= LevelFourMinPoints && points <= LevelFourMaxPoints) return LevelFourName; else if (points >= LevelFourPlusMinPoints && points <= LevelFourPlusMaxPoints) return LevelFourPlusName; else if (points >= LevelFiveMinPoints && points <= LevelFiveMaxPoints) return LevelFiveName; else if (points >= LevelSixMinPoints && points <= LevelSixMaxPoints) return LevelFiveName; else if (points >= LevelSevenMinPoints && points <= LevelSevenMaxPoints) return LevelSevenName; else if (points >= LevelEightMinPoints && points <= LevelEightMaxPoints) return LevelEightName; else if (points >= LevelEightPlusMinPoints && points <= LevelEightPlusMaxPoints) return LevelEightPlusName; else if (points >= LevelNineMinPoints && points <= LevelNineMaxPoints) return LevelNineName; else if (points >= LevelNineMinPoints && points <= LevelNineMaxPoints) return LevelNineName; else if (points >= LevelTenMinPoints) return LevelFourName; else return "No Rank"; } } Do you think this is the most efficient way to do this?

    Read the article

  • Reversing a number in c++

    - by Marcel Bujnowski
    I created a program to show the sum and show the reversed number a person has typed. The sum function works but the revers function is not. Can anyone give me any tips on how to fix it. I created a program to show the sum and show the reversed number a person has typed. The sum function works but the revers function is not. Can anyone give me any tips on how to fix it. #include<iostream> #include<iomanip> using namespace std; void printSum(int n, bool reverse); int sm(int n); int reverseInt(int n); void printAddTable(int n); int main() { int reverse; int sum=0; int n; cout<<"Enter N value:"<<endl; cin>>n; if(n>0) { reverse = true; printSum( n, reverse); // calls the printSum Method } else { //cout<<"enter positive Number only:"<<endl; } sum = sm(n); //err // calls the sum Method reverse = reverseInt(n); // calls the reverseInt Method cout<<"The reverse value is:"<<reverse; printAddTable(n); // calls the printAddTable Method //getch() } //end of main() void printSum(int n, bool reverse) { int sum=0; // print sum of reverse numbers for(int i=n; i>=1; i--) { sum=sum+i; cout<<i<< " "<<"+"<<" "; } cout<<sum; } int sm(int n) {int sum =0; for(int i=1; i<=n; i++) { sum = sum + i ; cout << endl; cout<<i<<" "<<"+"<<" "<<endl; // print n positive integers cout << endl; } cout<< "Are " <<n<< " positive integers"<<endl; cout<< "Sum is "<<sum <<endl; return sum; } int reverseInt(int n) { int reminder=0; int sum =0; while(n<=0) { reminder = n/10; sum = (sum * 10) + reminder; // it returns the reverse number n = n % 10; } return sum; } void printAddTable(int n) { for(int i=1; i<=n; i++) { cout<<i<<endl; for(int j=1; j<=n; j++) // print n X n add table { cout<<i+j<<endl; } } } {

    Read the article

  • Moq a function with 5+ parameters and access invocation arguments.

    - by beerncircus
    I have a function I want to Moq. The problem is that it takes 5 parameters. The framework only contains Action<T1,T2,T3,T4> and Moq's generic CallBack() only overloads Action and the four generic versions. Is there an elegant workaround for this? This is what I want to do: public class Filter : IFilter { public int Filter(int i1, int i2, int i3, int i4, int i5){return 0;} } //Moq code: var mocker = new Mock<IFilter>(); mocker.Setup(x => x.Filter( It.IsAny<int>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<int>()) .Callback ( (int i1, int i2, int i3, int i4, int i5) => i1 * 2 ); Moq doesn't allow this because there is no generic Action that takes 5+ parameters. I've resorted to making my own stub. Obviously, it would be better to use Moq with all of its verifications, etc.

    Read the article

  • How is conversion of float/double to int handled in printf?

    - by Sandip
    Consider this program int main() { float f = 11.22; double d = 44.55; int i,j; i = f; //cast float to int j = d; //cast double to int printf("i = %d, j = %d, f = %d, d = %d", i,j,f,d); //This prints the following: // i = 11, j = 44, f = -536870912, d = 1076261027 return 0; } Can someone explain why the casting from double/float to int works correctly in the first case, and does not work when done in printf? This program was compiled on gcc-4.1.2 on 32-bit linux machine. EDIT: Zach's answer seems logical, i.e. use of format specifiers to figure out what to pop off the stack. However then consider this follow up question: int main() { char c = 'd'; // sizeof c is 1, however sizeof character literal // 'd' is equal to sizeof(int) in ANSI C printf("lit = %c, lit = %d , c = %c, c = %d", 'd', 'd', c, c); //this prints: lit = d, lit = 100 , c = d, c = 100 //how does printf here pop off the right number of bytes even when //the size represented by format specifiers doesn't actually match //the size of the passed arguments(char(1 byte) & char_literal(4 bytes)) return 0; } How does this work?

    Read the article

  • Dll Import : Unable to find Entry Point "fnMultiply" in DLL "ImportDLL"

    - by user662285
    I am trying to use DLLImport for using Win32 dll method in C#. Win32 dll C++ // .h file #ifdef IMPORTDLL_EXPORTS #define IMPORTDLL_API __declspec(dllexport) #else #define IMPORTDLL_API __declspec(dllimport) #endif // This class is exported from the ImportDLL.dll class IMPORTDLL_API CImportDLL { public: CImportDLL(void); // TODO: add your methods here. int Add(int a , int b); }; extern IMPORTDLL_API int nImportDLL; IMPORTDLL_API int fnImportDLL(void); IMPORTDLL_API int fnMultiply(int a,int b); // .cpp file // ImportDLL.cpp : Defines the exported functions for the DLL application. // #include "stdafx.h" #include "ImportDLL.h" // This is an example of an exported variable IMPORTDLL_API int nImportDLL=0; // This is an example of an exported function. IMPORTDLL_API int fnImportDLL(void) { return 42; } IMPORTDLL_API int fnMultiply(int a , int b) { return (a*b); } Once i build this i get ImportDLL.dll Now i create Windows Application and add this dll in debug folder and try to use this method using DLLImport [DllImport("ImportDLL.dll")] public static extern int fnMultiply(int a, int b); And I try to call this in C# int a = fnMultiply(5, 6); // This line gives error Unable to find an entry point Can any body tell what i am missing? Thanks.

    Read the article

  • question about LSD radix sort

    - by davit-datuashvili
    hello i have following code public class LSD{ public static int R=1<<8; public static int bytesword=4; public static void radixLSD(int a[],int l,int r){ int aux[]=new int[a.length]; for (int d=bytesword-1;d>=0;d--){ int i, j; int count[]=new int[R+1]; for ( j=0;j<R;j++) count[j]=0; for (i=l;i<=r;i++) count[digit(a[i],d)+1]++; for (j=1;j<R;j++) count[j]+=count[j-1]; for (i=l;i<=r;i++) aux[count[digit(a[i],d)]++]=a[i]; for (i=l;i<=r;i++) a[i]=aux[i-1]; } } public static void main(String[]args){ int a[]=new int[]{3,6,5,7,4,8,9}; radixLSD(a,0,a.length-1); for (int i=0;i<a.length;i++){ System.out.println(a[i]); } } public static int digit(int n,int d){ return (n>>d)&1; } } but it show me mistake java.lang.ArrayIndexOutOfBoundsException: -1 at LSD.radixLSD(LSD.java:19) at LSD.main(LSD.java:29) please help me

    Read the article

  • What is the merit of the "function" type (not "pointer to function")

    - by anatolyg
    Reading the C++ Standard, i see that there are "function" types and "pointer to function" types: typedef int func(int); // function typedef int (*pfunc)(int); // pointer to function typedef func* pfunc; // same as above I have never seen the function types used outside of examples (or maybe i didn't recognize their usage?). Some examples: func increase, decrease; // declares two functions int increase(int), decrease(int); // same as above int increase(int x) {return x + 1;} // cannot use the typedef when defining functions int decrease(int x) {return x - 1;} // cannot use the typedef when defining functions struct mystruct { func add, subtract, multiply; // declares three member functions int member; }; int mystruct::add(int x) {return x + member;} // cannot use the typedef int mystruct::subtract(int x) {return x - member;} int main() { func k; // the syntax is correct but the variable k is useless! mystruct myobject; myobject.member = 4; cout << increase(5) << ' ' << decrease(5) << '\n'; // outputs 6 and 4 cout << myobject.add(5) << ' ' << myobject.subtract(5) << '\n'; // 9 and 1 } Seeing that the function types support syntax that doesn't appear in C (declaring member functions), i guess they are not just a part of C baggage that C++ has to support for backward compatibility. So is there any use for function types, other than demonstrating some funky syntax?

    Read the article

  • Function pointers to member functions

    - by Jacob
    There are several duplicates of this but nobody explains why I can use a member variable to store the pointer (in FOO) but when I try it with a local variable (in the commented portion of BAR), it's illegal. Could anybody explain this? #include <iostream> using namespace std; class FOO { public: int (FOO::*fptr)(int a, int b); int add_stuff(int a, int b) { return a+b; } void call_adder(int a, int b) { fptr = &FOO::add_stuff; cout<<(this->*fptr)(a,b)<<endl; } }; class BAR { public: int add_stuff(int a, int b) { return a+b; } void call_adder(int a, int b) { //int (BAR::*fptr)(int a, int b); //fptr = &BAR::add_stuff; //cout<<(*fptr)(a,b)<<endl; } }; int main() { FOO test; test.call_adder(10,20); return 0; }

    Read the article

  • select i th smallest element from array

    - by davit-datuashvili
    i have divide and conqurer method to find i th smalles element from array here is code public class rand_select{ public static int Rand_partition( int a[],int p,int q,int i){ //smallest in a[p..q] if ( p==q) return a[p]; int r=partition (a,p,q); int k=r-p+1; if (i==k) return a[r]; if (i<k){ return Rand_partition(a,p,r-1,i); } return Rand_partition(a,r-1,q,i-k); } public static void main(String[]args){ int a[]=new int []{6,10,13,15,8,3,2,12}; System.out.println(Rand_partition(a,0,a.length-1,7)); } public static int partition(int a[],int p,int q){ int m=a[0]; while ( p<q){ while (p<q && a[p++] <m){ p++; } while (q>p && a[q--]>m){ q--; } int t=a[p]; a[p]=a[q]; a[q]=t; } int k=0; for (int i=0;i<a.length;i++){ if ( a[i]==m){ k=i; } } return k; } } but here is problem java.lang.ArrayIndexOutOfBoundsException please help me

    Read the article

  • How do I declare and initialize a 2d int vector in C++?

    - by FrankTheTank
    I'm trying to do something like: #include <iostream> #include <vector> #include <ctime> class Clickomania { public: Clickomania(); std::vector<std::vector<int> > board; bool move(int, int); bool isSolved(); void print(); void pushDown(); }; Clickomania::Clickomania() : board(12, std::vector<int>(8,0)) { srand((unsigned)time(0)); for(int i = 0; i < 12; i++) { for(int j = 0; j < 8; j++) { int color = (rand() % 6) + 1; board[i][j] = color; } } } However, apparently I can't initialize the "board" vector of vectors this way. How can I create a public member of a 2d vector type and initialize it properly?

    Read the article

  • question about permutation problem

    - by davit-datuashvili
    i have posted similar problem here http://stackoverflow.com/questions/2920315/permutation-of-array but i want following we know that with length n there is n! possible permutation from which one such that all element are in order they are in sorted variant so i want break permutation when array is in order and print result but something is wrong i think that problem is repeated of permutation here is my code import java.util.*; public class permut{ public static Random r=new Random(); public static void display(int a[],int n){ for (int i=0;i<n;i++){ System.out.println(a[i]); } } public static void Permut(int a[],int n){ int j=0; int k=0; while (j<fact(n)){ int s=r.nextInt(n); for (int i=0;i<n;i++){ k=a[i]; a[i]=a[s]; a[s]=k; } j++; if (sorted(a,n)) display(a,n); break; } } public static void main(String[]args){ int a[]=new int[]{3,4,1,2}; int n=a.length; Permut(a,n); } public static int fact(int n){ if (n==0 || (n==1) ) return 1; return n*fact(n-1); } public static boolean sorted(int a[],int n ){ boolean flag=false; for (int i=0;i<n-1;i++){ if (a[i]<a[i+1]){ flag=true; } else{ flag=false; } } return flag; } } can anybody help me? result is nothing

    Read the article

  • Writing a recursive sorting algorithm of an array of integers

    - by 12345
    I am trying to write a recursive sorting algorithm for an array of integers. The following codes prints to the console: 3, 5, 2, 1, 1, 2, 6, 7, 8, 10, 20 The output should be sorted but somehow "it doesn't work". public static void main(String[] args) { int[] unsortedList = {20, 3, 1, 2, 1, 2, 6, 8, 10, 5, 7}; duplexSelectionSort(unsortedList, 0, unsortedList.length-1); for (int i = 0; i < unsortedList.length; i++) { System.out.println(unsortedList[i]); } } public static void duplexSelectionSort( int[] unsortedNumbers, int startIndex, int stopIndex) { int minimumIndex = 0; int maximumIndex = 0; if (startIndex < stopIndex) { int index = 0; while (index <= stopIndex) { if (unsortedNumbers[index] < unsortedNumbers[minimumIndex]) { minimumIndex = index; } if (unsortedNumbers[index] > unsortedNumbers[maximumIndex]) { maximumIndex = index; } index++; } swapEdges(unsortedNumbers, startIndex, stopIndex, minimumIndex, maximumIndex); duplexSelectionSort(unsortedNumbers, startIndex + 1, stopIndex - 1); } } public static void swapEdges( int[] listOfIntegers, int startIndex, int stopIndex, int minimumIndex, int maximumIndex) { if ((minimumIndex == stopIndex) && (maximumIndex == startIndex)) { swap(listOfIntegers, startIndex, stopIndex); } else { if (maximumIndex == startIndex) { swap(listOfIntegers, maximumIndex, stopIndex); swap(listOfIntegers, minimumIndex, startIndex); } else { swap(listOfIntegers, minimumIndex, startIndex); swap(listOfIntegers, maximumIndex, stopIndex); } } } public static void swap(int[] listOfIntegers, int index1, int index2) { int savedElementAtIndex1 = listOfIntegers[index1]; listOfIntegers[index1] = listOfIntegers[index2]; listOfIntegers[index2] = savedElementAtIndex1; }

    Read the article

  • Code Contracts: Unit testing contracted code

    - by DigiMortal
    Code contracts and unit tests are not replacements for each other. They both have different purpose and different nature. It does not matter if you are using code contracts or not – you still have to write tests for your code. In this posting I will show you how to unit test code with contracts. In my previous posting about code contracts I showed how to avoid ContractExceptions that are defined in code contracts runtime and that are not accessible for us in design time. This was one step further to make my randomizer testable. In this posting I will complete the mission. Problems with current code This is my current code. public class Randomizer {     public static int GetRandomFromRangeContracted(int min, int max)     {         Contract.Requires<ArgumentOutOfRangeException>(             min < max,             "Min must be less than max"         );           Contract.Ensures(             Contract.Result<int>() >= min &&             Contract.Result<int>() <= max,             "Return value is out of range"         );           var rnd = new Random();         return rnd.Next(min, max);     } } As you can see this code has some problems: randomizer class is static and cannot be instantiated. We cannot move this class between components if we need to, GetRandomFromRangeContracted() is not fully testable because we cannot currently affect random number generator output and therefore we cannot test post-contract. Now let’s solve these problems. Making randomizer testable As a first thing I made Randomizer to be class that must be instantiated. This is simple thing to do. Now let’s solve the problem with Random class. To make Randomizer testable I define IRandomGenerator interface and RandomGenerator class. The public constructor of Randomizer accepts IRandomGenerator as argument. public interface IRandomGenerator {     int Next(int min, int max); }   public class RandomGenerator : IRandomGenerator {     private Random _random = new Random();       public int Next(int min, int max)     {         return _random.Next(min, max);     } } And here is our Randomizer after total make-over. public class Randomizer {     private IRandomGenerator _generator;       private Randomizer()     {         _generator = new RandomGenerator();     }       public Randomizer(IRandomGenerator generator)     {         _generator = generator;     }       public int GetRandomFromRangeContracted(int min, int max)     {         Contract.Requires<ArgumentOutOfRangeException>(             min < max,             "Min must be less than max"         );           Contract.Ensures(             Contract.Result<int>() >= min &&             Contract.Result<int>() <= max,             "Return value is out of range"         );           return _generator.Next(min, max);     } } It seems to be inconvenient to instantiate Randomizer now but you can always use DI/IoC containers and break compiled dependencies between the components of your system. Writing tests for randomizer IRandomGenerator solved problem with testing post-condition. Now it is time to write tests for Randomizer class. Writing tests for contracted code is not easy. The main problem is still ContractException that we are not able to access. Still it is the main exception we get as soon as contracts fail. Although pre-conditions are able to throw exceptions with type we want we cannot do much when post-conditions will fail. We have to use Contract.ContractFailed event and this event is called for every contract failure. This way we find ourselves in situation where supporting well input interface makes it impossible to support output interface well and vice versa. ContractFailed is nasty hack and it works pretty weird way. Although documentation sais that ContractFailed is good choice for testing contracts it is still pretty painful. As a last chance I got tests working almost normally when I wrapped them up. Can you remember similar solution from the times of Visual Studio 2008 unit tests? Cannot understand how Microsoft was able to mess up testing again. [TestClass] public class RandomizerTest {     private Mock<IRandomGenerator> _randomMock;     private Randomizer _randomizer;     private string _lastContractError;       public TestContext TestContext { get; set; }       public RandomizerTest()     {         Contract.ContractFailed += (sender, e) =>         {             e.SetHandled();             e.SetUnwind();               throw new Exception(e.FailureKind + ": " + e.Message);         };     }       [TestInitialize()]     public void RandomizerTestInitialize()     {         _randomMock = new Mock<IRandomGenerator>();         _randomizer = new Randomizer(_randomMock.Object);         _lastContractError = string.Empty;     }       #region InputInterfaceTests     [TestMethod]     [ExpectedException(typeof(Exception))]     public void GetRandomFromRangeContracted_should_throw_exception_when_min_is_not_less_than_max()     {         try         {             _randomizer.GetRandomFromRangeContracted(100, 10);         }         catch (Exception ex)         {             throw new Exception(string.Empty, ex);         }     }       [TestMethod]     [ExpectedException(typeof(Exception))]     public void GetRandomFromRangeContracted_should_throw_exception_when_min_is_equal_to_max()     {         try         {             _randomizer.GetRandomFromRangeContracted(10, 10);         }         catch (Exception ex)         {             throw new Exception(string.Empty, ex);         }     }       [TestMethod]     public void GetRandomFromRangeContracted_should_work_when_min_is_less_than_max()     {         int minValue = 10;         int maxValue = 100;         int returnValue = 50;           _randomMock.Setup(r => r.Next(minValue, maxValue))             .Returns(returnValue)             .Verifiable();           var result = _randomizer.GetRandomFromRangeContracted(minValue, maxValue);           _randomMock.Verify();         Assert.AreEqual<int>(returnValue, result);     }     #endregion       #region OutputInterfaceTests     [TestMethod]     [ExpectedException(typeof(Exception))]     public void GetRandomFromRangeContracted_should_throw_exception_when_return_value_is_less_than_min()     {         int minValue = 10;         int maxValue = 100;         int returnValue = 7;           _randomMock.Setup(r => r.Next(10, 100))             .Returns(returnValue)             .Verifiable();           try         {             _randomizer.GetRandomFromRangeContracted(minValue, maxValue);         }         catch (Exception ex)         {             throw new Exception(string.Empty, ex);         }           _randomMock.Verify();     }       [TestMethod]     [ExpectedException(typeof(Exception))]     public void GetRandomFromRangeContracted_should_throw_exception_when_return_value_is_more_than_max()     {         int minValue = 10;         int maxValue = 100;         int returnValue = 102;           _randomMock.Setup(r => r.Next(10, 100))             .Returns(returnValue)             .Verifiable();           try         {             _randomizer.GetRandomFromRangeContracted(minValue, maxValue);         }         catch (Exception ex)         {             throw new Exception(string.Empty, ex);         }           _randomMock.Verify();     }     #endregion        } Although these tests are pretty awful and contain hacks we are at least able now to make sure that our code works as expected. Here is the test list after running these tests. Conclusion Code contracts are very new stuff in Visual Studio world and as young technology it has some problems – like all other new bits and bytes in the world. As you saw then making our contracted code testable is easy only to the point when pre-conditions are considered. When we start dealing with post-conditions we will end up with hacked tests. I hope that future versions of code contracts will solve error handling issues the way that testing of contracted code will be easier than it is right now.

    Read the article

  • Overlay bitmap on live video

    - by sijith
    Hi i want to Overlay bitmap on live video. Iam trying to do this with the directshow sample. I edited PlayCapMonker sample and added some functions to enable this. i did this with the procedure explained in below link http://www.ureader.com/msg/1471251.aspx Now i am gettting errors Error 2 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int Error 3 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int Error 5 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int Error 6 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int Error 8 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int Error 9 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int Error 21 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int Error 22 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int Error 26 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int Error 27 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int Error 36 error C2228: left of '.m_alpha' must have class/struct/union Error 38 error C2227: left of '-SetAlphaBitmap' must point to class/struct/union/generic type Error 7 error C2146: syntax error : missing ';' before identifier 'Pool' Error 4 error C2146: syntax error : missing ';' before identifier 'Format' c:\Program Files\Microsoft Platform SDK\include\Vmr9.h 368 PlayCapMoniker Error 1 error C2143: syntax error : missing ';' before '' Error 20 error C2143: syntax error : missing ';' before '' Error 25 error C2143: syntax error : missing ';' before '*' Error 30 error C2065: 'g_pMixerBitmap' : undeclared identifier Error 33 error C2065: 'g_pMixerBitmap' : undeclared identifier Error 37 error C2065: 'g_pMixerBitmap' : undeclared identifier Error 31 error C2065: 'g_hbm' : undeclared identifier Error 32 error C2065: 'g_hbm' : undeclared identifier Error 35 error C2065: 'config' : undeclared identifier Error 10 error C2061: syntax error : identifier 'IDirect3DSurface9' Error 11 error C2061: syntax error : identifier 'IDirect3DSurface9' Error 12 error C2061: syntax error : identifier 'IDirect3DSurface9' Error 13 error C2061: syntax error : identifier 'IDirect3DSurface9' Error 16 error C2061: syntax error : identifier 'IDirect3DSurface9' Error 19 error C2061: syntax error : identifier 'IDirect3DSurface9' Error 23 error C2061: syntax error : identifier 'IDirect3DSurface9' Error 24 error C2061: syntax error : identifier 'IDirect3DSurface9' Error 28 error C2061: syntax error : identifier 'IDirect3DSurface9' Error 29 error C2061: syntax error : identifier 'IDirect3DSurface9' Error 14 error C2061: syntax error : identifier 'IDirect3DDevice9' Error 15 error C2061: syntax error : identifier 'IDirect3DDevice9' Error 17 error C2061: syntax error : identifier 'IDirect3DDevice9' Error 18 error C2061: syntax error : identifier 'IDirect3DDevice9' Error 34 error C2039: 'pDDS' : is not a member of '_VMR9AlphaBitmap' SDK\Samples\Multimedia\DirectShow\Capture\PlayCapMoniker\PlayCapMoniker.cpp 263 PlayCapMoniker

    Read the article

  • Overlay bitmap on live video

    - by sijith
    Hi i want to Overlay bitmap on live video. Iam trying to do this with the directshow sample. I edited PlayCapMonker sample and added some functions to enable this. i did this with the procedure explained in below link http://www.ureader.com/msg/1471251.aspx Now i am gettting errors Error 2 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int Error 3 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int Error 5 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int Error 6 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int Error 8 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int Error 9 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int Error 21 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int Error 22 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int Error 26 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int Error 27 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int Error 36 error C2228: left of '.m_alpha' must have class/struct/union Error 38 error C2227: left of '-SetAlphaBitmap' must point to class/struct/union/generic type Error 7 error C2146: syntax error : missing ';' before identifier 'Pool' Error 4 error C2146: syntax error : missing ';' before identifier 'Format' c:\Program Files\Microsoft Platform SDK\include\Vmr9.h 368 PlayCapMoniker Error 1 error C2143: syntax error : missing ';' before '' Error 20 error C2143: syntax error : missing ';' before '' Error 25 error C2143: syntax error : missing ';' before '*' Error 30 error C2065: 'g_pMixerBitmap' : undeclared identifier Error 33 error C2065: 'g_pMixerBitmap' : undeclared identifier Error 37 error C2065: 'g_pMixerBitmap' : undeclared identifier Error 31 error C2065: 'g_hbm' : undeclared identifier Error 32 error C2065: 'g_hbm' : undeclared identifier Error 35 error C2065: 'config' : undeclared identifier Error 10 error C2061: syntax error : identifier 'IDirect3DSurface9' Error 11 error C2061: syntax error : identifier 'IDirect3DSurface9' Error 12 error C2061: syntax error : identifier 'IDirect3DSurface9' Error 13 error C2061: syntax error : identifier 'IDirect3DSurface9' Error 16 error C2061: syntax error : identifier 'IDirect3DSurface9' Error 19 error C2061: syntax error : identifier 'IDirect3DSurface9' Error 23 error C2061: syntax error : identifier 'IDirect3DSurface9' Error 24 error C2061: syntax error : identifier 'IDirect3DSurface9' Error 28 error C2061: syntax error : identifier 'IDirect3DSurface9' Error 29 error C2061: syntax error : identifier 'IDirect3DSurface9' Error 14 error C2061: syntax error : identifier 'IDirect3DDevice9' Error 15 error C2061: syntax error : identifier 'IDirect3DDevice9' Error 17 error C2061: syntax error : identifier 'IDirect3DDevice9' Error 18 error C2061: syntax error : identifier 'IDirect3DDevice9' Error 34 error C2039: 'pDDS' : is not a member of '_VMR9AlphaBitmap' SDK\Samples\Multimedia\DirectShow\Capture\PlayCapMoniker\PlayCapMoniker.cpp 263 PlayCapMoniker

    Read the article

  • GCC, -O2, and bitfields - is this a bug or a feature?

    - by Rooke
    Today I discovered alarming behavior when experimenting with bit fields. For the sake of discussion and simplicity, here's an example program: #include <stdio.h> struct Node { int a:16 __attribute__ ((packed)); int b:16 __attribute__ ((packed)); unsigned int c:27 __attribute__ ((packed)); unsigned int d:3 __attribute__ ((packed)); unsigned int e:2 __attribute__ ((packed)); }; int main (int argc, char *argv[]) { Node n; n.a = 12345; n.b = -23456; n.c = 0x7ffffff; n.d = 0x7; n.e = 0x3; printf("3-bit field cast to int: %d\n",(int)n.d); n.d++; printf("3-bit field cast to int: %d\n",(int)n.d); } The program is purposely causing the 3-bit bit-field to overflow. Here's the (correct) output when compiled using "g++ -O0": 3-bit field cast to int: 7 3-bit field cast to int: 0 Here's the output when compiled using "g++ -O2" (and -O3): 3-bit field cast to int: 7 3-bit field cast to int: 8 Checking the assembly of the latter example, I found this: movl $7, %esi movl $.LC1, %edi xorl %eax, %eax call printf movl $8, %esi movl $.LC1, %edi xorl %eax, %eax call printf xorl %eax, %eax addq $8, %rsp The optimizations have just inserted "8", assuming 7+1=8 when in fact the number overflows and is zero. Fortunately the code I care about doesn't overflow as far as I know, but this situation scares me - is this a known bug, a feature, or is this expected behavior? When can I expect gcc to be right about this? Edit (re: signed/unsigned) : It's being treated as unsigned because it's declared as unsigned. Declaring it as int you get the output (with O0): 3-bit field cast to int: -1 3-bit field cast to int: 0 An even funnier thing happens with -O2 in this case: 3-bit field cast to int: 7 3-bit field cast to int: 8 I admit that attribute is a fishy thing to use; in this case it's a difference in optimization settings I'm concerned about.

    Read the article

  • Casting an object using 'as' returns null: myObject = newObject as MyObject; // null

    - by John Russell
    I am trying to create a custom object in AS3 to pass information to and from a server, which in this case will be Red5. In the below screenshots you will see that I am able to send a request for an object from as3, and receive it successfully from the java server. However, when I try to cast the received object to my defined objectType using 'as', it takes the value of null. It is my understanding that that when using "as" your checking to see if your variable is a member of the specified data type. If the variable is not, then null will be returned. This screenshot illustrates that I am have successfully received my object 'o' from red5 and I am just about to cast it to the (supposedly) identical datatype testObject of LobbyData: However, when testObject = o as LobbyData; runs, it returns null. :( Below you will see my specifications both on the java server and the as3 client. I am confident that both objects are identical in every way, but for some reason flash does not think so. I have been pulling my hair out for a long time, does anyone have any thoughts? AS3 Object: import flash.utils.IDataInput; import flash.utils.IDataOutput; import flash.utils.IExternalizable; import flash.net.registerClassAlias; [Bindable] [RemoteClass(alias = "myLobbyData.LobbyData")] public class LobbyData implements IExternalizable { private var sent:int; // java sentinel private var u:String; // red5 username private var sen:int; // another sentinel? private var ui:int; // fb uid private var fn:String; // fb name private var pic:String; // fb pic private var inb:Boolean; // is in the table? private var t:int; // table number private var s:int; // seat number public function setSent(sent:int):void { this.sent = sent; } public function getSent():int { return sent; } public function setU(u:String):void { this.u = u; } public function getU():String { return u; } public function setSen(sen:int):void { this.sen = sen; } public function getSen():int { return sen; } public function setUi(ui:int):void { this.ui = ui; } public function getUi():int { return ui; } public function setFn(fn:String):void { this.fn = fn; } public function getFn():String { return fn; } public function setPic(pic:String):void { this.pic = pic; } public function getPic():String { return pic; } public function setInb(inb:Boolean):void { this.inb = inb; } public function getInb():Boolean { return inb; } public function setT(t:int):void { this.t = t; } public function getT():int { return t; } public function setS(s:int):void { this.s = s; } public function getS():int { return s; } public function readExternal(input:IDataInput):void { sent = input.readInt(); u = input.readUTF(); sen = input.readInt(); ui = input.readInt(); fn = input.readUTF(); pic = input.readUTF(); inb = input.readBoolean(); t = input.readInt(); s = input.readInt(); } public function writeExternal(output:IDataOutput):void { output.writeInt(sent); output.writeUTF(u); output.writeInt(sen); output.writeInt(ui); output.writeUTF(fn); output.writeUTF(pic); output.writeBoolean(inb); output.writeInt(t); output.writeInt(s); } } Java Object: package myLobbyData; import org.red5.io.amf3.IDataInput; import org.red5.io.amf3.IDataOutput; import org.red5.io.amf3.IExternalizable; public class LobbyData implements IExternalizable { private static final long serialVersionUID = 115280920; private int sent; // java sentinel private String u; // red5 username private int sen; // another sentinel? private int ui; // fb uid private String fn; // fb name private String pic; // fb pic private Boolean inb; // is in the table? private int t; // table number private int s; // seat number public void setSent(int sent) { this.sent = sent; } public int getSent() { return sent; } public void setU(String u) { this.u = u; } public String getU() { return u; } public void setSen(int sen) { this.sen = sen; } public int getSen() { return sen; } public void setUi(int ui) { this.ui = ui; } public int getUi() { return ui; } public void setFn(String fn) { this.fn = fn; } public String getFn() { return fn; } public void setPic(String pic) { this.pic = pic; } public String getPic() { return pic; } public void setInb(Boolean inb) { this.inb = inb; } public Boolean getInb() { return inb; } public void setT(int t) { this.t = t; } public int getT() { return t; } public void setS(int s) { this.s = s; } public int getS() { return s; } @Override public void readExternal(IDataInput input) { sent = input.readInt(); u = input.readUTF(); sen = input.readInt(); ui = input.readInt(); fn = input.readUTF(); pic = input.readUTF(); inb = input.readBoolean(); t = input.readInt(); s = input.readInt(); } @Override public void writeExternal(IDataOutput output) { output.writeInt(sent); output.writeUTF(u); output.writeInt(sen); output.writeInt(ui); output.writeUTF(fn); output.writeUTF(pic); output.writeBoolean(inb); output.writeInt(t); output.writeInt(s); } } AS3 Client: public function refreshRoom(event:Event) { var resp:Responder=new Responder(handleResp,null); ncLobby.call("getLobbyData", resp, null); } public function handleResp(o:Object):void { var testObject:LobbyData=new LobbyData; testObject = o as LobbyData; trace(testObject); } Java Client public LobbyData getLobbyData(String param) { LobbyData lobbyData1 = new LobbyData(); lobbyData1.setSent(5); lobbyData1.setU("lawlcats"); lobbyData1.setSen(5); lobbyData1.setUi(5); lobbyData1.setFn("lulz"); lobbyData1.setPic("lulzagain"); lobbyData1.setInb(true); lobbyData1.setT(5); lobbyData1.setS(5); return lobbyData1; }

    Read the article

  • Copy android.R.layout to my project

    - by eric
    Good advice from CommonWare and Steve H but it's not as easy to me as I first thought. Based on their advice I'm trying to copy android.R.layout to my project to ensure consistency. How do you do this? I looked in Eclipse's Package Explorer and under Android 1.5android.jarandroidR.classRlayout and find R$layout.class. Do I copy the code out of there into my own class? From my very limited knowledge of Java, the following code doesn't make much sense: public static final class android.R$layout { // Field descriptor #8 I public static final int activity_list_item = 17367040; // Field descriptor #8 I public static final int browser_link_context_header = 17367054; // Field descriptor #8 I public static final int expandable_list_content = 17367041; // Field descriptor #8 I public static final int preference_category = 17367042; // Field descriptor #8 I public static final int select_dialog_item = 17367057; // Field descriptor #8 I public static final int select_dialog_multichoice = 17367059; // Field descriptor #8 I public static final int select_dialog_singlechoice = 17367058; // Field descriptor #8 I public static final int simple_dropdown_item_1line = 17367050; // Field descriptor #8 I public static final int simple_expandable_list_item_1 = 17367046; // Field descriptor #8 I public static final int simple_expandable_list_item_2 = 17367047; // Field descriptor #8 I public static final int simple_gallery_item = 17367051; // Field descriptor #8 I public static final int simple_list_item_1 = 17367043; // Field descriptor #8 I public static final int simple_list_item_2 = 17367044; // Field descriptor #8 I public static final int simple_list_item_checked = 17367045; // Field descriptor #8 I public static final int simple_list_item_multiple_choice = 17367056; // Field descriptor #8 I public static final int simple_list_item_single_choice = 17367055; // Field descriptor #8 I public static final int simple_spinner_dropdown_item = 17367049; // Field descriptor #8 I public static final int simple_spinner_item = 17367048; // Field descriptor #8 I public static final int test_list_item = 17367052; // Field descriptor #8 I public static final int two_line_list_item = 17367053; // Method descriptor #50 ()V // Stack: 3, Locals: 1 public R$layout(); 0 aload_0 [this] 1 invokespecial java.lang.Object() [1] 4 new java.lang.RuntimeException [2] 7 dup 8 ldc <String "Stub!"> [3] 10 invokespecial java.lang.RuntimeException(java.lang.String) [4] 13 athrow Line numbers: [pc: 0, line: 899] Local variable table: [pc: 0, pc: 14] local: this index: 0 type: android.R.layout Inner classes: [inner class info: #5 android/R$layout, outer class info: #64 android/R inner name: #55 layout, accessflags: 25 public static final] }

    Read the article

  • BST insert operation. don't insert a node if a duplicate exists already

    - by jeev
    the following code reads an input array, and constructs a BST from it. if the current arr[i] is a duplicate, of a node in the tree, then arr[i] is discarded. count in the struct node refers to the number of times a number appears in the array. fi refers to the first index of the element found in the array. after the insertion, i am doing a post-order traversal of the tree and printing the data, count and index (in this order). the output i am getting when i run this code is: 0 0 7 0 0 6 thank you for your help. Jeev struct node{ int data; struct node *left; struct node *right; int fi; int count; }; struct node* binSearchTree(int arr[], int size); int setdata(struct node**node, int data, int index); void insert(int data, struct node **root, int index); void sortOnCount(struct node* root); void main(){ int arr[] = {2,5,2,8,5,6,8,8}; int size = sizeof(arr)/sizeof(arr[0]); struct node* temp = binSearchTree(arr, size); sortOnCount(temp); } struct node* binSearchTree(int arr[], int size){ struct node* root = (struct node*)malloc(sizeof(struct node)); if(!setdata(&root, arr[0], 0)) fprintf(stderr, "root couldn't be initialized"); int i = 1; for(;i<size;i++){ insert(arr[i], &root, i); } return root; } int setdata(struct node** nod, int data, int index){ if(*nod!=NULL){ (*nod)->fi = index; (*nod)->left = NULL; (*nod)->right = NULL; return 1; } return 0; } void insert(int data, struct node **root, int index){ struct node* new = (struct node*)malloc(sizeof(struct node)); setdata(&new, data, index); struct node** temp = root; while(1){ if(data<=(*temp)->data){ if((*temp)->left!=NULL) *temp=(*temp)->left; else{ (*temp)->left = new; break; } } else if(data>(*temp)->data){ if((*temp)->right!=NULL) *temp=(*temp)->right; else{ (*temp)->right = new; break; } } else{ (*temp)->count++; free(new); break; } } } void sortOnCount(struct node* root){ if(root!=NULL){ sortOnCount(root->left); sortOnCount(root->right); printf("%d %d %d\n", (root)->data, (root)->count, (root)->fi); } }

    Read the article

  • Why do I need an intermediate conversion to go from struct to decimal, but not struct to int?

    - by Jesse McGrew
    I have a struct like this, with an explicit conversion to float: struct TwFix32 { public static explicit operator float(TwFix32 x) { ... } } I can convert a TwFix32 to int with a single explicit cast: (int)fix32 But to convert it to decimal, I have to use two casts: (decimal)(float)fix32 There is no implicit conversion from float to either int or decimal. Why does the compiler let me omit the intermediate cast to float when I'm going to int, but not when I'm going to decimal?

    Read the article

  • Java: most efficient way to defensively copy an int[]?

    - by Jason S
    I have an interface DataSeries with a method int[] getRawData(); For various reasons (primarily because I'm using this with MATLAB, and MATLAB handles int[] well) I need to return an array rather than a List. I don't want my implementing classes to return the int[] array because it is mutable. What is the most efficient way to copy an int[] array (sizes in the 1000-1000000 length range) ? Is it clone()?

    Read the article

  • Do I need to cast the result of strtol to int?

    - by Kristo
    The following code does not give a warning with g++ 4.1.1 and -Wall. int octalStrToInt(const std::string& s) { return strtol(s.c_str(), 0, 8); } I was expecting a warning because strtol returns a long int but my function is only returning a plain int. Might other compilers emit a warning here? Should I cast the return value to int in this case as a good practice?

    Read the article

  • Code Contracts: Hiding ContractException

    - by DigiMortal
    It’s time to move on and improve my randomizer I wrote for an example of static checking of code contracts. In this posting I will modify contracts and give some explanations about pre-conditions and post-conditions. Also I will show you how to avoid ContractExceptions and how to replace them with your own exceptions. As a first thing let’s take a look at my randomizer. public class Randomizer {     public static int GetRandomFromRange(int min, int max)     {         var rnd = new Random();         return rnd.Next(min, max);     }       public static int GetRandomFromRangeContracted(int min, int max)     {         Contract.Requires(min < max, "Min must be less than max");           var rnd = new Random();         return rnd.Next(min, max);     } } We have some problems here. We need contract for method output and we also need some better exception handling mechanism. As ContractException as type is hidden from us we have to switch from ContractException to some other Exception type that we can catch. Adding post-condition Pre-conditions are contracts for method’s input interface. Read it as follows: pre-conditions make sure that all conditions for method’s successful run are met. Post-conditions are contracts for output interface of method. So, post-conditions are for output arguments and return value. My code misses the post-condition that checks return value. Return value in this case must be greater or equal to minimum value and less or equal to maximum value. To make sure that method can run only the correct value I added call to Contract.Ensures() method. public static int GetRandomFromRangeContracted(int min, int max) {     Contract.Requires(min < max, "Min must be less than max");       Contract.Ensures(         Contract.Result<int>() >= min &&         Contract.Result<int>() <= max,         "Return value is out of range"     );       var rnd = new Random();     return rnd.Next(min, max); } I think that the line I added does not need any further comments. Avoiding ContractException for input interface ContractException lives in hidden namespace and we cannot see it at design time. But it is common exception type for all contract exceptions that we do not switch over to some other type. The case of Contract.Requires() method is simple: we can tell it what kind of exception we need if something goes wrong with contract it ensures. public static int GetRandomFromRangeContracted(int min, int max) {     Contract.Requires<ArgumentOutOfRangeException>(         min < max,         "Min must be less than max"     );       Contract.Ensures(         Contract.Result<int>() >= min &&         Contract.Result<int>() <= max,         "Return value is out of range"     );       var rnd = new Random();     return rnd.Next(min, max); } Now, if we violate the input interface contract giving min value that is not less than max value we get ArgumentOutOfRangeException. Avoiding ContractException for output interface Output interface is more complex to control. We cannot give exception type there and hope that this type of exception will be thrown if something goes wrong. Instead we have to use delegate that gathers information about problem and throws the exception we expect to be thrown. From documentation you can find the following example about the delegate I mentioned. Contract.ContractFailed += (sender, e) => {     e.SetHandled();     e.SetUnwind(); // cause code to abort after event     Assert.Fail(e.FailureKind.ToString() + ":" + e.DebugMessage); }; We can use this delegate to throw the Exception. Let’s move the code to separate method too. Here is our method that uses now ContractException hiding. public static int GetRandomFromRangeContracted(int min, int max) {     Contract.Requires(min < max, "Min must be less than max");       Contract.Ensures(         Contract.Result<int>() >= min &&         Contract.Result<int>() <= max,         "Return value is out of range"     );     Contract.ContractFailed += Contract_ContractFailed;       var rnd = new Random();     return rnd.Next(min, max)+1000; } And here is the delegate that creates exception. public static void Contract_ContractFailed(object sender,     ContractFailedEventArgs e) {     e.SetHandled();     e.SetUnwind();       throw new Exception(e.FailureKind.ToString() + ":" + e.Message); } Basically we can do in this delegate whatever we like to do with output interface errors. We can even introduce our own contract exception type. As you can see later then ContractFailed event is very useful at unit testing.

    Read the article

< Previous Page | 24 25 26 27 28 29 30 31 32 33 34 35  | Next Page >