Search Results

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

Page 91/244 | < Previous Page | 87 88 89 90 91 92 93 94 95 96 97 98  | Next Page >

  • Custom Java Swing Meter Control

    - by Tyler
    I'm trying to make a custom swing control that is a meter. The arrow will move up and down. Here is my current code, but I feel I've done it wrong. import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.LinearGradientPaint; import java.awt.Polygon; import java.awt.Stroke; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import javax.swing.JFrame; import javax.swing.JPanel; public class meter extends JFrame { Stroke drawingStroke = new BasicStroke(2); Rectangle2D rect = new Rectangle2D.Double(105, 50, 40, 200); Double meterPercent = new Double(0.57); public meter() { setTitle("Meter"); setLayout(null); setSize(300, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } public void paint(Graphics g) { // Paint Meter Graphics2D g1 = (Graphics2D) g; g1.setStroke(drawingStroke); g1.draw(rect); // Set Meter Colors Point2D start = new Point2D.Float(0, 0); Point2D end = new Point2D.Float(0, this.getHeight()); float[] dist = { 0.1f, 0.5f, 0.9f }; Color[] colors = { Color.green, Color.yellow, Color.red }; LinearGradientPaint p = new LinearGradientPaint(start, end, dist, colors); g1.setPaint(p); g1.fill(rect); // Make a triangle - Arrow on Meter int[] x = new int[3]; int[] y = new int[3]; int n; // count of points // Set Points for Arrow Integer meterArrowHypotenuse = (int) rect.getX(); Integer meterArrowTip = (int) rect.getY() + (int) (rect.getHeight() * (1 - meterPercent)); x[0] = meterArrowHypotenuse - 25; x[1] = meterArrowHypotenuse - 25; x[2] = meterArrowHypotenuse - 5; y[0] = meterArrowTip - 20; // Top Left y[1] = meterArrowTip + 20; // Bottom Left y[2] = meterArrowTip; // Tip of Arrow n = 3; // Number of points, 3 because its a triangle // Draw Arrow Border Polygon myTriShadow = new Polygon(x, y, n); // a triangle g1.setPaint(Color.black); g1.fill(myTriShadow); // Set Points for Arrow Board x[0] = x[0] + 1; x[1] = x[1] + 1; x[2] = x[2] - 2; y[0] = y[0] + 3; y[1] = y[1] - 3; y[2] = y[2]; Robot robot = new Robot(); Color colorMeter = robot.getPixelColor(x[2]+10, y[2]); // Draw Arrow Polygon myTri = new Polygon(x, y, n); // a triangle Color colr = new Color(colorMeter.getRed(), colorMeter.getGreen(), colorMeter.getBlue()); g1.setPaint(colr); g1.fill(myTri); } public static void main(String[] args) { new meter(); } } Thanks for looking.

    Read the article

  • OpenXML sdk Modify a sheet in my Excel document

    - by user465202
    hi! I create an empty template in excel. I would like to open the template and edit the document but I do not know how to change the existing sheet. That's the code: using (SpreadsheetDocument xl = SpreadsheetDocument.Open(filename, true)) { WorkbookPart wbp = xl.WorkbookPart; WorkbookPart workbook = xl.WorkbookPart; // Get the worksheet with the required name. // To be used to match the ID for the required sheet data // because the Sheet class and the SheetData class aren't // linked to each other directly. Sheet s = null; if (wbp.Workbook.Sheets.Elements().Count(nm = nm.Name == sheetName) == 0) { // no such sheet with that name xl.Close(); return; } else { s = (Sheet)wbp.Workbook.Sheets.Elements().Where(nm = nm.Name == sheetName).First(); } WorksheetPart wsp = (WorksheetPart)xl.WorkbookPart.GetPartById(s.Id.Value); Worksheet worksheet = new Worksheet(); SheetData sd = new SheetData(); //SheetData sd = (SheetData)wsp.Worksheet.GetFirstChild(); Stylesheet styleSheet = workbook.WorkbookStylesPart.Stylesheet; //SheetData sheetData = new SheetData(); //build the formatted header style UInt32Value headerFontIndex = util.CreateFont( styleSheet, "Arial", 10, true, System.Drawing.Color.Red); //build the formatted date style UInt32Value dateFontIndex = util.CreateFont( styleSheet, "Arial", 8, true, System.Drawing.Color.Black); //set the background color style UInt32Value headerFillIndex = util.CreateFill( styleSheet, System.Drawing.Color.Black); //create the cell style by combining font/background UInt32Value headerStyleIndex = util.CreateCellFormat( styleSheet, headerFontIndex, headerFillIndex, null); /* * Create a set of basic cell styles for specific formats... * If you are controlling your table then you can simply create the styles you need, * this set of code is still intended to be generic. */ _numberStyleId = util.CreateCellFormat(styleSheet, null, null, UInt32Value.FromUInt32(3)); _doubleStyleId = util.CreateCellFormat(styleSheet, null, null, UInt32Value.FromUInt32(4)); _dateStyleId = util.CreateCellFormat(styleSheet, null, null, UInt32Value.FromUInt32(14)); _textStyleId = util.CreateCellFormat(styleSheet, headerFontIndex, headerFillIndex, null); _percentageStyleId = util.CreateCellFormat(styleSheet, null, null, UInt32Value.FromUInt32(9)); util.AddNumber(xl, sheetName, (UInt32)3, "E", "27", _numberStyleId); util.AddNumber(xl, sheetName, (UInt32)3, "F", "3.6", _doubleStyleId); util.AddNumber(xl, sheetName, (UInt32)5, "L", "5", _percentageStyleId); util.AddText(xl, sheetName, (UInt32)5, "M", "Dario", _textStyleId); util.AddDate(xl, sheetName, (UInt32)3, "J", DateTime.Now, _dateStyleId); util.AddImage(xl, sheetName, imagePath, "Smile", "Smile", 30, 30); util.MergeCells(xl, sheetName, "D12", "F12"); //util.DeleteValueCell(spreadsheet, sheetName, "F", (UInt32)8); txtCellText.Text = util.GetCellValue(xl, sheetName, (UInt32)5, "M"); double number = util.GetCellDoubleValue(xl, sheetName, (UInt32)3, "E"); double numberD = util.GetCellDoubleValue(xl, sheetName, (UInt32)3, "F"); DateTime datee = util.GetCellDateTimeValue(xl, sheetName, (UInt32)3, "J"); //txtDoubleCell.Text = util.GetCellValue(spreadsheet, sheetName, (UInt32)3, "P"); txtPercentualeCell.Text = util.GetCellValue(xl, sheetName, (UInt32)5, "L"); string date = util.GetCellValue(xl, sheetName, (UInt32)3, "J"); double dateD = Convert.ToDouble(date); DateTime dateTime = DateTime.FromOADate(dateD); txtDateCell.Text = dateTime.ToShortDateString(); //worksheet.Append(sd); /* Columns columns = new Columns(); columns.Append(util.CreateColumnData(10, 10, 40)); worksheet.Append(columns); */ SheetProtection sheetProtection1 = new SheetProtection() { Sheet = true, Objects = true, Scenarios = true, SelectLockedCells = true, SelectUnlockedCells = true }; worksheet.Append(sheetProtection1); wsp.Worksheet = worksheet; wsp.Worksheet.Save(); xl.WorkbookPart.Workbook.Save(); xl.Close(); thanks!

    Read the article

  • Database call crashes Android Application

    - by Darren Murtagh
    i am using a Android database and its set up but when i call in within an onClickListener and the app crashes the code i am using is mButton.setOnClickListener( new View.OnClickListener() { public void onClick(View view) { s = WorkoutChoice.this.weight.getText().toString(); s2 = WorkoutChoice.this.height.getText().toString(); int w = Integer.parseInt(s); double h = Double.parseDouble(s2); double BMI = (w/h)/h; t.setText(""+BMI); long id = db.insertTitle("001", ""+days, ""+BMI); Cursor c = db.getAllTitles(); if (c.moveToFirst()) { do { DisplayTitle(c); } while (c.moveToNext()); } } }); and the log cat for when i run it is: 04-01 18:21:54.704: E/global(6333): Deprecated Thread methods are not supported. 04-01 18:21:54.704: E/global(6333): java.lang.UnsupportedOperationException 04-01 18:21:54.704: E/global(6333): at java.lang.VMThread.stop(VMThread.java:85) 04-01 18:21:54.704: E/global(6333): at java.lang.Thread.stop(Thread.java:1391) 04-01 18:21:54.704: E/global(6333): at java.lang.Thread.stop(Thread.java:1356) 04-01 18:21:54.704: E/global(6333): at com.b00348312.workout.Splashscreen$1.run(Splashscreen.java:42) 04-01 18:22:09.444: D/dalvikvm(6333): GC_FOR_MALLOC freed 4221 objects / 252640 bytes in 31ms 04-01 18:22:09.474: I/dalvikvm(6333): Total arena pages for JIT: 11 04-01 18:22:09.574: D/dalvikvm(6333): GC_FOR_MALLOC freed 1304 objects / 302920 bytes in 29ms 04-01 18:22:09.744: D/dalvikvm(6333): GC_FOR_MALLOC freed 2480 objects / 290848 bytes in 33ms 04-01 18:22:10.034: D/dalvikvm(6333): GC_FOR_MALLOC freed 6334 objects / 374152 bytes in 36ms 04-01 18:22:14.344: D/AndroidRuntime(6333): Shutting down VM 04-01 18:22:14.344: W/dalvikvm(6333): threadid=1: thread exiting with uncaught exception (group=0x400259f8) 04-01 18:22:14.364: E/AndroidRuntime(6333): FATAL EXCEPTION: main 04-01 18:22:14.364: E/AndroidRuntime(6333): java.lang.IllegalStateException: database not open 04-01 18:22:14.364: E/AndroidRuntime(6333): at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1567) 04-01 18:22:14.364: E/AndroidRuntime(6333): at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1484) 04-01 18:22:14.364: E/AndroidRuntime(6333): at com.b00348312.workout.DataBaseHelper.insertTitle(DataBaseHelper.java:84) 04-01 18:22:14.364: E/AndroidRuntime(6333): at com.b00348312.workout.WorkoutChoice$3.onClick(WorkoutChoice.java:84) 04-01 18:22:14.364: E/AndroidRuntime(6333): at android.view.View.performClick(View.java:2408) 04-01 18:22:14.364: E/AndroidRuntime(6333): at android.view.View$PerformClick.run(View.java:8817) 04-01 18:22:14.364: E/AndroidRuntime(6333): at android.os.Handler.handleCallback(Handler.java:587) 04-01 18:22:14.364: E/AndroidRuntime(6333): at android.os.Handler.dispatchMessage(Handler.java:92) 04-01 18:22:14.364: E/AndroidRuntime(6333): at android.os.Looper.loop(Looper.java:144) 04-01 18:22:14.364: E/AndroidRuntime(6333): at android.app.ActivityThread.main(ActivityThread.java:4937) 04-01 18:22:14.364: E/AndroidRuntime(6333): at java.lang.reflect.Method.invokeNative(Native Method) 04-01 18:22:14.364: E/AndroidRuntime(6333): at java.lang.reflect.Method.invoke(Method.java:521) 04-01 18:22:14.364: E/AndroidRuntime(6333): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858) 04-01 18:22:14.364: E/AndroidRuntime(6333): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 04-01 18:22:14.364: E/AndroidRuntime(6333): at dalvik.system.NativeStart.main(Native Method) i have notice errors when the application opens but i dont no what thet are from. when i take out the statements to do with the database there is no errors and everthign runs smoothly

    Read the article

  • Concurrency and Calendar classes

    - by fbielejec
    I have a thread (class implementing runnable, called AnalyzeTree) organised around a hash map (ConcurrentMap slicesMap). The class goes through the data (called trees here) in the large text file and parses the geographical coordinates from it to the HashMap. The idea is to process one tree at a time and add or grow the values according to the key (which is just a Double value representing time). The relevant part of code looks like this: // grow map entry if key exists if (slicesMap.containsKey(sliceTime)) { double[] imputedLocation = imputeValue( location, parentLocation, sliceHeight, nodeHeight, parentHeight, rate, useTrueNoise, currentTreeNormalization, precisionArray); slicesMap.get(sliceTime).add( new Coordinates(imputedLocation[1], imputedLocation[0], 0.0)); // start new entry if no such key in the map } else { List<Coordinates> coords = new ArrayList<Coordinates>(); double[] imputedLocation = imputeValue( location, parentLocation, sliceHeight, nodeHeight, parentHeight, rate, useTrueNoise, currentTreeNormalization, precisionArray); coords.add(new Coordinates(imputedLocation[1], imputedLocation[0], 0.0)); slicesMap.putIfAbsent(sliceTime, coords); // slicesMap.put(sliceTime, coords); }// END: key check And the class is called like this (executor is ExecutorService executor = Executors.newFixedThreadPool(NTHREDS) ): mrsd = new SpreadDate(mrsdString); int readTrees = 1; while (treesImporter.hasTree()) { currentTree = (RootedTree) treesImporter.importNextTree(); executor.submit(new AnalyzeTree(currentTree, precisionString, coordinatesName, rateString, numberOfIntervals, treeRootHeight, timescaler, mrsd, slicesMap, useTrueNoise)); // new AnalyzeTree(currentTree, precisionString, // coordinatesName, rateString, numberOfIntervals, // treeRootHeight, timescaler, mrsd, slicesMap, // useTrueNoise).run(); readTrees++; }// END: while has trees Now this is running into troubles when executed in parallel (the commented part running sequentially is fine), I thought it might throw a ConcurrentModificationException, but apparently the problem is in mrsd (instance of SpreadDate object, which is simply a class for date related calculations). The SpreadDate class looks like this: public class SpreadDate { private Calendar cal; private SimpleDateFormat formatter; private Date stringdate; public SpreadDate(String date) throws ParseException { // if no era specified assume current era String line[] = date.split(" "); if (line.length == 1) { StringBuilder properDateStringBuilder = new StringBuilder(); date = properDateStringBuilder.append(date).append(" AD") .toString(); } formatter = new SimpleDateFormat("yyyy-MM-dd G", Locale.US); stringdate = formatter.parse(date); cal = Calendar.getInstance(); } public long plus(int days) { cal.setTime(stringdate); cal.add(Calendar.DATE, days); return cal.getTimeInMillis(); }// END: plus public long minus(int days) { cal.setTime(stringdate); cal.add(Calendar.DATE, -days); //line 39 return cal.getTimeInMillis(); }// END: minus public long getTime() { cal.setTime(stringdate); return cal.getTimeInMillis(); }// END: getDate } And the stack trace from when exception is thrown: java.lang.ArrayIndexOutOfBoundsException: 58 at sun.util.calendar.BaseCalendar.getCalendarDateFromFixedDate(BaseCalendar.java:454) at java.util.GregorianCalendar.computeFields(GregorianCalendar.java:2098) at java.util.GregorianCalendar.computeFields(GregorianCalendar.java:2013) at java.util.Calendar.setTimeInMillis(Calendar.java:1126) at java.util.GregorianCalendar.add(GregorianCalendar.java:1020) at utils.SpreadDate.minus(SpreadDate.java:39) at templates.AnalyzeTree.run(AnalyzeTree.java:88) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334) at java.util.concurrent.FutureTask.run(FutureTask.java:166) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) at java.lang.Thread.run(Thread.java:636) If a move the part initializing mrsd to the AnalyzeTree class it runs without any problems - however it is not very memory efficient to initialize class each time this thread is running, hence my concerns. How can it be remedied?

    Read the article

  • mysql_fetch_array() problem

    - by Marty
    So I have 3 DB tables that are all identical in every way (data is different) except the name of the table. I did this so I could use one piece of code with a switch like so: function disp_bestof($atts) { extract(shortcode_atts(array( 'topic' => '' ), $atts)); $connect = mysql_connect("localhost","foo","bar"); if (!$connect) { die('Could not connect: ' . mysql_error()); } switch ($topic) { case "attorneys": $bestof_query = "SELECT * FROM attorneys p JOIN (awards a, categories c, awardLevels l) ON (a.id = p.id AND c.id = a.category AND l.id = a.level) ORDER BY a.category, a.level ASC"; $category_query = "SELECT * FROM categories"; $db = mysql_select_db('roanoke_BestOf_TopAttorneys'); $query = mysql_query($bestof_query); $categoryQuery = mysql_query($category_query); break; case "physicians": $bestof_query = "SELECT * FROM physicians p JOIN (awards a, categories c, awardLevels l) ON (a.id = p.id AND c.id = a.category AND l.id = a.level) ORDER BY a.category, a.level ASC"; $category_query = "SELECT * FROM categories"; $db = mysql_select_db('roanoke_BestOf_TopDocs'); $query = mysql_query($bestof_query); $categoryQuery = mysql_query($category_query); break; case "dining": $bestof_query = "SELECT * FROM restaurants p JOIN (awards a, categories c, awardLevels l) ON (a.id = p.id AND c.id = a.category AND l.id = a.level) ORDER BY a.category, a.level ASC"; $category_query = "SELECT * FROM categories"; $db = mysql_select_db('roanoke_BestOf_DiningAwards'); $query = mysql_query($bestof_query); $categoryQuery = mysql_query($category_query); break; default: $bestof_query = "switch on $best did not match required case(s)"; break; } $category = ''; while( $result = mysql_fetch_array($query) ) { if( $result['category'] != $category ) { $category = $result['category']; //echo "<div class\"category\">"; $bestof_content .= "<h2>".$category."</h2>\n"; //echo "<ul>"; Now, this whole thing works PERFECT for the first two cases, but the third one "dining" breaks with this error: Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource ... on line 78 Line 78 is the while() at the bottom. I have checked and double checked and can't figure what the problem is. Here's the DB structure for 'restaurants': CREATE TABLE `restaurants` ( `id` int(10) NOT NULL auto_increment, `restaurant` varchar(255) default NULL, `address1` varchar(255) default NULL, `address2` varchar(255) default NULL, `city` varchar(255) default NULL, `state` varchar(255) default NULL, `zip` double default NULL, `phone` double default NULL, `URI` varchar(255) default NULL, `neighborhood` varchar(255) default NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=249 DEFAULT CHARSET=utf8 Does anyone see what I'm doing wrong here? I'm passing "dining" to the function and as I said before, the first two cases in the switch work fine. I'm sure it's something stupid...

    Read the article

  • Should I go along with my choice of web hosting company or still search?

    - by Devner
    Hi all, I have been searching for a good website hosting company that can offer me all the services that I need for hosting my PHP & MySQL based website. Now this is a community based website and users will be able to upload pictures, etc. The hosting company that I have in mind, currently lets me do everything... let me use mail(), supports CRON jobs, etc. Of course they are charging about $6/month. Now the only problem with this company is that they have a limit of 50,000 files that can exist within the hosting account at any time. This kind of contradicts their frontpage ad of "UNLIMITED SPACE" on their website. Apart from this, I know of no other reason why I should not go with this hosting company. But my issue is that 50,000 file limit is what I cannot live with, once the users increase in significant number and the files they upload, exceed 50,000 in number. Now since this is a dynamic website and also includes sensitive issues like payments, etc. I am not sure if I should go ahead with this company as I am just starting out and then later switch over to a better hosting company which does not limit me with 50,000 files. If I need to switch over once I host with this company, I will need to take backups of all the files located in my account (jpg, zip, etc.), then upload them to the new host. I am not aware of any tools that can help me in this process. Can you please mention if you know any? I can go ahead with the other companies right now, but their cost is double/triple of the current price and they all sport less features than my current choice. If I pay more, then they are ready to accommodate my higher demands. Unfortunately, the company that I am willing to go with now, does NOT have any other higher/better plans that I can switch to. So that's the really really bad part. So my question(s): Since I am starting out with my website and since the scope of users initially is going to be less/small, should I go ahead with the current choice and then once the demand increases, switch over to a better provider? If yes, how can I transfer my database, especially the jpg files, etc. to the new provider? I don't even know the tools required to backup and restore to another host. (I don't like this idea but still..) Should I go ahead and pay more right now and go with better providers (without knowing if the website is going to do really that well) just for saving myself the trouble of having to take a backup of the 50,000 files and upload to a new host from an old host and just start paying double/triple the price without even knowing if I would receive back the returns as I expected? Backup and Restore in such a bulky numbers is something that I have never done before and hence I am stuck here trying to decide what to do. The price per month is also a considerable factor in my decision. All these web hosting companies say one common thing: It is customers responsibility to backup and restore data and they are not liable for any loss. So no matter what hosting company that I would like to go with, they ask me to take backup via FTP so that I can restore them whenever I want (& it seems to be safer to have the files locally with me). Some are providing tools for backup and some are not and I am not sure how much their backup tools can be trusted considering the disclaimers they have. I have never backed-up and restored 50,000 files from one web host to another, so please, all you experienced people out there, leave your comments and let me know your suggestions so that I can decide. I have spent 2 days fighting with myself trying to decide what to do and finally concluded that this is a double-edged sword and I can't arrive at a satisfactory final decision without involving others suggestions. I believe that someone must be out there who may have had such troublesome decision to make. So all your suggestions to help me make my decision are appreciated. Thank you all.

    Read the article

  • Java algorithm for normalizing audio

    - by Marty Pitt
    I'm trying to normalize an audio file of speech. Specifically, where an audio file contains peaks in volume, I'm trying to level it out, so the quiet sections are louder, and the peaks are quieter. I know very little about audio manipulation, beyond what I've learnt from working on this task. Also, my math is embarrassingly weak. I've done some research, and the Xuggle site provides a sample which shows reducing the volume using the following code: (full version here) @Override public void onAudioSamples(IAudioSamplesEvent event) { // get the raw audio byes and adjust it's value ShortBuffer buffer = event.getAudioSamples().getByteBuffer().asShortBuffer(); for (int i = 0; i < buffer.limit(); ++i) buffer.put(i, (short)(buffer.get(i) * mVolume)); super.onAudioSamples(event); } Here, they modify the bytes in getAudioSamples() by a constant of mVolume. Building on this approach, I've attempted a normalisation modifies the bytes in getAudioSamples() to a normalised value, considering the max/min in the file. (See below for details). I have a simple filter to leave "silence" alone (ie., anything below a value). I'm finding that the output file is very noisy (ie., the quality is seriously degraded). I assume that the error is either in my normalisation algorithim, or the way I manipulate the bytes. However, I'm unsure of where to go next. Here's an abridged version of what I'm currently doing. Step 1: Find peaks in file: Reads the full audio file, and finds this highest and lowest values of buffer.get() for all AudioSamples @Override public void onAudioSamples(IAudioSamplesEvent event) { IAudioSamples audioSamples = event.getAudioSamples(); ShortBuffer buffer = audioSamples.getByteBuffer().asShortBuffer(); short min = Short.MAX_VALUE; short max = Short.MIN_VALUE; for (int i = 0; i < buffer.limit(); ++i) { short value = buffer.get(i); min = (short) Math.min(min, value); max = (short) Math.max(max, value); } // assign of min/max ommitted for brevity. super.onAudioSamples(event); } Step 2: Normalize all values: In a loop similar to step1, replace the buffer with normalized values, calling: buffer.put(i, normalize(buffer.get(i)); public short normalize(short value) { if (isBackgroundNoise(value)) return value; short rawMin = // min from step1 short rawMax = // max from step1 short targetRangeMin = 1000; short targetRangeMax = 8000; int abs = Math.abs(value); double a = (abs - rawMin) * (targetRangeMax - targetRangeMin); double b = (rawMax - rawMin); double result = targetRangeMin + ( a/b ); // Copy the sign of value to result. result = Math.copySign(result,value); return (short) result; } Questions: Is this a valid approach for attempting to normalize an audio file? Is my math in normalize() valid? Why would this cause the file to become noisy, where a similar approach in the demo code doesn't?

    Read the article

  • Difficulty creating classes and arrays of those classes C#

    - by Lucifer Fayte
    I'm trying to implement a Discrete Fourier Transformation algorithm for a project I'm doing in school. But creating a class is seeming to be difficult(which it shouldn't be). I'm using Visual Studio 2012. Basically I need a class called Complex to store the two values I get from a DFT; The real portion and the imaginary portion. This is what I have so far for that: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SoundEditor_V3 { public class Complex { public double real; public double im; public Complex() { real = 0; im = 0; } } } The problem is that it doesn't recognize the constructor as a constructor, now I'm just learning C#, but I looked it up online and this is how it's supposed to look apparently. It recognizes my constructor as a method. Why is that? Am I creating the class wrong? It's doing the same thing for my Fourier class as well. So each time I try to create a Fourier object and then use it's method...there is no such thing. example, I do this: Fourier fou = new Fourier(); fou.DFT(s, N, amp, 0); and it tells me fou is a 'field' but is used like a 'type' why is it saying that? Here is the code for my Fourier class as well: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SoundEditor_V3 { public class Fourier { //FOURIER //N = number of samples //s is the array of samples(data) //amp is the array where the complex result will be written to //start is the where in the array to start public void DFT(byte[] s, int N, ref Complex[] amp, int start) { Complex tem = new Complex(); int f; int t; for (f = 0; f < N; f++) { tem.real = 0; tem.im = 0; for (t = 0; t < N; t++) { tem.real += s[t + start] * Math.Cos(2 * Math.PI * t * f / N); tem.im -= s[t + start] * Math.Sin(2 * Math.PI * t * f / N); } amp[f].real = tem.real; amp[f].im = tem.im; } } //INVERSE FOURIER public void IDFT(Complex[] A, ref int[] s) { int N = A.Length; int t, f; double result; for (t = 0; t < N; t++) { result = 0; for (f = 0; f < N; f++) { result += A[f].real * Math.Cos(2 * Math.PI * t * f / N) - A[f].im * Math.Sin(2 * Math.PI * t * f / N); } s[t] = (int)Math.Round(result); } } } } I'm very much stuck at the moment, any and all help would be appreciated. Thank you.

    Read the article

  • Java curious Loop Performance

    - by user1680583
    I have a big problem while evaluate my java code. To simplify the problem I wrote the following code which produce the same curious behavior. Important is the method run() and given double value rate. For my runtime test (in the main method) I set the rate to 0.5 one times and 1.0 the other time. With the value 1.0 the if-statement will be executed in each loop iteration and with the value 0.5 the if-statement will be executed half as much. For this reason I expected longer runtime by the first case but opposite is true. Can anybody explain me this phenomenon?? The result of main: Test mit rate = 0.5 Length: 50000000, IF executions: 25000856 Execution time was 4329 ms. Length: 50000000, IF executions: 24999141 Execution time was 4307 ms. Length: 50000000, IF executions: 25001582 Execution time was 4223 ms. Length: 50000000, IF executions: 25000694 Execution time was 4328 ms. Length: 50000000, IF executions: 25004766 Execution time was 4346 ms. ================================= Test mit rate = 1.0 Length: 50000000, IF executions: 50000000 Execution time was 3482 ms. Length: 50000000, IF executions: 50000000 Execution time was 3572 ms. Length: 50000000, IF executions: 50000000 Execution time was 3529 ms. Length: 50000000, IF executions: 50000000 Execution time was 3479 ms. Length: 50000000, IF executions: 50000000 Execution time was 3473 ms. The Code public ArrayList<Byte> list = new ArrayList<Byte>(); public final int LENGTH = 50000000; public PerformanceTest(){ byte[]arr = new byte[LENGTH]; Random random = new Random(); random.nextBytes(arr); for(byte b : arr) list.add(b); } public void run(double rate){ byte b = 0; int count = 0; for (int i = 0; i < LENGTH; i++) { if(getRate(rate)){ list.set(i, b); count++; } } System.out.println("Length: " + LENGTH + ", IF executions: " + count); } public boolean getRate(double rate){ return Math.random() < rate; } public static void main(String[] args) throws InterruptedException { PerformanceTest test = new PerformanceTest(); long start, end; System.out.println("Test mit rate = 0.5"); for (int i = 0; i < 5; i++) { start=System.currentTimeMillis(); test.run(0.5); end = System.currentTimeMillis(); System.out.println("Execution time was "+(end-start)+" ms."); Thread.sleep(500); } System.out.println("================================="); System.out.println("Test mit rate = 1.0"); for (int i = 0; i < 5; i++) { start=System.currentTimeMillis(); test.run(1.0); end = System.currentTimeMillis(); System.out.println("Execution time was "+(end-start)+" ms."); Thread.sleep(500); } }

    Read the article

  • Why is there a Null Pointer Exception in this Java Code?

    - by algorithmicCoder
    This code takes in users and movies from two separate files and computes a user score for a movie. When i run the code I get the following error: Exception in thread "main" java.lang.NullPointerException at RecommenderSystem.makeRecommendation(RecommenderSystem.java:75) at RecommenderSystem.main(RecommenderSystem.java:24) I believe the null pointer exception is due to an error in this particular class but I can't spot it....any thoughts? import java.io.*; import java.lang.Math; public class RecommenderSystem { private Movie[] m_movies; private User[] m_users; /** Parse the movies and users files, and then run queries against them. */ public static void main(String[] argv) throws FileNotFoundException, ParseError, RecommendationError { FileReader movies_fr = new FileReader("C:\\workspace\\Recommender\\src\\IMDBTop10.txt"); FileReader users_fr = new FileReader("C:\\workspace\\Recommender\\src\\IMDBTop10-users.txt"); MovieParser mp = new MovieParser(movies_fr); UserParser up = new UserParser(users_fr); Movie[] movies = mp.getMovies(); User[] users = up.getUsers(); RecommenderSystem rs = new RecommenderSystem(movies, users); System.out.println("Alice would rate \"The Shawshank Redemption\" with at least a " + rs.makeRecommendation("The Shawshank Redemption", "asmith")); System.out.println("Carol would rate \"The Dark Knight\" with at least a " + rs.makeRecommendation("The Dark Knight", "cd0")); } /** Instantiate a recommender system. * * @param movies An array of Movie that will be copied into m_movies. * @param users An array of User that will be copied into m_users. */ public RecommenderSystem(Movie[] movies, User[] users) throws RecommendationError { m_movies = movies; m_users = users; } /** Suggest what the user with "username" would rate "movieTitle". * * @param movieTitle The movie for which a recommendation is made. * @param username The user for whom the recommendation is made. */ public double makeRecommendation(String movieTitle, String username) throws RecommendationError { int userNumber; int movieNumber; int j=0; double weightAvNum =0; double weightAvDen=0; for (userNumber = 0; userNumber < m_users.length; ++userNumber) { if (m_users[userNumber].getUsername().equals(username)) { break; } } for (movieNumber = 0; movieNumber < m_movies.length; ++movieNumber) { if (m_movies[movieNumber].getTitle().equals(movieTitle)) { break; } } // Use the weighted average algorithm here (don't forget to check for // errors). while(j<m_users.length){ if(j!=userNumber){ weightAvNum = weightAvNum + (m_users[j].getRating(movieNumber)- m_users[j].getAverageRating())*(m_users[userNumber].similarityTo(m_users[j])); weightAvDen = weightAvDen + (m_users[userNumber].similarityTo(m_users[j])); } j++; } return (m_users[userNumber].getAverageRating()+ (weightAvNum/weightAvDen)); } } class RecommendationError extends Exception { /** An error for when something goes wrong in the recommendation process. * * @param s A string describing the error. */ public RecommendationError(String s) { super(s); } }

    Read the article

  • Critique my heap debugger

    - by FredOverflow
    I wrote the following heap debugger in order to demonstrate memory leaks, double deletes and wrong forms of deletes (i.e. trying to delete an array with delete p instead of delete[] p) to beginning programmers. I would love to get some feedback on that from strong C++ programmers because I have never done this before and I'm sure I've done some stupid mistakes. Thanks! #include <cstdlib> #include <iostream> #include <new> namespace { const int ALIGNMENT = 16; const char* const ERR = "*** ERROR: "; int counter = 0; struct heap_debugger { heap_debugger() { std::cerr << "*** heap debugger started\n"; } ~heap_debugger() { std::cerr << "*** heap debugger shutting down\n"; if (counter > 0) { std::cerr << ERR << "failed to release memory " << counter << " times\n"; } else if (counter < 0) { std::cerr << ERR << (-counter) << " double deletes detected\n"; } } } instance; void* allocate(size_t size, const char* kind_of_memory, size_t token) throw (std::bad_alloc) { void* raw = malloc(size + ALIGNMENT); if (raw == 0) throw std::bad_alloc(); *static_cast<size_t*>(raw) = token; void* payload = static_cast<char*>(raw) + ALIGNMENT; ++counter; std::cerr << "*** allocated " << kind_of_memory << " at " << payload << " (" << size << " bytes)\n"; return payload; } void release(void* payload, const char* kind_of_memory, size_t correct_token, size_t wrong_token) throw () { if (payload == 0) return; std::cerr << "*** releasing " << kind_of_memory << " at " << payload << '\n'; --counter; void* raw = static_cast<char*>(payload) - ALIGNMENT; size_t* token = static_cast<size_t*>(raw); if (*token == correct_token) { *token = 0xDEADBEEF; free(raw); } else if (*token == wrong_token) { *token = 0x177E6A7; std::cerr << ERR << "wrong form of delete\n"; } else { std::cerr << ERR << "double delete\n"; } } } void* operator new(size_t size) throw (std::bad_alloc) { return allocate(size, "non-array memory", 0x5AFE6A8D); } void* operator new[](size_t size) throw (std::bad_alloc) { return allocate(size, " array memory", 0x5AFE6A8E); } void operator delete(void* payload) throw () { release(payload, "non-array memory", 0x5AFE6A8D, 0x5AFE6A8E); } void operator delete[](void* payload) throw () { release(payload, " array memory", 0x5AFE6A8E, 0x5AFE6A8D); }

    Read the article

  • Rewrite C++ code into Objective C

    - by Phil_M
    Hello I got some C++ Sourcecode that I would like to rewrite into Objective C. It would help me alot if someone could write me a header file for this Code. When I get the Headerfile I would be able to rewrite the rest of the Sourcecode. It would be very nice if someone could help me please. Thanks I will poste the sourcecode here: #include <stdlib.h> #include <iostream.h> #define STATES 5 int transitionTable[STATES][STATES]; // function declarations: double randfloat (void); int chooseNextEventFromTable (int current, int table[STATES][STATES]); int chooseNextEventFromTransitionTablee (int currentState); void setTable (int value, int table[STATES][STATES]); ////////////////////////////////////////////////////////////////////////// int main(void) { int i; // for demo purposes: transitionTable[0][0] = 0; transitionTable[0][1] = 20; transitionTable[0][2] = 30; transitionTable[0][3] = 50; transitionTable[0][4] = 0; transitionTable[1][0] = 35; transitionTable[1][1] = 25; transitionTable[1][2] = 20; transitionTable[1][3] = 30; transitionTable[1][4] = 0; transitionTable[2][0] = 70; transitionTable[2][1] = 0; transitionTable[2][2] = 15; transitionTable[2][3] = 0; transitionTable[2][4] = 15; transitionTable[3][0] = 0; transitionTable[3][1] = 25; transitionTable[3][2] = 25; transitionTable[3][3] = 0; transitionTable[3][4] = 50; transitionTable[4][0] = 13; transitionTable[4][1] = 17; transitionTable[4][2] = 22; transitionTable[4][3] = 48; transitionTable[4][4] = 0; int currentState = 0; for (i=0; i<10; i++) { std::cout << currentState << " "; currentState = chooseNextEventFromTransitionTablee(currentState); } return 0; }; ////////////////////////////////////////////////////////////////////////// ////////////////////////////// // // chooseNextEventFromTransitionTable -- choose the next note. // int chooseNextEventFromTransitionTablee(int currentState) { int targetSum = 0; int sum = 0; int targetNote = 0; int totalevents = 0; int i; currentState = currentState % STATES; // remove any octave value for (i=0; i<STATES; i++) { totalevents += transitionTable[currentState][i]; } targetSum = (int)(randfloat() * totalevents + 0.5); while (targetNote < STATES && sum+transitionTable[currentState][targetNote] < targetSum) { sum += transitionTable[currentState][targetNote]; targetNote++; } return targetNote; } ////////////////////////////// // // randfloat -- returns a random number between 0.0 and 1.0. // double randfloat(void) { return (double)rand()/RAND_MAX; } ////////////////////////////// // // setTable -- set all values in the transition table to the given value. // void setTable(int value, int table[STATES][STATES]) { int i, j; for (i=0; i<STATES; i++) { for (j=0; j<STATES; j++) { table[i][j] = value; } } }

    Read the article

  • 10000's+ UI elements, bind or draw?

    - by jpiccolo
    I am drawing a header for a timeline control. It looks like this: I go to 0.01 millisecond per line, so for a 10 minute timeline I am looking at drawing 60000 lines + 6000 labels. This takes a while, ~10 seconds. I would like to offload this from the UI thread. My code is currently: private void drawHeader() { Header.Children.Clear(); switch (viewLevel) { case ViewLevel.MilliSeconds100: double hWidth = Header.Width; this.drawHeaderLines(new TimeSpan(0, 0, 0, 0, 10), 100, 5, hWidth); //Was looking into background worker to off load UI //backgroundWorker = new BackgroundWorker(); //backgroundWorker.DoWork += delegate(object sender, DoWorkEventArgs args) // { // this.drawHeaderLines(new TimeSpan(0, 0, 0, 0, 10), 100, 5, hWidth); // }; //backgroundWorker.RunWorkerAsync(); break; } } private void drawHeaderLines(TimeSpan timeStep, int majorEveryXLine, int distanceBetweenLines, double headerWidth) { var currentTime = new TimeSpan(0, 0, 0, 0, 0); const int everyXLine100 = 10; double currentX = 0; var currentLine = 0; while (currentX < headerWidth) { var l = new Line { ToolTip = currentTime.ToString(@"hh\:mm\:ss\.fff"), StrokeThickness = 1, X1 = 0, X2 = 0, Y1 = 30, Y2 = 25 }; if (((currentLine % majorEveryXLine) == 0) && currentLine != 0) { l.StrokeThickness = 2; l.Y2 = 15; var textBlock = new TextBlock { Text = l.ToolTip.ToString(), FontSize = 8, FontFamily = new FontFamily("Tahoma"), Foreground = new SolidColorBrush(Color.FromRgb(255, 255, 255)) }; Canvas.SetLeft(textBlock, (currentX - 22)); Canvas.SetTop(textBlock, 0); Header.Children.Add(textBlock); } if ((((currentLine % everyXLine100) == 0) && currentLine != 0) && (currentLine % majorEveryXLine) != 0) { l.Y2 = 20; var textBlock = new TextBlock { Text = string.Format(".{0}", TimeSpan.Parse(l.ToolTip.ToString()).Milliseconds), FontSize = 8, FontFamily = new FontFamily("Tahoma"), Foreground = new SolidColorBrush(Color.FromRgb(192, 192, 192)) }; Canvas.SetLeft(textBlock, (currentX - 8)); Canvas.SetTop(textBlock, 8); Header.Children.Add(textBlock); } l.Stroke = new SolidColorBrush(Color.FromRgb(255, 255, 255)); Header.Children.Add(l); Canvas.SetLeft(l, currentX); currentX += distanceBetweenLines; currentLine++; currentTime += timeStep; } } I had looked into BackgroundWorker, except you can't create UI elements on a non-UI thread. Is it possible at all to do drawHeaderLines in a non-UI thread? Could I use data binding for drawing the lines? Would this help with UI responsiveness? I would imagine I can use databinding, but the Styling is probably beyond my current WPF ability (coming from winforms and trying to learn what all these style objects are and binding them). Would anyone be able to supply a starting point for tempting this out? Or Google a tutorial that would get me started?

    Read the article

  • Passing multiple simple POST Values to ASP.NET Web API

    - by Rick Strahl
    A few weeks backs I posted a blog post  about what does and doesn't work with ASP.NET Web API when it comes to POSTing data to a Web API controller. One of the features that doesn't work out of the box - somewhat unexpectedly -  is the ability to map POST form variables to simple parameters of a Web API method. For example imagine you have this form and you want to post this data to a Web API end point like this via AJAX: <form> Name: <input type="name" name="name" value="Rick" /> Value: <input type="value" name="value" value="12" /> Entered: <input type="entered" name="entered" value="12/01/2011" /> <input type="button" id="btnSend" value="Send" /> </form> <script type="text/javascript"> $("#btnSend").click( function() { $.post("samples/PostMultipleSimpleValues?action=kazam", $("form").serialize(), function (result) { alert(result); }); }); </script> or you might do this more explicitly by creating a simple client map and specifying the POST values directly by hand:$.post("samples/PostMultipleSimpleValues?action=kazam", { name: "Rick", value: 1, entered: "12/01/2012" }, $("form").serialize(), function (result) { alert(result); }); On the wire this generates a simple POST request with Url Encoded values in the content:POST /AspNetWebApi/samples/PostMultipleSimpleValues?action=kazam HTTP/1.1 Host: localhost User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0.1 Accept: application/json Connection: keep-alive Content-Type: application/x-www-form-urlencoded; charset=UTF-8 X-Requested-With: XMLHttpRequest Referer: http://localhost/AspNetWebApi/FormPostTest.html Content-Length: 41 Pragma: no-cache Cache-Control: no-cachename=Rick&value=12&entered=12%2F10%2F2011 Seems simple enough, right? We are basically posting 3 form variables and 1 query string value to the server. Unfortunately Web API can't handle request out of the box. If I create a method like this:[HttpPost] public string PostMultipleSimpleValues(string name, int value, DateTime entered, string action = null) { return string.Format("Name: {0}, Value: {1}, Date: {2}, Action: {3}", name, value, entered, action); }You'll find that you get an HTTP 404 error and { "Message": "No HTTP resource was found that matches the request URI…"} Yes, it's possible to pass multiple POST parameters of course, but Web API expects you to use Model Binding for this - mapping the post parameters to a strongly typed .NET object, not to single parameters. Alternately you can also accept a FormDataCollection parameter on your API method to get a name value collection of all POSTed values. If you're using JSON only, using the dynamic JObject/JValue objects might also work. ModelBinding is fine in many use cases, but can quickly become overkill if you only need to pass a couple of simple parameters to many methods. Especially in applications with many, many AJAX callbacks the 'parameter mapping type' per method signature can lead to serious class pollution in a project very quickly. Simple POST variables are also commonly used in AJAX applications to pass data to the server, even in many complex public APIs. So this is not an uncommon use case, and - maybe more so a behavior that I would have expected Web API to support natively. The question "Why aren't my POST parameters mapping to Web API method parameters" is already a frequent one… So this is something that I think is fairly important, but unfortunately missing in the base Web API installation. Creating a Custom Parameter Binder Luckily Web API is greatly extensible and there's a way to create a custom Parameter Binding to provide this functionality! Although this solution took me a long while to find and then only with the help of some folks Microsoft (thanks Hong Mei!!!), it's not difficult to hook up in your own projects. It requires one small class and a GlobalConfiguration hookup. Web API parameter bindings allow you to intercept processing of individual parameters - they deal with mapping parameters to the signature as well as converting the parameters to the actual values that are returned. Here's the implementation of the SimplePostVariableParameterBinding class:public class SimplePostVariableParameterBinding : HttpParameterBinding { private const string MultipleBodyParameters = "MultipleBodyParameters"; public SimplePostVariableParameterBinding(HttpParameterDescriptor descriptor) : base(descriptor) { } /// <summary> /// Check for simple binding parameters in POST data. Bind POST /// data as well as query string data /// </summary> public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken) { // Body can only be read once, so read and cache it NameValueCollection col = TryReadBody(actionContext.Request); string stringValue = null; if (col != null) stringValue = col[Descriptor.ParameterName]; // try reading query string if we have no POST/PUT match if (stringValue == null) { var query = actionContext.Request.GetQueryNameValuePairs(); if (query != null) { var matches = query.Where(kv => kv.Key.ToLower() == Descriptor.ParameterName.ToLower()); if (matches.Count() > 0) stringValue = matches.First().Value; } } object value = StringToType(stringValue); // Set the binding result here SetValue(actionContext, value); // now, we can return a completed task with no result TaskCompletionSource<AsyncVoid> tcs = new TaskCompletionSource<AsyncVoid>(); tcs.SetResult(default(AsyncVoid)); return tcs.Task; } private object StringToType(string stringValue) { object value = null; if (stringValue == null) value = null; else if (Descriptor.ParameterType == typeof(string)) value = stringValue; else if (Descriptor.ParameterType == typeof(int)) value = int.Parse(stringValue, CultureInfo.CurrentCulture); else if (Descriptor.ParameterType == typeof(Int32)) value = Int32.Parse(stringValue, CultureInfo.CurrentCulture); else if (Descriptor.ParameterType == typeof(Int64)) value = Int64.Parse(stringValue, CultureInfo.CurrentCulture); else if (Descriptor.ParameterType == typeof(decimal)) value = decimal.Parse(stringValue, CultureInfo.CurrentCulture); else if (Descriptor.ParameterType == typeof(double)) value = double.Parse(stringValue, CultureInfo.CurrentCulture); else if (Descriptor.ParameterType == typeof(DateTime)) value = DateTime.Parse(stringValue, CultureInfo.CurrentCulture); else if (Descriptor.ParameterType == typeof(bool)) { value = false; if (stringValue == "true" || stringValue == "on" || stringValue == "1") value = true; } else value = stringValue; return value; } /// <summary> /// Read and cache the request body /// </summary> /// <param name="request"></param> /// <returns></returns> private NameValueCollection TryReadBody(HttpRequestMessage request) { object result = null; // try to read out of cache first if (!request.Properties.TryGetValue(MultipleBodyParameters, out result)) { // parsing the string like firstname=Hongmei&lastname=Ge result = request.Content.ReadAsFormDataAsync().Result; request.Properties.Add(MultipleBodyParameters, result); } return result as NameValueCollection; } private struct AsyncVoid { } }   The ExecuteBindingAsync method is fired for each parameter that is mapped and sent for conversion. This custom binding is fired only if the incoming parameter is a simple type (that gets defined later when I hook up the binding), so this binding never fires on complex types or if the first type is not a simple type. For the first parameter of a request the Binding first reads the request body into a NameValueCollection and caches that in the request.Properties collection. The request body can only be read once, so the first parameter request reads it and then caches it. Subsequent parameters then use the cached POST value collection. Once the form collection is available the value of the parameter is read, and the value is translated into the target type requested by the Descriptor. SetValue writes out the value to be mapped. Once you have the ParameterBinding in place, the binding has to be assigned. This is done along with all other Web API configuration tasks at application startup in global.asax's Application_Start:GlobalConfiguration.Configuration.ParameterBindingRules .Insert(0, (HttpParameterDescriptor descriptor) => { var supportedMethods = descriptor.ActionDescriptor.SupportedHttpMethods; // Only apply this binder on POST and PUT operations if (supportedMethods.Contains(HttpMethod.Post) || supportedMethods.Contains(HttpMethod.Put)) { var supportedTypes = new Type[] { typeof(string), typeof(int), typeof(decimal), typeof(double), typeof(bool), typeof(DateTime) }; if (supportedTypes.Where(typ => typ == descriptor.ParameterType).Count() > 0) return new SimplePostVariableParameterBinding(descriptor); } // let the default bindings do their work return null; });   The ParameterBindingRules.Insert method takes a delegate that checks which type of requests it should handle. The logic here checks whether the request is POST or PUT and whether the parameter type is a simple type that is supported. Web API calls this delegate once for each method signature it tries to map and the delegate returns null to indicate it's not handling this parameter, or it returns a new parameter binding instance - in this case the SimplePostVariableParameterBinding. Once the parameter binding and this hook up code is in place, you can now pass simple POST values to methods with simple parameters. The examples I showed above should now work in addition to the standard bindings. Summary Clearly this is not easy to discover. I spent quite a bit of time digging through the Web API source trying to figure this out on my own without much luck. It took Hong Mei at Micrsoft to provide a base example as I asked around so I can't take credit for this solution :-). But once you know where to look, Web API is brilliantly extensible to make it relatively easy to customize the parameter behavior. I'm very stoked that this got resolved  - in the last two months I've had two customers with projects that decided not to use Web API in AJAX heavy SPA applications because this POST variable mapping wasn't available. This might actually change their mind to still switch back and take advantage of the many great features in Web API. I too frequently use plain POST variables for communicating with server AJAX handlers and while I could have worked around this (with untyped JObject or the Form collection mostly), having proper POST to parameter mapping makes things much easier. I said this in my last post on POST data and say it again here: I think POST to method parameter mapping should have been shipped in the box with Web API, because without knowing about this limitation the expectation is that simple POST variables map to parameters just like query string values do. I hope Microsoft considers including this type of functionality natively in the next version of Web API natively or at least as a built-in HttpParameterBinding that can be just added. This is especially true, since this binding doesn't affect existing bindings. Resources SimplePostVariableParameterBinding Source on GitHub Global.asax hookup source Mapping URL Encoded Post Values in  ASP.NET Web API© Rick Strahl, West Wind Technologies, 2005-2012Posted in Web Api  AJAX   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • Move Files from a Failing PC with an Ubuntu Live CD

    - by Trevor Bekolay
    You’ve loaded the Ubuntu Live CD to salvage files from a failing system, but where do you store the recovered files? We’ll show you how to store them on external drives, drives on the same PC, a Windows home network, and other locations. We’ve shown you how to recover data like a forensics expert, but you can’t store recovered files back on your failed hard drive! There are lots of ways to transfer the files you access from an Ubuntu Live CD to a place that a stable Windows machine can access them. We’ll go through several methods, starting each section from the Ubuntu desktop – if you don’t yet have an Ubuntu Live CD, follow our guide to creating a bootable USB flash drive, and then our instructions for booting into Ubuntu. If your BIOS doesn’t let you boot using a USB flash drive, don’t worry, we’ve got you covered! Use a Healthy Hard Drive If your computer has more than one hard drive, or your hard drive is healthy and you’re in Ubuntu for non-recovery reasons, then accessing your hard drive is easy as pie, even if the hard drive is formatted for Windows. To access a hard drive, it must first be mounted. To mount a healthy hard drive, you just have to select it from the Places menu at the top-left of the screen. You will have to identify your hard drive by its size. Clicking on the appropriate hard drive mounts it, and opens it in a file browser. You can now move files to this hard drive by drag-and-drop or copy-and-paste, both of which are done the same way they’re done in Windows. Once a hard drive, or other external storage device, is mounted, it will show up in the /media directory. To see a list of currently mounted storage devices, navigate to /media by clicking on File System in a File Browser window, and then double-clicking on the media folder. Right now, our media folder contains links to the hard drive, which Ubuntu has assigned a terribly uninformative label, and the PLoP Boot Manager CD that is currently in the CD-ROM drive. Connect a USB Hard Drive or Flash Drive An external USB hard drive gives you the advantage of portability, and is still large enough to store an entire hard disk dump, if need be. Flash drives are also very quick and easy to connect, though they are limited in how much they can store. When you plug a USB hard drive or flash drive in, Ubuntu should automatically detect it and mount it. It may even open it in a File Browser automatically. Since it’s been mounted, you will also see it show up on the desktop, and in the /media folder. Once it’s been mounted, you can access it and store files on it like you would any other folder in Ubuntu. If, for whatever reason, it doesn’t mount automatically, click on Places in the top-left of your screen and select your USB device. If it does not show up in the Places list, then you may need to format your USB drive. To properly remove the USB drive when you’re done moving files, right click on the desktop icon or the folder in /media and select Safely Remove Drive. If you’re not given that option, then Eject or Unmount will effectively do the same thing. Connect to a Windows PC on your Local Network If you have another PC or a laptop connected through the same router (wired or wireless) then you can transfer files over the network relatively quickly. To do this, we will share one or more folders from the machine booted up with the Ubuntu Live CD over the network, letting our Windows PC grab the files contained in that folder. As an example, we’re going to share a folder on the desktop called ToShare. Right-click on the folder you want to share, and click Sharing Options. A Folder Sharing window will pop up. Check the box labeled Share this folder. A window will pop up about the sharing service. Click the Install service button. Some files will be downloaded, and then installed. When they’re done installing, you’ll be appropriately notified. You will be prompted to restart your session. Don’t worry, this won’t actually log you out, so go ahead and press the Restart session button. The Folder Sharing window returns, with Share this folder now checked. Edit the Share name if you’d like, and add checkmarks in the two checkboxes below the text fields. Click Create Share. Nautilus will ask your permission to add some permissions to the folder you want to share. Allow it to Add the permissions automatically. The folder is now shared, as evidenced by the new arrows above the folder’s icon. At this point, you are done with the Ubuntu machine. Head to your Windows PC, and open up Windows Explorer. Click on Network in the list on the left, and you should see a machine called UBUNTU in the right pane. Note: This example is shown in Windows 7; the same steps should work for Windows XP and Vista, but we have not tested them. Double-click on UBUNTU, and you will see the folder you shared earlier! As well as any other folders you’ve shared from Ubuntu. Double click on the folder you want to access, and from there, you can move the files from the machine booted with Ubuntu to your Windows PC. Upload to an Online Service There are many services online that will allow you to upload files, either temporarily or permanently. As long as you aren’t transferring an entire hard drive, these services should allow you to transfer your important files from the Ubuntu environment to any other machine with Internet access. We recommend compressing the files that you want to move, both to save a little bit of bandwidth, and to save time clicking on files, as uploading a single file will be much less work than a ton of little files. To compress one or more files or folders, select them, and then right-click on one of the members of the group. Click Compress…. Give the compressed file a suitable name, and then select a compression format. We’re using .zip because we can open it anywhere, and the compression rate is acceptable. Click Create and the compressed file will show up in the location selected in the Compress window. Dropbox If you have a Dropbox account, then you can easily upload files from the Ubuntu environment to Dropbox. There is no explicit limit on the size of file that can be uploaded to Dropbox, though a free account begins with a total limit of 2 GB of files in total. Access your account through Firefox, which can be opened by clicking on the Firefox logo to the right of the System menu at the top of the screen. Once into your account, press the Upload button on top of the main file list. Because Flash is not installed in the Live CD environment, you will have to switch to the basic uploader. Click Browse…find your compressed file, and then click Upload file. Depending on the size of the file, this could take some time. However, once the file has been uploaded, it should show up on any computer connected through Dropbox in a matter of minutes. Google Docs Google Docs allows the upload of any type of file – making it an ideal place to upload files that we want to access from another computer. While your total allocation of space varies (mine is around 7.5 GB), there is a per-file maximum of 1 GB. Log into Google Docs, and click on the Upload button at the top left of the page. Click Select files to upload and select your compressed file. For safety’s sake, uncheck the checkbox concerning converting files to Google Docs format, and then click Start upload. Go Online – Through FTP If you have access to an FTP server – perhaps through your web hosting company, or you’ve set up an FTP server on a different machine – you can easily access the FTP server in Ubuntu and transfer files. Just make sure you don’t go over your quota if you have one. You will need to know the address of the FTP server, as well as the login information. Click on Places > Connect to Server… Choose the FTP (with login) Service type, and fill in your information. Adding a bookmark is optional, but recommended. You will be asked for your password. You can choose to remember it until you logout, or indefinitely. You can now browse your FTP server just like any other folder. Drop files into the FTP server and you can retrieve them from any computer with an Internet connection and an FTP client. Conclusion While at first the Ubuntu Live CD environment may seem claustrophobic, it has a wealth of options for connecting to peripheral devices, local computers, and machines on the Internet – and this article has only scratched the surface. Whatever the storage medium, Ubuntu’s got an interface for it! Similar Articles Productive Geek Tips Backup Your Windows Live Writer SettingsMove a Window Without Clicking the Titlebar in UbuntuRecover Deleted Files on an NTFS Hard Drive from a Ubuntu Live CDCreate a Bootable Ubuntu USB Flash Drive the Easy WayReset Your Ubuntu Password Easily from the Live CD TouchFreeze Alternative in AutoHotkey The Icy Undertow Desktop Windows Home Server – Backup to LAN The Clear & Clean Desktop Use This Bookmarklet to Easily Get Albums Use AutoHotkey to Assign a Hotkey to a Specific Window Latest Software Reviews Tinyhacker Random Tips Acronis Online Backup DVDFab 6 Revo Uninstaller Pro Registry Mechanic 9 for Windows Tech Fanboys Field Guide Check these Awesome Chrome Add-ons iFixit Offers Gadget Repair Manuals Online Vista style sidebar for Windows 7 Create Nice Charts With These Web Based Tools Track Daily Goals With 42Goals

    Read the article

  • Clustering Basics and Challenges

    - by Karoly Vegh
    For upcoming posts it seemed to be a good idea to dedicate some time for cluster basic concepts and theory. This post misses a lot of details that would explode the articlesize, should you have questions, do not hesitate to ask them in the comments.  The goal here is to get some concepts straight. I can't promise to give you an overall complete definitions of cluster, cluster agent, quorum, voting, fencing, split brain condition, so the following is more of an explanation. Here we go. -------- Cluster, HA, failover, switchover, scalability -------- An attempted definition of a Cluster: A cluster is a set (2+) server nodes dedicated to keep application services alive, communicating through the cluster software/framework with eachother, test and probe health status of servernodes/services and with quorum based decisions and with switchover/failover techniques keep the application services running on them available. That is, should a node that runs a service unexpectedly lose functionality/connection, the other ones would take over the and run the services, so that availability is guaranteed. To provide availability while strictly sticking to a consistent clusterconfiguration is the main goal of a cluster.  At this point we have to add that this defines a HA-cluster, a High-Availability cluster, where the clusternodes are planned to run the services in an active-standby, or failover fashion. An example could be a single instance database. Some applications can be run in a distributed or scalable fashion. In the latter case instances of the application run actively on separate clusternodes serving servicerequests simultaneously. An example for this version could be a webserver that forwards connection requests to many backend servers in a round-robin way. Or a database running in active-active RAC setup.  -------- Cluster arhitecture, interconnect, topologies -------- Now, what is a cluster made of? Servers, right. These servers (the clusternodes) need to communicate. This of course happens over the network, usually over dedicated network interfaces interconnecting all the clusternodes. These connection are called interconnects.How many clusternodes are in a cluster? There are different cluster topologies. The most simple one is a clustered pair topology, involving only two clusternodes:  There are several more topologies, clicking the image above will take you to the relevant documentation. Also, to answer the question Solaris Cluster allows you to run up to 16 servers in a cluster. Where shall these clusternodes be placed? A very important question. The right answer is: It depends on what you plan to achieve with the cluster. Do you plan to avoid only a server outage? Then you can place them right next to eachother in the datacenter. Do you need to avoid DataCenter outage? In that case of course you should place them at least in different fire zones. Or in two geographically distant DataCenters to avoid disasters like floods, large-scale fires or power outages. We call this a stretched- or campus cluster, the clusternodes being several kilometers away from eachother. To cover really large distances, you probably need to move to a GeoCluster, which is a different kind of animal.  What is a geocluster? A Geographic Cluster in Solaris Cluster terms is actually a metacluster between two, separate (locally-HA) clusters.  -------- Cluster resource types, agents, resources, resource groups -------- So how does the cluster manage my applications? The cluster needs to start, stop and probe your applications. If you application runs, the cluster needs to check regularly if the application state is healthy, does it respond over the network, does it have all the processes running, etc. This is called probing. If the cluster deems the application is in a faulty state, then it can try to restart it locally or decide to switch (stop on node A, start on node B) the service. Starting, stopping and probing are the three actions that a cluster agent does. There are many different kinds of agents included in Solaris Cluster, but you can build your own too. Examples are an agent that manages (mounts, moves) ZFS filesystems, or the Oracle DB HA agent that cares about the database, or an agent that moves a floating IP address between nodes. There are lots of other agents included for Apache, Tomcat, MySQL, Oracle DB, Oracle Weblogic, Zones, LDoms, NFS, DNS, etc.We also need to clarify the difference between a cluster resource and the cluster resource group.A cluster resource is something that is managed by a cluster agent. Cluster resource types are included in Solaris cluster (see above, e.g. HAStoragePlus, HA-Oracle, LogicalHost). You can group cluster resources into cluster resourcegroups, and switch these groups together from one node to another. To stick to the example above, to move an Oracle DB service from one node to another, you have to switch the group between nodes, and the agents of the cluster resources in the group will do the following:  On node A Shut down the DB Unconfigure the LogicalHost IP the DB Listener listens on unmount the filesystem   Then, on node B: mount the FS configure the IP  startup the DB -------- Voting, Quorum, Split Brain Condition, Fencing, Amnesia -------- How do the clusternodes agree upon their action? How do they decide which node runs what services? Another important question. Running a cluster is a strictly democratic thing.Every node has votes, and you need the majority of votes to have the deciding power. Now, this is usually no problem, clusternodes think very much all alike. Still, every action needs to be governed upon in a productive system, and has to be agreed upon. Agreeing is easy as long as the clusternodes all behave and talk to eachother over the interconnect. But if the interconnect is gone/down, this all gets tricky and confusing. Clusternodes think like this: "My job is to run these services. The other node does not answer my interconnect communication, it must be down. I'd better take control and run the services!". The problem is, as I have already mentioned, clusternodes very much think alike. If the interconnect is gone, they all assume the other node is down, and they all want to mount the data backend, enable the IP and run the database. Double IPs, double mounts, double DB instances - now that is trouble. Also, in a 2-node cluster they both have only 50% of the votes, that is, they themselves alone are not allowed to run a cluster.  This is where you need a quorum device. According to Wikipedia, the "requirement for a quorum is protection against totally unrepresentative action in the name of the body by an unduly small number of persons.". They need additional votes to run the cluster. For this requirement a 2-node cluster needs a quorum device or a quorum server. If the interconnect is gone, (this is what we call a split brain condition) both nodes start to race and try to reserve the quorum device to themselves. They do this, because the quorum device bears an additional vote, that could ensure majority (50% +1). The one that manages to lock the quorum device (e.g. if it's an FC LUN, it SCSI reserves it) wins the right to build/run a cluster, the other one - realizing he was late - panics/reboots to ensure the cluster config stays consistent.  Losing the interconnect isn't only endangering the availability of services, but it also endangers the cluster configuration consistence. Just imagine node A being down and during that the cluster configuration changes. Now node B goes down, and node A comes up. It isn't uptodate about the cluster configuration's changes so it will refuse to start a cluster, since that would lead to cluster amnesia, that is the cluster had some changes, but now runs with an older cluster configuration repository state, that is it's like it forgot about the changes.  Also, to ensure application data consistence, the clusternode that wins the race makes sure that a server that isn't part of or can't currently join the cluster can access the devices. This procedure is called fencing. This usually happens to storage LUNs via SCSI reservation.  Now, another important question: Where do I place the quorum disk?  Imagine having two sites, two separate datacenters, one in the north of the city and the other one in the south part of it. You run a stretched cluster in the clustered pair topology. Where do you place the quorum disk/server? If you put it into the north DC, and that gets hit by a meteor, you lose one clusternode, which isn't a problem, but you also lose your quorum, and the south clusternode can't keep the cluster running lacking the votes. This problem can't be solved with two sites and a campus cluster. You will need a third site to either place the quorum server to, or a third clusternode. Otherwise, lacking majority, if you lose the site that had your quorum, you lose the cluster. Okay, we covered the very basics. We haven't talked about virtualization support, CCR, ClusterFilesystems, DID devices, affinities, storage-replication, management tools, upgrade procedures - should those be interesting for you, let me know in the comments, along with any other questions. Given enough demand I'd be glad to write a followup post too. Now I really want to move on to the second part in the series: ClusterInstallation.  Oh, as for additional source of information, I recommend the documentation: http://docs.oracle.com/cd/E23623_01/index.html, and the OTN Oracle Solaris Cluster site: http://www.oracle.com/technetwork/server-storage/solaris-cluster/index.html

    Read the article

  • ODEE Green Field (Windows) Part 5 - Deployment and Validation

    - by AndyL-Oracle
    And here we are, almost finished with our installation of Oracle Documaker Enterprise Edition ("ODEE") in a Windows green field environment. Let's recap what we've done so far: In part 1, I went over the basic process that I intended to show with installing an ODEE on a green field server. I walked you through the basic installation of Oracle 11g database In part 2, I covered the installation of WebLogic application server. In part 3, I showed you how to install SOA Suite for WebLogic. In part 4, we did the first part of the installation of ODEE itself. What remains after all of that, is the deployment of the ODEE components onto the database and application server - so let's get to it! DATABASE First, we'll deploy the schemas to the database. The schemas are created during the ODEE installation according to the responses provided during the install process. To deploy the schemas, you'll need to login to the database server in your green field environment. Open a command line and CD into ODEE_HOME\documaker\database\oracle11g.Run SQLPLUS as SYSDBA and execute dmkr_admin.sql:  sqlplus / as sysdba @dmkr_admin.sql Execute dmkr_asline.sql, dmkr_admin_correspondence_example.sql.  If you require additional languages, run the appropriate SQL scripts (e.g. dmkr_asline_es.sql for Spanish). APPLICATION SERVER Next, we'll deploy the WebLogic domain and it's components - Documaker web services, Documaker Interactive, Documaker dashboard, and more. To deploy the components, you'll need to login to the application server in your green field environment. 1. Open Windows Explorer and navigate to ODEE_HOME\documaker\j2ee\weblogic\oracle11g\scripts.2. Using a text editor such as Notepad++, modify weblogic_installation_properties and set location of MIDDLEWARE_HOME and ODEE HOME. If you have used the defaults you’ll probably need to change the E: to C: and that’s it. Save the changes.3. Continuing in the same directory, use your text editor to modify set_middleware_env.cmd and set the drive and path to MIDDLEWARE_HOME. If you have used the defaults you’ll probably need to just change E: to C: and that’s it. Save the changes.4. In the same directory, execute wls_create_domain.cmd by double-clicking it. This should run to completion. If it does not, review any errors and correct them, and rerun the script.5. In the same directory, execute wls_add_correspondence.cmd by double-clicking it - again this should run to completion. 6. Next, we'll start the AdminServer - this is the main WebLogic domain server. To start it, use Windows Explorer and navigate to MIDDLEWARE_HOME\user_projects\domains\idocumaker_domain. Double-click startWebLogic.cmd and the server startup will begin. Once you see output that indicates that the server status changed to RUNNING you may proceed.  a. Note: if you saw database connection errors, you probably didn’t make sure your database name and connection type match. You can change this manually in the WebLogic Console. Open a browser and navigate to http://localhost:7001/console (replace localhost with the name of your application server host if you aren't opening the browser on the server), and login with the the weblogic credential you provided in the ODEE installation process. b. Once you're logged in, open Services?Data Sources. Select dmkr_admin and click Connection Pool.  c. The end of the URL should match the connection type you chose. If you chose ServiceName, the URL should be: jdbc:oracle:thin:@//<hostname>:1521/<serviceName> and if you chose SID, the URL should be: jdbc:oracle:thin:@//<hostname>:1521/<SIDname> d. An example serviceName is a fully qualified DNS-style name, e.g. "idmaker.us.oracle.com". (It does not need to actually resolve in DNS). An example SID is just a name, e.g. IDMAKER. e. Save the change and repeat for the data source dmkr_asline.  f. You will also need to make the same changes in the ODEE_HOME/documaker/docfactory/config/context/.bindings file - open the file in a text editor, locate the URL lines and make the appropriate change, then save the file.  7. Back in the ODEE_HOME\documaker\j2ee\weblogic\oracle11g\scripts directory, execute create_users_groups.cmd. 8. In the same directory, execute create_users_groups_correspondence_example.cmd. 9. Open a browser and navigate to http://localhost:7001/jpsquery. Replace localhost with the name of your application server host if you aren't running the browser on the application server. If you changed the default port for the AdminServer from 7001, use the port you changed it to. You should see output like this: 10. Start the WebLogic managed servers by opening a command prompt and navigating to MIDDLEWARE_HOME/user_projects/domains/idocumaker_domain/bin/. When you start the servers listed below, you will be prompted to enter the WebLogic credentials to start the server. You can prevent this by providing the credential in the startManagedwebLogic.cmd file for the WLS_USER and WLS_PASS values. Note that the credential will be stored in cleartext. To start the server, type in the command shown. a. Start the JMS Server: ./startManagedWebLogic.cmd jms_server b. Start Dashboard/Documaker Administrator: ./startManagedWebLogic.cmd dmkr_server c. Start Documaker Interactive for Correspondence: ./startManagedWebLogic.cmd idm_server SOA Composites  If you're planning on testing out the approval process components of BPEL that can be used with Documaker Interactive, then use the following steps to deploy the SOA composites. If you're not going to use BPEL, you can skip to the next section.1. Stop the servers listed in the previous section (Step 10) in the reverse order that they were started.2. Run the Domain configuration command: navigate to and execute MIDDLEWARE_HOME/wlserver_10.3/common/bin/config.cmd.3. Select Extend and click next. 4. Select the iDocumaker Domain and click Next. 5. Select the Oracle SOA Suite – 11.1.1.0 (this may automatically select other components which is OK). Click Next. 6. View the Configure JDBC resources screen. You should not make any changes. Click Next. 7. Check both connections and click Test Connections. After successful test, click Next. If the tests fail, something is broken. Go back to configure JDBC resources and check your service name/SID. 8. Check all schemas. Set a password (will be the same for all schemas). Enter the database information (service name, host name, port). Click Next. 9. Connections should test successfully. If not, go back and fix any errors. Click Next. 10. Click Next to pass through Optional Configuration. 11. Click Extend. 12. Click Done. 13. Open a terminal window and navigate to/execute: ODEE_HOME/documaker/j2ee/weblogic/oracle11g/bpel/antbuild.cmd14. Start the WebLogic Servers – AdminServer, jms_server, dmkr_server, idm_server. If you forgot how to do this, see the previous section Step 10. Note: if you previously changed the startManagedWebLogic.cmd script for WLS_USER and WLS_PASS you will need to make those changes again. 15. Start the WebLogic server soa_server1: MIDDLEWARE_HOME/user_projects/domains/idocumaker_domain/bin/startManagedWebLogic.cmd soa_server116. Open a browser to http://localhost:7001/console and login. 17. Navigate to Services?Data Sources and select DMKR_ASLINE. 18. Click the Targets tab. Check soa_server1, then click Save. Repeat for the DMKR_ADMIN data source. 19. Open a command prompt and navigate to ODEE_HOME/j2ee/weblogic/oracle11g/scripts, then execute deploy_soa.cmd. That's it! (As if that wasn't enough?) DOCUMAKER Deploy the sample MRL resources by navigating to/executing ODEE_HOME/documaker/mstrres/dmres/deploysamplemrl.bat. You should see approximately 500 resources deployed into the database. Start the Factory Services. Start?Run?services.msc. Locate the service named "ODDF xxxx" and right-click, select Start. Note that each Assembly Line has a separate Factory setup, including its own Factory service and Docupresentment service. The services are named for the assembly line and the machine on which they are installed (because you could have multiple machines servicing a single assembly line, so this allows for easy scripting to control all the services if you choose to do so. Repeat for the Docupresentment service. Note that each Assembly Line has a separate Docupresentment. Using Windows Explorer, navigate to ODEE_HOME/documaker/mstrres/dmres/input and select one of the XML files, and copy it into ODEE_HOME/documaker/hotdirectory. Note: if you chose a different hot directory during installation, copy the file there instead. Momentarily you should see the XML file disappear! Open browser and navigate to http://localhost:10001/DocumakerDashboard (previous versions 12.0-12.2 use http://localhost:10001/dashboard) and verify that job processed successfully. Note that some transactions may fail if you do not have a properly configured email server, and this is ok. You can set up a simple SMTP server (just search the internet for "SMTP developer" and you'll get several to choose from.  So... that's it? Where are we at this point? You now have a completely functional ODEE installation, from soup to nuts as they say. You can further expand your installation by doing some of the following activities: clustering WebLogic services configuring WebLogic for redundancy configuring Oracle 11g for RAC adding additional Factory servers for redundancy/processing capacity setting up a real MRL (instead of the sample resources) testing Documaker Web Services for job submission and more!  I certainly hope you've enjoyed this and find it useful. If you find yourself running into trouble, visit the Oracle Community for Documaker - there is plenty of activity there and you can ask questions. For more concentrated assistance, you can engage an Oracle consultant who is a subject matter expert to assist you. Feel free to email me [andy (dot) little (at) oracle (dot) com] and I can connect you with the appropriate resource to get started. Best of luck! -Andy 

    Read the article

  • How to configure Visual Studio 2010 code coverage for ASP.NET MVC unit tests

    - by DigiMortal
    I just got Visual Studio 2010 code coverage work with ASP.NET MVC application unit tests. Everything is simple after you have spent some time with forums, blogs and Google. To save your valuable time I wrote this posting to guide you through the process of making code coverage work with ASP.NET MVC application unit tests. After some fighting with Visual Studio I got everything to work as expected. I am still not very sure why users must deal with this mess, but okay – I survived it. Before you start configuring Visual Studio I expect your solution meets the following needs: there are at least one library that will be tested, there is at least on library that contains tests to be run, there are some classes and some tests for them, and, of course, you are using version of Visual Studio 2010 that supports tests (I have Visual Studio 2010 Ultimate). Now open the following screenshot to separate windows and follow the steps given below. Visual Studio 2010 Test Settings window. Click on image to see it at original size.  Double click on Local.testsettings under Solution Items. Test settings window will be opened. Select “Data and Diagnostics” from left pane. Mark checkboxes “ASP.NET Profiler” and “Code Coverage”. Move cursor to “Code Coverage” line and press Configure button or make double click on line. Assemblies selection window will be opened. Mark checkboxes that are located before assemblies about what you want code coverage reports and apply settings. Save your project and close Visual Studio. Run Visual Studio as Administrator and run tests. NB! Select Test => Run => Tests in Current Context from menu. When tests are run you can open code coverage results by selecting Test => Windows => Code Coverage Results from menu. Here you can see my example test results. Visual Studio 2010 Test Results window. All my tests passed this time. :) Click on image to see it at original size.  And here are the code coverage results. Visual Studio 2101 Code Coverage Results. I need a lot more tests for sure. Click on image to see it at original size.  As you can see everything was pretty simple. But it took me sometime to figure out how to get everything work as expected. Problems? You may face some problems when making code coverage work. Here is my short list of possible problems. Make sure you have all assemblies available for code coverage. In some cases it needs more libraries to be referenced as you currently have. By example, I had to add some more Enterprise Library assemblies to my project. You can use EventViewer to discover errors that where given during testing. Make sure you selected all testable assemblies from Code Coverage settings like shown above. Otherwise you may get empty results. Tests with code coverage are slower because we need ASP.NET profiler. If your machine slows down then try to free more resources.

    Read the article

  • Make Your PC Look Like Windows Phone 7

    - by Matthew Guay
    Windows Phone 7 offers a unique and exciting UI that displays lots of information efficiently on the screen.  And with a simple Rainmeter theme, you can have the same UI and content directly on your Windows 7 desktop. Turn your Desktop into a Windows Phone 7 lookalike To give your Windows 7 desktop a Windows Phone 7 makeover, first you need to have the free Rainmeter application installed.  If you do not have it installed, download it from the link below and run the setup.  Accept the license agreement, and install it with the default settings. By default Rainmeter will automatically run when you start your computer.  If you do not want this, you can uncheck the box during the setup. Now, download the Omnimo UI theme for Rainmeter (link below).  You will need to unzip the folder first. This theme uses the Segoe UI and the Segoe UI Light font, so Windows Vista users need to install the segoeuil.ttf font first, and XP users need to install both the segoeui.ttf and the segoeuil.ttf font first.  Copy the appropriate fonts to C:\Windows\Fonts, or in Vista double-click on the font and select Install. Now, run the Rainmeter theme setup.  Double-click on the Rainstaller.exe in the Omnimo folder. Click Express install to add the theme and skin to Rainmeter. Click Finish, and by default Rainmeter will open with your new theme. When the new theme opens the first time, you will be asked to read the readme, or simply go to the gallery. When you open the gallery, you can choose from a wide variety of tiles and gadgets to place on your desktop.  You can also choose a different color scheme for your tiles. Once you’re done, click the X in the top right hand corner to close the Gallery.  Welcome to your Windows Phone 7 desktop!  Many of the gadgets are dynamic, and you can change the settings for most of them.  The only thing missing is the transition animations that Windows Phone 7 shows when you launch an application. To make it look even more like Windows Phone 7, you can change your background to black.  This makes the desktop theme really dramatic. And, if you want to add gadgets or change the color scheme, simply click on the + logo on the top. Windows Phone 7 Desktop Wallpapers If you’d prefer to simply change your background, My Microsoft Life has several very nice Windows Phone 7 wallpapers available for free.  Click the link below to download these and other Microsoft-centric wallpapers. If you can’t wait to get the new Windows phone 7, this is a great way to start experiencing the beauty of the phone UI on your desktop. Links Download Rainmeter Download the Omnimo UI Rainmeter theme Download Windows Phone 7 inspired wallpapers Similar Articles Productive Geek Tips Try out Windows Phone 7 on your PC todayTest All Features of Windows Phone 7 On Your PCHow-To Geek on Lifehacker: How to Make Windows Vista Less AnnoyingCreate a Shortcut or Hotkey to Mute the System Volume in WindowsMake Ubuntu Automatically Save Changes to Your Session TouchFreeze Alternative in AutoHotkey The Icy Undertow Desktop Windows Home Server – Backup to LAN The Clear & Clean Desktop Use This Bookmarklet to Easily Get Albums Use AutoHotkey to Assign a Hotkey to a Specific Window Latest Software Reviews Tinyhacker Random Tips DVDFab 6 Revo Uninstaller Pro Registry Mechanic 9 for Windows PC Tools Internet Security Suite 2010 Norwegian Life If Web Browsers Were Modes of Transportation Google Translate (for animals) Roadkill’s Scan Port scans for open ports Out of 100 Tweeters Out of band Security Update for Internet Explorer

    Read the article

  • IntelliTrace As a Learning Tool for MVC2 in a VS2010 Project

    - by Sam Abraham
    IntelliTrace is a new feature in Visual Studio 2010 Ultimate Edition. I see this valuable tool as a “Program Execution Recorder” that captures information about events and calls taking place as soon as we hit the VS2010 play (Start Debugging) button or the F5 key. Many online resources already discuss IntelliTrace and the benefit it brings to both developers and testers alike so I see no value of just repeating this information.  In this brief blog entry, I would like to share with you how I will be using IntelliTrace in my upcoming talk at the Ft Lauderdale ArcSig .Net User Group Meeting on April 20th 2010 (check http://www.fladotnet.com for more information), as a learning tool to demonstrate the internals of the lifecycle of an MVC2 application.  I will also be providing some helpful links that cover IntelliTrace in more detail at the end of my article for reference. IntelliTrace is setup by default to only capture execution events. Microsoft did such a great job on optimizing its recording process that I haven’t even felt the slightest performance hit with IntelliTrace running as I was debugging my solutions and projects.  For my purposes here however, I needed to capture more information beyond execution events, so I turned on the option for capturing calls in addition to events as shown in Figures 1 and 2. Changing capture options will require us to stop our debugging session and start over for the new settings to take place. Figure 1 – Access IntelliTrace options via the Tools->Options menu items Figure 2 – Change IntelliTrace Options to capture call information as well as events Notice the warning with regards to potentially degrading performance when selecting to capture call information in addition to the default events-only setting. I have found this warning to be sure true. My subsequent tests showed slowness in page load times compared to rendering those same exact pages with the “event-only” option selected. Execution recording is auto-started along with the new debugging session of our project. At this point, we can simply interact with the application and continue executing normally until we decide to “playback” the code we have executed so far.  For code replay, first step is to “break” the current execution as show in Figure 3.   Figure 3 – Break to replay recording A few tries later, I found a good process to quickly find and demonstrate the MVC2 page lifecycle. First-off, we start with the event view as shown in Figure 4 until we find an interesting event that needs further studying.  Figure 4 – Going through IntelliTrace’s events and picking as specific entry of interest We now can, for instance, study how the highlighted HTTP GET request is being handled, by clicking on the “Calls View” for that particular event. Notice that IntelliTrace shows us all calls that took place in servicing that GET request. Double clicking on any call takes us to a more granular view of the call stack within that clicked call, up until getting to a specific line of code where we can do a line-by-line replay of the execution from that point onwards using F10 or F11 just like our typical good old VS2008 debugging helped us accomplish. Figure 5 – switching to call view on an event of interest Figure 6 – Double clicking on call shows a more granular view of the call stack. In conclusion, the introduction of IntelliTrace as a new addition to the VS developers’ tool arsenal enhances development and debugging experience and effectively tackles the “no-repro” problem. It will also hopefully enhance my audience’s experience listening to me speaking about  an MVC2 page lifecycle which I can now easily visually demonstrate, thereby improving the probability of keeping everybody awake a little longer. IntelliTrace References: http://msdn.microsoft.com/en-us/magazine/ee336126.aspx http://msdn.microsoft.com/en-us/library/dd264944(VS.100).aspx

    Read the article

  • Manage Your WordPress Blog Comments from Your Windows Desktop

    - by Matthew Guay
    Are you never more than a few steps away from your PC and want to keep up with comments on your blog?  Then here’s how you can stay on top of your WordPress comments right from your desktop. Wp-comment-notifier is a small free app for Windows that lets you easily view, approve, reply to, and delete comments from your WordPress blog.  Whether you have a free WordPress.com blog or are running WordPress on your own server, this tool can keep you connected to your comments.  Unfortunately it only lets you manage comments at one blog, so if manage multiple WordPress-powered sites you may find this a downside.  Otherwise, it works great and helps you stay on top of the conversation at your blog. Get notified with wp-comment-notifier Download the wp-comment-notifier (link below) and install as usual. Run it once it’s installed.  Enter your blog address, username, and password when prompted. Wp-comment-notifier will automatically setup your account and download recent comments. Finally, enter your blog’s name, and click Finish. Review Comments with wp-comment-notifier You can now review your comments directly by double-clicking the new WordPress icon in your system tray.  The window has 3 tabs…comments, pending, and spam.  Select a comment to reply, edit, spam, or delete it directly from your desktop. If you select Edit, then you can edit the HTML of the comment (including links) directly from within the notifier. You can approve or permanently delete any spam messages that are caught by your blog’s spam filter. Whenever new comments come in, you’ll see a tray popup letting you know how many comments are waiting to be approved or are in the spam folder.  Click the popup to open the editor. Now, you can directly approve that pending comment without going to your WordPress admin page.  When you’re done, just press Enter on your Keyboard to post the reply. Or, if you want to reply to the comment, click the reply link and enter your comment in the entry box at the bottom. If you ever want to double-check if there’s any new comments, just right-click on the tray icon and select refresh. Finally, you can change the settings from the Configuration link in the tray button or by clicking the gear button on the bottom of the review window.  You can change how often it checks for new comments, not to start the notifier at system startup, and edit your account information. Conclusion Whether you’re managing your personal blog or administer a site with millions of hits per day, staying on top of the conversation is one of the best ways to build and maintain your audience.  With wp-comment-notifier, you can be sure that you’re always in control of your blogs comments.  This app is especially useful if you review all comments before allowing them to be published. Download wp-comment-notifier Similar Articles Productive Geek Tips How-To Geek SoftwareHow-To Geek Software: WordPress Comment Moderation NotifierSave Time Commenting with Pre-Fill Comments Greasemonkey ScriptAdd Social Bookmarking (Digg This!) Links to your Wordpress BlogTools to Help Post Content On Your WordPress Blog TouchFreeze Alternative in AutoHotkey The Icy Undertow Desktop Windows Home Server – Backup to LAN The Clear & Clean Desktop Use This Bookmarklet to Easily Get Albums Use AutoHotkey to Assign a Hotkey to a Specific Window Latest Software Reviews Tinyhacker Random Tips VMware Workstation 7 Acronis Online Backup DVDFab 6 Revo Uninstaller Pro Error Goblin Explains Windows Error Codes Twelve must-have Google Chrome plugins Cool Looking Skins for Windows Media Player 12 Move the Mouse Pointer With Your Face Movement Using eViacam Boot Windows Faster With Boot Performance Diagnostics Create Ringtones For Your Android Phone With RingDroid

    Read the article

  • Where Next for Google Translate? And What of Information Quality?

    - by ultan o'broin
    Fascinating article in the UK Guardian newspaper called Can Google break the computer language barrier? In it, Andreas Zollman, who works on Google Translate, comments that the quality of Google Translate's output relative to the amount of data required to create that output is clearly now falling foul of the law of diminishing returns. He says: "Each doubling of the amount of translated data input led to about a 0.5% improvement in the quality of the output," he suggests, but the doublings are not infinite. "We are now at this limit where there isn't that much more data in the world that we can use," he admits. "So now it is much more important again to add on different approaches and rules-based models." The Translation Guy has a further discussion on this, called Google Translate is Finished. He says: "And there aren't that many doublings left, if any. I can't say how much text Google has assimilated into their machine translation databases, but it's been reported that they have scanned about 11% of all printed content ever published. So double that, and double it again, and once more, shoveling all that into the translation hopper, and pretty soon you get the sum of all human knowledge, which means a whopping 1.5% improvement in the quality of the engines when everything has been analyzed. That's what we've got to look forward to, at best, since Google spiders regularly surf the Web, which in its vastness dwarfs all previously published content. So to all intents and purposes, the statistical machine translation tools of Google are done. Outstanding job, Googlers. Thanks." Surprisingly, all this analysis hasn't raised that much comment from the fans of machine translation, or its detractors either for that matter. Perhaps, it's the season of goodwill? What is clear to me, however, of course is that Google Translate isn't really finished (in any sense of the word). I am sure Google will investigate and come up with new rule-based translation models to enhance what they have already and that will also scale effectively where others didn't. So too, will they harness human input, which really is the way to go to train MT in the quality direction. But that aside, what does it say about the quality of the data that is being used for statistical machine translation in the first place? From the Guardian article it's clear that a huge humanly translated corpus drove the gains for Google Translate and now what's left is the dregs of badly translated and poorly created source materials that just can't deliver quality translations. There's a message about information quality there, surely. In the enterprise applications space, where we have some control over content this whole debate reinforces the relationship between information quality at source and translation efficiency, regardless of the technology used to do the translation. But as more automation comes to the fore, that information quality is even more critical if you want anything approaching a scalable solution. This is important for user experience professionals. Issues like user generated content translation, multilingual personalization, and scalable language quality are central to a superior global UX; it's a competitive issue we cannot ignore.

    Read the article

  • Read Mobi eBooks on Kindle for PC

    - by Matthew Guay
    Do you use your PC as a eBook reader?  Kindle for PC makes it easy to read thousands of books from the Kindle Store on your computer. What you may not know is that is also works with .mobi format too, so you can increase the amount of books you can read. Amazon has jumpstarted the eBook market with their popular Kindle device.  Last fall Amazon unveiled Kindle for PC, and we reviewed how you can Read Kindle Books On Your Computer with Kindle for PC.  Whether or not you own a Kindle or other eBook reader, this is a great way to take advantage of the thousands of eBooks available from the Kindle Store today. It supports azw, prc, and tpz format, which are sold from the Kindle store, but it also supports Mobipocket (.mobi) eBooks that are not DRM protected.  Here’s how you can add them to Kindle for PC so you can easily read them on your PC Getting Started: First, make sure you have Kindle for PC (link below) installed on your computer. Sign in with your Amazon account when you first run it. Kindle for PC lets you easily read eBooks downloaded from the Kindle Store, but it doesn’t have any way to add other eBooks directly from the program. To add eBooks, you can sometimes download and double-click on the books, and they will open in Kindle for PC and be automatically added to the library.  However, this does not always seem to work. So instead, browse to your Documents folder (simply click on the Documents link on your Start menu), and double-click on the My Kindle Content folder. This folder contains all the Kindle books you have downloaded.  If you have other eBooks you would like to add to Kindle for PC, simply drag-and-drop or copy and paste them into this folder.  Here we have a .mobi formatted book downloaded from the Gutenberg Project that we’re dragging into the folder. Now, close and reopen Kindle for PC.  It should now show your new eBook right beside the eBooks you have downloaded from the Kindle Store. These eBooks work just the same as the ones downloaded from the Kindle store, and you can change font size and add bookmarks just as with other eBooks. The eBooks downloaded this way may show up with either a Amazon logo or a mobile device icon.  You should only see the mobile device icon on .mobi files formatted for mobile devices; other ones should show up with the Amazon logo.  In this screen, Pilgrim’s Progress is a standard .mobi book, The Adventures of Sherlock Holmes is a mobipocket book, and the others are downloaded from the Kindle Store. Conclusion This is a great way to read eBooks from across the internet on Kindle for PC.  Wikipedia’s Kindle page has a list of websites that offer eBooks formatted for the Kindle, so be sure to check it out for more books. Links Download Kindle for PC List of websites that offer eBooks that will work on Kindle – via Wikipedia Similar Articles Productive Geek Tips Read Kindle Books On Your Computer with Kindle for PCInstall Adobe PDF Reader on Ubuntu EdgyHow to Access your Box.Net Account from Ubuntu the Easy Way TouchFreeze Alternative in AutoHotkey The Icy Undertow Desktop Windows Home Server – Backup to LAN The Clear & Clean Desktop Use This Bookmarklet to Easily Get Albums Use AutoHotkey to Assign a Hotkey to a Specific Window Latest Software Reviews Tinyhacker Random Tips Revo Uninstaller Pro Registry Mechanic 9 for Windows PC Tools Internet Security Suite 2010 PCmover Professional New Stinger from McAfee Helps Remove ‘FakeAlert’ Threats Google Apps Marketplace: Tools & Services For Google Apps Users Get News Quick and Precise With Newser Scan for Viruses in Ubuntu using ClamAV Replace Your Windows Task Manager With System Explorer Create Talking Photos using Fotobabble

    Read the article

  • Use Any Folder For Your Ubuntu Desktop (Even a Dropbox Folder)

    - by Trevor Bekolay
    By default, Ubuntu creates a folder called Desktop in your home directory that gets displayed on your desktop. What if you want to use something else, like your Dropbox folder? Here we look at how to use any folder for your desktop. Not only can you change your desktop folder, you can change the location of any other folder Ubuntu creates for you in your home folder, like Documents or Music – and this works in any Linux distribution using the Gnome desktop manager. In this example, we’re going to change desktop to show our Dropbox folder. Open your home folder in a File Browser by clicking on Places > Home Folder. In the Home Folder, open the .config folder. By default, .config is hidden, so you may have to show hidden folders (temporarily) by clicking on View > Show Hidden Files. Then open the .config folder by double-clicking on it. Now open the user-dirs.dirs file… If double-clicking on it does not open it in a text editor, right-click on it and choose Open with Other Application… and find a text editor like Gedit. Change the entry associated with XDG_DESKTOP_DIR to the folder you want to be shown as your desktop. In our case, this is $HOME/Dropbox. Note: The “~” shortcut for the home directory won’t work in this file (use $HOME for that), but an absolute path (i.e. a path starting with “/”) will work. Feel free to change the locations of the other folders as well. Save and close user-dirs.dirs. At this point you can either log off and then log back on to get your desktop back, or open a terminal window Applications > Accessories > Terminal and enter: killall nautilus Nautilus (the file manager in Gnome) will restart itself and display your newly chosen folder as the desktop! This is a cool trick to use any folder for your Ubuntu desktop. What did you use as your desktop folder? Let us know in the comments! Similar Articles Productive Geek Tips Sync Your Pidgin Profile Across Multiple PCs with DropboxAdd "My Dropbox" to Your Windows 7 Start MenuCreate a Keyboard Shortcut to Access Hidden Desktop Icons and FilesAdd "My Computer" to Your Windows 7 / Vista TaskbarCheck your Disk Usage on Ubuntu with Disk Usage Analyzer TouchFreeze Alternative in AutoHotkey The Icy Undertow Desktop Windows Home Server – Backup to LAN The Clear & Clean Desktop Use This Bookmarklet to Easily Get Albums Use AutoHotkey to Assign a Hotkey to a Specific Window Latest Software Reviews Tinyhacker Random Tips VMware Workstation 7 Acronis Online Backup DVDFab 6 Revo Uninstaller Pro Use Flixtime To Create Video Slideshows Creating a Password Reset Disk in Windows Bypass Waiting Time On Customer Service Calls With Lucyphone MELTUP – "The Beginning Of US Currency Crisis And Hyperinflation" Enable or Disable the Task Manager Using TaskMgrED Explorer++ is a Worthy Windows Explorer Alternative

    Read the article

  • How do I implement a quaternion based camera?

    - by kudor gyozo
    I looked at several tutorials about this and when I thought I understood I tried to implement a quaternion based camera. The problem is it doesn't work correctly, after rotating for approx. 10 degrees it jumps back to -10 degrees. I have no idea what's wrong. I'm using openTK and it already has a quaternion class. I'm a noob at opengl, I'm doing this just for fun, and don't really understand quaternions, so probably I'm doing something stupid here. Here is some code: (Actually almost all the code except the methods that load and draw a vbo (it is taken from an OpenTK sample that demonstrates vbo-s)) I load a cube into a vbo and initialize the quaternion for the camera protected override void OnLoad(EventArgs e) { base.OnLoad(e); cameraPos = new Vector3(0, 0, 7); cameraRot = Quaternion.FromAxisAngle(new Vector3(0,0,-1), 0); GL.ClearColor(System.Drawing.Color.MidnightBlue); GL.Enable(EnableCap.DepthTest); vbo = LoadVBO(CubeVertices, CubeElements); } I load a perspective projection here. This is loaded at the beginning and every time I resize the window. protected override void OnResize(EventArgs e) { base.OnResize(e); GL.Viewport(0, 0, Width, Height); float aspect_ratio = Width / (float)Height; Matrix4 perpective = Matrix4.CreatePerspectiveFieldOfView(MathHelper.PiOver4, aspect_ratio, 1, 64); GL.MatrixMode(MatrixMode.Projection); GL.LoadMatrix(ref perpective); } Here I get the last rotation value and create a new quaternion that represents only the last rotation and multiply it with the camera quaternion. After this I transform this into axis-angle so that opengl can use it. (This is how I understood it from several online quaternion tutorials) protected override void OnRenderFrame(FrameEventArgs e) { base.OnRenderFrame(e); GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); double speed = 1; double rx = 0, ry = 0; if (Keyboard[Key.A]) { ry = -speed * e.Time; } if (Keyboard[Key.D]) { ry = +speed * e.Time; } if (Keyboard[Key.W]) { rx = +speed * e.Time; } if (Keyboard[Key.S]) { rx = -speed * e.Time; } Quaternion tmpQuat = Quaternion.FromAxisAngle(new Vector3(0,1,0), (float)ry); cameraRot = tmpQuat * cameraRot; cameraRot.Normalize(); GL.MatrixMode(MatrixMode.Modelview); GL.LoadIdentity(); Vector3 axis; float angle; cameraRot.ToAxisAngle(out axis, out angle); GL.Rotate(angle, axis); GL.Translate(-cameraPos); Draw(vbo); SwapBuffers(); } Here are 2 images to explain better: I rotate a while and from this: it jumps into this Any help is appreciated. Update1: I add these to a streamwriter that writes into a file: sw.WriteLine("camerarot: X:{0} Y:{1} Z:{2} W:{3} L:{4}", cameraRot.X, cameraRot.Y, cameraRot.Z, cameraRot.W, cameraRot.Length); sw.WriteLine("ry: {0}", ry); The log is available here: http://www.pasteall.org/26133/text. At line 770 the cube jumps from right to left, when camerarot.Y changes signs. I don't know if this is normal. Update2 Here is the complete project.

    Read the article

< Previous Page | 87 88 89 90 91 92 93 94 95 96 97 98  | Next Page >