Search Results

Search found 3437 results on 138 pages for 'append'.

Page 15/138 | < Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >

  • Is it possible to create the following XML using Xdocument and append the relevant protion in subseq

    - by Newbie
    <?xml version='1.0' encoding='UTF-8'?> <StockMarket> <StockDate Day = "02" Month="06" Year="2010"> <Stock> <Symbol>ABC</Symbol> <Amount>110.45</Amount> </Stock> <Stock> <Symbol>XYZ</Symbol> <Amount>366.25</Amount> </Stock> </StockDate> <StockDate Day = "03" Month="06" Year="2010"> <Stock> <Symbol>ABC</Symbol> <Amount>110.35</Amount> </Stock> <Stock> <Symbol>XYZ</Symbol> <Amount>369.70</Amount> </Stock> </StockDate> </StockMarket> My approach so far is XDocument doc = new XDocument( new XElement("StockMarket", new XElement("StockDate", new XAttribute("Day", "02"),new XAttribute("Month","06"),new XAttribute("Year","2010")), new XElement("Stock", new XElement("Symbol", "ABC"), new XElement("Amount", "110.45")) ) ); Since I am new to Linq to XML, I am presently struggling a lot and henceforth seeking for help. What I need is to generate the above XML programatically(I mean to say that some kind of looping...) The values will be passed from textbox and hence will be filled at runtime. At present the one which I have done is a kind of static one. This entire stuff has to be done at runtime. One more problem that I am facing is at the time of saving the record for the second time. Suppose first time I executed the code and saved it(Using the program I have done). Next time when I will try to save then only <StockDate Day = "xx" Month="xx" Year="xxxx"> <Stock> <Symbol>ABC</Symbol> <Amount>110.45</Amount> </Stock> <Stock> <Symbol>XYZ</Symbol> <Amount>366.25</Amount> </Stock> </StockDate> should get save(or better appended) and not <StockMarket> .... </StockMarket>.. Because that will be created only at the first time when the XML will be generated or created. I hope I am able to convey my problem properly. If you people is having difficulty in understanding my situation, kindly let me know. Using C#3.0 . Thanks

    Read the article

  • Why does Google append while(1); in front of their JSON responses?

    - by Andrew Koester
    This is something I've always been curious about, is exactly why Google appends while(1); in front of their (private) JSON responses. For example, here's a response while turning a calendar on and off in Google Calendar: while(1);[['u',[['smsSentFlag','false'],['hideInvitations','false'],['remindOnRespondedEventsOnly','true'],['hideInvitations_remindOnRespondedEventsOnly','false_true'],['Calendar ID stripped for privacy','false'],['smsVerifiedFlag','true']]]] I would assume this is to prevent people from doing an eval() on it, but all you'd really have to do is replace the while and then you'd be set. I would assume eval prevention is to make sure people write safe JSON parsing code. I've seen this used in a couple other places, too, but a lot more so with Google (Mail, Calendar, Contacts, etc.) Strangely enough, Google Docs starts with &&&START&&& instead, and Google Contacts seems to start with while(1); &&&START&&&. Does anyone know what's going on here?

    Read the article

  • How can I hit my database with an AJAX call using javascript?

    - by tmedge
    I am pretty new at this stuff, so bear with me. I am using ASP.NET MVC. I have created an overlay to cover the page when someone clicks a button corresponding to a certain database entry. Because of this, ALL of my code for this functionality is in a .js file contained within my project. What I need to do is pull the info corresponding to my entry from the database itself using an AJAX call, and place that into my textboxes. Then, after the end-user has made the desired changes, I need to update that entry's values to match the input. I've been surfing the web for a while, and have failed to find an example that fits my needs effectively. Here is my code in my javascript file thus far: function editOverlay(picId) { //pull up an overlay $('body').append('<div class="overlay" />'); var $overlayClass = $('.overlay'); $overlayClass.append('<div class="dataModal" />'); var $data = $('.dataModal'); overlaySetup($overlayClass, $data); //set up form $data.append('<h1>Edit Picture</h1><br /><br />'); $data.append('Picture name: &nbsp;'); $data.append('<input class="picName" /> <br /><br /><br />'); $data.append('Relative url: &nbsp;'); $data.append('<input class="picRelURL" /> <br /><br /><br />'); $data.append('Description: &nbsp;'); $data.append('<textarea class="picDescription" /> <br /><br /><br />'); var $nameBox = $('.picName'); var $urlBox = $('.picRelURL'); var $descBox = $('.picDescription'); var pic = null; //this is where I need to pull the actual object from the db //var imgList = for (var temp in imgList) { if (temp.Id == picId) { pic= temp; } } /* $nameBox.attr('value', pic.Name); $urlBox.attr('value', pic.RelativeURL); $descBox.attr('value', pic.Description); */ //close buttons $data.append('<input type="button" value="Save Changes" class="saveButton" />'); $data.append('<input type="button" value="Cancel" class="cancelButton" />'); $('.saveButton').click(function() { /* pic.Name = $nameBox.attr('value'); pic.RelativeURL = $urlBox.attr('value'); pic.Description = $descBox.attr('value'); */ //make a call to my Save() method in my repository CloseOverlay(); }); $('.cancelButton').click(function() { CloseOverlay(); }); } The stuff I have commented out is what I need to accomplish and/or is not available until prior issues are resolved. Any and all advice is appreciated! Remember, I am VERY new to this stuff (two weeks, to be exact) and will probably need highly explicit instructions. BTW: overlaySetup() and CloseOverlay() are functions I have living someplace else. Thanks!

    Read the article

  • Problem with ArrayList

    - by Houssem
    Hello, I'm reading an xml file from resources, that file contains a list of travel agencies location and adresses and i'm trying to put this list after parsing in an arraylist to use it with maps. So each time I use agencies.add(agency) it adds it to the array but also changes all previous items with the new value. Here's my code if someone can help or explain : public class Main extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView myXmlContent = (TextView)findViewById(R.id.my_xml); String stringXmlContent; try { stringXmlContent = getEventsFromAnXML(this); myXmlContent.setText(stringXmlContent); } catch (XmlPullParserException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } boolean na=false; List<Agency> agencies = new ArrayList(); Agency agency=new Agency(); int i=0; private String getEventsFromAnXML(Activity activity) throws XmlPullParserException, IOException { StringBuffer stringBuffer = new StringBuffer(); Resources res = activity.getResources(); XmlResourceParser xpp = res.getXml(R.xml.hotels); xpp.next(); int eventType = xpp.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if(eventType == XmlPullParser.START_DOCUMENT) { stringBuffer.append("--- Start XML ---"); } else if(eventType == XmlPullParser.START_TAG) { if (xpp.getName().equals("DataBase")){ agency.ResetTsp(); String name=xpp.getAttributeValue(null, "name"); agency.setTspTitle(name); na=true; stringBuffer.append("\nAgence : "+ name); } if (xpp.getName().equals("Title")){ xpp.next(); agency.setTitle(xpp.getText()); stringBuffer.append("\nFiliale: "+xpp.getText()); xpp.nextTag(); } if (xpp.getName().equals("Address")){ xpp.next(); agency.setAddress(xpp.getText()); stringBuffer.append("\nAdresse: "+xpp.getText()); xpp.nextTag(); } if (xpp.getName().equals("Phone") && na==true){ xpp.next(); agency.setTspPhone(xpp.getText()); stringBuffer.append("\nPhone: "+xpp.getText()); xpp.nextTag(); }else{ if (xpp.getName().equals("Phone") && na==false){ xpp.next(); agency.setPhone(xpp.getText()); stringBuffer.append("\nPhone: "+xpp.getText()); xpp.nextTag(); } } if (xpp.getName().equals("Fax")){ xpp.next(); agency.setFax(xpp.getText()); stringBuffer.append("\nFax: "+xpp.getText()); xpp.nextTag(); } if (xpp.getName().equals("e-Mail")){ xpp.next(); agency.setMail(xpp.getText()); stringBuffer.append("\ne-Mail: "+xpp.getText()); xpp.nextTag(); } if (xpp.getName().equals("Latitude")){ xpp.next(); agency.setLatitude(Double.parseDouble(xpp.getText())); stringBuffer.append("\nLatitude: "+xpp.getText()); xpp.nextTag(); } if (xpp.getName().equals("Longitude")){ xpp.next(); agency.setLongitude(Double.parseDouble(xpp.getText())); stringBuffer.append("\nLongitude: "+xpp.getText()); } } else if(eventType == XmlPullParser.END_TAG) { if (xpp.getName().equals("DataBase") || xpp.getName().equals("Agency")){ agencies.add(i,agency); i=i+1; Agency agency = new Agency(); } } eventType = xpp.next(); } stringBuffer.append("\n--- End XML ---"); return stringBuffer.toString(); } } thank you

    Read the article

  • Append Results from two queries and output as a single table.

    - by tHeSiD
    I have two queries that I have to run, I cannon join them But their resultant tables have the same structrure. For example I have select * from products where producttype=magazine select * from products where producttype = book I have to combine the result of these two queries, and then output it as one single result. I have to do this inside a stored procedure. PS These are just examples I provided, i have a complex table structure. The main thing is I cannot join them.

    Read the article

  • How to combine two arrays of same length to one array with two fields (not append/merge)

    - by Raj
    Say, I have an array with months $months = array('Jan', 'Feb', 'Mar'...'Dec'); And another, with days (say, for year 2010) $mdays = array(31, 28, 31...31); I want to merge/combine these two arrays, into an array like this: $monthdetails[0] = ('month' => 'Jan', 'days' => 31) $monthdetails[1] = ('month' => 'Feb', 'days' => 28) ... $monthdetails[11] = ('month' => 'Dec', 'days' => 31) I can loop through both the arrays and fill the $monthdetails. I want to know whether there are any functions/easier way for achieving the same result. Thanks! Raj

    Read the article

  • Loop through a set of HTML files and append text at top and bottom of each file

    - by NJTechGuy
    For instance, I have an HTML file like this : a.htm <body> Hello world! </body> I want : a.htm <html> <LINK href='style.css' rel=stylesheet type='text/css'> <body> Hello world! </body> </html> The code I have so far is : #!/bin/sh for i in `ls *.htm` do @echo off echo ***New top line*** > temp.txt type i >> temp.txt echo ***New bottom line*** >> temp.txt move /y temp.txt i done Errors : abc@bunny:~/fileAppendText$ ./loopAllFilesTest.sh ./loopAllFilesTest.sh: line 5: @echo: command not found ./loopAllFilesTest.sh: line 7: type: i: not found ./loopAllFilesTest.sh: line 9: move: command not found ./loopAllFilesTest.sh: line 5: @echo: command not found ./loopAllFilesTest.sh: line 7: type: i: not found ./loopAllFilesTest.sh: line 9: move: command not found ./loopAllFilesTest.sh: line 5: @echo: command not found ./loopAllFilesTest.sh: line 7: type: i: not found ./loopAllFilesTest.sh: line 9: move: command not found Please help. Thanks!

    Read the article

  • Vi/Vim: How to pipe visually selected text to a UNIX command and append output to current file

    - by drsnyder
    Using Vim, I'm trying to pipe visually selected text to a UNIX command and have the output appended to the end of the current file. For example, say we have a SQL command such as: SELECT * FROM mytable; I want to do something like the following: V # select text :'<,'!mysql -uuser -ppass mydb But instead of having the output overwrite the currently selected text, I would like to have the output appended to the end of the file. You probably see where this is going. I'm working on using VIM as a simple SQL editor. That way, I don't have to leave VIM to edit, tweak, test SQL code. Thanks!

    Read the article

  • How to append to all urls in a string?

    - by Echo
    How should I go about appending to the end of all urls in string of html that is about to be sent out as as email? I want to add the google analytics campaign tracking to it like this: ?utm_source=email&utm_medium=email&utm_campaign=product_notify 99% of the pages will not end in '.html' and some urls might already have things like ?sr=1 at the end of them.

    Read the article

  • Append an onClick event to an anchor tag using jquery?

    - by M.Woodard
    I am trying to add an onClick event to an anchor tag ... Previously i had ... <a href="somlink.html" onClick="pageTracker._link(this.href); return false;"> But i am trying to avoid the inline onClick event because it interferes with another script.. So using jQuery i am trying the following code ... <script> $(document).ready(function() { $('a#tracked').attr('onClick').click(function() {window.onbeforeunload = null; pageTracker._link(this.href); return false; }); }); </script> with the html like so <a id="tracked" href="something.html"> So my question is should this be working, and if not what would be the best solution?

    Read the article

  • How can I combine sequential expression trees into a fast method?

    - by chillitom
    Suppose I have the following expressions: Expression<Action<T, StringBuilder>> expr1 = (t, sb) => sb.Append(t.Name); Expression<Action<T, StringBuilder>> expr2 = (t, sb) => sb.Append(", "); Expression<Action<T, StringBuilder>> expr3 = (t, sb) => sb.Append(t.Description); I'd like to be able to compile these into a method/delegate equivalent to the following: void Method(T t, StringBuilder sb) { sb.Append(t.Name); sb.Append(", "); sb.Append(t.Description); } What is the best way to approach this? I'd like it to perform well, ideally with performance equivalent to the above method.

    Read the article

  • C# StringBuilder related question

    - by Sef
    Hello, I have written a program for a stack. For this i needed a StringBuilder to be able to show me what was in the stack else i would get the class name instead of the actual values inside. My question is there any other way except for a StringBuilder for such kind of problem? Also in what other kind of cases does this kind of problem happen? Also the way i have written the StringBuilder felt very awkward when i needed several things on 1 line. public override string ToString() { StringBuilder builder = new StringBuilder(); foreach (int value in tabel) { builder.Append(value); builder.Append(" "); } if (tabel.Length == tabel.Length) // this is a bit messy, since I couldn't append after the rest above { builder.Append("(top:"); builder.Append(top); builder.Append(")"); } return builder.ToString(); }/*ToString*/ Regards.

    Read the article

  • StringBuilder related question

    - by Sef
    I have written a program for a stack. (http://stackoverflow.com/questions/2617367?tab=votes#tab-top) For this i needed a StringBuilder to be able to show me what was in the stack else i would get the class name instead of the actual values inside. My question is there any other way except for a StringBuilder for such kind of problem? Also in what other kind of cases does this kind of problem happen? Also the way i have written the StringBuilder felt very awkward when i needed several things on 1 line. public override string ToString() { StringBuilder builder = new StringBuilder(); foreach (int value in tabel) { builder.Append(value); builder.Append(" "); } if (tabel.Length == tabel.Length) // this is a bit messy, since I couldn't append after the rest above { builder.Append("(top:"); builder.Append(top); builder.Append(")"); } return builder.ToString(); }/*ToString*/

    Read the article

  • Which is better: string html generation or jquery DOM element creation?

    - by Ed Woodcock
    Ok, I'm rewriting some vanilla JS functions in my current project, and I'm at a point where there's a lot of HTML being generated for tooltips etc. My question is, is it better/preferred to do this: var html = '<div><span>Some More Stuff</span></div>'; if (someCondition) { html += '<div>Some Conditional Content</div>'; } $('#parent').append(html); OR var html = $('<div/>').append($('<span/>').append('Some More Stuff')); if (someCondition) { html.append($('<div/>').append('Some conditionalContent'); } $('#parent').append(html); ?

    Read the article

  • Display radio buttons in prolog xpce

    - by Ben03
    I created a menu with Radio Buttons in XPCE prolog, but my radio buttons are showing on the same line, and I want to have each one on a separate line. My code is the following: new(D, dialog('title')), send(D, size, size(500,500)), send(D, append, new(Op, menu(options, marked))), send(Op, append, option1), send(Op, append, option2), send(Op, append, option3), send(Op, size, size(300,300)), send(D, display, Op, point(100, 40)), send(D, append(new(B1,button(ok, message(D, return, Op?selection))))), send(D, display, B1, point(100, 100)), send(D, append(button(cancel, message(D, return, @nil)))), send(D, default_button(ok)), get(D, confirm, Rval), free(D). Thanks in advance

    Read the article

  • how to use method in AsyncTask in android?

    - by J.R.P
    In my application use JASON webservice to get data from Google Navigarion api. I use the Code is below. i got Exception android.os.NetworkOnMainThreadException. how to use AsyncTask? here is my code. Thanks.`public class MainActivity extends MapActivity { MapView mapView ; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); System.out.println("*************1**************1"); setContentView(R.layout.activity_main); System.out.println("*************2**************"); mapView = (MapView) findViewById(R.id.mapv); System.out.println("*************3**************"); Route route = directions(new GeoPoint((int)(26.2*1E6),(int)(50.6*1E6)), new GeoPoint((int)(26.3*1E6),(int)(50.7*1E6))); RouteOverlay routeOverlay = new RouteOverlay(route, Color.BLUE); mapView.getOverlays().add(routeOverlay); mapView.invalidate(); System.out.println("*************4**************"); } @SuppressLint("ParserError") private Route directions(final GeoPoint start, final GeoPoint dest) { //https://developers.google.com/maps/documentation/directions/#JSON <- get api String jsonURL = "http://maps.googleapis.com/maps/api/directions/json?"; final StringBuffer sBuf = new StringBuffer(jsonURL); sBuf.append("origin="); sBuf.append(start.getLatitudeE6()/1E6); sBuf.append(','); sBuf.append(start.getLongitudeE6()/1E6); sBuf.append("&destination="); sBuf.append(dest.getLatitudeE6()/1E6); sBuf.append(','); sBuf.append(dest.getLongitudeE6()/1E6); sBuf.append("&sensor=true&mode=driving"); Parser parser = new GoogleParser(sBuf.toString()); Route r = parser.parse(); System.out.println("********r in thread*****" +r); return r; } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } @Override protected boolean isRouteDisplayed() { // TODO Auto-generated method stub return false; } } `

    Read the article

  • delete a row in html table using a hidden type and javascript

    - by kawtousse
    Hi, I have a table with HTML constructed using my servlet class. When trying to delete a row in this table using a javascript function I must first of all put different id to separate elements.and i resolove it with hidden type like that: retour.append("<td>"); retour.append("<input type=\"hidden\" id=\"id_"+nomTab+"_"+compteur+"\" value=\""+object.getIdDailyTimeSheet()+"\"/>"); retour.append("<button id=\"del\" name=\"del\" type=\"button\" onClick=DeleteARow('+id_"+nomTab+"_"+compteur+"')>"); retour.append("<img src=icon_delete.gif />"); retour.append("</button>"); retour.append("</td>"); As you can see each element has a delete button. What i want to know how can i delete one row. thinks.

    Read the article

  • MySQL for Excel 1.1.0 GA has been released

    - by Javier Treviño
    The MySQL Windows Experience Team is proud to announce the release of MySQL for Excel version 1.1.0 GA, one of our newest products contained in the MySQL Installer suite. You can download it from our official Downloads page at http://dev.mysql.com/downloads/installer/. The 1.1.0 release of MySQL for Excel introduces the following features: Edit MySQL Data. Edit MySQL Data This may be the coolest feature so far; users will be able to edit the data in a MySQL table using MS Excel in a very friendly and intuitive way.  Edit Data supports inserting new rows, deleting existing rows and updating existing data as easy as playing with data in an Excel’s spreadsheet and pushing changes back to the server.  Also this version contains the following bug fixes: Enabled the following checkboxes in the Append Data's Advanced Options dialog and added code in the Append Data dialog to use the checkboxes as follows: Automatically store the column mapping for the given table     If checked the current mapping will be stored automatically after clicking the Append button if the append operation is successful and there is no mapping for the current connection.schema.table already; the new mapping is stored with a proposed name of Mapping. Reload stored column mapping for the selected table automatically     If checked the first Stored Mapping found where all column names in the source grid match all column names in the target grid is automatically selected and applied when the Append Data dialog is loaded. Fixed code in Append Data that applies a stored column mapping to skip target columns where the associated mapping is empty (saved as a -1). Enclosed the Add-In's startup code in a try-catch block in order to log any possible error thrown during startup; and added information messages to the log at the beginning of the Add-In's startup code and at the end of the shutdown code.  Also changed the wrapper method that calls the MySQLUtility to write messages to the log to make logging easier, thus changed the log call throughout all the code that contains a try-catch block. Added code to the main wix configuration file to check if a newer version is already installed and if so abort the installation Fixed code to refresh the Import Procedure Form's preview grid's data source to repaint its contents every time the Call button is pressed. Added code to re-pull connections after connections are migrated from Excel to Workbench. Fixed code so when the Append Data's Automatic Mapping is performed any subsequent change on a mapping resets the mapping to a Manual Mapping. Added code to the InfoDialog class to set the button text to "Show Details" or "Hide Details" depending on the status of the Details text container. Fixed a GUID in the main wix configuration file so now previous versions are uninstalled during a new installation. Added an option to the Export Data's Advanced Options dialog to remove columns with no data, by default the Export Dialog will only flag those columns as Excluded. Added code to display a warning and paint a column red if the column name in the Export Data dialog is not set, display a warning if the table name is not set, and stack warnings but not display them if a column is Excluded, warnings are displayed normally for columns if they are not Excluded anymore.  Added code to prevent the Append and Export of Data if more than 1 selection is made (selecting more than 1 area holding the Ctrl key while selecting Excel cells). Fixed problem that prevented MySQL for Excel from loading when Display settings in Windows 7 is set to Adjust to Best Performance (Oracle bug 14521405 - UNHANDLED EXCEPTION IS THROWN WHEN LOADING MYSQL FOR EXCEL). Fixed code that renames the auto-generated Primary Key column when the Table name changes since it was not detecting if a column with the same name already existed in the table. The column duplication was not actually happening, it looked that way because the automatically generated PK column was not detecting a column had that same name. Fixed code in Export Data dialog to always set an empty string instead of null to the MySQLDataColumn properties that stores MySQL data types (MySQLDataType, RowsFrom1stDataType and RowsFrom2ndDataType). Added code to display a warning and color red a column which Data Type has not been set by the user or has been manually cleared. Added code to output to the application log exception messages consistently in all places where exceptions are catched. A series of blog posts explaining the new Edit MySQL Data feature and the other existing features are coming in this blog. You can access the MySQL for Excel documentation at http://dev.mysql.com/doc/refman/5.5/en/mysql-for-excel.html You can also post questions on our MySQL for Excel forum found at http://forums.mysql.com/. You can also post questions on our MySQL for Excel forum found at http://forums.mysql.com/. Enjoy and thanks for the support!

    Read the article

  • Calculating the Size (in Bytes and MB) of a Oracle Coherence Cache

    - by Ricardo Ferreira
    The concept and usage of data grids are becoming very popular in this days since this type of technology are evolving very fast with some cool lead products like Oracle Coherence. Once for a while, developers need an programmatic way to calculate the total size of a specific cache that are residing in the data grid. In this post, I will show how to accomplish this using Oracle Coherence API. This example has been tested with 3.6, 3.7 and 3.7.1 versions of Oracle Coherence. To start the development of this example, you need to create a POJO ("Plain Old Java Object") that represents a data structure that will hold user data. This data structure will also create an internal fat so I call that should increase considerably the size of each instance in the heap memory. Create a Java class named "Person" as shown in the listing below. package com.oracle.coherence.domain; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Random; @SuppressWarnings("serial") public class Person implements Serializable { private String firstName; private String lastName; private List<Object> fat; private String email; public Person() { generateFat(); } public Person(String firstName, String lastName, String email) { setFirstName(firstName); setLastName(lastName); setEmail(email); generateFat(); } private void generateFat() { fat = new ArrayList<Object>(); Random random = new Random(); for (int i = 0; i < random.nextInt(18000); i++) { HashMap<Long, Double> internalFat = new HashMap<Long, Double>(); for (int j = 0; j < random.nextInt(10000); j++) { internalFat.put(random.nextLong(), random.nextDouble()); } fat.add(internalFat); } } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } Now let's create a Java program that will start a data grid into Coherence and will create a cache named "People", that will hold people instances with sequential integer keys. Each person created in this program will trigger the execution of a custom constructor created in the People class that instantiates an internal fat (the random amount of data generated to increase the size of the object) for each person. Create a Java class named "CreatePeopleCacheAndPopulateWithData" as shown in the listing below. package com.oracle.coherence.demo; import com.oracle.coherence.domain.Person; import com.tangosol.net.CacheFactory; import com.tangosol.net.NamedCache; public class CreatePeopleCacheAndPopulateWithData { public static void main(String[] args) { // Asks Coherence for a new cache named "People"... NamedCache people = CacheFactory.getCache("People"); // Creates three people that will be putted into the data grid. Each person // generates an internal fat that should increase its size in terms of bytes... Person pessoa1 = new Person("Ricardo", "Ferreira", "[email protected]"); Person pessoa2 = new Person("Vitor", "Ferreira", "[email protected]"); Person pessoa3 = new Person("Vivian", "Ferreira", "[email protected]"); // Insert three people at the data grid... people.put(1, pessoa1); people.put(2, pessoa2); people.put(3, pessoa3); // Waits for 5 minutes until the user runs the Java program // that calculates the total size of the people cache... try { System.out.println("---> Waiting for 5 minutes for the cache size calculation..."); Thread.sleep(300000); } catch (InterruptedException ie) { ie.printStackTrace(); } } } Finally, let's create a Java program that, using the Coherence API and JMX, will calculate the total size of each cache that the data grid is currently managing. The approach used in this example was retrieve every cache that the data grid are currently managing, but if you are interested on an specific cache, the same approach can be used, you should only filter witch cache will be looked for. Create a Java class named "CalculateTheSizeOfPeopleCache" as shown in the listing below. package com.oracle.coherence.demo; import java.text.DecimalFormat; import java.util.Map; import java.util.Set; import java.util.TreeMap; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.ObjectName; import com.tangosol.net.CacheFactory; public class CalculateTheSizeOfPeopleCache { @SuppressWarnings({ "unchecked", "rawtypes" }) private void run() throws Exception { // Enable JMX support in this Coherence data grid session... System.setProperty("tangosol.coherence.management", "all"); // Create a sample cache just to access the data grid... CacheFactory.getCache(MBeanServerFactory.class.getName()); // Gets the JMX server from Coherence data grid... MBeanServer jmxServer = getJMXServer(); // Creates a internal data structure that would maintain // the statistics from each cache in the data grid... Map cacheList = new TreeMap(); Set jmxObjectList = jmxServer.queryNames(new ObjectName("Coherence:type=Cache,*"), null); for (Object jmxObject : jmxObjectList) { ObjectName jmxObjectName = (ObjectName) jmxObject; String cacheName = jmxObjectName.getKeyProperty("name"); if (cacheName.equals(MBeanServerFactory.class.getName())) { continue; } else { cacheList.put(cacheName, new Statistics(cacheName)); } } // Updates the internal data structure with statistic data // retrieved from caches inside the in-memory data grid... Set<String> cacheNames = cacheList.keySet(); for (String cacheName : cacheNames) { Set resultSet = jmxServer.queryNames( new ObjectName("Coherence:type=Cache,name=" + cacheName + ",*"), null); for (Object resultSetRef : resultSet) { ObjectName objectName = (ObjectName) resultSetRef; if (objectName.getKeyProperty("tier").equals("back")) { int unit = (Integer) jmxServer.getAttribute(objectName, "Units"); int size = (Integer) jmxServer.getAttribute(objectName, "Size"); Statistics statistics = (Statistics) cacheList.get(cacheName); statistics.incrementUnit(unit); statistics.incrementSize(size); cacheList.put(cacheName, statistics); } } } // Finally... print the objects from the internal data // structure that represents the statistics from caches... cacheNames = cacheList.keySet(); for (String cacheName : cacheNames) { Statistics estatisticas = (Statistics) cacheList.get(cacheName); System.out.println(estatisticas); } } public MBeanServer getJMXServer() { MBeanServer jmxServer = null; for (Object jmxServerRef : MBeanServerFactory.findMBeanServer(null)) { jmxServer = (MBeanServer) jmxServerRef; if (jmxServer.getDefaultDomain().equals(DEFAULT_DOMAIN) || DEFAULT_DOMAIN.length() == 0) { break; } jmxServer = null; } if (jmxServer == null) { jmxServer = MBeanServerFactory.createMBeanServer(DEFAULT_DOMAIN); } return jmxServer; } private class Statistics { private long unit; private long size; private String cacheName; public Statistics(String cacheName) { this.cacheName = cacheName; } public void incrementUnit(long unit) { this.unit += unit; } public void incrementSize(long size) { this.size += size; } public long getUnit() { return unit; } public long getSize() { return size; } public double getUnitInMB() { return unit / (1024.0 * 1024.0); } public double getAverageSize() { return size == 0 ? 0 : unit / size; } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("\nCache Statistics of '").append(cacheName).append("':\n"); sb.append(" - Total Entries of Cache -----> " + getSize()).append("\n"); sb.append(" - Used Memory (Bytes) --------> " + getUnit()).append("\n"); sb.append(" - Used Memory (MB) -----------> " + FORMAT.format(getUnitInMB())).append("\n"); sb.append(" - Object Average Size --------> " + FORMAT.format(getAverageSize())).append("\n"); return sb.toString(); } } public static void main(String[] args) throws Exception { new CalculateTheSizeOfPeopleCache().run(); } public static final DecimalFormat FORMAT = new DecimalFormat("###.###"); public static final String DEFAULT_DOMAIN = ""; public static final String DOMAIN_NAME = "Coherence"; } I've commented the overall example so, I don't think that you should get into trouble to understand it. Basically we are dealing with JMX. The first thing to do is enable JMX support for the Coherence client (ie, an JVM that will only retrieve values from the data grid and will not integrate the cluster) application. This can be done very easily using the runtime "tangosol.coherence.management" system property. Consult the Coherence documentation for JMX to understand the possible values that could be applied. The program creates an in memory data structure that holds a custom class created called "Statistics". This class represents the information that we are interested to see, which in this case are the size in bytes and in MB of the caches. An instance of this class is created for each cache that are currently managed by the data grid. Using JMX specific methods, we retrieve the information that are relevant for calculate the total size of the caches. To test this example, you should execute first the CreatePeopleCacheAndPopulateWithData.java program and after the CreatePeopleCacheAndPopulateWithData.java program. The results in the console should be something like this: 2012-06-23 13:29:31.188/4.970 Oracle Coherence 3.6.0.4 <Info> (thread=Main Thread, member=n/a): Loaded operational configuration from "jar:file:/E:/Oracle/Middleware/oepe_11gR1PS4/workspace/calcular-tamanho-cache-coherence/lib/coherence.jar!/tangosol-coherence.xml" 2012-06-23 13:29:31.219/5.001 Oracle Coherence 3.6.0.4 <Info> (thread=Main Thread, member=n/a): Loaded operational overrides from "jar:file:/E:/Oracle/Middleware/oepe_11gR1PS4/workspace/calcular-tamanho-cache-coherence/lib/coherence.jar!/tangosol-coherence-override-dev.xml" 2012-06-23 13:29:31.219/5.001 Oracle Coherence 3.6.0.4 <D5> (thread=Main Thread, member=n/a): Optional configuration override "/tangosol-coherence-override.xml" is not specified 2012-06-23 13:29:31.266/5.048 Oracle Coherence 3.6.0.4 <D5> (thread=Main Thread, member=n/a): Optional configuration override "/custom-mbeans.xml" is not specified Oracle Coherence Version 3.6.0.4 Build 19111 Grid Edition: Development mode Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. 2012-06-23 13:29:33.156/6.938 Oracle Coherence GE 3.6.0.4 <Info> (thread=Main Thread, member=n/a): Loaded Reporter configuration from "jar:file:/E:/Oracle/Middleware/oepe_11gR1PS4/workspace/calcular-tamanho-cache-coherence/lib/coherence.jar!/reports/report-group.xml" 2012-06-23 13:29:33.500/7.282 Oracle Coherence GE 3.6.0.4 <Info> (thread=Main Thread, member=n/a): Loaded cache configuration from "jar:file:/E:/Oracle/Middleware/oepe_11gR1PS4/workspace/calcular-tamanho-cache-coherence/lib/coherence.jar!/coherence-cache-config.xml" 2012-06-23 13:29:35.391/9.173 Oracle Coherence GE 3.6.0.4 <D4> (thread=Main Thread, member=n/a): TCMP bound to /192.168.177.133:8090 using SystemSocketProvider 2012-06-23 13:29:37.062/10.844 Oracle Coherence GE 3.6.0.4 <Info> (thread=Cluster, member=n/a): This Member(Id=2, Timestamp=2012-06-23 13:29:36.899, Address=192.168.177.133:8090, MachineId=55685, Location=process:244, Role=Oracle, Edition=Grid Edition, Mode=Development, CpuCount=2, SocketCount=2) joined cluster "cluster:0xC4DB" with senior Member(Id=1, Timestamp=2012-06-23 13:29:14.031, Address=192.168.177.133:8088, MachineId=55685, Location=process:1128, Role=CreatePeopleCacheAndPopulateWith, Edition=Grid Edition, Mode=Development, CpuCount=2, SocketCount=2) 2012-06-23 13:29:37.172/10.954 Oracle Coherence GE 3.6.0.4 <D5> (thread=Cluster, member=n/a): Member 1 joined Service Cluster with senior member 1 2012-06-23 13:29:37.188/10.970 Oracle Coherence GE 3.6.0.4 <D5> (thread=Cluster, member=n/a): Member 1 joined Service Management with senior member 1 2012-06-23 13:29:37.188/10.970 Oracle Coherence GE 3.6.0.4 <D5> (thread=Cluster, member=n/a): Member 1 joined Service DistributedCache with senior member 1 2012-06-23 13:29:37.188/10.970 Oracle Coherence GE 3.6.0.4 <Info> (thread=Main Thread, member=n/a): Started cluster Name=cluster:0xC4DB Group{Address=224.3.6.0, Port=36000, TTL=4} MasterMemberSet ( ThisMember=Member(Id=2, Timestamp=2012-06-23 13:29:36.899, Address=192.168.177.133:8090, MachineId=55685, Location=process:244, Role=Oracle) OldestMember=Member(Id=1, Timestamp=2012-06-23 13:29:14.031, Address=192.168.177.133:8088, MachineId=55685, Location=process:1128, Role=CreatePeopleCacheAndPopulateWith) ActualMemberSet=MemberSet(Size=2, BitSetCount=2 Member(Id=1, Timestamp=2012-06-23 13:29:14.031, Address=192.168.177.133:8088, MachineId=55685, Location=process:1128, Role=CreatePeopleCacheAndPopulateWith) Member(Id=2, Timestamp=2012-06-23 13:29:36.899, Address=192.168.177.133:8090, MachineId=55685, Location=process:244, Role=Oracle) ) RecycleMillis=1200000 RecycleSet=MemberSet(Size=0, BitSetCount=0 ) ) TcpRing{Connections=[1]} IpMonitor{AddressListSize=0} 2012-06-23 13:29:37.891/11.673 Oracle Coherence GE 3.6.0.4 <D5> (thread=Invocation:Management, member=2): Service Management joined the cluster with senior service member 1 2012-06-23 13:29:39.203/12.985 Oracle Coherence GE 3.6.0.4 <D5> (thread=DistributedCache, member=2): Service DistributedCache joined the cluster with senior service member 1 2012-06-23 13:29:39.297/13.079 Oracle Coherence GE 3.6.0.4 <D4> (thread=DistributedCache, member=2): Asking member 1 for 128 primary partitions Cache Statistics of 'People': - Total Entries of Cache -----> 3 - Used Memory (Bytes) --------> 883920 - Used Memory (MB) -----------> 0.843 - Object Average Size --------> 294640 I hope that this post could save you some time when calculate the total size of Coherence cache became a requirement for your high scalable system using data grids. See you!

    Read the article

  • qemu -cdrom ubuntu.iso -boot d -net nic,model=virtio -m 1024 -curses

    - by Gert Cuykens
    How do I disable frame buffers in Ubuntu 13.10 Saucy kernel, I tried all kinds of kernel parameters but none work? DEFAULT ramdisk LABEL ramdisk kernel /casper/vmlinuz append boot=casper toram initrd=/casper/initrd.img -- vesafb.nonsense=1 LABEL isotest kernel /casper/vmlinuz append boot=casper integrity-check initrd=/casper/initrd.img -- vesafb.nonsense=1 LABEL memtest kernel /install/memtest append - DISPLAY isolinux.txt TIMEOUT 300 PROMPT 1

    Read the article

  • android get duration from maps.google.com directions

    - by urobo
    At the moment I am using this code to inquire google maps for directions from an address to another one, then I simply draw it on a mapview from its GeometryCollection. But yet this isn't enough I need also to extract the total expected duration from the kml. can someone give a little sample code to help me? thanks StringBuilder urlString = new StringBuilder(); urlString.append("http://maps.google.com/maps?f=d&hl=en"); urlString.append("&saddr=");//from urlString.append( Double.toString((double)src.getLatitudeE6()/1.0E6 )); urlString.append(","); urlString.append( Double.toString((double)src.getLongitudeE6()/1.0E6 )); urlString.append("&daddr=");//to urlString.append( Double.toString((double)dest.getLatitudeE6()/1.0E6 )); urlString.append(","); urlString.append( Double.toString((double)dest.getLongitudeE6()/1.0E6 )); urlString.append("&ie=UTF8&0&om=0&output=kml"); //Log.d("xxx","URL="+urlString.toString()); // get the kml (XML) doc. And parse it to get the coordinates(direction route). Document doc = null; HttpURLConnection urlConnection= null; URL url = null; try { url = new URL(urlString.toString()); urlConnection=(HttpURLConnection)url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.connect(); dbf = DocumentBuilderFactory.newInstance(); db = dbf.newDocumentBuilder(); doc = db.parse(urlConnection.getInputStream()); if(doc.getElementsByTagName("GeometryCollection").getLength()>0) { //String path = doc.getElementsByTagName("GeometryCollection").item(0).getFirstChild().getFirstChild().getNodeName(); String path = doc.getElementsByTagName("GeometryCollection").item(0).getFirstChild().getFirstChild().getFirstChild().getNodeValue() ; //Log.d("xxx","path="+ path); String[] pairs = path.split(" "); String[] lngLat = pairs[0].split(","); // lngLat[0]=longitude lngLat[1]=latitude lngLat[2]=height // src GeoPoint startGP = new GeoPoint((int)(Double.parseDouble(lngLat[1])*1E6),(int)(Double.parseDouble(lngLat[0])*1E6)); mMapView01.getOverlays().add(new MyOverLay(startGP,startGP,1)); GeoPoint gp1; GeoPoint gp2 = startGP; for(int i=1;i<pairs.length;i++) // the last one would be crash { lngLat = pairs[i].split(","); gp1 = gp2; // watch out! For GeoPoint, first:latitude, second:longitude gp2 = new GeoPoint((int)(Double.parseDouble(lngLat[1])*1E6),(int)(Double.parseDouble(lngLat[0])*1E6)); mMapView01.getOverlays().add(new MyOverLay(gp1,gp2,2,color)); //Log.d("xxx","pair:" + pairs[i]); } mMapView01.getOverlays().add(new MyOverLay(dest,dest, 3)); // use the default color } }catch (MalformedURLException e){ e.printStackTrace(); }catch (IOException e){ e.printStackTrace(); }catch (SAXException e){ e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } }

    Read the article

  • Using SQL Alchemy and pyodbc with IronPython 2.6.1

    - by beargle
    I'm using IronPython and the clr module to retrieve SQL Server information via SMO. I'd like to retrieve/store this data in a SQL Server database using SQL Alchemy, but am having some trouble loading the pyodbc module. Here's the setup: IronPython 2.6.1 (installed at D:\Program Files\IronPython) CPython 2.6.5 (installed at D:\Python26) SQL Alchemy 0.6.1 (installed at D:\Python26\Lib\site-packages\sqlalchemy) pyodbc 2.1.7 (installed at D:\Python26\Lib\site-packages) I have these entries in the IronPython site.py to import CPython standard and third-party libraries: # Add CPython standard libs and DLLs import sys sys.path.append(r"D:\Python26\Lib") sys.path.append(r"D:\Python26\DLLs") sys.path.append(r"D:\Python26\lib-tk") sys.path.append(r"D:\Python26") # Add CPython third-party libs sys.path.append(r"D:\Python26\Lib\site-packages") # sqlite3 sys.path.append(r"D:\Python26\Lib\sqlite3") # Add SQL Server SMO sys.path.append(r"D:\Program Files\Microsoft SQL Server\100\SDK\Assemblies") import clr clr.AddReferenceToFile('Microsoft.SqlServer.Smo.dll') clr.AddReferenceToFile('Microsoft.SqlServer.SqlEnum.dll') clr.AddReferenceToFile('Microsoft.SqlServer.ConnectionInfo.dll') SQL Alchemy imports OK in IronPython, put I receive this error message when trying to connect to SQL Server: IronPython 2.6.1 (2.6.10920.0) on .NET 2.0.50727.3607 Type "help", "copyright", "credits" or "license" for more information. >>> import sqlalchemy >>> e = sqlalchemy.MetaData("mssql://") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "D:\Python26\Lib\site-packages\sqlalchemy\schema.py", line 1780, in __init__ File "D:\Python26\Lib\site-packages\sqlalchemy\schema.py", line 1828, in _bind_to File "D:\Python26\Lib\site-packages\sqlalchemy\engine\__init__.py", line 241, in create_engine File "D:\Python26\Lib\site-packages\sqlalchemy\engine\strategies.py", line 60, in create File "D:\Python26\Lib\site-packages\sqlalchemy\connectors\pyodbc.py", line 29, in dbapi ImportError: No module named pyodbc This code works just fine in CPython, but it looks like the pyodbc module isn't accessible from IronPython. Any suggestions? I realize that this may not be the best way to approach the problem, so I'm open to tackling this a different way. Just wanted to get some experience with using SQL Alchemy and pyodbc.

    Read the article

< Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >