Search Results

Search found 10693 results on 428 pages for 'reading'.

Page 17/428 | < Previous Page | 13 14 15 16 17 18 19 20 21 22 23 24  | Next Page >

  • MATLAB query about for loop, reading in data and plotting

    - by mp7
    Hi there, I am a complete novice at using matlab and am trying to work out if there is a way of optimising my code. Essentially I have data from model outputs and I need to plot them using matlab. In addition I have reference data (with 95% confidence intervals) which I plot on the same graph to get a visual idea on how close the model outputs and reference data is. In terms of the model outputs I have several thousand files (number sequentially) which I open in a loop and plot. The problem/question I have is whether I can preprocess the data and then plot later - to save time. The issue I seem to be having when I try this is that I have a legend which either does not appear or is inaccurate. My code (apolgies if it not elegant): fn= xlsread(['tbobserved' '.xls']); time= fn(:,1); totalreference=fn(:,4); totalreferencelowerci=fn(:,6); totalreferenceupperci=fn(:,7); figure plot(time,totalrefrence,'-', time, totalreferencelowerci,'--', time, totalreferenceupperci,'--'); xlabel('Year'); ylabel('Reference incidence per 100,000 population'); title ('Total'); clickableLegend('Observed reference data', 'Totalreferencelowerci', 'Totalreferenceupperci','Location','BestOutside'); xlim([1910 1970]); hold on start_sim=10000; end_sim=10005; h = zeros (1,1000); for i=start_sim:end_sim %is there any way of doing this earlier to save time? a=int2str(i); incidenceFile =strcat('result_', 'Sim', '_', a, 'I_byCal_total.xls'); est_tot=importdata(incidenceFile, '\t', 1); cal_tot=est_tot.data; magnitude=1; t1=cal_tot(:,1)+1750; totalmodel=cal_tot(:,3)+cal_tot(:,5); h(a)=plot(t1,totalmodel); xlim([1910 1970]); ylim([0 500]); hold all clickableLegend(h(a),a,'Location','BestOutside') end Essentially I was hoping to have a way of reading in the data and then plot later - ie. optimise the code. I hope you might be able to help. Thanks. mp

    Read the article

  • c++ setting string attribute value in class is throwing "Access violation reading location"

    - by user259789
    I am having some trouble getting this simple code to work: class CreateUserView { public: CreateUserView(void); ~CreateUserView(void); UserController* controller; void showView(); string name; string lastname; string address; string email; string dateOfBirth; }; All i need is to set these attributes in the implementation with getline(). CreateUserView::CreateUserView(void) { } void CreateUserView::showView() { cout << endl << " New User" << endl; cout << "--------------------------" << endl; cout << " Name\t\t: "; getline(cin, name); cout << " Lastname\t: "; getline(cin, lastname); cout << " Email\t\t: "; getline(cin, email); cout << " ===============================" << endl; cout << " 1. SAVE 2.CHANGE 3.CANCEL" << endl; cout << " ===============================" << endl; cout << " choice: "; int choice; cin >> choice; cin.ignore(); controller->createUser_choice(choice); } I keep getting this "Access violation reading location" error at this line: getline(cin, name); what's the best way of assigning a value to an std::string attribute of a class? even name = "whatever" is throwing that error!! thanks

    Read the article

  • How to resolve "dpkg: error processing /var/cache/apt/archives/python-apport_2.0.1-0ubuntu9_all.deb"?

    - by raz7588
    Update Manager will not update although I have over 100 updates to do I get a error message like this: installArchives() failed: Extracting templates from packages: 29%% Extracting templates from packages: 58%% Extracting templates from packages: 88%% Extracting templates from packages: 100%% Preconfiguring packages ... Extracting templates from packages: 29%% Extracting templates from packages: 58%% Extracting templates from packages: 88%% Extracting templates from packages: 100%% Preconfiguring packages ... Extracting templates from packages: 29%% Extracting templates from packages: 58%% Extracting templates from packages: 88%% Extracting templates from packages: 100%% Preconfiguring packages ... Extracting templates from packages: 29%% Extracting templates from packages: 58%% Extracting templates from packages: 88%% Extracting templates from packages: 100%% Preconfiguring packages ... (Reading database ... (Reading database ... 5%% (Reading database ... 10%% (Reading database ... 15%% (Reading database ... 20%% (Reading database ... 25%% (Reading database ... 30%% (Reading database ... 35%% (Reading database ... 40%% (Reading database ... 45%% (Reading database ... 50%% (Reading database ... 55%% (Reading database ... 60%% (Reading database ... 65%% (Reading database ... 70%% (Reading database ... 75%% (Reading database ... 80%% (Reading database ... 85%% (Reading database ... 90%% (Reading database ... 95%% (Reading database ... 100%% (Reading database ... 189751 files and directories currently installed.) Preparing to replace python-problem-report 2.0.1-0ubuntu7 (using .../python-problem-report_2.0.1-0ubuntu9_all.deb) ... Traceback (most recent call last): File "/usr/bin/pyclean", line 33, in <module> from debpython.namespace import add_namespace_files ValueError: bad marshal data (unknown type code) dpkg: warning: subprocess old pre-removal script returned error exit status 1 dpkg - trying script from the new package instead ... Traceback (most recent call last): File "/usr/bin/pyclean", line 33, in <module> from debpython.namespace import add_namespace_files ValueError: bad marshal data (unknown type code) dpkg: error processing /var/cache/apt/archives/python-problem-report_2.0.1-0ubuntu9_all.deb (--unpack): subprocess new pre-removal script returned error exit status 1 No apport report written because MaxReports is reached already Traceback (most recent call last): File "/usr/bin/pycompile", line 39, in <module> from debpython.namespace import add_namespace_files ValueError: bad marshal data (unknown type code) dpkg: error while cleaning up: subprocess installed post-installation script returned error exit status 1 Preparing to replace python-apport 2.0.1-0ubuntu7 (using .../python-apport_2.0.1-0ubuntu9_all.deb) ... Traceback (most recent call last): File "/usr/bin/pyclean", line 33, in <module> from debpython.namespace import add_namespace_files ValueError: bad marshal data (unknown type code) dpkg: warning: subprocess old pre-removal script returned error exit status 1 dpkg - trying script from the new package instead ... Traceback (most recent call last): File "/usr/bin/pyclean", line 33, in <module> from debpython.namespace import add_namespace_files ValueError: bad marshal data (unknown type code) dpkg: error processing /var/cache/apt/archives/python-apport_2.0.1-0ubuntu9_all.deb (--unpack): subprocess new pre-removal script returned error exit status 1 No apport report written because MaxReports is reached already Traceback (most recent call last): File "/usr/bin/pycompile", line 39, in <module> from debpython.namespace import add_namespace_files ValueError: bad marshal data (unknown type code) dpkg: error while cleaning up: subprocess installed post-installation script returned error exit status 1 Preparing to replace apport 2.0.1-0ubuntu7 (using .../apport_2.0.1-0ubuntu9_all.deb) ... apport stop/waiting Traceback (most recent call last): File "/usr/bin/pyclean", line 33, in <module> from debpython.namespace import add_namespace_files ValueError: bad marshal data (unknown type code) dpkg: warning: subprocess old pre-removal script returned error exit status 1 dpkg - trying script from the new package instead ... Traceback (most recent call last): File "/usr/bin/pyclean", line 33, in <module> from debpython.namespace import add_namespace_files ValueError: bad marshal data (unknown type code) dpkg: error processing /var/cache/apt/archives/apport_2.0.1-0ubuntu9_all.deb (--unpack): subprocess new pre-removal script returned error exit status 1 No apport report written because MaxReports is reached already apport start/running Traceback (most recent call last): File "/usr/bin/pycompile", line 39, in <module> from debpython.namespace import add_namespace_files ValueError: bad marshal data (unknown type code) dpkg: error while cleaning up: subprocess installed post-installation script returned error exit status 1 Preparing to replace gnome-orca 3.4.1-0ubuntu0.1 (using .../gnome-orca_3.4.2-0ubuntu0.1_all.deb) ... Traceback (most recent call last): File "/usr/bin/pyclean", line 33, in <module> from debpython.namespace import add_namespace_files ValueError: bad marshal data (unknown type code) dpkg: warning: subprocess old pre-removal script returned error exit status 1 dpkg - trying script from the new package instead ... Traceback (most recent call last): File "/usr/bin/pyclean", line 33, in <module> from debpython.namespace import add_namespace_files ValueError: bad marshal data (unknown type code) dpkg: error processing /var/cache/apt/archives/gnome-orca_3.4.2-0ubuntu0.1_all.deb (--unpack): subprocess new pre-removal script returned error exit status 1 No apport report written because MaxReports is reached already Traceback (most recent call last): File "/usr/bin/pycompile", line 39, in <module> from debpython.namespace import add_namespace_files ValueError: bad marshal data (unknown type code) dpkg: error while cleaning up: subprocess installed post-installation script returned error exit status 1 Preparing to replace python-piston-mini-client 0.7.2-0ubuntu1 (using .../python-piston-mini-client_0.7.2+bzr57-0ubuntu1_all.deb) ... Traceback (most recent call last): File "/usr/bin/pyclean", line 33, in <module> from debpython.namespace import add_namespace_files ValueError: bad marshal data (unknown type code) dpkg: warning: subprocess old pre-removal script returned error exit status 1 dpkg - trying script from the new package instead ... Traceback (most recent call last): File "/usr/bin/pyclean", line 33, in <module> from debpython.namespace import add_namespace_files ValueError: bad marshal data (unknown type code) dpkg: error processing /var/cache/apt/archives/python-piston-mini-client_0.7.2+bzr57-0ubuntu1_all.deb (--unpack): subprocess new pre-removal script returned error exit status 1 No apport report written because MaxReports is reached already Traceback (most recent call last): File "/usr/bin/pycompile", line 39, in <module> from debpython.namespace import add_namespace_files ValueError: bad marshal data (unknown type code) dpkg: error while cleaning up: subprocess installed post-installation script returned error exit status 1 Preparing to replace oneconf 0.2.8 (using .../oneconf_0.2.8.1_all.deb) ... Traceback (most recent call last): File "/usr/bin/pyclean", line 33, in <module> from debpython.namespace import add_namespace_files ValueError: bad marshal data (unknown type code) dpkg: warning: subprocess old pre-removal script returned error exit status 1 dpkg - trying script from the new package instead ... Traceback (most recent call last): File "/usr/bin/pyclean", line 33, in <module> from debpython.namespace import add_namespace_files ValueError: bad marshal data (unknown type code) dpkg: error processing /var/cache/apt/archives/oneconf_0.2.8.1_all.deb (--unpack): subprocess new pre-removal script returned error exit status 1 No apport report written because MaxReports is reached already Traceback (most recent call last): File "/usr/bin/pycompile", line 39, in <module> from debpython.namespace import add_namespace_files ValueError: bad marshal data (unknown type code) dpkg: error while cleaning up: subprocess installed post-installation script returned error exit status 1 Preparing to replace software-center 5.2.2 (using .../software-center_5.2.2.2_all.deb) ... Traceback (most recent call last): File "/usr/bin/pyclean", line 33, in <module> from debpython.namespace import add_namespace_files ValueError: bad marshal data (unknown type code) dpkg: warning: subprocess old pre-removal script returned error exit status 1 dpkg - trying script from the new package instead ... Traceback (most recent call last): File "/usr/bin/pyclean", line 33, in <module> from debpython.namespace import add_namespace_files ValueError: bad marshal data (unknown type code) dpkg: error processing /var/cache/apt/archives/software-center_5.2.2.2_all.deb (--unpack): subprocess new pre-removal script returned error exit status 1 No apport report written because MaxReports is reached already Traceback (most recent call last): File "/usr/bin/pycompile", line 39, in <module> from debpython.namespace import add_namespace_files ValueError: bad marshal data (unknown type code) dpkg: error while cleaning up: subprocess installed post-installation script returned error exit status 1 Preparing to replace libglade2-0 1:2.6.4-1ubuntu1 (using .../libglade2-0_1%%3a2.6.4-1ubuntu1.1_amd64.deb) ... Unpacking replacement libglade2-0 ... Preparing to replace libv4l-0 0.8.6-1ubuntu1 (using .../libv4l-0_0.8.6-1ubuntu2_amd64.deb) ... De-configuring libv4l-0:i386 ... Unpacking replacement libv4l-0 ... Preparing to replace libv4l-0:i386 0.8.6-1ubuntu1 (using .../libv4l-0_0.8.6-1ubuntu2_i386.deb) ... Unpacking replacement libv4l-0:i386 ... Preparing to replace libv4lconvert0:i386 0.8.6-1ubuntu1 (using .../libv4lconvert0_0.8.6-1ubuntu2_i386.deb) ... De-configuring libv4lconvert0 ... Unpacking replacement libv4lconvert0:i386 ... Preparing to replace libv4lconvert0 0.8.6-1ubuntu1 (using .../libv4lconvert0_0.8.6-1ubuntu2_amd64.deb) ... Unpacking replacement libv4lconvert0 ... Errors were encountered while processing: /var/cache/apt/archives/python-problem-report_2.0.1-0ubuntu9_all.deb /var/cache/apt/archives/python-apport_2.0.1-0ubuntu9_all.deb /var/cache/apt/archives/apport_2.0.1-0ubuntu9_all.deb /var/cache/apt/archives/gnome-orca_3.4.2-0ubuntu0.1_all.deb /var/cache/apt/archives/python-piston-mini-client_0.7.2+bzr57-0ubuntu1_all.deb /var/cache/apt/archives/oneconf_0.2.8.1_all.deb /var/cache/apt/archives/software-center_5.2.2.2_all.deb Error in function: SystemError: E:Sub-process /usr/bin/dpkg returned an error code (1) Setting up libglade2-0 (1:2.6.4-1ubuntu1.1) ... dpkg: error processing gnome-orca (--configure): Package is in a very bad inconsistent state - you should reinstall it before attempting configuration. dpkg: error processing python-problem-report (--configure): Package is in a very bad inconsistent state - you should reinstall it before attempting configuration. Setting up libv4lconvert0 (0.8.6-1ubuntu2) ... Setting up libv4lconvert0:i386 (0.8.6-1ubuntu2) ... dpkg: error processing python-piston-mini-client (--configure): Package is in a very bad inconsistent state - you should reinstall it before attempting configuration. Setting up libv4l-0 (0.8.6-1ubuntu2) ... Setting up libv4l-0:i386 (0.8.6-1ubuntu2) ... dpkg: dependency problems prevent configuration of python-apport: python-apport depends on python-problem-report (>= 0.94); however: Package python-problem-report is not configured yet. dpkg: error processing python-apport (--configure): dependency problems - leaving unconfigured dpkg: dependency problems prevent configuration of software-center: software-center depends on python-piston-mini-client (>= 0.1+bzr29); however: Package python-piston-mini-client is not configured yet. dpkg: error processing software-center (--configure): dependency problems - leaving unconfigured dpkg: dependency problems prevent configuration of oneconf: oneconf depends on python-piston-mini-client (>= 0.3+bzr32-0ubuntu1); however: Package python-piston-mini-client is not configured yet. dpkg: error processing oneconf (--configure): dependency problems - leaving unconfigured dpkg: dependency problems prevent configuration of apport: apport depends on python-apport (>= 2.0.1-0ubuntu7); however: Package python-apport is not configured yet. dpkg: error processing apport (--configure): dependency problems - leaving unconfigured Processing triggers for libc-bin ... ldconfig deferred processing now taking place This has been going on for two weeks now and I cannot get any updates. Any help would be great.

    Read the article

  • Reading XML element & child nodes using LINQ in Vb.net- help me in where condition :(

    - by New Linq Baby
    Hi, I am new in LINQ world. I need an urgent help in reading the xml elements using LINQ with specific where condition. I need to find the max air_temp for a county i.e where county name = "Boone" and hour id = "06/03/2009 09:00CDT" i tried something like below, but no luck : Dim custs As IEnumerable = From c In Element.Load("C:\meridian.xml").Elements("county") _ Select c.Elements("hour").Elements("air_temp").Max() For Each x In custs Response.Write(custs(0).ToString()) Next ------------------- here is the xml file : <forecasts> <issued>06/02/2009 12:00CDT</issued> - <county name="Adair"> - <hour id="06/02/2009 12:00CDT"> <air_temp>61</air_temp> <cloud_cover>overcast</cloud_cover> <dew_point>59</dew_point> <precip_prob>90</precip_prob> <precip_rate>0.12</precip_rate> <precip_type>rain</precip_type> <snow_rate>0.0</snow_rate> <wind_direction>NE</wind_direction> <wind_speed>12</wind_speed> <dew_point_confidence>-3/+3</dew_point_confidence> <road_temp>64</road_temp> <road_frost_prob>0</road_frost_prob> <road_potential_evap_rate>429</road_potential_evap_rate> <road_temp_confidence>-3/+2</road_temp_confidence> <dew_point_confidence>-3/+3</dew_point_confidence> <bridge_temp>63</bridge_temp> <bridge_temp_confidence>-4/+2</bridge_temp_confidence> <bridge_frost>NO</bridge_frost> </hour> - <hour id="06/02/2009 13:00CDT"> <air_temp>61</air_temp> <cloud_cover>overcast</cloud_cover> <dew_point>60</dew_point> <precip_prob>70</precip_prob> <precip_rate>0.01</precip_rate> <precip_type>rain</precip_type> <snow_rate>0.0</snow_rate> <wind_direction>ENE</wind_direction> <wind_speed>10</wind_speed> <dew_point_confidence>-3/+3</dew_point_confidence> <road_temp>65</road_temp> <road_frost_prob>0</road_frost_prob> <road_potential_evap_rate>411</road_potential_evap_rate> <road_temp_confidence>-3/+2</road_temp_confidence> <dew_point_confidence>-3/+3</dew_point_confidence> <bridge_temp>64</bridge_temp> <bridge_temp_confidence>-4/+1</bridge_temp_confidence> <bridge_frost>NO</bridge_frost> </hour>

    Read the article

  • Reading XML File

    - by Joy
    I'm developping an iphone application which uses google weather api to forecast the weather. The webservice is giving me data in the following format:- <?xml version="1.0"?> <xml_api_reply version="1"> <weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0" > <forecast_information> <city data="Kolkata, West Bengal"/> <postal_code data="Kolkata"/> <latitude_e6 data=""/> <longitude_e6 data=""/> <forecast_date data="2010-04-28"/> <current_date_time data="2010-04-28 10:20:00 +0000"/> <unit_system data="US"/> </forecast_information> <current_conditions ><condition data="Haze"/> <temp_f data="97"/> <temp_c data="36"/> <humidity data="Humidity: 53%"/> <icon data="/ig/images/weather/haze.gif"/> <wind_condition data="Wind: S at 12 mph"/> </current_conditions> <forecast_conditions> <day_of_week data="Wed"/> <low data="82"/> <high data="91"/> <icon data="/ig/images/weather/chance_of_rain.gif"/> <condition data="Chance of Rain"/> </forecast_conditions> <forecast_conditions> <day_of_week data="Thu"/> <low data="82"/> <high data="96"/> <icon data="/ig/images/weather/rain.gif"/> <condition data="Rain"/> </forecast_conditions> <forecast_conditions> <day_of_week data="Fri"/> <low data="82"/> <high data="96"/> <icon data="/ig/images/weather/sunny.gif"/> <condition data="Clear"/> </forecast_conditions> <forecast_conditions> <day_of_week data="Sat"/> <low data="78"/> <high data="98"/> <icon data="/ig/images/weather/mostly_sunny.gif"/> <condition data="Mostly Sunny"/> </forecast_conditions> </weather> As I'm new to iPhone development so i'm facing problem while reading this using xmlparser. Please help me out of this problem. Looking forward to your valuable reply. Thanks in advance..

    Read the article

  • Reading xml document in firefox

    - by Searock
    I am trying to read customers.xml using javascript. My professor has taught us to read xml using `ActiveXObjectand he has given us an assignment to create a sample login page which checks username and password by reading customers.xml. I am trying to use DOMParser so that it works with firefox. But when I click on Login button I get this error. Error: syntax error Source File: file:///C:/Users/Searock/Desktop/home/project/project/login.html Line: 1, Column: 1 Source Code: customers.xml Here's my code. login.js var xmlDoc = 0; function checkUser() { var user = document.login.txtLogin.value; var pass = document.login.txtPass.value; //xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); /* xmlDoc = document.implementation.createDocument("","",null); xmlDoc.async = "false"; xmlDoc.onreadystatechange = redirectUser; xmlDoc.load("customers.xml"); */ var parser = new DOMParser(); xmlDoc = parser.parseFromString("customers.xml", "text/xml"); alert(xmlDoc.documentElement.nodeName); xmlDoc.async = "false"; xmlDoc.onreadystatechange = redirectUser; } function redirectUser() { alert(''); var user = document.login.txtLogin.value; var pass = document.login.txtPass.value; var log = 0; if(xmlDoc.readyState == 4) { xmlObj = xmlDoc.documentElement; var len = xmlObj.childNodes.length; for(i = 0; i < len; i++) { var nodeElement = xmlObj.childNodes[i]; var userXml = nodeElement.childNodes[0].firstChild.nodeValue; var passXml = nodeElement.childNodes[1].firstChild.nodeValue; var idXML = nodeElement.attributes[0].value if(userXml == user && passXml == pass) { log = 1; document.cookie = escape(idXML); document.login.submit(); } } } if(log == 0) { var divErr = document.getElementById('Error'); divErr.innerHTML = "<b>Login Failed</b>"; } } customers.xml <?xml version="1.0" encoding="UTF-8"?> <customers> <customer custid="CU101"> <user>jack</user> <pwd>PW101</pwd> <email>[email protected]</email> </customer> <customer custid="CU102"> <user>jill</user> <pwd>PW102</pwd> <email>[email protected]</email> </customer> <customer custid="CU103"> <user>john</user> <pwd>PW103</pwd> <email>[email protected]</email> </customer> <customer custid="CU104"> <user>jeff</user> <pwd>PW104</pwd> <email>[email protected]</email> </customer> </customers> I get parsererror message on line alert(xmlDoc.documentElement.nodeName); I don't know what's wrong with my code. Can some one point me in a right direction? Edit : Ok, I found a solution. var xmlDoc = 0; var xhttp = 0; function checkUser() { var user = document.login.txtLogin.value; var pass = document.login.txtPass.value; var err = ""; if(user == "" || pass == "") { if(user == "") { alert("Enter user name"); } if(pass == "") { alert("Enter Password"); } return; } if (window.XMLHttpRequest) { xhttp=new XMLHttpRequest(); } else // IE 5/6 { xhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.onreadystatechange = redirectUser; xhttp.open("GET","customers.xml",true); xhttp.send(); } function redirectUser() { var log = 2; var user = document.login.txtLogin.value; var pass = document.login.txtPass.value; if (xhttp.readyState == 4) { log = 0; xmlDoc = xhttp.responseXML; var xmlUsers = xmlDoc.getElementsByTagName('user'); var xmlPasswords = xmlDoc.getElementsByTagName('pwd'); var userLen = xmlDoc.getElementsByTagName('customer').length; var xmlCustomers = xmlDoc.getElementsByTagName('customer'); for (var i = 0; i < userLen; i++) { var xmlUser = xmlUsers[i].childNodes[0].nodeValue; var xmlPass = xmlPasswords[i].childNodes[0].nodeValue; var xmlId = xmlCustomers.item(i).attributes[0].nodeValue; if(xmlUser == user && xmlPass == pass) { log = 1; document.cookie = xmlId; document.login.submit(); break; } } } if(log == 0) { alert("Login failed"); } } Thanks.

    Read the article

  • C# Reading and Writing a Char[] to and from a Byte[] - Updated with Solution

    - by Simon G
    Hi, I have a byte array of around 10,000 bytes which is basically a blob from delphi that contains char, string, double and arrays of various types. This need to be read in and updated via C#. I've created a very basic reader that gets the byte array from the db and converts the bytes to the relevant object type when accessing the property which works fine. My problem is when I try to write to a specific char[] item, it doesn't seem to update the byte array. I've created the following extensions for reading and writing: public static class CharExtension { public static byte ToByte( this char c ) { return Convert.ToByte( c ); } public static byte ToByte( this char c, int position, byte[] blob ) { byte b = c.ToByte(); blob[position] = b; return b; } } public static class CharArrayExtension { public static byte[] ToByteArray( this char[] c ) { byte[] b = new byte[c.Length]; for ( int i = 1; i < c.Length; i++ ) { b[i] = c[i].ToByte(); } return b; } public static byte[] ToByteArray( this char[] c, int positon, int length, byte[] blob ) { byte[] b = c.ToByteArray(); Array.Copy( b, 0, blob, positon, length ); return b; } } public static class ByteExtension { public static char ToChar( this byte[] b, int position ) { return Convert.ToChar( b[position] ); } } public static class ByteArrayExtension { public static char[] ToCharArray( this byte[] b, int position, int length ) { char[] c = new char[length]; for ( int i = 0; i < length; i++ ) { c[i] = b.ToChar( position ); position += 1; } return c; } } to read and write chars and char arrays my code looks like: Byte[] _Blob; // set from a db field public char ubin { get { return _tariffBlob.ToChar( 14 ); } set { value.ToByte( 14, _Blob ); } } public char[] usercaplas { get { return _tariffBlob.ToCharArray( 2035, 10 ); } set { value.ToByteArray( 2035, 10, _Blob ); } } So to write to the objects I can do: ubin = 'C'; // this will update the byte[] usercaplas = new char[10] { 'A', 'B', etc. }; // this will update the byte[] usercaplas[3] = 'C'; // this does not update the byte[] I know the reason is that the setter property is not being called but I want to know is there a way around this using code similar to what I already have? I know a possible solution is to use a private variable called _usercaplas that I set and update as needed however as the byte array is nearly 10,000 bytes in length the class is already long and I would like a simpler approach as to reduce the overall code length and complexity. Thank Solution Here's my solution should anyone want it. If you have a better way of doing then let me know please. First I created a new class for the array: public class CharArrayList : ArrayList { char[] arr; private byte[] blob; private int length = 0; private int position = 0; public CharArrayList( byte[] blob, int position, int length ) { this.blob = blob; this.length = length; this.position = position; PopulateInternalArray(); SetArray(); } private void PopulateInternalArray() { arr = blob.ToCharArray( position, length ); } private void SetArray() { foreach ( char c in arr ) { this.Add( c ); } } private void UpdateInternalArray() { this.Clear(); SetArray(); } public char this[int i] { get { return arr[i]; } set { arr[i] = value; UpdateInternalArray(); } } } Then I created a couple of extension methods to help with converting to a byte[] public static byte[] ToByteArray( this CharArrayList c ) { byte[] b = new byte[c.Count]; for ( int i = 0; i < c.Count; i++ ) { b[i] = Convert.ToChar( c[i] ).ToByte(); } return b; } public static byte[] ToByteArray( this CharArrayList c, byte[] blob, int position, int length ) { byte[] b = c.ToByteArray(); Array.Copy( b, 0, blob, position, length ); return b; } So to read and write to the object: private CharArrayList _usercaplass; public CharArrayList usercaplas { get { if ( _usercaplass == null ) _usercaplass = new CharArrayList( _tariffBlob, 2035, 100 ); return _usercaplass; } set { _usercaplass = value; _usercaplass.ToByteArray( _tariffBlob, 2035, 100 ); } } As mentioned before its not an ideal solutions as I have to have private variables and extra code in the setter but I couldnt see a way around it.

    Read the article

  • ASP.NET application partially reading external configuration

    - by Trent
    I have an ASP.NET web app and am attempting to reference an external config (using enterprise application blocks configuration) for some of the configuration but it is not entirely working. I previously had all of the configuration info in the web.config (and it was working), but we are wanting to share some of this configuration information between multiple apps. When I put configurationSource tag in the web.config, and read the configuration through the WebConfigurationManager object, it loads some of the external config info (Logging) but not the connectionStrings and not the custom section I created. So its reading it (logging is working), but some dots aren't being connected and my connection strings aren't coming through. Again, it worked when it was all in the web.config. Any idea what needs to change to be able to reference an external configuration source and have it all come through? [Code that accesses web.config] Configuration webConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~"); ConnectionStringSettingsCollection connectionStrings = System.Web.Configuration.WebConfigurationManager.ConnectionStrings; [web.config] <configuration> <configSections> <section name="enterpriseLibrary.ConfigurationSource" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ConfigurationSourceSection, Microsoft.Practices.EnterpriseLibrary.Common, Version=4.1.0.0, Culture=neutral, PublicKeyToken=74025d8738dfe4ce" /> <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"> <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"> <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" /> <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"> <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere" /> <section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" /> <section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" /> <section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" /> </sectionGroup> </sectionGroup> </sectionGroup> </configSections> <enterpriseLibrary.ConfigurationSource selectedSource="File Configuration Source"> <sources> <add name="File Configuration Source" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.FileConfigurationSource, Microsoft.Practices.EnterpriseLibrary.Common, Version=4.1.0.0, Culture=neutral, PublicKeyToken=74025d8738dfe4ce" filePath="C:\MSEAB\MSEAB.config" /> </sources> </enterpriseLibrary.ConfigurationSource> ... ... </configuration> [external MSEAB.config] <configuration> <configSections> <section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=74025d8738dfe4ce" /> <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=4.1.0.0, Culture=neutral, PublicKeyToken=74025d8738dfe4ce" /> <sectionGroup name="customSectionGroup"> <section name="customSection" type="app.customSection" allowLocation="true" allowDefinition="Everywhere" /> </sectionGroup> </configSections> <loggingConfiguration name="Logging Application Block" tracingEnabled="true" defaultCategory="General" logWarningsWhenNoCategoriesMatch="true"> ... </loggingConfiguration> <connectionStrings> <clear /> <add name="DB.DEV" connectionString="User ID=user;Password=pwd;Data Source=DV408;" providerName="Oracle.DataAccess.Client"/> <add name="DB.TEST" connectionString="User ID=user;Password=pwd;Data Source=TS408;" providerName="Oracle.DataAccess.Client"/> ... </connectionStrings> <customSectionGroup> <customSection notificationemail="[email protected]" dirPath="C:\Dir" initialrowlimit="500" maxrowlimit="1500" adminadgroup="_admins"> </customSection> </customSectionGroup> </configuration>

    Read the article

  • C++ Linked List - Reading data from a file with a sentinel

    - by Nick
    So I've done quite a bit of research on this and can't get my output to work correctly. I need to read in data from a file and have it stored into a Linked List. The while loop used should stop once it hits the $$$$$ sentinel. Then I am to display the data (by searching by ID Number[user input]) I am not that far yet I just want to properly display the data and get it read in for right now. My problem is when it displays the data is isn't stopping at the $$$$$ (even if I do "inFile.peek() != EOF and omit the $$$$$) I am still getting an extra garbage record. I know it has something to do with my while loop and how I am creating a new Node but I can't get it to work any other way. Any help would be appreciated. students.txt Nick J Cooley 324123 60 70 80 90 Jay M Hill 412254 70 80 90 100 $$$$$ assign6.h file #pragma once #include <iostream> #include <string> using namespace std; class assign6 { public: assign6(); // constructor void displayStudents(); private: struct Node { string firstName; string midIni; string lastName; int idNum; int sco1; //Test score 1 int sco2; //Test score 2 int sco3; //Test score 3 int sco4; //Test score 4 Node *next; }; Node *head; Node *headPtr; }; assign6Imp.cpp // Implementation File #include "assign6.h" #include <fstream> #include <iostream> #include <string> using namespace std; assign6::assign6() //constructor { ifstream inFile; inFile.open("students.txt"); head = NULL; head = new Node; headPtr = head; while (inFile.peek() != EOF) //reading in from file and storing in linked list { inFile >> head->firstName >> head->midIni >> head->lastName; inFile >> head->idNum; inFile >> head->sco1; inFile >> head->sco2; inFile >> head->sco3; inFile >> head->sco4; if (inFile != "$$$$$") { head->next = NULL; head->next = new Node; head = head->next; } } head->next = NULL; inFile.close(); } void assign6::displayStudents() { int average = 0; for (Node *cur = headPtr; cur != NULL; cur = cur->next) { cout << cur->firstName << " " << cur->midIni << " " << cur->lastName << endl; cout << cur->idNum << endl; average = (cur->sco1 + cur->sco2 + cur->sco3 + cur->sco4)/4; cout << cur->sco1 << " " << cur->sco2 << " " << cur->sco3 << " " << cur->sco4 << " " << "average: " << average << endl; } }

    Read the article

  • Access violation reading location 0x00184000.

    - by numerical25
    having troubles with the following line HR(md3dDevice->CreateBuffer(&vbd, &vinitData, &mVB)); it appears the CreateBuffer method is having troubles reading &mVB. mVB is defined in box.h and looks like this ID3D10Buffer* mVB; Below is the code it its entirety. this is all files that mVB is in. //Box.cpp #include "Box.h" #include "Vertex.h" #include <vector> Box::Box() : mNumVertices(0), mNumFaces(0), md3dDevice(0), mVB(0), mIB(0) { } Box::~Box() { ReleaseCOM(mVB); ReleaseCOM(mIB); } float Box::getHeight(float x, float z)const { return 0.3f*(z*sinf(0.1f*x) + x*cosf(0.1f*z)); } void Box::init(ID3D10Device* device, float m, float n, float dx) { md3dDevice = device; mNumVertices = m*n; mNumFaces = 12; float halfWidth = (n-1)*dx*0.5f; float halfDepth = (m-1)*dx*0.5f; std::vector<Vertex> vertices(mNumVertices); for(DWORD i = 0; i < m; ++i) { float z = halfDepth - (i * dx); for(DWORD j = 0; j < n; ++j) { float x = -halfWidth + (j* dx); float y = getHeight(x,z); vertices[i*n+j].pos = D3DXVECTOR3(x, y, z); if(y < -10.0f) vertices[i*n+j].color = BEACH_SAND; else if( y < 5.0f) vertices[i*n+j].color = LIGHT_YELLOW_GREEN; else if (y < 12.0f) vertices[i*n+j].color = DARK_YELLOW_GREEN; else if (y < 20.0f) vertices[i*n+j].color = DARKBROWN; else vertices[i*n+j].color = WHITE; } } D3D10_BUFFER_DESC vbd; vbd.Usage = D3D10_USAGE_IMMUTABLE; vbd.ByteWidth = sizeof(Vertex) * mNumVertices; vbd.BindFlags = D3D10_BIND_VERTEX_BUFFER; vbd.CPUAccessFlags = 0; vbd.MiscFlags = 0; D3D10_SUBRESOURCE_DATA vinitData; vinitData.pSysMem = &vertices; HR(md3dDevice->CreateBuffer(&vbd, &vinitData, &mVB)); //create the index buffer std::vector<DWORD> indices(mNumFaces*3); // 3 indices per face int k = 0; for(DWORD i = 0; i < m-1; ++i) { for(DWORD j = 0; j < n-1; ++j) { indices[k] = i*n+j; indices[k+1] = i*n+j+1; indices[k+2] = (i*1)*n+j; indices[k+3] = (i*1)*n+j; indices[k+4] = i*n+j+1; indices[k+5] = (i*1)*n+j+1; k+= 6; } } D3D10_BUFFER_DESC ibd; ibd.Usage = D3D10_USAGE_IMMUTABLE; ibd.ByteWidth = sizeof(DWORD) * mNumFaces*3; ibd.BindFlags = D3D10_BIND_INDEX_BUFFER; ibd.CPUAccessFlags = 0; ibd.MiscFlags = 0; D3D10_SUBRESOURCE_DATA iinitData; iinitData.pSysMem = &indices; HR(md3dDevice->CreateBuffer(&ibd, &iinitData, &mIB)); } void Box::Draw() { UINT stride = sizeof(Vertex); UINT offset = 0; md3dDevice->IASetVertexBuffers(0, 1, &mVB, &stride, &offset); md3dDevice->IASetIndexBuffer(mIB, DXGI_FORMAT_R32_UINT, 0); md3dDevice->DrawIndexed(mNumFaces*3, 0 , 0); } //Box.h #ifndef _BOX_H #define _BOX_H #include "d3dUtil.h" Box.h class Box { public: Box(); ~Box(); void init(ID3D10Device* device, float m, float n, float dx); void Draw(); float getHeight(float x, float z)const; private: DWORD mNumVertices; DWORD mNumFaces; ID3D10Device* md3dDevice; ID3D10Buffer* mVB; ID3D10Buffer* mIB; }; #endif Thanks again for the help

    Read the article

  • Perl - Reading .txt files line-by-line and using compare function (printing non-matches only once)

    - by Kurt W
    I am really struggling and have spent about two full days on this banging my head against receiving the same result every time I run this perl script. I have a Perl script that connects to a vendor tool and stores data for ~26 different elements within @data. There is a foreach loop for @data that breaks the 26 elements into $e-{'element1'), $e-{'element2'), $e-{'element3'), $e-{'element4'), etc. etc. etc. I am also reading from the .txt files within a directory (line-by-line) and comparing the server names that exist within the text files with what exists in $e-{'element4'}. The Problem: Matches are working perfectly and only printing one line for each of the 26 elements when there is a match, however non-matches are producing one line for every entry within the .txt files (37 in all). So if there are 100 entries (each entry having 26 elements) stored within @data, then there are 100 x 37 entries being printed. So for every non-match in the: if ($e-{'element4'} eq '6' && $_ =~ /$e-{element7}/i) statement below, I am receiving a print out saying that there is not a match. 37 entries for the same identical 26 elements (because there are 37 total entries in all of the .txt files). The Goal: I need to print out only 1 line for each unique entry (a unique entry being $e-{element1} thru $e-{element26}). It is already printing one 1 line for matches, but it is printing out 37 entries when there is not a match. I need to treat matches and non-matches differently. Code: foreach my $e (@data) { # Open the .txt files stored within $basePath and use for comparison: opendir(DIRC, $basePath . "/") || die ("cannot open directory"); my @files=(readdir(DIRC)); my @MPG_assets = grep(/(.*?).txt/, @files); # Loop through each system name found and compare it with the data in SC for a match: foreach(@MPG_assets) { $filename = $_; open (MPGFILES, $basePath . "/" . $filename) || die "canot open the file"; while(<MPGFILES>) { if ($e->{'element4'} eq '6' && $_ =~ /$e->{'element7'}/i) { ## THIS SECTION WORKS PERFECTLY AND ONLY PRINTS MATCHES WHERE $_ ## (which contains the servernames (1 per line) in the .txt files) ## EQUALS $e->{'element7'}. print $e->{'element1'} . "\n"; print $e->{'element2'} . "\n"; print $e->{'element3'} . "\n"; print $e->{'element4'} . "\n"; print $e->{'element5'} . "\n"; # ... print $e->{'element26'} . "\n"; } else { ## **THIS SECTION DOES NOT WORK**. FOR EVERY NON-MATCH, THERE IS A ## LINE PRINTED WITH 26 IDENTICAL ELEMENTS BECAUSE ITS LOOPING THRU ## THE 37 LINES IN THE *.TXT FILES. print $e->{'element1'} . "\n"; print $e->{'element2'} . "\n"; print $e->{'element3'} . "\n"; print $e->{'element4'} . "\n"; print $e->{'element5'} . "\n"; # ... print $e->{'element26'} . "\n"; } # End of 'if ($e->{'element4'} eq..' statement } # End of while loop } # End of 'foreach(@MPG_assets)' } # End of 'foreach my $e (@data)' I think I need something to identical unique elements and define what fields make up a unique element but honestly I have tried everything I know. If you would be so kind to provide actual code fixes, that would be wonderful because I am headed to production with this script quite soon. Also. I am looking for code (ideally) that is very human-readable because I will need to document it so others can understand. Please let me know if you need additional information.

    Read the article

  • Reading a child process's /proc/pid/mem file from the parent

    - by Amittai Aviram
    In the program below, I am trying to cause the following to happen: Process A assigns a value to a stack variable a. Process A (parent) creates process B (child) with PID child_pid. Process B calls function func1, passing a pointer to a. Process B changes the value of variable a through the pointer. Process B opens its /proc/self/mem file, seeks to the page containing a, and prints the new value of a. Process A (at the same time) opens /proc/child_pid/mem, seeks to the right page, and prints the new value of a. The problem is that, in step 6, the parent only sees the old value of a in /proc/child_pid/mem, while the child can indeed see the new value in its /proc/self/mem. Why is this the case? Is there any way that I can get the parent to to see the child's changes to its address space through the /proc filesystem? #include <fcntl.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/wait.h> #include <unistd.h> #define PAGE_SIZE 0x1000 #define LOG_PAGE_SIZE 0xc #define PAGE_ROUND_DOWN(v) ((v) & (~(PAGE_SIZE - 1))) #define PAGE_ROUND_UP(v) (((v) + PAGE_SIZE - 1) & (~(PAGE_SIZE - 1))) #define OFFSET_IN_PAGE(v) ((v) & (PAGE_SIZE - 1)) # if defined ARCH && ARCH == 32 #define BP "ebp" #define SP "esp" #else #define BP "rbp" #define SP "rsp" #endif typedef struct arg_t { int a; } arg_t; void func1(void * data) { arg_t * arg_ptr = (arg_t *)data; printf("func1: old value: %d\n", arg_ptr->a); arg_ptr->a = 53; printf("func1: address: %p\n", &arg_ptr->a); printf("func1: new value: %d\n", arg_ptr->a); } void expore_proc_mem(void (*fn)(void *), void * data) { off_t frame_pointer, stack_start; char buffer[PAGE_SIZE]; const char * path = "/proc/self/mem"; int child_pid, status; int parent_to_child[2]; int child_to_parent[2]; arg_t * arg_ptr; off_t child_offset; asm volatile ("mov %%"BP", %0" : "=m" (frame_pointer)); stack_start = PAGE_ROUND_DOWN(frame_pointer); printf("Stack_start: %lx\n", (unsigned long)stack_start); arg_ptr = (arg_t *)data; child_offset = OFFSET_IN_PAGE((off_t)&arg_ptr->a); printf("Address of arg_ptr->a: %p\n", &arg_ptr->a); pipe(parent_to_child); pipe(child_to_parent); bool msg; int child_mem_fd; char child_path[0x20]; child_pid = fork(); if (child_pid == -1) { perror("fork"); exit(EXIT_FAILURE); } if (!child_pid) { close(child_to_parent[0]); close(parent_to_child[1]); printf("CHILD (pid %d, parent pid %d).\n", getpid(), getppid()); fn(data); msg = true; write(child_to_parent[1], &msg, 1); child_mem_fd = open("/proc/self/mem", O_RDONLY); if (child_mem_fd == -1) { perror("open (child)"); exit(EXIT_FAILURE); } printf("CHILD: child_mem_fd: %d\n", child_mem_fd); if (lseek(child_mem_fd, stack_start, SEEK_SET) == (off_t)-1) { perror("lseek"); exit(EXIT_FAILURE); } if (read(child_mem_fd, buffer, sizeof(buffer)) != sizeof(buffer)) { perror("read"); exit(EXIT_FAILURE); } printf("CHILD: new value %d\n", *(int *)(buffer + child_offset)); read(parent_to_child[0], &msg, 1); exit(EXIT_SUCCESS); } else { printf("PARENT (pid %d, child pid %d)\n", getpid(), child_pid); printf("PARENT: child_offset: %lx\n", child_offset); read(child_to_parent[0], &msg, 1); printf("PARENT: message from child: %d\n", msg); snprintf(child_path, 0x20, "/proc/%d/mem", child_pid); printf("PARENT: child_path: %s\n", child_path); child_mem_fd = open(path, O_RDONLY); if (child_mem_fd == -1) { perror("open (child)"); exit(EXIT_FAILURE); } printf("PARENT: child_mem_fd: %d\n", child_mem_fd); if (lseek(child_mem_fd, stack_start, SEEK_SET) == (off_t)-1) { perror("lseek"); exit(EXIT_FAILURE); } if (read(child_mem_fd, buffer, sizeof(buffer)) != sizeof(buffer)) { perror("read"); exit(EXIT_FAILURE); } printf("PARENT: new value %d\n", *(int *)(buffer + child_offset)); close(child_mem_fd); printf("ENDING CHILD PROCESS.\n"); write(parent_to_child[1], &msg, 1); if (waitpid(child_pid, &status, 0) == -1) { perror("waitpid"); exit(EXIT_FAILURE); } } } int main(void) { arg_t arg; arg.a = 42; printf("In main: address of arg.a: %p\n", &arg.a); explore_proc_mem(&func1, &arg.a); return EXIT_SUCCESS; } This program produces the output below. Notice that the value of a (boldfaced) differs between parent's and child's reading of the /proc/child_pid/mem file. In main: address of arg.a: 0x7ffffe1964f0 Stack_start: 7ffffe196000 Address of arg_ptr-a: 0x7ffffe1964f0 PARENT (pid 20376, child pid 20377) PARENT: child_offset: 4f0 CHILD (pid 20377, parent pid 20376). func1: old value: 42 func1: address: 0x7ffffe1964f0 func1: new value: 53 PARENT: message from child: 1 CHILD: child_mem_fd: 4 PARENT: child_path: /proc/20377/mem CHILD: new value 53 PARENT: child_mem_fd: 7 PARENT: new value 42 ENDING CHILD PROCESS.

    Read the article

  • Reading Data from DDFS ValueError: No JSON object could be decoded

    - by secumind
    I'm running dozens of map reduce jobs for a number of different purposes using disco. My data has grown enormous and I thought I would try using DDFS for a change rather than standard txt files. I've followed the DISCO map/reduce example Counting Words as a map/reduce job, without to much difficulty and with the help of others, Reading JSON specific data into DISCO I've gotten past one of my latest problems. I'm trying to read data in/out of ddfs to better chunk and distribute it but am having a bit of trouble. Here's an example file: file.txt {"favorited": false, "in_reply_to_user_id": null, "contributors": null, "truncated": false, "text": "I'll call him back tomorrow I guess", "created_at": "Mon Feb 13 05:34:27 +0000 2012", "retweeted": false, "in_reply_to_status_id_str": null, "coordinates": null, "in_reply_to_user_id_str": null, "entities": {"user_mentions": [], "hashtags": [], "urls": []}, "in_reply_to_status_id": null, "id_str": "168931016843603968", "place": null, "user": {"follow_request_sent": null, "profile_use_background_image": true, "profile_background_image_url_https": "https://si0.twimg.com/profile_background_images/305726905/FASHION-3.png", "verified": false, "profile_image_url_https": "https://si0.twimg.com/profile_images/1818996723/image_normal.jpg", "profile_sidebar_fill_color": "292727", "is_translator": false, "id": 113532729, "profile_text_color": "000000", "followers_count": 78, "protected": false, "location": "With My Niggas In Paris!", "default_profile_image": false, "listed_count": 0, "utc_offset": -21600, "statuses_count": 6733, "description": "Made in CHINA., Educated && Making My Own $$. Fear GOD && Put Him 1st. #TeamFollowBack #TeamiPhone\n", "friends_count": 74, "profile_link_color": "b03f3f", "profile_image_url": "http://a2.twimg.com/profile_images/1818996723/image_normal.jpg", "notifications": null, "show_all_inline_media": false, "geo_enabled": true, "profile_background_color": "1f9199", "id_str": "113532729", "profile_background_image_url": "http://a3.twimg.com/profile_background_images/305726905/FASHION-3.png", "name": "Bee'Jay", "lang": "en", "profile_background_tile": true, "favourites_count": 19, "screen_name": "OohMyBEEsNice", "url": "http://www.bitchimpaid.org", "created_at": "Fri Feb 12 03:32:54 +0000 2010", "contributors_enabled": false, "time_zone": "Central Time (US & Canada)", "profile_sidebar_border_color": "000000", "default_profile": false, "following": null}, "in_reply_to_screen_name": null, "retweet_count": 0, "geo": null, "id": 168931016843603968, "source": "<a href=\"http://twitter.com/#!/download/iphone\" rel=\"nofollow\">Twitter for iPhone</a>"} {"favorited": false, "in_reply_to_user_id": 50940453, "contributors": null, "truncated": false, "text": "@LegaMrvica @MimozaBand makasi om artis :D kadoo kadoo", "created_at": "Mon Feb 13 05:34:27 +0000 2012", "retweeted": false, "in_reply_to_status_id_str": "168653037894770688", "coordinates": null, "in_reply_to_user_id_str": "50940453", "entities": {"user_mentions": [{"indices": [0, 11], "screen_name": "LegaMrvica", "id": 50940453, "name": "Lega_thePianis", "id_str": "50940453"}, {"indices": [12, 23], "screen_name": "MimozaBand", "id": 375128905, "name": "Mimoza", "id_str": "375128905"}], "hashtags": [], "urls": []}, "in_reply_to_status_id": 168653037894770688, "id_str": "168931016868761600", "place": null, "user": {"follow_request_sent": null, "profile_use_background_image": true, "profile_background_image_url_https": "https://si0.twimg.com/profile_background_images/347686061/Galungan_dan_Kuningan.jpg", "verified": false, "profile_image_url_https": "https://si0.twimg.com/profile_images/1803845596/Picture_20124_normal.jpg", "profile_sidebar_fill_color": "DDFFCC", "is_translator": false, "id": 48293450, "profile_text_color": "333333", "followers_count": 182, "protected": false, "location": "\u00dcT: -6.906799,107.622383", "default_profile_image": false, "listed_count": 0, "utc_offset": -28800, "statuses_count": 3052, "description": "Fashion design maranatha '11 // traditional dancer (bali) at sanggar tampak siring & Natya Nataraja", "friends_count": 206, "profile_link_color": "0084B4", "profile_image_url": "http://a3.twimg.com/profile_images/1803845596/Picture_20124_normal.jpg", "notifications": null, "show_all_inline_media": false, "geo_enabled": true, "profile_background_color": "9AE4E8", "id_str": "48293450", "profile_background_image_url": "http://a0.twimg.com/profile_background_images/347686061/Galungan_dan_Kuningan.jpg", "name": "nana afiff", "lang": "en", "profile_background_tile": true, "favourites_count": 2, "screen_name": "hasnfebria", "url": null, "created_at": "Thu Jun 18 08:50:29 +0000 2009", "contributors_enabled": false, "time_zone": "Pacific Time (US & Canada)", "profile_sidebar_border_color": "BDDCAD", "default_profile": false, "following": null}, "in_reply_to_screen_name": "LegaMrvica", "retweet_count": 0, "geo": null, "id": 168931016868761600, "source": "<a href=\"http://blackberry.com/twitter\" rel=\"nofollow\">Twitter for BlackBerry\u00ae</a>"} {"favorited": false, "in_reply_to_user_id": 27260086, "contributors": null, "truncated": false, "text": "@justinbieber u were born to be somebody, and u're super important in beliebers' life. thanks for all biebs. I love u. follow me? 84", "created_at": "Mon Feb 13 05:34:27 +0000 2012", "retweeted": false, "in_reply_to_status_id_str": null, "coordinates": null, "in_reply_to_user_id_str": "27260086", "entities": {"user_mentions": [{"indices": [0, 13], "screen_name": "justinbieber", "id": 27260086, "name": "Justin Bieber", "id_str": "27260086"}], "hashtags": [], "urls": []}, "in_reply_to_status_id": null, "id_str": "168931016856178688", "place": null, "user": {"follow_request_sent": null, "profile_use_background_image": true, "profile_background_image_url_https": "https://si0.twimg.com/profile_background_images/416005864/Captura.JPG", "verified": false, "profile_image_url_https": "https://si0.twimg.com/profile_images/1808883280/Captura6_normal.JPG", "profile_sidebar_fill_color": "f5e7f3", "is_translator": false, "id": 406750700, "profile_text_color": "333333", "followers_count": 1122, "protected": false, "location": "Adentro de una supra.", "default_profile_image": false, "listed_count": 0, "utc_offset": -14400, "statuses_count": 20966, "description": "Mi \u00eddolo es @justinbieber , si te gusta \u00a1genial!, si no, solo respetalo. El cambi\u00f3 mi vida completamente y mi sue\u00f1o es conocerlo #TrueBelieber . ", "friends_count": 1015, "profile_link_color": "9404b8", "profile_image_url": "http://a1.twimg.com/profile_images/1808883280/Captura6_normal.JPG", "notifications": null, "show_all_inline_media": false, "geo_enabled": false, "profile_background_color": "f9fcfa", "id_str": "406750700", "profile_background_image_url": "http://a3.twimg.com/profile_background_images/416005864/Captura.JPG", "name": "neversaynever,right?", "lang": "es", "profile_background_tile": false, "favourites_count": 22, "screen_name": "True_Belieebers", "url": "http://www.wehavebieber-fever.tumblr.com", "created_at": "Mon Nov 07 04:17:40 +0000 2011", "contributors_enabled": false, "time_zone": "Santiago", "profile_sidebar_border_color": "C0DEED", "default_profile": false, "following": null}, "in_reply_to_screen_name": "justinbieber", "retweet_count": 0, "geo": null, "id": 168931016856178688, "source": "<a href=\"http://yfrog.com\" rel=\"nofollow\">Yfrog</a>"} I load it into DDFS with: # ddfs chunk data:test1 ./file.txt created: disco://localhost/ddfs/vol0/blob/44/file_txt-0$549-db27b-125e1 I test that the file is indeed loaded into ddfs with: # ddfs xcat data:test1 {"favorited": false, "in_reply_to_user_id": null, "contributors": null, "truncated": false, "text": "I'll call him back tomorrow I guess", "created_at": "Mon Feb 13 05:34:27 +0000 2012", "retweeted": false, "in_reply_to_status_id_str": null, "coordinates": null, "in_reply_to_user_id_str": null, "entities": {"user_mentions": [], "hashtags": [], "urls": []}, "in_reply_to_status_id": null, "id_str": "168931016843603968", "place": null, "user": {"follow_request_sent": null, "profile_use_background_image": true, "profile_background_image_url_https": "https://si0.twimg.com/profile_background_images/305726905/FASHION-3.png", "verified": false, "profile_image_url_https": "https://si0.twimg.com/profile_images/1818996723/image_normal.jpg", "profile_sidebar_fill_color": "292727", "is_translator": false, "id": 113532729, "profile_text_color": "000000", "followers_count": 78, "protected": false, "location": "With My Niggas In Paris!", "default_profile_image": false, "listed_count": 0, "utc_offset": -21600, "statuses_count": 6733, "description": "Made in CHINA., Educated && Making My Own $$. Fear GOD && Put Him 1st. #TeamFollowBack #TeamiPhone\n", "friends_count": 74, "profile_link_color": "b03f3f", "profile_image_url": "http://a2.twimg.com/profile_images/1818996723/image_normal.jpg", "notifications": null, "show_all_inline_media": false, "geo_enabled": true, "profile_background_color": "1f9199", "id_str": "113532729", "profile_background_image_url": "http://a3.twimg.com/profile_background_images/305726905/FASHION-3.png", "name": "Bee'Jay", "lang": "en", "profile_background_tile": true, "favourites_count": 19, "screen_name": "OohMyBEEsNice", "url": "http://www.bitchimpaid.org", "created_at": "Fri Feb 12 03:32:54 +0000 2010", "contributors_enabled": false, "time_zone": "Central Time (US & Canada)", "profile_sidebar_border_color": "000000", "default_profile": false, "following": null}, "in_reply_to_screen_name": null, "retweet_count": 0, "geo": null, "id": 168931016843603968, "source": "<a href=\"http://twitter.com/#!/download/iphone\" rel=\"nofollow\">Twitter for iPhone</a>"} {"favorited": false, "in_reply_to_user_id": 50940453, "contributors": null, "truncated": false, "text": "@LegaMrvica @MimozaBand makasi om artis :D kadoo kadoo", "created_at": "Mon Feb 13 05:34:27 +0000 2012", "retweeted": false, "in_reply_to_status_id_str": "168653037894770688", "coordinates": null, "in_reply_to_user_id_str": "50940453", "entities": {"user_mentions": [{"indices": [0, 11], "screen_name": "LegaMrvica", "id": 50940453, "name": "Lega_thePianis", "id_str": "50940453"}, {"indices": [12, 23], "screen_name": "MimozaBand", "id": 375128905, "name": "Mimoza", "id_str": "375128905"}], "hashtags": [], "urls": []}, "in_reply_to_status_id": 168653037894770688, "id_str": "168931016868761600", "place": null, "user": {"follow_request_sent": null, "profile_use_background_image": true, "profile_background_image_url_https": "https://si0.twimg.com/profile_background_images/347686061/Galungan_dan_Kuningan.jpg", "verified": false, "profile_image_url_https": "https://si0.twimg.com/profile_images/1803845596/Picture_20124_normal.jpg", "profile_sidebar_fill_color": "DDFFCC", "is_translator": false, "id": 48293450, "profile_text_color": "333333", "followers_count": 182, "protected": false, "location": "\u00dcT: -6.906799,107.622383", "default_profile_image": false, "listed_count": 0, "utc_offset": -28800, "statuses_count": 3052, "description": "Fashion design maranatha '11 // traditional dancer (bali) at sanggar tampak siring & Natya Nataraja", "friends_count": 206, "profile_link_color": "0084B4", "profile_image_url": "http://a3.twimg.com/profile_images/1803845596/Picture_20124_normal.jpg", "notifications": null, "show_all_inline_media": false, "geo_enabled": true, "profile_background_color": "9AE4E8", "id_str": "48293450", "profile_background_image_url": "http://a0.twimg.com/profile_background_images/347686061/Galungan_dan_Kuningan.jpg", "name": "nana afiff", "lang": "en", "profile_background_tile": true, "favourites_count": 2, "screen_name": "hasnfebria", "url": null, "created_at": "Thu Jun 18 08:50:29 +0000 2009", "contributors_enabled": false, "time_zone": "Pacific Time (US & Canada)", "profile_sidebar_border_color": "BDDCAD", "default_profile": false, "following": null}, "in_reply_to_screen_name": "LegaMrvica", "retweet_count": 0, "geo": null, "id": 168931016868761600, "source": "<a href=\"http://blackberry.com/twitter\" rel=\"nofollow\">Twitter for BlackBerry\u00ae</a>"} {"favorited": false, "in_reply_to_user_id": 27260086, "contributors": null, "truncated": false, "text": "@justinbieber u were born to be somebody, and u're super important in beliebers' life. thanks for all biebs. I love u. follow me? 84", "created_at": "Mon Feb 13 05:34:27 +0000 2012", "retweeted": false, "in_reply_to_status_id_str": null, "coordinates": null, "in_reply_to_user_id_str": "27260086", "entities": {"user_mentions": [{"indices": [0, 13], "screen_name": "justinbieber", "id": 27260086, "name": "Justin Bieber", "id_str": "27260086"}], "hashtags": [], "urls": []}, "in_reply_to_status_id": null, "id_str": "168931016856178688", "place": null, "user": {"follow_request_sent": null, "profile_use_background_image": true, "profile_background_image_url_https": "https://si0.twimg.com/profile_background_images/416005864/Captura.JPG", "verified": false, "profile_image_url_https": "https://si0.twimg.com/profile_images/1808883280/Captura6_normal.JPG", "profile_sidebar_fill_color": "f5e7f3", "is_translator": false, "id": 406750700, "profile_text_color": "333333", "followers_count": 1122, "protected": false, "location": "Adentro de una supra.", "default_profile_image": false, "listed_count": 0, "utc_offset": -14400, "statuses_count": 20966, "description": "Mi \u00eddolo es @justinbieber , si te gusta \u00a1genial!, si no, solo respetalo. El cambi\u00f3 mi vida completamente y mi sue\u00f1o es conocerlo #TrueBelieber . ", "friends_count": 1015, "profile_link_color": "9404b8", "profile_image_url": "http://a1.twimg.com/profile_images/1808883280/Captura6_normal.JPG", "notifications": null, "show_all_inline_media": false, "geo_enabled": false, "profile_background_color": "f9fcfa", "id_str": "406750700", "profile_background_image_url": "http://a3.twimg.com/profile_background_images/416005864/Captura.JPG", "name": "neversaynever,right?", "lang": "es", "profile_background_tile": false, "favourites_count": 22, "screen_name": "True_Belieebers", "url": "http://www.wehavebieber-fever.tumblr.com", "created_at": "Mon Nov 07 04:17:40 +0000 2011", "contributors_enabled": false, "time_zone": "Santiago", "profile_sidebar_border_color": "C0DEED", "default_profile": false, "following": null}, "in_reply_to_screen_name": "justinbieber", "retweet_count": 0, "geo": null, "id": 168931016856178688, "source": "<a href=\"http://yfrog.com\" rel=\"nofollow\">Yfrog</a> At this point everything is great, I load up the script that resulted from a previous Stack Post: from disco.core import Job, result_iterator import gzip def map(line, params): import unicodedata import json r = json.loads(line).get('text') s = unicodedata.normalize('NFD', r).encode('ascii', 'ignore') for word in s.split(): yield word, 1 def reduce(iter, params): from disco.util import kvgroup for word, counts in kvgroup(sorted(iter)): yield word, sum(counts) if __name__ == '__main__': job = Job().run(input=["tag://data:test1"], map=map, reduce=reduce) for word, count in result_iterator(job.wait(show=True)): print word, count NOTE: That this script runs file if the input=["file.txt"], however when I run it with "tag://data:test1" I get the following error: # DISCO_EVENTS=1 python count_normal_words.py Job@549:db30e:25bd8: Status: [map] 0 waiting, 1 running, 0 done, 0 failed 2012/11/25 21:43:26 master New job initialized! 2012/11/25 21:43:26 master Starting job 2012/11/25 21:43:26 master Starting map phase 2012/11/25 21:43:26 master map:0 assigned to solice 2012/11/25 21:43:26 master ERROR: Job failed: Worker at 'solice' died: Traceback (most recent call last): File "/home/DISCO/data/solice/01/Job@549:db30e:25bd8/usr/local/lib/python2.7/site-packages/disco/worker/__init__.py", line 329, in main job.worker.start(task, job, **jobargs) File "/home/DISCO/data/solice/01/Job@549:db30e:25bd8/usr/local/lib/python2.7/site-packages/disco/worker/__init__.py", line 290, in start self.run(task, job, **jobargs) File "/home/DISCO/data/solice/01/Job@549:db30e:25bd8/usr/local/lib/python2.7/site-packages/disco/worker/classic/worker.py", line 286, in run getattr(self, task.mode)(task, params) File "/home/DISCO/data/solice/01/Job@549:db30e:25bd8/usr/local/lib/python2.7/site-packages/disco/worker/classic/worker.py", line 299, in map for key, val in self['map'](entry, params): File "count_normal_words.py", line 12, in map File "/usr/lib64/python2.7/json/__init__.py", line 326, in loads return _default_decoder.decode(s) File "/usr/lib64/python2.7/json/decoder.py", line 366, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib64/python2.7/json/decoder.py", line 384, in raw_decode raise ValueError("No JSON object could be decoded") ValueError: No JSON object could be decoded 2012/11/25 21:43:26 master WARN: Job killed Status: [map] 1 waiting, 0 running, 0 done, 1 failed Traceback (most recent call last): File "count_normal_words.py", line 28, in <module> for word, count in result_iterator(job.wait(show=True)): File "/usr/local/lib/python2.7/site-packages/disco/core.py", line 348, in wait timeout, poll_interval * 1000) File "/usr/local/lib/python2.7/site-packages/disco/core.py", line 309, in check_results raise JobError(Job(name=jobname, master=self), "Status %s" % status) disco.error.JobError: Job Job@549:db30e:25bd8 failed: Status dead The Error states: ValueError: No JSON object could be decoded. Again, this works fine using the text file as input but now DDFS. Any ideas, I'm open to suggestions?

    Read the article

  • Slowdowns when reading from an urlconnection's inputstream (even with byte[] and buffers)

    - by user342677
    Ok so after spending two days trying to figure out the problem, and reading about dizillion articles, i finally decided to man up and ask to for some advice(my first time here). Now to the issue at hand - I am writing a program which will parse api data from a game, namely battle logs. There will be A LOT of entries in the database(20+ million) and so the parsing speed for each battle log page matters quite a bit. The pages to be parsed look like this: http://api.erepublik.com/v1/feeds/battle_logs/10000/0. (see source code if using chrome, it doesnt display the page right). It has 1000 hit entries, followed by a little battle info(lastpage will have <1000 obviously). On average, a page contains 175000 characters, UTF-8 encoding, xml format(v 1.0). Program will run locally on a good PC, memory is virtually unlimited(so that creating byte[250000] is quite ok). The format never changes, which is quite convenient. Now, I started off as usual: //global vars,class declaration skipped public WebObject(String url_string, int connection_timeout, int read_timeout, boolean redirects_allowed, String user_agent) throws java.net.MalformedURLException, java.io.IOException { // Open a URL connection java.net.URL url = new java.net.URL(url_string); java.net.URLConnection uconn = url.openConnection(); if (!(uconn instanceof java.net.HttpURLConnection)) { throw new java.lang.IllegalArgumentException("URL protocol must be HTTP"); } conn = (java.net.HttpURLConnection) uconn; conn.setConnectTimeout(connection_timeout); conn.setReadTimeout(read_timeout); conn.setInstanceFollowRedirects(redirects_allowed); conn.setRequestProperty("User-agent", user_agent); } public void executeConnection() throws IOException { try { is = conn.getInputStream(); //global var l = conn.getContentLength(); //global var } catch (Exception e) { //handling code skipped } } //getContentStream and getLength methods which just return'is' and 'l' are skipped Here is where the fun part began. I ran some profiling (using System.currentTimeMillis()) to find out what takes long ,and what doesnt. The call to this method takes only 200ms on avg public InputStream getWebPageAsStream(int battle_id, int page) throws Exception { String url = "http://api.erepublik.com/v1/feeds/battle_logs/" + battle_id + "/" + page; WebObject wobj = new WebObject(url, 10000, 10000, true, "Mozilla/5.0 " + "(Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3 ( .NET CLR 3.5.30729)"); wobj.executeConnection(); l = wobj.getContentLength(); // global variable return wobj.getContentStream(); //returns 'is' stream } 200ms is quite expected from a network operation, and i am fine with it. BUT when i parse the inputStream in any way(read it into string/use java XML parser/read it into another ByteArrayStream) the process takes over 1000ms! for example, this code takes 1000ms IF i pass the stream i got('is') above from getContentStream() directly to this method: public static Document convertToXML(InputStream is) throws ParserConfigurationException, IOException, SAXException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(is); doc.getDocumentElement().normalize(); return doc; } this code too, takes around 920ms IF the initial InputStream 'is' is passed in(dont read into the code itself - it just extracts the data i need by directly counting the characters, which can be done thanks to the rigid api feed format): public static parsedBattlePage convertBattleToXMLWithoutDOM(InputStream is) throws IOException { // Point A BufferedReader br = new BufferedReader(new InputStreamReader(is)); LinkedList ll = new LinkedList(); String str = br.readLine(); while (str != null) { ll.add(str); str = br.readLine(); } if (((String) ll.get(1)).indexOf("error") != -1) { return new parsedBattlePage(null, null, true, -1); } //Point B Iterator it = ll.iterator(); it.next(); it.next(); it.next(); it.next(); String[][] hits_arr = new String[1000][4]; String t_str = (String) it.next(); String tmp = null; int j = 0; for (int i = 0; t_str.indexOf("time") != -1; i++) { hits_arr[i][0] = t_str.substring(12, t_str.length() - 11); tmp = (String) it.next(); hits_arr[i][1] = tmp.substring(14, tmp.length() - 9); tmp = (String) it.next(); hits_arr[i][2] = tmp.substring(15, tmp.length() - 10); tmp = (String) it.next(); hits_arr[i][3] = tmp.substring(18, tmp.length() - 13); it.next(); it.next(); t_str = (String) it.next(); j++; } String[] b_info_arr = new String[9]; int[] space_nums = {13, 10, 13, 11, 11, 12, 5, 10, 13}; for (int i = 0; i < space_nums.length; i++) { tmp = (String) it.next(); b_info_arr[i] = tmp.substring(space_nums[i] + 4, tmp.length() - space_nums[i] - 1); } //Point C return new parsedBattlePage(hits_arr, b_info_arr, false, j); } I have tried replacing the default BufferedReader with BufferedReader br = new BufferedReader(new InputStreamReader(is), 250000); This didnt change much. My second try was to replace the code between A and B with: Iterator it = IOUtils.lineIterator(is, "UTF-8"); Same result, except this time A-B was 0ms, and B-C was 1000ms, so then every call to it.next() must have been consuming some significant time.(IOUtils is from apache-commons-io library). And here is the culprit - the time taken to parse the stream to string, be it by an iterator or BufferedReader in ALL cases was about 1000ms, while the rest of the code took 0ms(e.g. irrelevant). This means that parsing the stream to LinkedList, or iterating over it, for some reason was eating up a lot of my system resources. question was - why? Is it just the way java is made...no...thats just stupid, so I did another experiment. In my main method I added after the getWebPageAsStream(): //Point A ba = new byte[l]; // 'l' comes from wobj.getContentLength above bytesRead = is.read(ba); //'is' is our URLConnection original InputStream offset = bytesRead; while (bytesRead != -1) { bytesRead = is.read(ba, offset - 1, l - offset); offset += bytesRead; } //Point B InputStream is2 = new ByteArrayInputStream(ba); //Now just working with 'is2' - the "copied" stream The InputStream-byte[] conversion took again 1000ms - this is the way many ppl suggested to read an InputStream, and stil it is slow. And guess what - the 2 parser methods above (convertToXML() and convertBattlePagetoXMLWithoutDOM(), when passed 'is2' instead of 'is' took, in all 4 cases, under 50ms to complete. I read a suggestion that the stream waits for connection to close before unblocking, so i tried using HttpComponentsClient 4.0 (http://hc.apache.org/httpcomponents-client/index.html) instead, but the initial InputStream took just as long to parse. e.g. this code: public InputStream getWebPageAsStream2(int battle_id, int page) throws Exception { String url = "http://api.erepublik.com/v1/feeds/battle_logs/" + battle_id + "/" + page; HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url); HttpParams p = new BasicHttpParams(); HttpConnectionParams.setSocketBufferSize(p, 250000); HttpConnectionParams.setStaleCheckingEnabled(p, false); HttpConnectionParams.setConnectionTimeout(p, 5000); httpget.setParams(p); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); l = (int) entity.getContentLength(); return entity.getContent(); } took even longer to process(50ms more for just the network) and the stream parsing times remained the same. Obviously it can be instantiated so as to not create HttpClient and properties every time(faster network time), but the stream issue wont be affected by that. So we come to the center problem - why does the initial URLConnection InputStream(or HttpClient InputStream) take so long to process, while any stream of same size and content created locally is orders of magnitude faster? I mean, the initial response is already somewhere in RAM, and I cant see any good reasong why it is processed so slowly compared to when a same stream is just created from a byte[]. Considering I have to parse million of entries and thousands of pages like that, a total processing time of almost 1.5s/page seems WAY WAY too long. Any ideas? P.S. Please ask in any more code is required - the only thing I do after parsing is make a PreparedStatement and put the entries into JavaDB in packs of 1000+, and the perfomance is ok ~ 200ms/1000entries, prb could be optimized with more cache but I didnt look into it much.

    Read the article

  • Reading php generated XML in flash?

    - by AdonisSMU
    Here is part 1 of our problem (Loading a dynamically generated XML file as PHP in Flash). Now we were able to get Flash to read the XML file, but we can only see the Flash render correctly when tested(test movie) from the actual Flash program. However, when we upload our files online to preview the Flash does not render correctly, missing some vital information(thumbnails, titles, video etc..). Here is a link to the Flash file using a manually created XML file (The Flash renders correctly): http://www.gaban.com/stackoverflow/TEN_xml.html Here is the path to the manually created XML file: http://dev.touchstorm.com/ten_hpn_admin2/client_user2.xml Now here is the link to the Flash file using the PHP generated XML file (Renders incomplete): http://www.gaban.com/stackoverflow/TEN_php.html Path to the PHP generated file (exactly the same as the manually created one): http://dev.touchstorm.com/ten_hpn_admin2/client_user.php?id=2 Additional information: The SWF file exists on Domain 1 The XML & PHP file both exists on Domain 2 And the HTML file with the embed code lies on Domain 3 Wondering if this could be a crossdomain issue? We have one of those files in place on Domain 1 & 2 where we have access too, however for Domain 3 we can't have a crossdomain.xml file there. Here is the PHP code: $xml = new XMLWriter(); $xml->openMemory(); $xml->setIndent(true); $xml->setIndentString("\t"); $xml->startDocument(); $xml->startElement('data'); $xml->startElement('config'); $xml->startElement('hex'); $xml->writeCData('0x' . $widget_profile['background_color']); $xml->endElement(); $xml->startElement('width'); $xml->writeCData($widget_profile['width']); $xml->endElement(); $xml->startElement('height'); $xml->writeCData($widget_profile['height']); $xml->endElement(); $xml->startElement('fullscreen'); $xml->writeCData('false'); $xml->endElement(); $xml->startElement('special'); $xml->writeCData('false'); $xml->endElement(); $xml->startElement('specialName'); $xml->writeCData('Tools & Offers'); $xml->endElement(); $xml->startElement('specialLink'); $xml->writeCData('http://bettycrocker.com'); $xml->endElement(); $xml->startElement('client'); $xml->writeCData($widget_profile['site_url']); $xml->endElement(); $xml->endElement(); if (count($widget_content) > 0) { foreach ($widget_content as $tab) { $xml->startElement('tab'); $xml->writeAttribute('id', $tab['tabname']); if (count($tab['video']) > 0) { foreach ($tab['video'] as $video) { $video_sql = "select VID, flvdoname, title from video where VID='" . $video . "'"; $video_result = $howdini->query($video_sql); if ($video_result->rowCount() > 0) { foreach ($video_result as $video_row) { $video_row['flvdoname'] = substr($video_row['flvdoname'], 35, -4); $xml->startElement('vid'); $xml->writeAttribute('flv', $video_row['flvdoname']); $xml->writeAttribute('thumb', 'http://www.howdini.com/thumb/' . $video_row['VID'] . '.jpg'); $xml->writeAttribute('title', $video_row['title']); $xml->endElement(); } } } } $xml->endElement(); } } $xml->endElement(); $xml->endDocument(); header('Content-Type: text/xml; charset=UTF-8'); echo $xml->flush(); Thanks in advance for any answers! EDIT: I have included the change and now Firebug sees the XML. Now it's just not seeing the swf file but I can see the swf file in other parts of the page.

    Read the article

  • IOException reading from HttpWebResponse response stream over SSL

    - by Lawrence Johnston
    I get the following exception when attempting to read the response from my HttpWebRequest: System.IO.IOException: Received an unexpected EOF or 0 bytes from the transport stream. at System.Net.ConnectStream.Read(Byte[] buffer, Int32 offset, Int32 size) at System.IO.StreamReader.ReadBuffer() at System.IO.StreamReader.ReadToEnd() ... My code functions without issue when using http. I am talking to a third-party device; I do not have access to the server code. My code is as follows: private string MakeRequest() { // Disable SSL certificate verification per // http://www.thejoyofcode.com/WCF_Could_not_establish_trust_relationship_for_the_SSL_TLS_secure_channel_with_authority.aspx ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; }); Uri uri = new Uri("https://mydevice/mypath"); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); request.Method = WebRequestMethods.Http.Get; using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (Stream responseStream = response.GetResponseStream()) { using (StreamReader sr = new StreamReader(responseStream.)) { return sr.ReadToEnd(); } } } } Does anybody have any thoughts about what might be causing it?

    Read the article

  • Reading .ppt (MS PowerPoint) file in Cocoa Touch

    - by Biranchi
    Hi All, Any idea how to read a .ppt file in Cocoa Touch ? I tried to load the contents of the file in UIWebView but it didn't work. Here is the code : [aWebView loadData:[NSData dataWithContentsOfFile:filePath] MIMEType:@"application/vnd.ms-powerpoint" textEncodingName:@"utf-8" baseURL:[NSURL fileURLWithPath:filePath]]; [powerWeb loadData:[NSData dataWithContentsOfFile:filePath] MIMEType:@"application/vnd.ms-powerpoint" textEncodingName:@"utf-8" baseURL:[NSURL fileURLWithPath:filePath]]; All suggestions are highly appreciated. Thanks

    Read the article

  • Issue reading packets from a pcap file. dpkt

    - by Chris
    I am running the following test script to try to read packets from a sample .pcap file I have downloaded. import socket import dpkt import sys pcapReader = dpkt.pcap.Reader(file("test1.pcap", "rb")) for ts, data in pcapReader: ether = dpkt.ethernet.Ethernet(data) if ether.type != dpkt.ethernet.ETH_TYPE_IP: raise ip = ether.data src = socket.inet_ntoa(ip.src) dst = socket.inet_ntoa(ip.dst) print "%s -> %s" % (src, dst) For some reason, this is not being interpreted properly. When running it, I get KeyError: 138 module body in test.py at line 4 function __init__ in pcap.py at line 105 Program exited. Why is this? What's wrong?

    Read the article

  • Reading non-standard elements in a SyndicationItem with SyndicationFeed

    - by Jared
    With .net 3.5, there is a SyndicationFeed that will load in a RSS feed and allow you to run LINQ on it. Here is an example of the RSS that I am loading: <rss version="2.0" xmlns:media="http://search.yahoo.com/mrss/"> <channel> <title>Title of RSS feed</title> <link>http://www.google.com</link> <description>Details about the feed</description> <pubDate>Mon, 24 Nov 08 21:44:21 -0500</pubDate> <language>en</language> <item> <title>Article 1</title> <description><![CDATA[How to use StackOverflow.com]]></description> <link>http://youtube.com/?v=y6_-cLWwEU0</link> <media:player url="http://youtube.com/?v=y6_-cLWwEU0" /> <media:thumbnail url="http://img.youtube.com/vi/y6_-cLWwEU0/default.jpg" width="120" height="90" /> <media:title>Jared on StackOverflow</media:title> <media:category label="Tags">tag1, tag2</media:category> <media:credit>Jared</media:credit> <enclosure url="http://youtube.com/v/y6_-cLWwEU0.swf" length="233" type="application/x-shockwave-flash"/> </item> </channel> When I loop through the items, I can get back the title and the link through the public properties of SyndicationItem. I can't seem to figure out how to get the attributes of the enclosure tag, or the values of the media tags. I tried using SyndicationItem.ElementExtensions.ReadElementExtensions<string>("player", "http://search.yahoo.com/mrss/") Any help with either of these?

    Read the article

  • Why does this silverlight code get a "catastrophic failure" when reading a BitmapImage out of Isolat

    - by Edward Tanguay
    In a Silverlight app, I save a Bitmap like this: public static void SaveBitmapImageToIsolatedStorageFile(OpenReadCompletedEventArgs e, string fileName) { using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication()) { using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(fileName, FileMode.Create, isf)) { Int64 imgLen = (Int64)e.Result.Length; byte[] b = new byte[imgLen]; e.Result.Read(b, 0, b.Length); isfs.Write(b, 0, b.Length); isfs.Flush(); isfs.Close(); isf.Dispose(); } } } and read it back out like this: public static BitmapImage LoadBitmapImageFromIsolatedStorageFile(string fileName) { string text = String.Empty; using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication()) { if (!isf.FileExists(fileName)) return null; using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication()) { using (IsolatedStorageFileStream isoStream = isoStore.OpenFile(fileName, FileMode.Open)) { BitmapImage bitmapImage = new BitmapImage(); bitmapImage.SetSource(isoStream); return bitmapImage; // "Catastrophic Failure: HRESULT: 0x8000FFFF (E_UNEXPECTED))" } } } } but this always gives me a "Catastrophic Failure: HRESULT: 0x8000FFFF (E_UNEXPECTED))" error. I've seen this error before when I tried to read a png file* off a server which was actually a **text file, so I assume the Bitmap is not being saved correctly, I got the code here. Can anyone see how the BitmapImage is not being saved correctly? Or why it would be giving me this error?

    Read the article

  • Reading EventLog C# Errors

    - by Robert
    I have this code in my ASP.NET application written in C# that is trying to read the eventlog, but it returns an error. EventLog aLog = new EventLog(); aLog.Log = "Application"; aLog.MachineName = "."; // Local machine foreach (EventLogEntry entry in aLog.Entries) { if (entry.Source.Equals("tvNZB")) Label_log.Text += "<p>" + entry.Message; } One of the entries it returns is "The description for Event ID '0' in Source 'tvNZB' cannot be found. The local computer may not have the necessary registry information or message DLL files to display the message, or you may not have permission to access them. The following information is part of the event:'Service started successfully.'" I only want the 'Service started successfully'. Any ideas?

    Read the article

  • C# Winforms TabControl elements reading as empty until TabPage selected

    - by Geo Ego
    I have Winform app I am writing in C#. On my form, I have a TabControl with seven pages, each full of elements (TextBoxes and DropDownLists, primarily). I pull some information in with a DataReader, populate a DataTable, and use the elements' DataBindings.Add method to fill those elements with the current values. The user is able to enter data into these elements, press "Save", and I then set the parameters of an UPDATE query using the elements' Text fields. For instance: updateCommand.Parameters.Add("@CustomerName", SqlDbType.VarChar, 100).Value = CustomerName.Text; The problem I have is that once I load the form, all of the elements are apparently considered empty until I select each tab manually. Thus, if I press "Save" immediately upon loading the form, all of the fields on the TabPages that I have not yet selected try to UPDATE with empty data (not nice). As I select each TabPage, those elements will now send their data along properly. For the time being, I've worked out a (very) ugly workaround where I programmatically select each TabPage when the data is populated for the first time, but that's an unacceptable long-term solution. My question is, how can I get all of the elements on the TabPages to return their data properly before the user selects that TabPage?

    Read the article

  • Error reading in date using Zoo in R

    - by SASnewby
    I am trying to use the Zoo package to read in daily observations which do not occur on each day. The date format looks like this, and it is in the first column of dataset: 25-May-07 The command I use is: z <- read.zoo("multiplier7.csv", sep = ";", header = TRUE, format="%d-%b-%y") I get this error: Error in strptime(x, format, tz = "GMT") : input string is too long First question is: 1. Is Zoo the right package to use if I want to use lm regression with a spline time dummy? The bs command does not work because I need to convert it into a time series. 2. Why is this error occurring and how to fix?

    Read the article

  • IOException reading a large file from a UNC path into a byte array using .NET

    - by Matt
    I am using the following code to attempt to read a large file (280Mb) into a byte array from a UNC path public void ReadWholeArray(string fileName, byte[] data) { int offset = 0; int remaining = data.Length; log.Debug("ReadWholeArray"); FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read); while (remaining > 0) { int read = stream.Read(data, offset, remaining); if (read <= 0) throw new EndOfStreamException (String.Format("End of stream reached with {0} bytes left to read", remaining)); remaining -= read; offset += read; } } This is blowing up with the following error. System.IO.IOException: Insufficient system resources exist to complete the requested If I run this using a local path it works fine, in my test case the UNC path is actually pointing to the local box. Any thoughts what is going on here ?

    Read the article

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