Search Results

Search found 3440 results on 138 pages for 'returning'.

Page 21/138 | < Previous Page | 17 18 19 20 21 22 23 24 25 26 27 28  | Next Page >

  • MEF GetExports<T, TMetaDataView> returning nothing with AllowMultiple = True

    - by sohum
    I don't understand MEF very well, so hopefully this is a simple fix of how I think it works. I'm trying to use MEF to get some information about a class and how it should be used. I'm using the Metadata options to try to achieve this. My interfaces and attribute looks like this: public interface IMyInterface { } public interface IMyInterfaceInfo { Type SomeProperty1 { get; } double SomeProperty2 { get; } string SomeProperty3 { get; } } [MetadataAttribute] [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class ExportMyInterfaceAttribute : ExportAttribute, IMyInterfaceInfo { public ExportMyInterfaceAttribute(Type someProperty1, double someProperty2, string someProperty3) : base(typeof(IMyInterface)) { SomeProperty1 = someProperty1; SomeProperty2 = someProperty2; SomeProperty3 = someProperty3; } public Type SomeProperty1 { get; set; } public double SomeProperty2 { get; set; } public string SomeProperty3 { get; set; } } The class that is decorated with the attribute looks like this: [ExportMyInterface(typeof(string), 0.1, "whoo data!")] [ExportMyInterface(typeof(int), 0.4, "asdfasdf!!")] public class DecoratedClass : IMyInterface { } The method that is trying to use the import looks like this: private void SomeFunction() { // CompositionContainer is an instance of CompositionContainer var myExports = CompositionContainer.GetExports<IMyInterface, IMyInterfaceInfo>(); } In my case myExports is always empty. In my CompositionContainer, I have a Part in my catalog that has two ExportDefinitions, both with the following ContractName: "MyNamespace.IMyInterface". The Metadata is also loaded correctly per my exports. If I remove the AllowMultiple setter and only include one exported attribute, the myExports variable now has the single export with its loaded metadata. What am I doing wrong?

    Read the article

  • Mysqli prepared insert statements always returning false

    - by user1754679
    I'm writing prepared statements that are supposed to insert data into a table, on a database that's been pre-selected in the variable $GLOBALS['mysqli']. The connection has been tested, and that's not the problem I'm having. I'm only running into trouble whenever my prepared statement involves INSERT INTO. I know the tablename, and field names are correct, but $stmt is ALWAYS false. What gives? $stmt = $GLOBALS['mysqli']->prepare("INSERT INTO audit_RefreshCount (user, count, lastrefresh) values (?,?,?)"); if ($stmt == TRUE) { $stmt->bindParam('ssi', $_SESSION['username'], '0', time()); //$stmt->bind_Param('ssi', $_SESSION['username'], '0', time()); // Also doesn't work. $stmt->execute(); }

    Read the article

  • Returning multiple aggregate functions as rows

    - by SDLFunTimes
    I need some help formulating a select statement. I need to select the total quantity shipped for each part with a distinct color. So the result should be a row with the color name and the total. Here's my schema: create table s ( sno char(5) not null, sname char(20) not null, status smallint, city char(15), primary key (sno) ); create table p ( pno char(6) not null, pname char(20) not null, color char(6), weight smallint, city char(15), primary key (pno) ); create table sp ( sno char(5) not null, pno char(6) not null, qty integer not null, primary key (sno, pno) );

    Read the article

  • Returning new base class when the parent class shared pointer is the return type

    - by Ben Dol
    Can you have a parent class shared pointer return type of a function and then return a new child class without it being a shared pointer? I'm not sure how shared pointers work in these situations, do they act like a regular pointer? Here is my example: BaseEventPtr Actions::getEvent(const std::string& nodeName) { if(asLowerCaseString(nodeName) == "action") return new ActionEvent(&m_interface); return nullptr; } ActionEvent is the subclass of BaseEvent in this situation. Cheers!

    Read the article

  • json returning string instead of object

    - by peter
    i have $age = implode(',', $wage); // which is object return: [1,4],[7,11],[15,11] $ww = json_encode($age); and then i retrieve it here var age = JSON.parse(<?php echo json_encode($ww); ?>); so if i make alert(typeof(<?php echo $age; ?>)) // object alert(typeof(age)) //string in my case JSON.parse retuned as string. how can i let json return as object? EDIT: var age = JSON.parse(<?php echo $ww; ?>); // didnt work , its something syntax error

    Read the article

  • MVC: returning multiple results on stream connection to implement HTML5 SSE

    - by eddo
    I am trying to set up a lightweight HTML5 Server-Sent Event implementation on my MVC 4 Web, without using one of the libraries available to implement sockets and similars. The lightweight approach I am trying is: Client side: EventSource (or jquery.eventsource for IE) Server side: long polling with AsynchController (sorry for dropping here the raw test code but just to give an idea) public class HTML5testAsyncController : AsyncController { private static int curIdx = 0; private static BlockingCollection<string> _data = new BlockingCollection<string>(); static HTML5testAsyncController() { addItems(10); } //adds some test messages static void addItems(int howMany) { _data.Add("started"); for (int i = 0; i < howMany; i++) { _data.Add("HTML5 item" + (curIdx++).ToString()); } _data.Add("ended"); } // here comes the async action, 'Simple' public void SimpleAsync() { AsyncManager.OutstandingOperations.Increment(); Task.Factory.StartNew(() => { var result = string.Empty; var sb = new StringBuilder(); string serializedObject = null; //wait up to 40 secs that a message arrives if (_data.TryTake(out result, TimeSpan.FromMilliseconds(40000))) { JavaScriptSerializer ser = new JavaScriptSerializer(); serializedObject = ser.Serialize(new { item = result, message = "MSG content" }); sb.AppendFormat("data: {0}\n\n", serializedObject); } AsyncManager.Parameters["serializedObject"] = serializedObject; AsyncManager.OutstandingOperations.Decrement(); }); } // callback which returns the results on the stream public ActionResult SimpleCompleted(string serializedObject) { ServerSentEventResult sar = new ServerSentEventResult(); sar.Content = () => { return serializedObject; }; return sar; } //pushes the data on the stream in a format conforming HTML5 SSE public class ServerSentEventResult : ActionResult { public ServerSentEventResult() { } public delegate string GetContent(); public GetContent Content { get; set; } public int Version { get; set; } public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException("context"); } if (this.Content != null) { HttpResponseBase response = context.HttpContext.Response; // this is the content type required by chrome 6 for server sent events response.ContentType = "text/event-stream"; response.BufferOutput = false; // this is important because chrome fails with a "failed to load resource" error if the server attempts to put the char set after the content type response.Charset = null; string[] newStrings = context.HttpContext.Request.Headers.GetValues("Last-Event-ID"); if (newStrings == null || newStrings[0] != this.Version.ToString()) { string value = this.Content(); response.Write(string.Format("data:{0}\n\n", value)); //response.Write(string.Format("id:{0}\n", this.Version)); } else { response.Write(""); } } } } } The problem is on the server side as there is still a big gap between the expected result and what's actually going on. Expected result: EventSource opens a stream connection to the server, the server keeps it open for a safe time (say, 2 minutes) so that I am protected from thread leaking from dead clients, as new message events are received by the server (and enqueued to a thread safe collection such as BlockingCollection) they are pushed in the open stream to the client: message 1 received at T+0ms, pushed to the client at T+x message 2 received at T+200ms, pushed to the client at T+x+200ms Actual behaviour: EventSource opens a stream connection to the server, the server keeps it open until a message event arrives (thanks to long polling) once a message is received, MVC pushes the message and closes the connection. EventSource has to reopen the connection and this happens after a couple of seconds. message 1 received at T+0ms, pushed to the client at T+x message 2 received at T+200ms, pushed to the client at T+x+3200ms This is not OK as it defeats the purpose of using SSE as the clients start again reconnecting as in normal polling and message delivery gets delayed. Now, the question: is there a native way to keep the connection open after sending the first message and sending further messages on the same connection?

    Read the article

  • Google Search API - Only returning 4 results

    - by user353829
    After much experimenting and googling, the following Python code successfully calls Google's Search APi - but only returns 4 results: after reading the Google Search API docs, I thought the 'start=' would return additional results: but this not happen. Can anyone give pointers? Thanks. Python code: /usr/bin/python import urllib import simplejson query = urllib.urlencode({'q' : 'site:example.com'}) url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s&start=50' \ % (query) search_results = urllib.urlopen(url) json = simplejson.loads(search_results.read()) results = json['responseData']['results'] for i in results: print i['title'] + ": " + i['url']

    Read the article

  • Returning currently displayed index of an array Javascript...

    - by Jeff Kindred
    I have a simple array with x number of items. I am displaying them individually via a link click... I want to update a number that say 1 of 10. when the next one is displayed i want it to display 2 of 10 etc... I have looked all around and my brain is fried right now... I know its simple I just cant get it out. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>Page Title</title> <link rel="stylesheet" href="style.css" type="text/css" media="screen" charset="utf-8"/> <script type="text/javascript"> var quotations = new Array() quotations[0]= "1" quotations[1]= "2" quotations[2]= "3" quotations[3]= "4" quotations[4]= "5" quotations[5]= "6" quotations[6]= "7" numQuotes = quotations.length; curQuote = 1; function move( xflip ) { curQuote = curQuote + xflip; if (curQuote > numQuotes) { curQuote = 1 ; } if (curQuote == 0) { curQuote = numQuotes ; } document.getElementById('quotation').innerHTML=quotations[curQuote - 1]; } var curPage = //this is where the current index should go </script> </head> <body> <div id="quotation"> <script type="text/javascript">document.write(quotations[0]);</script> </div> <div> <p><a href="javascript();" onclick="move(-1)">GO back</a> <script type="text/javascript">document.write(curPage + " of " + numQuotes)</script> <a href="javascript();" onclick="move(1)">GO FORTH</a></p> </div> </body> </html>

    Read the article

  • ValidationProperty not returning entered value for textbox

    - by nat
    hi I have a custom control, (relevant code at the bottom) it consists of some text/links and a hidden textbox (rather than a hidden input). when rendered, the user via another dialog and some JS sets the value of the textbox to an integer and clicks submit on the form. i am trying to assure that the user has entered a number (via the JS) and that the textbox is not still set to its default of "0" the requiredfieldvalidator works just fine, if i dont change the value it spots it on the client and fills the validation summary on the page with the appropriate message. unfortunately when i do fill the textbox, the validator also rejests the post as the controls textbox text value is still set to "0", even though on the form it has changed. clearly i am doing something wrong.. but cant work out what it is? could someone enlighten me please, this is driving me potty if i step through the code, when the get of the mediaidtext is hit,the findcontrol finds the textbox, but the value is still set to "0" many thanks code below nat [ValidationProperty("MediaIdText")] public class MediaLibraryFileControl: CompositeControl { private int mediaId = 0; public int MediaId { get { return mediaId; } set { mediaId = value; } } public string MediaIdText { get { string txt = "0"; Control ctrl = this.FindControl(this.UniqueID+ "_hidden"); try { txt = ((TextBox)ctrl).Text; MediaId = Convert.ToInt32(txt); } catch { MediaId = 0; } return txt; } } protected override void CreateChildControls() { this.Controls.Add(new LiteralControl("<span>")); this.Controls.Add(new LiteralControl("<span id=\"" + TextControlName + "\">" + getMediaDetails() + "</span>")); TextBox tb = new TextBox(); tb.Text = this.MediaId.ToString(); tb.ID = this.UniqueID + "_hidden"; tb.CssClass = "hidden"; this.Controls.Add(tb); if (Select == true) { this.Controls.Add(new LiteralControl(string.Format("&nbsp;[<a href=\"javascript:{0}(this,'{1}','{2}')\" class=\"select\">{3}</a>]", dialog, this.UniqueID, this.categoryId, "select"))); this.Controls.Add(new LiteralControl(string.Format("&nbsp;[<a href=\"javascript:{0}(this,'{1}')\" class=\"select\">{2}</a>]", clearDialog, this.ID, "clear"))); } this.Controls.Add(new LiteralControl("</span>")); } protected virtual string getMediaDetails() { //... return String.Empty; } } this is the code adding the validationcontrol the editcontrol is the instance of the control above public override Control RenderValidationControl(Control editControl) { Control ctrl = new PlaceHolder(); RequiredFieldValidator req = new RequiredFieldValidator(); req.ID = editControl.ClientID + "_validator"; req.ControlToValidate = editControl.ID; req.Display = ValidatorDisplay.None; req.InitialValue = "0"; req.EnableClientScript = false; req.ErrorMessage = "control cannot be blank"; ctrl.Controls.Add(req); return ctrl; }

    Read the article

  • WCF returning custom types

    - by Gena Verdel
    Hi. I'm a newbie to WCF, trying to perform relatively simple task. I'm trying to return list of objects read from the database but cannot overcome some really annoying exceptions. The question is very simple? What's wrong with the picture? [ServiceContract] public interface IDBService { [OperationContract] string Ping(string name); [OperationContract] InitBDResult InitBD(); } public InitBDResult InitBD() { _dc = new CentralDC(); InitBDResult result = new InitBDResult(); result.ord = _dc.Orders.First(); return result; } [DataContract] public class InitBDResult { //[DataMember] //public List<Order> Orders { get; set; } [DataMember] public Order ord { get; set; } }

    Read the article

  • Lightcore IoC is returning the same instance when it should give a new one

    - by Anthony
    I have the following code using the lightcore IoC container. But it fails with "NUnit.Framework.AssertionException: Contained objects are equal" which indicates that the objects that should be transient, are not. Is this a bug in lightcore, or am I doing it wrong? [Test] public void JellybeanDispenserHasNewInstanceEachTimeWithDefault() { var builder = new ContainerBuilder(); builder.Register<IJellybeanDispenser, VanillaJellybeanDispenser>(); builder.Register<SweetVendingMachine>().ControlledBy<TransientLifecycle>(); builder.Register<SweetShop>(); builder.DefaultControlledBy<TransientLifecycle>(); IContainer container = builder.Build(); SweetShop sweetShop = container.Resolve<SweetShop>(); SweetShop sweetShop2 = container.Resolve<SweetShop>(); Assert.IsFalse(ReferenceEquals(sweetShop, sweetShop2), "Root objects are equal"); Assert.IsFalse(ReferenceEquals(sweetShop.SweetVendingMachine, sweetShop2.SweetVendingMachine), "Contained objects are equal"); Assert.IsFalse(ReferenceEquals(sweetShop.SweetVendingMachine.JellybeanDispenser, sweetShop2.SweetVendingMachine.JellybeanDispenser), "services are equal"); } PS: I would tag this question with "lightcore", but suddenly my reputation isn't good enough to make a new tag. Huh.

    Read the article

  • wssql always returning zero rows

    - by Lavinski
    I'm using the windows search 4.0 service (wssql) to find some files, it works fine on my computer but on our server which has two drives C: and D: always returns 0 rows when searching D: Also i'm not sure if it's related but cd d: goes back to c: in the command prompt.

    Read the article

  • PHP readdir() not returning files in alphabetical order

    - by Buggabill
    I am reading through a directory with some pictures and such using a pretty simple implementation of readdir() like the following: if ($handle = opendir($path)) { while (false !== ($szFilename = readdir($handle))) { if ($szFilename[0] !== '.') { if (is_file($path.$szFilename)) { // do stuff } } } } The problem that I am having is that the files are not being read in alphabetical order as the docs for readdir() state: Returns the filename of the next file from the directory. The filenames are returned in the order in which they are stored by the filesystem. Another weird thing is that, on the local testing server, the same code works great. This is running on a server using the LAMP stack in both cases. I know that I can build an array and just sort it, but I was wondering if I was missing something in what I was doing. Thanks for any insight!

    Read the article

  • Method not returning string value c# <List>

    - by Santii20
    public List<string> Test_IsDataLoaded() { try { if (GRIDTest.Rows.Count != 0) { int countvalue = GRIDTest.Rows.Count; GRIDTest.Rows[0].WaitForControlReady(); List<string> ReleaseIDList = new List<string>(); int nCellCount = GRIDTest.Cells.Count; for(int nCount = 0;nCount<nCellCount ;nCount++) { if(nCount %5==0) ReleaseIDList.Add((GRIDTest.Cells[0].GetProperty("Value").ToString())); } return ReleaseIDList; } } catch (Exception) { } } Method throws me error = Not all code path return a value. Whats wrong in code.

    Read the article

  • sfConfig::get is not returning constants defined in app.yml

    - by morpheous
    I have an interesting problem. I am using Symfony 1.3.2. I have defined some constants in project/apps/frontend/config/app.yml and project/config/app.yml When I use the constant (correct spelling) in a piece of code like this $test=sfConfig::get('app_foobar'); the variable $test is assigned a null value. This is what I have checked so far: CHECK: cache files generated? (YES) CHECK: Do the cache files (config_app.yml.php) in the cache directory contain the constants defined in the app.yml file (YES) CHECK: Constant names used in the code matches the array keys found in config_app.yml? (YES) At this stage, I have run out of ideas. I dont want to supply a default value as a hack, because when I need to change the value of the constant, I will have to replace this in potentially hundreds of instances (too error prone). Is there anything that I have missed?. What could be causing this?

    Read the article

  • decode mysql query before returning it to view

    - by stormdrain
    I'm running a query to mysql that returns encrypted data. I'd like, if possible, to decode the results before sending it to the view. It seems like better form to handle the decoding in the controller (or even the model) rather than inside the view. I can't seem to wrap my head around how to do it, though. I was thinking I could iterate through the object, decodode it, and push it to another array that would be sent to the view. Problem with this is I won't know (and need to keep) the indexes of the query. So the query might return something like: [id] => 742 [client_id] => 000105 [last] => dNXcw6mQPaGQ4rXfgIGJMq1pZ1dYAim0 [first] => dDF7VoO37qdtYoYKfp1ena5mjBXXU0K3dDlcq1ssSvCgpOx75y0A== [middle] =>iXy6OWa48kCamViDZFv++K6okIkalC0am3OMPcBwK8sA== [phone] => eRY3zBhAw2H8tKE Any ideas?

    Read the article

  • StreamReader returning another char

    - by Fernando
    I'm trying to read the content of a file with a StreamReader, that receives a FileStream. The file has some spaces inside (char 32) and the StreamReader is reading them as 0 (char 48). The screenshot shows the FileStream buffer and the StreamReader buffer. Both have the value 32, but when I call Read(), it returns 48. Am I missing something here? By the way, the code is running under .NET Compact Framework. The code that reads the data: public void Read() { using (StreamReader reader = new StreamReader(InputStream, Encoding.ASCII)) { foreach (var property in DataObject.EnumerateProperties()) { OffsetInfo offset = property.GetTextOffset(); reader.BaseStream.Position = offset.Start - 1; StringBuilder builder = new StringBuilder(offset.Size); int count = 0; while (reader.Peek() >= 0 && count < offset.Size) { char c = (char)reader.Read(); if ((int)c != 32 && c != '\r' && c != '\n') { builder.Append(c); count++; } else { reader.BaseStream.Position++; } } property.SetValue(DataObject, Convert.ChangeType(builder.ToString(), property.PropertyType, CultureInfo.CurrentCulture), null ); } } }

    Read the article

  • Strange behavior while returning csv file from spring controller

    - by Fanooos
    I working in a spring application which have an action method that returns a CSV file. This action works fine but in some cases it throws a predefined exception (MyAppException). I have another method that is annotated @ExceptionHandler(MyAppException.class) In the exception handler method I return another csv file but with different contents. The code that returns the csv file is almost the same in the two methods. List<String[]> list= new ArrayList<String[]>(); list.add(new String[]{ integrationRequestErrorLog.getErrorMessage(), Long.toString(integrationRequestErrorLog.getId()), Integer.toString(integrationRequestErrorLog.getErrorCode()) }); CSVWriter writer = new CSVWriter(response.getWriter(), ','); writer.writeAll(list); writer.close(); the difference between the two method is the list of contents. In the first method the file is returned normally while in the exception handler method I have a strange behavior. The exception handler method works fine with Opera browser while it gives me a 404 with FireFox. Opera browser give me 404 also but it download the file while firefox does not? Really I do not understand what is the difference here.

    Read the article

  • Oracle function always returning null

    - by JavaRocky
    I can't get this function to behave as i desire. Can anyone point out why it always returns null instead of CURRENT_TIMESTAMP? CREATE OR REPLACE FUNCTION nowts RETURN TIMESTAMP IS vTimestamp TIMESTAMP; BEGIN SELECT type_date INTO vTimestamp FROM param_table WHERE param_table = 3 AND exists ( SELECT * FROM param_table WHERE param_table = 2 ); IF vTimestamp IS NULL THEN vTimestamp := CURRENT_TIMESTAMP; END IF; return vTimestamp; END nowts; Right now there is nothing in the table named param_table.

    Read the article

  • C socket programming: select() is returning 0 despite messages sent from server

    - by Fantastic Fourier
    Hey all, I'm using select() to recv() messages from server, using TCP/IP. When I send() messages from the server, it returns a reasonable number of bytes, saying it's sent successful. And it does get to the client successfully when I use while loop to just recv(). Everything is fine and dandy. while(1) recv() // obviously pseudocode However, when I try to use select(), select() returns 0 from timeout (which is set to 1 second) and for the life of me I cannot figure out why it doesn't see the messages sent from the server. I should also mention that when the server disconnects, select() doesn't see that either, where as if I were to use recv(), it would return 0 to indicate that the connection using the socket has been closed. Any inputs or thoughts are deeply appreciated. #include <arpa/inet.h> #include <errno.h> #include <fcntl.h> #include <netdb.h> #include <netinet/in.h> #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <strings.h> #include <sys/select.h> #include <sys/socket.h> #include <sys/time.h> #include <sys/types.h> #include <time.h> #include <unistd.h> #define SERVER_PORT 10000 #define MAX_CONNECTION 20 #define MAX_MSG 50 struct client { char c_name[MAX_MSG]; char g_name[MAX_MSG]; int csock; int host; // 0 = not host of a multicast group struct sockaddr_in client_address; struct client * next_host; struct client * next_client; }; struct fd_info { char c_name[MAX_MSG]; int socks_inuse[MAX_CONNECTION]; int sock_fd, max_fd; int exit; struct client * c_sys; struct sockaddr_in c_address[MAX_CONNECTION]; struct sockaddr_in server_address; struct sockaddr_in client_address; fd_set read_set; }; struct message { char c_name[MAX_MSG]; char g_name[MAX_MSG]; char _command[3][MAX_MSG]; char _payload[MAX_MSG]; struct sockaddr_in client_address; struct client peer; }; int main(int argc, char * argv[]) { char * host; char * temp; int i, sockfd; int msg_len, rv, ready; int connection, management, socketread; int sockfds[MAX_CONNECTION]; // for three threads that handle new connections, user inputs and select() for sockets pthread_t connection_handler, manager, socket_reader; struct sockaddr_in server_address, client_address; struct hostent * hserver, cserver; struct timeval timeout; struct message msg; struct fd_info info; info.exit = 0; // exit information: if exit = 1, threads quit info.c_sys = NULL; // looking up from the host database if (argc == 3) { host = argv[1]; // server address strncpy(info.c_name, argv[2], strlen(argv[2])); // client name } else { printf("plz read the manual, kthxbai\n"); exit(1); } printf("host is %s and hp is %p\n", host, hserver); hserver = gethostbyname(host); if (hserver) { printf("host found: %s\n", hserver->h_name ); } else { printf("host not found\n"); exit(1); } // setting up address and port structure information on serverside bzero((char * ) &server_address, sizeof(server_address)); // copy zeroes into string server_address.sin_family = AF_INET; memcpy(&server_address.sin_addr, hserver->h_addr, hserver->h_length); server_address.sin_port = htons(SERVER_PORT); bzero((char * ) &client_address, sizeof(client_address)); // copy zeroes into string client_address.sin_family = AF_INET; client_address.sin_addr.s_addr = htonl(INADDR_ANY); client_address.sin_port = htons(SERVER_PORT); // opening up socket sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) exit(1); else { printf("socket is opened: %i \n", sockfd); info.sock_fd = sockfd; } // sets up time out option for the bound socket timeout.tv_sec = 1; // seconds timeout.tv_usec = 0; // micro seconds ( 0.5 seconds) setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(struct timeval)); // binding socket to a port rv = bind(sockfd, (struct sockaddr *) &client_address, sizeof(client_address)); if (rv < 0) { printf("MAIN: ERROR bind() %i: %s\n", errno, strerror(errno)); exit(1); } else printf("socket is bound\n"); printf("MAIN: %li \n", client_address.sin_addr.s_addr); // connecting rv = connect(sockfd, (struct sockaddr *) &server_address, sizeof(server_address)); info.server_address = server_address; info.client_address = client_address; info.sock_fd = sockfd; info.max_fd = sockfd; printf("rv = %i\n", rv); if (rv < 0) { printf("MAIN: ERROR connect() %i: %s\n", errno, strerror(errno)); exit(1); } else printf("connected\n"); fd_set readset; FD_ZERO(&readset); FD_ZERO(&info.read_set); FD_SET(info.sock_fd, &info.read_set); while(1) { readset = info.read_set; printf("MAIN: %i \n", readset); ready = select((info.max_fd)+1, &readset, NULL, NULL, &timeout); if(ready == -1) { sleep(2); printf("TEST: MAIN: ready = -1. %s \n", strerror(errno)); } else if (ready == 0) { sleep(2); printf("TEST: MAIN: ready = 0. %s \n", strerror(errno)); } else if (ready > 0) { printf("TEST: MAIN: ready = %i. %s at socket %i \n", ready, strerror(errno), i); for(i = 0; i < ((info.max_fd)+1); i++) { if(FD_ISSET(i, &readset)) { rv = recv(sockfd, &msg, 500, 0); if(rv < 0) continue; else if(rv > 0) printf("MAIN: TEST: %s %s \n", msg._command[0], msg._payload); else if (rv == 0) { sleep(3); printf("MAIN: TEST: SOCKET CLOSEDDDDDD \n"); } FD_CLR(i, &readset); } } } info.read_set = readset; } // close connection close(sockfd); printf("socket closed. BYE! \n"); return(0); }

    Read the article

  • C++ class with char pointers returning garbage

    - by JMP
    I created a class "Entry" to handle Dictionary entries, but in my main(), I create the Entry() and try to cout the char typed public members, but I get garbage. When I look at the Watch list in debugger, I see the values being set, but as soon as I access the values, there is garbage. Can anyone elaborate on what I might be missing? #include <iostream> using namespace std; class Entry { public: Entry(const char *line); char *Word; char *Definition; }; Entry::Entry(const char *line) { char tmp[100]; strcpy(tmp, line); Word = strtok(tmp, ",") + '\0'; Definition = strtok(0,",") + '\0'; } int main() { Entry *e = new Entry("drink,What you need after a long day's work"); cout << "Word: " << e->Word << endl; cout << "Def: " << e->Definition << endl; cout << endl; delete e; e = 0; return 0; }

    Read the article

  • Returning JSON in CFFunction and appending it to layer is causing an error

    - by Mel
    I'm using the qTip jQuery plugin to generate a dynamic tooltip. I'm getting an error in my JS, and I'm unsure if its source is the JSON or the JS. The tooltip calls the following function: (sorry about all this code, but it's necessary) <cffunction name="fGameDetails" access="remote" returnType="any" returnformat="JSON" output="false" hint="This grabs game details for the games.cfm page"> <!---Argument, which is the game ID---> <cfargument name="gameID" type="numeric" required="true" hint="CFC will look for GameID and retrieve its details"> <!---Local var---> <cfset var qGameDetails = ""> <!---Database query---> <cfquery name="qGameDetails" datasource="#REQUEST.datasource#"> SELECT titles.titleName AS tName, titles.titleBrief AS tBrief, games.gameID, games.titleID, games.releaseDate AS rDate, genres.genreName AS gName, platforms.platformAbbr AS pAbbr, platforms.platformName AS pName, creviews.cReviewScore AS rScore, ratings.ratingName AS rName FROM games Inner Join platforms ON platforms.platformID = games.platformID Inner Join titles ON titles.titleID = games.titleID Inner Join genres ON genres.genreID = games.genreID Inner Join creviews ON games.gameID = creviews.gameID Inner Join ratings ON ratings.ratingID = games.ratingID WHERE (games.gameID = #ARGUMENTS.gameID#); </cfquery> <cfreturn qGameDetails> </cffunction> This function returns the following JSON: { "COLUMNS": [ "TNAME", "TBRIEF", "GAMEID", "TITLEID", "RDATE", "GNAME", "PABBR", "PNAME", "RSCORE", "RNAME" ], "DATA": [ [ "Dark Void", "Ancient gods known as 'The Watchers,' once banished from our world by superhuman Adepts, have returned with a vengeance.", 154, 54, "January, 19 2010 00:00:00", "Action & Adventure", "PS3", "Playstation 3", 3.3, "14 Anos" ] ] } The problem I'm having is every time I try to append the JSON to the layer #catalog, I get a syntax error that says "missing parenthetical." This is the JavaScript I'm using: $(document).ready(function() { $('#catalog a[href]').each(function() { $(this).qtip( { content: { url: '/gamezilla/resources/components/viewgames.cfc?method=fGameDetails', data: { gameID: $(this).attr('href').match(/gameID=([0-9]+)$/)[1] }, method: 'get' }, api: { beforeContentUpdate: function(content) { var json = eval('(' + content + ')'); content = $('<div />').append( $('<h1 />', { html: json.TNAME })); return content; } }, style: { width: 300, height: 300, padding: 0, name: 'light', tip: { corner: 'leftMiddle', size: { x: 40, y : 40 } } }, position: { corner: { target: 'rightMiddle', tooltip: 'leftMiddle' } } }); }); }); Any ideas where I'm going wrong? I tried many things for several days and I can't find the issue. Many thanks!

    Read the article

  • Memory Leak in returning NSMutableArray from class

    - by Structurer
    Hi I am quite new to Objective C for the iPhone, so I hope you wont kill me for asking a simple question. I have made an App that works fine, except that Instruments reports memory leaks from the class below. I use it to store settings from one class and then retrieve them from another class. These settings are stored on a file so they can be retrieved every time the App is ran. What can I do do release the "setting" and is there anything that can be done to call (use) the class in a smarter way? Thanks ----- Below is Settings.m ----- import "Settings.h" @implementation Settings @synthesize settings; -(NSString *)dataFilePath // Return path for settingfile, including filename { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; return [documentsDirectory stringByAppendingPathComponent:kUserSettingsFileName]; } -(NSMutableArray *)getParameters // Return settings from disk after checking if file exist (if not create with default values) { NSString *filePath = [self dataFilePath]; if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) // Getting data from file { settings = [[NSMutableArray alloc] initWithContentsOfFile:filePath]; } else // Creating default settings { settings = [[NSMutableArray alloc] initWithObjects: [NSNumber numberWithInteger:50], [NSNumber numberWithInteger:50], nil]; [settings writeToFile:[self dataFilePath] atomically:YES]; } return settings; } ----- Below is my other class from where I call my Settings class ----- // Get settings from file Settings *aSetting = [[Settings alloc] init]; mySettings = [aSetting getParameters]; [aSetting release];

    Read the article

< Previous Page | 17 18 19 20 21 22 23 24 25 26 27 28  | Next Page >