Search Results

Search found 6094 results on 244 pages for 'double gras'.

Page 47/244 | < Previous Page | 43 44 45 46 47 48 49 50 51 52 53 54  | Next Page >

  • Java: Detecting image format, resize (scale) and save as JPEG

    - by BoDiE2003
    This is the code I have, it actually works, not perfectly but it does, the problem is that the resized thumbnails are not pasting on the white Drawn rectangle, breaking the images aspect ratio, here is the code, could someone suggest me a fix for it, please? Thank you import java.awt.Color; import java.awt.Graphics2D; import java.awt.Image; import java.awt.RenderingHints; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import javax.imageio.ImageIO; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class ImageScalerImageIoImpl implements ImageScaler { private static final String OUTPUT_FORMAT_ID = "jpeg"; // Re-scaling image public byte[] scaleImage(byte[] originalImage, int targetWidth, int targetHeight) { try { InputStream imageStream = new BufferedInputStream( new ByteArrayInputStream(originalImage)); Image image = (Image) ImageIO.read(imageStream); int thumbWidth = targetWidth; int thumbHeight = targetHeight; // Make sure the aspect ratio is maintained, so the image is not skewed double thumbRatio = (double)thumbWidth / (double)thumbHeight; int imageWidth = image.getWidth(null); int imageHeight = image.getHeight(null); double imageRatio = (double)imageWidth / (double)imageHeight; if (thumbRatio < imageRatio) { thumbHeight = (int)(thumbWidth / imageRatio); } else { thumbWidth = (int)(thumbHeight * imageRatio); } // Draw the scaled image BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); System.out.println("Thumb width Buffered: " + thumbWidth + " || Thumb height Buffered: " + thumbHeight); Graphics2D graphics2D = thumbImage.createGraphics(); // Use of BILNEAR filtering to enable smooth scaling graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); // graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null); // White Background graphics2D.setPaint(Color.WHITE); graphics2D.fill(new Rectangle2D.Double(0, 0, targetWidth, targetHeight)); graphics2D.fillRect(0, 0, targetWidth, targetHeight); System.out.println("Target width: " + targetWidth + " || Target height: " + targetHeight); // insert the resized thumbnail between X and Y of the image graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null); System.out.println("Thumb width: " + thumbWidth + " || Thumb height: " + thumbHeight); // Write the scaled image to the outputstream ByteArrayOutputStream out = new ByteArrayOutputStream(); ImageIO.write(thumbImage, OUTPUT_FORMAT_ID, out); return out.toByteArray(); } catch (IOException ioe) { throw new ImageResizingException(ioe); } } }

    Read the article

  • gcc, strict-aliasing, and casting through a union

    - by Joseph Quinsey
    About a year ago the following paragraph was added to the GCC Manual, version 4.3.4, regarding -fstrict-aliasing: Similarly, access by taking the address, casting the resulting pointer and dereferencing the result has undefined behavior [emphasis added], even if the cast uses a union type, e.g.: union a_union { int i; double d; }; int f() { double d = 3.0; return ((union a_union *)&d)->i; } Does anyone have an example to illustrate this undefined behavior? Note this question is not about what the C99 standard says, or does not say. It is about the actual functioning of gcc, and other existing compilers, today. My simple, naive, attempt fails. For example: #include <stdio.h> union a_union { int i; double d; }; int f1(void) { union a_union t; t.d = 3333333.0; return t.i; // gcc manual: 'type-punning is allowed, provided ...' } int f2(void) { double d = 3333333.0; return ((union a_union *)&d)->i; // gcc manual: 'undefined behavior' } int main(void) { printf("%d\n", f1()); printf("%d\n", f2()); return 0; } works fine, giving on CYGWIN: -2147483648 -2147483648 Also note that taking addresses is obviously wrong (or right, if you are trying to illustrate undefined behavior). For example, just as we know this is wrong: extern void foo(int *, double *); union a_union t; t.d = 3.0; foo(&t.i, &t.d); // UD behavior so is this wrong: extern void foo(int *, double *); double d = 3.0; foo(&((union a_union *)&d)->i, &d); // UD behavior For background discussion about this, see for example: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1422.pdf http://gcc.gnu.org/ml/gcc/2010-01/msg00013.html http://davmac.wordpress.com/2010/02/26/c99-revisited/ http://cellperformance.beyond3d.com/articles/2006/06/understanding-strict-aliasing.html http://stackoverflow.com/questions/98650/what-is-the-strict-aliasing-rule http://stackoverflow.com/questions/2771023/c99-strict-aliasing-rules-in-c-gcc/2771041#2771041 The first link, draft minutes of an ISO meeting seven months ago, notes in section 4.16: Is there anybody that thinks the rules are clear enough? No one is really able to interpret tham.

    Read the article

  • Mock Object and Interface

    - by tunl
    I'm a newbie in Unit Test with Mock Object. I use EasyMock. I try to understand this example: import java.io.IOException; public interface ExchangeRate { double getRate(String inputCurrency, String outputCurrency) throws IOException; } import java.io.IOException; public class Currency { private String units; private long amount; private int cents; public Currency(double amount, String code) { this.units = code; setAmount(amount); } private void setAmount(double amount) { this.amount = new Double(amount).longValue(); this.cents = (int) ((amount * 100.0) % 100); } public Currency toEuros(ExchangeRate converter) { if ("EUR".equals(units)) return this; else { double input = amount + cents/100.0; double rate; try { rate = converter.getRate(units, "EUR"); double output = input * rate; return new Currency(output, "EUR"); } catch (IOException ex) { return null; } } } public boolean equals(Object o) { if (o instanceof Currency) { Currency other = (Currency) o; return this.units.equals(other.units) && this.amount == other.amount && this.cents == other.cents; } return false; } public String toString() { return amount + "." + Math.abs(cents) + " " + units; } } import junit.framework.TestCase; import org.easymock.EasyMock; import java.io.IOException; public class CurrencyTest extends TestCase { public void testToEuros() throws IOException { Currency testObject = new Currency(2.50, "USD"); Currency expected = new Currency(3.75, "EUR"); ExchangeRate mock = EasyMock.createMock(ExchangeRate.class); EasyMock.expect(mock.getRate("USD", "EUR")).andReturn(1.5); EasyMock.replay(mock); Currency actual = testObject.toEuros(mock); assertEquals(expected, actual); } } So, i wonder how to Currency use ExchangeRate in toEuros(..) method. rate = converter.getRate(units, "EUR"); The behavior of getRate(..) method is not specified because ExchangeRate is an interface.

    Read the article

  • Problem separating C++ code in header, inline functions and code.

    - by YuppieNetworking
    Hello all, I have the simplest code that I want to separate in three files: Header file: class and struct declarations. No implementations at all. Inline functions file: implementation of inline methods in header. Code file: normal C++ code for more complicated implementations. When I was about to implement an operator[] method, I couldn't manage to compile it. Here is a minimal example that shows the same problem: Header (myclass.h): #ifndef _MYCLASS_H_ #define _MYCLASS_H_ class MyClass { public: MyClass(const int n); virtual ~MyClass(); double& operator[](const int i); double operator[](const int i) const; void someBigMethod(); private: double* arr; }; #endif /* _MYCLASS_H_ */ Inline functions (myclass-inl.h): #include "myclass.h" inline double& MyClass::operator[](const int i) { return arr[i]; } inline double MyClass::operator[](const int i) const { return arr[i]; } Code (myclass.cpp): #include "myclass.h" #include "myclass-inl.h" #include <iostream> inline MyClass::MyClass(const int n) { arr = new double[n]; } inline MyClass::~MyClass() { delete[] arr; } void MyClass::someBigMethod() { std::cout << "Hello big method that is not inlined" << std::endl; } And finally, a main to test it all: #include "myclass.h" #include <iostream> using namespace std; int main(int argc, char *argv[]) { MyClass m(123); double x = m[1]; m[1] = 1234; cout << "m[1]=" << m[1] << endl; x = x + 1; return 0; } void nothing() { cout << "hello world" << endl; } When I compile it, it says: main.cpp:(.text+0x1b): undefined reference to 'MyClass::MyClass(int)' main.cpp:(.text+0x2f): undefined reference to 'MyClass::operator[](int)' main.cpp:(.text+0x49): undefined reference to 'MyClass::operator[](int)' main.cpp:(.text+0x65): undefined reference to 'MyClass::operator[](int)' However, when I move the main method to the MyClass.cpp file, it works. Could you guys help me spot the problem? Thank you.

    Read the article

  • Java: Detecting image formate - resize (scale) and save as JPEG

    - by BoDiE2003
    This is the code I have, it actually works, not perfectly but it does, the problem is that the resized thumbnails are not pasting on the white Drawn rectangle, breaking the images aspect ratio, here is the code, could someone suggest me a fix for it, please? Thank you import java.awt.Color; import java.awt.Graphics2D; import java.awt.Image; import java.awt.RenderingHints; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import javax.imageio.ImageIO; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class ImageScalerImageIoImpl implements ImageScaler { private static final String OUTPUT_FORMAT_ID = "jpeg"; // Re-scaling image public byte[] scaleImage(byte[] originalImage, int targetWidth, int targetHeight) { try { InputStream imageStream = new BufferedInputStream( new ByteArrayInputStream(originalImage)); Image image = (Image) ImageIO.read(imageStream); int thumbWidth = targetWidth; int thumbHeight = targetHeight; // Make sure the aspect ratio is maintained, so the image is not skewed double thumbRatio = (double)thumbWidth / (double)thumbHeight; int imageWidth = image.getWidth(null); int imageHeight = image.getHeight(null); double imageRatio = (double)imageWidth / (double)imageHeight; if (thumbRatio < imageRatio) { thumbHeight = (int)(thumbWidth / imageRatio); } else { thumbWidth = (int)(thumbHeight * imageRatio); } // Draw the scaled image BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); System.out.println("Thumb width Buffered: " + thumbWidth + " || Thumb height Buffered: " + thumbHeight); Graphics2D graphics2D = thumbImage.createGraphics(); // Use of BILNEAR filtering to enable smooth scaling graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); // graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null); // White Background graphics2D.setPaint(Color.WHITE); graphics2D.fill(new Rectangle2D.Double(0, 0, targetWidth, targetHeight)); graphics2D.fillRect(0, 0, targetWidth, targetHeight); System.out.println("Target width: " + targetWidth + " || Target height: " + targetHeight); // insert the resized thumbnail between X and Y of the image graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null); System.out.println("Thumb width: " + thumbWidth + " || Thumb height: " + thumbHeight); // Write the scaled image to the outputstream ByteArrayOutputStream out = new ByteArrayOutputStream(); ImageIO.write(thumbImage, OUTPUT_FORMAT_ID, out); return out.toByteArray(); } catch (IOException ioe) { throw new ImageResizingException(ioe); } } }

    Read the article

  • due at midnight - program compiles but has logic error(s)

    - by Leslie Laraia
    not sure why this program isn't working. it compiles, but doesn't provide the expected output. the input file is basically just this: Smith 80000 Jones 100000 Scott 75000 Washington 110000 Duffy 125000 Jacobs 67000 Here is the program: import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; /** * * @author Leslie */ public class Election { /** * @param args the command line arguments */ public static void main(String[] args) throws FileNotFoundException { // TODO code application logic here File inputFile = new File("C:\\Users\\Leslie\\Desktop\\votes.txt"); Scanner in = new Scanner(inputFile); int x = 0; String line = ""; Scanner lineScanner = new Scanner(line); line = in.nextLine(); while (in.hasNextLine()) { line = in.nextLine(); x++; } String[] senatorName = new String[x]; int[] votenumber = new int[x]; double[] votepercent = new double[x]; System.out.printf("%44s", "Election Results for State Senator"); System.out.println(); System.out.printf("%-22s", "Candidate"); //Prints the column headings to the screen System.out.printf("%22s", "Votes Received"); System.out.printf("%22s", "%of Total Votes"); int i; for(i=0; i<x; i++) { while(in.hasNextLine()) { line = in.nextLine(); String candidateName = lineScanner.next(); String candidate = candidateName.trim(); senatorName[i] = candidate; int votevalue = lineScanner.nextInt(); votenumber[i] = votevalue; } } votepercent = percentages(votenumber, x); for (i = 0; i < x; i++) { System.out.println(); System.out.printf("%-22s", senatorName[i]); System.out.printf("%22d", votenumber[i]); System.out.printf("%22.2f", votepercent[i]); System.out.println(); } } public static double [] percentages(int[] votenumber, int z) { double [] percentage = new double [z]; double total = 0; for (double element : votenumber) { total = total + element; } for(int i=0; i < votenumber.length; i++) { int y = votenumber[i]; percentage[i] = (y/total) * 100; } return percentage; } }

    Read the article

  • I have problems with adding rows to data-binded DataGridView in desktop app.

    - by Mishko
    DataTable table1 = new DataTable(); double brutoUkupno1 = 0; double porezUkupno1 = 0; double doprinosUkupno1 = 0; double netoUkupno1 = 0; double doprinosTeretUkupno1 = 0; double topliObrokUkupno1 = 0; double regresUkupno1 = 0; Connection con = new Connection(); table1 = con.boundTable(month, Convert.ToInt32(year)); //This is method which returns DataTable table1.Rows.Add(null, null, null, null, null, null, null, null, null, null, null, null, null, null); table1.Rows.Add(null, null, null, null, null, null, null, null, null, null, null, null, null, null); dgv2.Visible = true; dgv2.DataSource = table1; for (int i = 0; i < dgv2.RowCount - 2; i++) { topliObrokUkupno1 += Convert.ToDouble(dgv2.Rows[i].Cells[7].Value); regresUkupno1 += Convert.ToDouble(dgv2.Rows[i].Cells[8].Value); brutoUkupno1 += Convert.ToDouble(dgv2.Rows[i].Cells[9].Value); porezUkupno1 += Convert.ToDouble(dgv2.Rows[i].Cells[10].Value); doprinosUkupno1 += Convert.ToDouble(dgv2.Rows[i].Cells[11].Value); netoUkupno1 += Convert.ToDouble(dgv2.Rows[i].Cells[12].Value); doprinosTeretUkupno1 += Convert.ToDouble(dgv2.Rows[i].Cells[13].Value); //Now I am having problems with this below, putting things above to dgv2 : } dgv2.Rows[dgv2.Rows.Count - 1].Cells[0].Value = "Ukupno"; dgv2.Rows[dgv2.Rows.Count - 1].Cells[3].Value = month.ToString(); dgv2.Rows[dgv2.Rows.Count - 1].Cells[4].Value = year.ToString(); dgv2.Rows[dgv2.Rows.Count - 1].Cells[7].Value = topliObrokUkupno1.ToString(); dgv2.Rows[dgv2.Rows.Count - 1].Cells[8].Value = regresUkupno1.ToString(); dgv2.Rows[dgv2.Rows.Count - 1].Cells[9].Value = brutoUkupno1.ToString(); dgv2.Rows[dgv2.Rows.Count - 1].Cells[10].Value = porezUkupno1.ToString(); dgv2.Rows[dgv2.Rows.Count - 1].Cells[11].Value = doprinosUkupno1.ToString(); dgv2.Rows[dgv2.Rows.Count - 1].Cells[12].Value = netoUkupno1.ToString(); dgv2.Rows[dgv2.Rows.Count - 1].Cells[13].Value = doprinosTeretUkupno1.ToString(); dgv2.Rows[dgv2.RowCount - 2].Height = 3; dgv2.Rows[dgv2.RowCount - 2].DefaultCellStyle.BackColor = Color.Black;

    Read the article

  • Multiset container appears to stop sorting

    - by Sarah
    I would appreciate help debugging some strange behavior by a multiset container. Occasionally, the container appears to stop sorting. This is an infrequent error, apparent in only some simulations after a long time, and I'm short on ideas. (I'm an amateur programmer--suggestions of all kinds are welcome.) My container is a std::multiset that holds Event structs: typedef std::multiset< Event, std::less< Event > > EventPQ; with the Event structs sorted by their double time members: struct Event { public: explicit Event(double t) : time(t), eventID(), hostID(), s() {} Event(double t, int eid, int hid, int stype) : time(t), eventID( eid ), hostID( hid ), s(stype) {} bool operator < ( const Event & rhs ) const { return ( time < rhs.time ); } double time; ... }; The program iterates through periods of adding events with unordered times to EventPQ currentEvents and then pulling off events in order. Rarely, after some events have been added (with perfectly 'legal' times), events start getting executed out of order. What could make the events ever not get ordered properly? (Or what could mess up the iterator?) I have checked that all the added event times are legitimate (i.e., all exceed the current simulation time), and I have also confirmed that the error does not occur because two events happen to get scheduled for the same time. I'd love suggestions on how to work through this. The code for executing and adding events is below for the curious: double t = 0.0; double nextTimeStep = t + EPID_DELTA_T; EventPQ::iterator eventIter = currentEvents.begin(); while ( t < EPID_SIM_LENGTH ) { // Add some events to currentEvents while ( ( *eventIter ).time < nextTimeStep ) { Event thisEvent = *eventIter; t = thisEvent.time; executeEvent( thisEvent ); eventCtr++; currentEvents.erase( eventIter ); eventIter = currentEvents.begin(); } t = nextTimeStep; nextTimeStep += EPID_DELTA_T; } void Simulation::addEvent( double et, int eid, int hid, int s ) { assert( currentEvents.find( Event(et) ) == currentEvents.end() ); Event thisEvent( et, eid, hid, s ); currentEvents.insert( thisEvent ); }

    Read the article

  • DataGridView validating old value insted of new value.

    - by Scott Chamberlain
    I have a DataGridView that is bound to a DataTable, it has a column that is a double and the values need to be between 0 and 1. Here is my code private void dgvImpRDP_InfinityRDPLogin_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) { if (e.ColumnIndex == dtxtPercentageOfUsersAllowed.Index) { double percentage; if(dgvImpRDP_InfinityRDPLogin[e.ColumnIndex, e.RowIndex].Value.GetType() == typeof(double)) percentage = (double)dgvImpRDP_InfinityRDPLogin[e.ColumnIndex, e.RowIndex].Value; else if (!double.TryParse(dgvImpRDP_InfinityRDPLogin[e.ColumnIndex, e.RowIndex].Value.ToString(), out percentage)) { e.Cancel = true; dgvImpRDP_InfinityRDPLogin[e.ColumnIndex, e.RowIndex].ErrorText = "The value must be between 0 and 1"; return; } if (percentage < 0 || percentage > 1) { e.Cancel = true; dgvImpRDP_InfinityRDPLogin[e.ColumnIndex, e.RowIndex].ErrorText = "The value must be between 0 and 1"; } } } However my issue when dgvImpRDP_InfinityRDPLogin_CellValidating fires dgvImpRDP_InfinityRDPLogin[e.ColumnIndex, e.RowIndex].Value will contain the old value before the edit, not the new value. For example lets say the old value was .1 and I enter 3. The above code runs when you exit the cell and dgvImpRDP_InfinityRDPLogin[e.ColumnIndex, e.RowIndex].Value will be .1 for that run, the code validates and writes 3 the data to the DataTable. I click on it a second time, try to leave, and this time it behaves like it should, it raises the error icon for the cell and prevents me from leaving. I try to enter the correct value (say .7) but the the Value will still be 3 and there is now no way out of the cell because it is locked due to the error and my validation code will never push the new value. Any recommendations would be greatly appreciated. EDIT -- New version of the code based off of Stuart's suggestion and mimicking the style the MSDN article uses. Still behaves the same. private void dgvImpRDP_InfinityRDPLogin_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) { if (e.ColumnIndex == dtxtPercentageOfUsersAllowed.Index) { dgvImpRDP_InfinityRDPLogin[e.ColumnIndex, e.RowIndex].ErrorText = String.Empty; double percentage; if (!double.TryParse(dgvImpRDP_InfinityRDPLogin[e.ColumnIndex, e.RowIndex].FormattedValue.ToString(), out percentage) || percentage < 0 || percentage > 1) { e.Cancel = true; dgvImpRDP_InfinityRDPLogin[e.ColumnIndex, e.RowIndex].ErrorText = "The value must be between 0 and 1"; return; } } }

    Read the article

  • Returning different data types C#

    - by user1810659
    i have create a class library (DLL) with many different methods. and the return different types of data(string string[] double double[]). Therefore i have created one class i called CustomDataType for all the methods containing different data types so each method in the Library can return object of the custom class and this way be able to return multiple data types I have done it like this: public class CustomDataType { public double Value; public string Timestamp; public string Description; public string Unit; // special for GetparamterInfo public string OpcItemUrl; public string Source; public double Gain; public double Offset; public string ParameterName; public int ParameterID; public double[] arrayOfValue; public string[] arrayOfTimestamp; // public string[] arrayOfParameterName; public string[] arrayOfUnit; public string[] arrayOfDescription; public int[] arrayOfParameterID; public string[] arrayOfItemUrl; public string[] arrayOfSource; public string[] arrayOfModBusRegister; public string[] arrayOfGain; public string[] arrayOfOffset; } The Library contains methods like these: public CustomDataType GetDeviceParameters(string deviceName) { ...................... code getDeviceParametersObj.arrayOfParameterName; return getDeviceParametersObj; } public CustomDataType GetMaxMin(string parameterName, string period, string maxMin) { .....................................code getMaxMingObj.Value = (double)reader["MaxMinValue"]; getMaxMingObj.Timestamp = reader["MeasurementDateTime"].ToString(); getMaxMingObj.Unit = reader["Unit"].ToString(); getMaxMingObj.Description = reader["Description"].ToString(); return getMaxMingObj; } public CustomDataType GetSelectedMaxMinData(string[] parameterName, string period, string mode) {................................code selectedMaxMinObj.arrayOfValue = MaxMinvalueList.ToArray(); selectedMaxMinObj.arrayOfTimestamp = MaxMintimeStampList.ToArray(); selectedMaxMinObj.arrayOfDescription = MaxMindescriptionList.ToArray(); selectedMaxMinObj.arrayOfUnit = MaxMinunitList.ToArray(); return selectedMaxMinObj; } As illustrated thi different methods returns different data types,and it works fine for me but when i import the DLL and want to use the methods Visual studio shwos all the data types in the CustomDataType class as suggestion for all the methods even though the return different data.This is illusrtated in the picture below. As we can see from the picture with the suggestion of all the different return data the user can get confused and choose wrong return data for some of the methods. So my question is how can i improve this. so Visual studio suggest just the belonging return data type for each method.

    Read the article

  • Is throwing an exception a healthy way to exit?

    - by ramaseshan
    I have a setup that looks like this. class Checker { // member data Results m_results; // see below public: bool Check(); private: bool Check1(); bool Check2(); // .. so on }; Checker is a class that performs lengthy check computations for engineering analysis. Each type of check has a resultant double that the checker stores. (see below) bool Checker::Check() { // initilisations etc. Check1(); Check2(); // ... so on } A typical Check function would look like this: bool Checker::Check1() { double result; // lots of code m_results.SetCheck1Result(result); } And the results class looks something like this: class Results { double m_check1Result; double m_check2Result; // ... public: void SetCheck1Result(double d); double GetOverallResult() { return max(m_check1Result, m_check2Result, ...); } }; Note: all code is oversimplified. The Checker and Result classes were initially written to perform all checks and return an overall double result. There is now a new requirement where I only need to know if any of the results exceeds 1. If it does, subsequent checks need not be carried out(it's an optimisation). To achieve this, I could either: Modify every CheckN function to keep check for result and return. The parent Check function would keep checking m_results. OR In the Results::SetCheckNResults(), throw an exception if the value exceeds 1 and catch it at the end of Checker::Check(). The first is tedious, error prone and sub-optimal because every CheckN function further branches out into sub-checks etc. The second is non-intrusive and quick. One disadvantage is I can think of is that the Checker code may not necessarily be exception-safe(although there is no other exception being thrown anywhere else). Is there anything else that's obvious that I'm overlooking? What about the cost of throwing exceptions and stack unwinding? Is there a better 3rd option?

    Read the article

  • Mixing C and C++, raw pointers and (boost) shared pointers

    - by oompahloompah
    I am working in C++ with some legacy C code. I have a data structure that (during initialisation), makes a copy of the structure pointed to a ptr passed to its initialisation pointer. Here is a simplification of what I am trying to do - hopefully, no important detail has been lost in the "simplification": /* C code */ typedef struct MyData { double * elems; unsigned int len; }; int NEW_mydata(MyData* data, unsigned int len) { // no error checking data->elems = (double *)calloc(len, sizeof(double)); return 0; } typedef struct Foo { MyData data data_; }; void InitFoo(Foo * foo, const MyData * the_data) { //alloc mem etc ... then assign the STRUCTURE foo.data_ = *thedata ; } C++ code ------------- typedef boost::shared_ptr<MyData> MyDataPtr; typedef std::map<std::string, MyDataPtr> Datamap; class FooWrapper { public: FooWrapper(const std::string& key) { MyDataPtr mdp = dmap[key]; InitFoo(&m_foo, const_cast<MyData*>((*mdp.get()))); } ~FooWrapper(); double get_element(unsigned int index ) const { return m_foo.elems[index]; } private: // non copyable, non-assignable FooWrapper(const FooWrapper&); FooWrapper& operator= (const FooWrapper&); Foo m_foo; }; int main(int argc, char *argv[]) { MyData data1, data2; Datamap dmap; NEW_mydata(&data1, 10); data1->elems[0] = static_cast<double>(22/7); NEW_mydata(&data2, 42); data2->elems[0] = static_cast<double>(13/21); boost::shared_ptr d1(&data1), d2(&data2); dmap["data1"] = d1; dmap["data2"] = d2; FooWrapper fw("data1"); //expect 22/7, get something else (random number?) double ret fw.get_element(0); } Essentially, what I want to know is this: Is there any reason why the data retrieved from the map is different from the one stored in the map?

    Read the article

  • WP7 Return the last 7 days of data from an xml web service

    - by cvandal
    Hello, I'm trying to return the last 7 days of data from an xml web service but with no luck. Could someone please explain me to how I would accomplish this? The XML is as follows: <node> <api> <usagelist> <usage day="2011-01-01"> <traffic name="total" unit="bytes">23579797</traffic> </usage> <usage day="2011-01-02"> <traffic name="total" unit="bytes">23579797</traffic> </usage> <usage day="2011-01-03"> <traffic name="total" unit="bytes">23579797</traffic> </usage> <usage day="2011-01-04"> <traffic name="total" unit="bytes">23579797</traffic> </usage> </usagelist> </api> </node> EDIT The data I want to retrieve will be used to populate a line graph. Specificly I require the day attribute value and the traffic element value for the past 7 days. At the moment, I have the code below in place, howevewr it's only showing the first day 7 times and traffic for the first day 7 times. XDocument xDocument = XDocument.Parse(e.Result); var values = from query in xDocument.Descendants("usagelist") select new History { day = query.Element("usage").Attribute("day").Value, traffic = query.Element("usage").Element("traffic").Value }; foreach (History history in values) { ObservableCollection<LineGraphItem> Data = new ObservableCollection<LineGraphItem>() { new LineGraphItem() { yyyymmdd = history.day, value = double.Parse(history.traffic) }, new LineGraphItem() { yyyymmdd = history.day, value = double.Parse(history.traffic) }, new LineGraphItem() { yyyymmdd = history.day, value = double.Parse(history.traffic) }, new LineGraphItem() { yyyymmdd = history.day, value = double.Parse(history.traffic) }, new LineGraphItem() { yyyymmdd = history.day, value = double.Parse(history.traffic) }, new LineGraphItem() { yyyymmdd = history.day, value = double.Parse(history.traffic) }, new LineGraphItem() { yyyymmdd = history.day, value = double.Parse(history.traffic) }, }; lineGraph1.DataSource = Data; }

    Read the article

  • How to use enumeration types in C++?

    - by Sagistic
    I do not understand how to use enumeration types. I understand what they are, but I don't quite get their purpose. I have made a program that inputs three sides of a triangle and outputs whether or not they are isosceles, scalene, or equilateral. I'm suppose to incorporate the enumeration type somewhere, but don't get where and how to use them. Any help would be appreciated. #include <iostream> using namespace std; enum triangleType {scalene, isosceles, equilateral, noTriangle}; void triangleShape(double x, double y, double z); int main() { double x, y, z; cout << "Please enter the three sides of a triangle:" << endl; cout << "Enter side 1: "; cin >> x; cout << endl; cout << "Enter side 2: "; cin >> y; cout << endl; cout << "Enter side 3: "; cin >> z; cout << endl; triangleShape(x, y, z); return 0; } void triangleShape(double x, double y, double z) { if (((x+y) > z) && ((x+z) > y) && ((y+z) > x)) { cout << "You have a triangle!" << endl; if (x == y && y == z) cout << "Your triangle is an equilateral" << endl; else if (x == y || x == z || y == z) cout << "Your triangle is an isosceles" << endl; else cout << "Your triangle is a scalene" << endl; } else if ((x+y) <= z || ((x+z) <= y) || ((y+z) <= x)) cout << "You do not have a triangle." << endl; }

    Read the article

  • How to use enumeration types in C++? Apply within example.

    - by Sagistic
    I do not understand how to use enumeration types. I understand what they are, but I don't quite get their purpose. I have made a program that inputs three sides of a triangle and outputs whether or not they are isosceles, scalene, or equilateral. I'm suppose to incorporate the enumeration type somewhere, but don't get where and how to use them. Any help would be appreciated. // h8p466x1.cpp : Defines the entry point for the console application. // include "stdafx.h" int _tmain(int argc, _TCHAR* argv[]) { return 0; } include using namespace std; enum triangleType {scalene, isosceles, equilateral, noTriangle}; void triangleShape(double x, double y, double z); int main() { double x, y, z; cout << "Please enter the three sides of a triangle:" << endl; cout << "Enter side 1: "; cin >> x; cout << endl; cout << "Enter side 2: "; cin >> y; cout << endl; cout << "Enter side 3: "; cin >> z; cout << endl; triangleShape(x, y, z); return 0; } void triangleShape(double x, double y, double z) { if (((x+y) z) && ((x+z) y) && ((y+z) x)) { cout << "You have a triangle!" << endl; if (x == y && y == z) cout << "Your triangle is an equilateral" << endl; else if (x == y || x == z || y == z) cout << "Your triangle is an isosceles" << endl; else cout << "Your triangle is a scalene" << endl; } else if ((x+y) <= z || ((x+z) <= y) || ((y+z) <= x)) cout << "You do not have a triangle." << endl; }

    Read the article

  • Build problems when adding `__str__` method to Boost Python C++ class

    - by Rickard
    I have started to play around with boost python a bit and ran into a problem. I tried to expose a C++ class to python which posed no problems. But I can't seem to manage to implement the __str__ functionality for the class without getting build errors I don't understand. I'm using boost 1_42 prebuild by boostpro. I build the library using cmake and the vs2010 compiler. I have a very simple setup. The header-file (tutorial.h) looks like the following: #include <iostream> namespace TestBoostPython{ class TestClass { private: double m_x; public: TestClass(double x); double Get_x() const; void Set_x(double x); }; std::ostream &operator<<(std::ostream &ostr, const TestClass &ts); }; and the corresponding cpp-file looks like: #include <boost/python.hpp> #include "tutorial.h" using namespace TestBoostPython; TestClass::TestClass(double x) { m_x = x; } double TestClass::Get_x() const { return m_x; } void TestClass::Set_x(double x) { m_x = x; } std::ostream &operator<<(std::ostream &ostr, TestClass &ts) { ostr << ts.Get_x() << "\n"; return ostr; } BOOST_PYTHON_MODULE(testme) { using namespace boost::python; class_<TestClass>("TestClass", init<double>()) .add_property("x", &TestClass::Get_x, &TestClass::Set_x) .def(str(self)) ; } The CMakeLists.txt looks like the following: CMAKE_MINIMUM_REQUIRED(VERSION 2.8) project (testme) FIND_PACKAGE( Boost REQUIRED ) FIND_PACKAGE( Boost COMPONENTS python REQUIRED ) FIND_PACKAGE( PythonLibs REQUIRED ) set(Boost_USE_STATIC_LIBS OFF) set(Boost_USE_MULTITHREAD ON) INCLUDE_DIRECTORIES(${Boost_INCLUDE_DIRS}) INCLUDE_DIRECTORIES ( ${PYTHON_INCLUDE_PATH} ) add_library(testme SHARED tutorial.cpp) target_link_libraries(testme ${Boost_PYTHON_LIBRARY}) target_link_libraries(testme ${PYTHON_LIBRARY} The build error I get is the following: Compiling... tutorial.cpp C:\Program Files (x86)\boost\boost_1_42\boost/python/def_visitor.hpp(31) : error C2780: 'void boost::python::api::object_operators::visit(ClassT &,const char *,const boost::python::detail::def_helper &) const' : expects 3 arguments - 1 provided with [ U=boost::python::api::object ] C:\Program Files (x86)\boost\boost_1_42\boost/python/object_core.hpp(203) : see declaration of 'boost::python::api::object_operators::visit' with [ U=boost::python::api::object ] C:\Program Files (x86)\boost\boost_1_42\boost/python/def_visitor.hpp(67) : see reference to function template instantiation 'void boost::python::def_visitor_access::visit,classT>(const V &,classT &)' being compiled with [ DerivedVisitor=boost::python::api::object, classT=boost::python::class_, V=boost::python::def_visitor ] C:\Program Files (x86)\boost\boost_1_42\boost/python/class.hpp(225) : see reference to function template instantiation 'void boost::python::def_visitor::visit>(classT &) const' being compiled with [ DerivedVisitor=boost::python::api::object, W=TestBoostPython::TestClass, classT=boost::python::class_ ] .\tutorial.cpp(29) : see reference to function template instantiation 'boost::python::class_ &boost::python::class_::def(const boost::python::def_visitor &)' being compiled with [ W=TestBoostPython::TestClass, U=boost::python::api::object, DerivedVisitor=boost::python::api::object ] Does anyone have any idea on what went wrrong? If I remove the .def(str(self)) part from the wrapper code, everything compiles fine and the class is usable from python. I'd be very greatful for assistance. Thank you, Rickard

    Read the article

  • MSChart on ASP.NET MVC 2

    - by Adron
    I upgraded my MVC Application using MSChart to MVC 2 and have ended up with broken image links for the charts. See my blog entry here: http://blog.adronbhall.com/post/2010/04/12/MVC-2-Breaks-my-Charts.aspx I get no build errors anymore, and have completed the following steps. First, I setup the following web.config lines. add tagPrefix="asp" namespace="System.Web.UI.DataVisualization.Charting" assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" and add path="ChartImg.axd" verb="GET,HEAD" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false" (NOTE: I took the chevrons off so the lines would appear) The next thing I did was create this page with the following code. Which should, according to it working in MVC<1, showed 4 charts. <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> <%@ Import Namespace="Scorecard.Views" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> Scorecard </asp:Content> <asp:Content ID="applicationTitle" ContentPlaceHolderID="ContentPlaceHolderApplicationName" runat="server"> <%=Html.Encode(ViewData["ApplicationTitle"])%> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <form id="form1" runat="server"> <h2> Web Analysis Scorecard </h2> <table> <tr> <td> <% ChartHelper chartHelper = new ChartHelper("Top Countries", (double[])ViewData["TopCountryCounts"], (string[])ViewData["TopCountries"], SeriesChartType.Pie); Chart chartPieTwo = chartHelper.ResultingChart; // Explode data point with label "USA" chartPieTwo.Series["DefaultSeries"].Points[3]["Exploded"] = "true"; chartHelper.RenderChart(this); %> </td> <td> <% chartHelper = new ChartHelper("View Cart Trend", (double[])ViewData["LineValues"], (string[])ViewData["TopEngines"], SeriesChartType.Line); chartHelper.RenderChart(this); %> </td> </tr> <tr> <td> <% chartHelper = new ChartHelper("Yesterday's Page Views", (double[])ViewData["ColumnStats"], (string[])ViewData["ColumnStatHeaders"], SeriesChartType.Column); chartHelper.RenderChart(this); %> </td> <td> <% double[] theValues = (double[])ViewData["ColumnStats"]; double[] newValues = new double[] { 0, 0, 0, 0 }; int count = 0; int daysInMonth = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month); foreach (double d in theValues) { newValues[count] += d * daysInMonth; count++; } chartHelper = new ChartHelper("Current Month Page Views", newValues, (string[])ViewData["ColumnStatHeaders"], SeriesChartType.Bar); chartHelper.RenderChart(this); %> </td> </tr> </table> </form>

    Read the article

  • What causes Windows Media Player on Windows 8 to not play the entire library?

    - by somequixotic
    Behavior 1: Verify that the WMP playlist is clear of all songs. Turn on the "Shuffle" and "Repeat" features. Double-click on a music track in the Library. Click the "Next" button (double right angle brackets). A random song from any track in the Library is randomly chosen and played. When observing the Playlist (clicking the "Play" tab), the entire contents of the Library appears in the Playlist. Behavior 2: Verify that the WMP playlist is clear of all songs. Turn on the "Shuffle" and "Repeat" features. Double-click on a music track in the Library. Click the "Next" button (double right angle brackets). The button visually depresses like it has registered the click, but nothing happens. Absolutely nothing. Moreover, the "Previous" button is grayed out. When observing the Playlist, only the one song that was double-clicked appears in the Playlist. What causes Behavior 2? I cannot correlate any specific action I've taken with Behavior 2, and Behavior 1 has been the case as long as I can remember, all the way back to Windows XP. Even earlier during my usage of Windows 8, I recall Behavior 1 working correctly. But suddenly, inexplicably, without changing any settings in WMP, Behavior 2 kicked in, and persists after reboots. I've tried sfc /scannow in an administrator prompt. All system files are in order. I've downloaded all Windows Updates and driver updates. I've attempted to alter WMP options and playback settings to no avail. So... what is causing Behavior 2? Is this an intended, valid behavior, or is something malfunctioning? How would I know what that "something" is? How would I go about fixing it without just reinstalling Windows 8 fresh?

    Read the article

  • n68 s-ucc front panel audio

    - by user264522
    I have a motherboard asrock n68 s-ucc, and i need a hand identifying which pins on the board to connect my front audio header connectors to. On the connectors I have: double connector: GND and MIC IN double connector: LINE OUT FL and LINE OUT RL double connector: LINE OUT FR and LINE OUT RR simple connector: MIC POWER On the motherboard I have: GND PRESENCE# MIC_RET OUT_RET MIC2_L MIC2_R OUT2_R J_SENSE OUT2_L manual of motherboard and my front panel Thanks so much to all

    Read the article

  • Looking for advice on Hyper-v storage replication

    - by Notre1
    I am designing a 2-host Hyper-V R2 cluster with 6-10 guests stored on a SMB iSCSI SAN device (probably Promise VessRAID). I will be getting at least two of the SAN devices and need to eliminate the storage a single point of failure. Ideally, that would involve real-time failover for the storage, like the Windows failover clustering does for the hosts. This design will be used at around six of our sites, and I would like to allow for us to eventually setup a cluster at colocation site and replicate each site's VMs there for DR. (Ideally a live multi-site cluster, but a manual import of the VMs would be fine for this sort of DR.) The tools that come with enterprise SANs, like EMC and NetApp, seem to be the most commonly used items for a Hyper-V cluster, but I can't afford their prices with my budget. Outside of them, the two tools that seem to be most common for Hyper-V storage replication are SteelEye (now SIOS) DataKeeper Cluster Edition and Double-Take Availability. Originally, I was planning on using Clustered Shared Volume(s) (CSV), but it seems like replication support for these is either not available or brand new in both these products. It looks like CSVs are supported in Double-Take 5.22, see this discussion, but I don't think I want to run something that new in production. Right now, it seems like the best option for me is not to implement CSVs, implement some sort of storage replication, and upgrade to CSVs at a later date once replicating them is more mature. I would love to have live migration, and CSVs are not required for live migration if you are using one LUN per VM, so I guess this is what I'll do. I would prefer to stick to the using the Microsoft Windows Server and Hyper-V tools and features as much as possible. From that standpoint, SteelEye looks more appealing than Double-Take because they make the DataKeeper volume(s) available to the Failover Clustering Manager and then failover clustering is all configured and managed through the native Microsoft tools. Double-Take says that "clustered Hyper-V hosts are not supported," and Double-Take Availability itself seems to be what is used for the actual clustering and failover. Does anyone know if any of these replication tools work with more than two hosts in the cluster? All the information I can find on the web only uses two hosts in their examples. Are there any better tools than SteelEye and Double-Take for doing what I am trying to do, which is eliminate the storage as as single point of failure? Neverfail, AppAssure, and DataCore all seem to offer similar functionality, but they don't seems to be as popular as SteelEye and Double-Take. I have seen a number of people suggest using Starwind iSCSI SAN software for the shared storage, which includes replication (and CSV replication at that). There are a couple of reasons I have not seriously considered this route: 1) The company I work for is exclusively a Dell shop and Dell does not have any servers with that I can pack with more than six 3.5" SATA drives. 2) In the future, it could be advantegous for us to not be locked into a particular brand or type of storage and third-party replication softwares all allow replication to heterogeneous storage devices. I am pretty new to iSCSI and clustering, so please let me know if it looks like I am planning something that goes against best practices or overlooking/missing something.

    Read the article

  • Windows file association for README, INSTALL, LICENSE and the like [closed]

    - by Lumi
    Possible Duplicate: How to set the default program for opening files without an extension in Windows? Many files originating in the UNIX world come without file extension. Popular examples include README, INSTALL, LICENSE. We know for a fact that these are text files. It is therefore a bit disappointing not to be able to just double-click them open in Explorer and see them in Notepad (actually, Notepad2 because of the UNIX line endings which silly Microsoft Notepad doesn't render correctly). Does anyone know of a way to create a file association for, say, README files without extension? This could then be replicated to cover the most frequently occurring file types, and then double-clicking them open would work. Update (Sort of in response to all your comments.) Thanks, folks, your comments and answers have helped me. @Indrek, yes, I was under the assumption that you could somehow create an association for just README or Makefile, and couldn't do so for files without extension. Turns out the contrary is true, and yes, that is a workaround that neatly solves the issue. Ultimately, I just want to be able to double-click to open a README or Makefile, that's all. @Sampo, the SendMe trick is also useful, although usability is not as great as a straight double-click. (I'm really lazy sometimes.) Turns out the following trick using ftype and ftype from an Administrator prompt does the double-click enabling job: assoc .=no_ext ftype no_ext=%SystemRoot%\system32\NOTEPAD.EXE %1 :: You can see it created some entries in the registry: reg query hkcr\no_ext /s reg query hkcr\. /s

    Read the article

  • Looking for advice on Hyper-v storage replication

    - by Notre1
    I am designing a 2-host Hyper-V R2 cluster with 6-10 guests stored on a SMB iSCSI SAN device (probably Promise VessRAID). I will be getting at least two of the SAN devices and need to eliminate the storage a single point of failure. Ideally, that would involve real-time failover for the storage, like the Windows failover clustering does for the hosts. This design will be used at around six of our sites, and I would like to allow for us to eventually setup a cluster at colocation site and replicate each site's VMs there for DR. (Ideally a live multi-site cluster, but a manual import of the VMs would be fine for this sort of DR.) The tools that come with enterprise SANs, like EMC and NetApp, seem to be the most commonly used items for a Hyper-V cluster, but I can't afford their prices with my budget. Outside of them, the two tools that seem to be most common for Hyper-V storage replication are SteelEye (now SIOS) DataKeeper Cluster Edition and Double-Take Availability. Originally, I was planning on using Clustered Shared Volume(s) (CSV), but it seems like replication support for these is either not available or brand new in both these products. It looks like CSVs are supported in Double-Take 5.22, see this discussion, but I don't think I want to run something that new in production. Right now, it seems like the best option for me is not to implement CSVs, implement some sort of storage replication, and upgrade to CSVs at a later date once replicating them is more mature. I would love to have live migration, and CSVs are not required for live migration if you are using one LUN per VM, so I guess this is what I'll do. I would prefer to stick to the using the Microsoft Windows Server and Hyper-V tools and features as much as possible. From that standpoint, SteelEye looks more appealing than Double-Take because they make the DataKeeper volume(s) available to the Failover Clustering Manager and then failover clustering is all configured and managed through the native Microsoft tools. Double-Take says that "clustered Hyper-V hosts are not supported," and Double-Take Availability itself seems to be what is used for the actual clustering and failover. Does anyone know if any of these replication tools work with more than two hosts in the cluster? All the information I can find on the web only uses two hosts in their examples. Are there any better tools than SteelEye and Double-Take for doing what I am trying to do, which is eliminate the storage as as single point of failure? Neverfail, AppAssure, and DataCore all seem to offer similar functionality, but they don't seems to be as popular as SteelEye and Double-Take. I have seen a number of people suggest using Starwind iSCSI SAN software for the shared storage, which includes replication (and CSV replication at that). There are a couple of reasons I have not seriously considered this route: 1) The company I work for is exclusively a Dell shop and Dell does not have any servers with that I can pack with more than six 3.5" SATA drives. 2) In the future, it could be advantegous for us to not be locked into a particular brand or type of storage and third-party replication softwares all allow replication to heterogeneous storage devices. I am pretty new to iSCSI and clustering, so please let me know if it looks like I am planning something that goes against best practices or overlooking/missing something.

    Read the article

  • Mac OS 10.7 DMG files don't pop up anymore?

    - by Sosukodo
    Has anybody noticed that double-clicking on a DMG file no longer raises the mounted image to the front of all windows? It used to be that when you double-clicked a dmg file, it would pop-up but now you have to click Finder and click on the mounted image. Is this a bug, by design or a setting that I can change? Update: As per Daniel Beck's suggestion, I created a new account and downloaded the most recent version of Firefox via Safari. It still exhibited the same behavior. However, I noticed that if I double-click thew DMG from within the Downloads folder in Finder, it does pop up. But when I double-click the DMG within Safari (and Firefox also) it does not pop up over all other windows.

    Read the article

  • LINQ and Aggregate function

    - by vik20000in
    LINQ also provides with itself important aggregate function. Aggregate function are function that are applied over a sequence like and return only one value like Average, count, sum, Maximum etc…Below are some of the Aggregate functions provided with LINQ and example of their implementation. Count     int[] primeFactorsOf300 = { 2, 2, 3, 5, 5 };     int uniqueFactors = primeFactorsOf300.Distinct().Count();The below example provided count for only odd number.     int[] primeFactorsOf300 = { 2, 2, 3, 5, 5 };     int uniqueFactors = primeFactorsOf300.Distinct().Count(n => n%2 = 1);  Sum     int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };        double numSum = numbers.Sum();  Minimum      int minNum = numbers.Min(); Maximum      int maxNum = numbers.Max();Average      double averageNum = numbers.Average();  Aggregate      double[] doubles = { 1.7, 2.3, 1.9, 4.1, 2.9 };     double product = doubles.Aggregate((runningProduct, nextFactor) => runningProduct * nextFactor);  Vikram

    Read the article

< Previous Page | 43 44 45 46 47 48 49 50 51 52 53 54  | Next Page >