Friday, May 6, 2011

Java date iterator factory, with rules specifying how to calculate the intervals

I am looking for a Java class where I can specify a set of date rules, such as "every 3rd sunday" and "the first occurrence of a monday every second month". I want to be able to get something like an infinite iterator out of it (.next() would return the next date matching the rules set).

I think I'd be able to build it myself - but calendars are a hassle, and it feels like something similar should exist already. I hate being the one to reinvent a crappier wheel.

Is anyone aware of something like this? I have been looking at JODA, and it seems to lay the groundwork for it, but does not appear to give the full functionality I want..

From stackoverflow
  • I don't think there's any readily made iterators for joda-time or Java Calendar API for that matter, however with joda it's so easy that you should just go with it. For example after re-familiarizing myself with joda after a few months pause I made this in about 10 minutes:

    public class InstantIterator implements Iterator<Instant>,
                                            Iterable<Instant> {
    
        private Instant current;
        private final Instant original;
        private Duration skip;
        private List<Instant> skipThese;
    
        public InstantIterator(Instant startFrom, Duration skip) {
            this.current = original = startFrom;
            this.skip = skip;
            skipThese = new Vector<Instant>();
        }
    
        public boolean hasNext() {
            return true;
        }
    
        public Instant next() {
            Instant currentNext = current.toInstant();
            current = current.plus(skip);
            while (skipThese.contains(currentNext)) {
                currentNext = current.toInstant();
                current = current.plus(skip);
            }
            return currentNext;
        }
    
        public void remove() {
            skipThese.add(current.toInstant());
        }
    
        public Iterator<Instant> iterator() {
            return this;
        }
    
        public void rewind() {
            current = original.toInstant();
        }
    
        public void resetRemoved() {
            skipThese.clear();
        }
    
        public void resetIterator() {
            rewind();
            resetRemoved();
        }
    }
    

    Joda Time is awesome :-)

    Jacob Hansson : You rocked my afternoon - thanks mate!
    Esko : While not important at all, I just want to say that this is the second Iterator I've ever made which supports remove(), usually I've found it to be too cumbersome to support it.
  • My company has something very much like you want but it's for .NET so it probably won't do you any good.

  • You could have a look at Quartz which is designed for job scheduling.

How to get dynamic intervals in Dundas / Microsoft Chart Controls for WinForms?

Hi,

I'm using the Microsoft Chart Controls for .NET 3.5, and struggles with getting the chart control to support window/control resizing.

I have graphs where the X value is dates, and want the chart to display the maximum available of intervals/labels on the chart axis when I resize the window.

The closes I've come is to call this from the PrePaint event:

double interval = chart.Series[0].Points.Count / ((double)chart.Width / 90);
foreach (var area in chart.ChartAreas.Where(ca => ca.Visible))
{
    area.AxisX.Interval = interval;
}

This makes the intervals and labels fit perfectly along the X axis, but the dates are not shown correctly. This first label seems to be right (some date in 2008), but the rest of the labels along the axis are displayed as some date in 1900 instead.

Anyone know the preferred way of doing this?

From stackoverflow
  • for dates in ms charts u have to explicitly specify the minimum dates to start with. otherwise it takes 29th december 1899 as origin. u can set minimum and max dates on chart like

    chart.ChartAreas[0].AxisY.Minimum = (new DateTime(2010, 5, 1)).ToOADate();
                    chart.ChartAreas[0].AxisY.Maximum = (new DateTime(2011, 4, 1)).ToOADate();
    

    this post has some valuable information on ms charts HTH
    regards

Parsing XML with AS3

Here is my entire Script as I can't seem to figure out where the problem is.

The symptoms are that where I addChild(book) , is not the appropriate place for this to be added properly and sequentially with the thumbs as well. As a result, and to my surprise, the only way I can get these to appear so far is by writing a faulty trace statement which somehow pops them up in the top left corner. Any suggestions would be greatly appreciated! Thank you!!

var rowsW:Number;
var my_xW:Number;
var my_yW:Number;
var my_thumb_widthW:Number;
var my_thumb_heightW:Number;
var my_imagesW:XMLList;
var my_totalW:Number;

var container_mcW:MovieClip;
var preloaders_mcW:MovieClip;
var book:TextField = new TextField();
var author:TextField = new TextField();
var publisher:TextField = new TextField();
book.selectable = true;

var x_counterW:Number = 0;
var y_counterW:Number = 0;

var my_tweensW:Array = [];
var container_mc_tweenW:Tween;

var myXMLLoaderW:URLLoader = new URLLoader();

myXMLLoaderW.load(new URLRequest("WORKS.xml"));
myXMLLoaderW.addEventListener(Event.COMPLETE, processXMLW);

createContainerW();
callThumbsW();

function processXMLW(e:Event):void {
var myXMLW:XML = new XML(e.target.data);

rowsW = myXMLW.@ROWS;
my_xW = myXMLW.@XPOSITION;
my_yW = myXMLW.@YPOSITION;
my_thumb_widthW = myXMLW.@WIDTH;
my_thumb_heightW = myXMLW.@HEIGHT;
my_imagesW = myXMLW.IMAGE;
my_totalW = my_imagesW.length();

myXMLLoaderW.removeEventListener(Event.COMPLETE, processXMLW);
myXMLLoaderW = null;

}

function createContainerW():void {
container_mcW = new MovieClip();
container_mcW.x = my_xW;
container_mcW.y = my_yW;
addChild(container_mcW);


preloaders_mcW = new MovieClip();
preloaders_mcW.x = container_mcW.x;
preloaders_mcW.y = container_mcW.y;
addChild(preloaders_mcW);
}

function callThumbsW():void {
for (var i:Number = 0; i < my_totalW; i++) {

 var thumb_urlW = my_imagesW[i].@THUMB;
 book.text = my_imagesW[i].@TITLE;
 author.text = my_imagesW[i].@AUTHOR;
 publisher.text = my_imagesW[i].@PUBLISHER;

 var thumb_loaderW = new Loader();
 thumb_loaderW.load(new URLRequest(thumb_urlW));

thumb_loaderW.contentLoaderInfo.addEventListener(Event.COMPLETE,thumbLoadedW);

 thumb_loaderW.name = i;

 book.x = (40)*x_counterW;
 book.y = (my_thumb_heightW+40)*y_counterW;
 thumb_loaderW.x = (my_thumb_widthW+10)*x_counterW;
 thumb_loaderW.y = (my_thumb_heightW+10)*y_counterW;


 container_mcW.addChild(book);
 container_mcW.addChild(author);
 container_mcW.addChild(publisher);
 trace("my x equals" (book.x));

 if (y_counterW+1 < rowsW) {
  y_counterW++;
 } else {
  y_counterW = 0;
  x_counterW++;
 }
 var preloader_pbW:ProgressBar = new ProgressBar();
 preloader_pbW.source = thumb_loaderW.contentLoaderInfo;
 preloader_pbW.x = thumb_loaderW.x;
 preloader_pbW.y = thumb_loaderW.y;
 preloader_pbW.width = my_thumb_widthW;
 preloader_pbW.height = my_thumb_heightW;
 preloaders_mcW.addChild(preloader_pbW);

 preloader_pbW.addEventListener(Event.COMPLETE, donePbW);

}
}

function thumbLoadedW(e:Event):void {
var my_thumbW:Loader = Loader(e.target.loader);
container_mcW.addChild(my_thumbW);

my_tweensW[Number(my_thumbW.name)]=new Tween(my_thumbW, "alpha", Strong.easeIn, 0,1,0.5, true);

my_thumbW.contentLoaderInfo.removeEventListener(Event.COMPLETE, thumbLoadedW);
}

function donePbW(e:Event):void {
var my_pbW:ProgressBar = ProgressBar(e.target);
preloaders_mcW.removeChild(my_pbW);
my_pbW.removeEventListener(Event.COMPLETE, donePbW);
}
From stackoverflow
  • It doesn't seem to me that you're loading your XML properly. You should be using a URLLoader, not a loader to load the XML. You'll then need to wait til Event.COMPLETE is trigged to parse the data and add your text fields.

    From sephiroth (http://www.sephiroth.it/tutorials/flashPHP/E4X/):

    import flash.net.URLLoader
    import flash.net.URLRequest
    import flash.xml.XML
    import flash.event.*
    import flash.error.*
    
    var mainXML:XML;
    var loader:URLLoader = new URLLoader();
    loader.addEventListener(Event.COMPLETE, onComplete);
    loader.load(new URLRequest("http://www.sephiroth.it/tutorials/flashPHP/E4X/files/test.xml"));
    
    
    function onComplete(evt:Event)
    {
        mainXML = new XML(loader.data)
        trace("xml loaded, start parsing using E4X syntax");
    }
    

    Well, now that you've massively edited your question, yes, it's obvious you already have that in there. I'd try tracing/watching loader.data before you try to parse it into an xml object to see exactly what data you're trying to parse into XML. It sounds like you're maybe getting some data you're not expecting.

    Trip : Hmm..I already had that part in there. I have reason to believe its in its sequential order. Will let you know when I find an answer. Thanks!
    Trip : Haha sorry about the massive edit, I figured out how to place code in the comments ;) . I've been doing a lot of tracing, and its definately there. Occasionally I can see a glimpse of it, but only in a failed trace statement. Wierd right? I can't imagine how this works.
    Trip : Still working on this. Its been one week so far, I havn't been able to break out anything. I have read every single url regarding parsing xml attributes, and I can not figure this out.
    quoo : Hm. Not quite sure what you mean by a failed trace. If I understand correctly, if you trace 'e.target.data' in the complete handler, you get the correct xml? If so, I'd try simplifying your code, removing the tweens for now, and just trying to place your mc's once they're filled with content. There's a lot going on in your code, maybe the xml is not what's breaking things?
    Beau Martínez : Awesome link, been looking for some definitive xml-parsing howto for as3 to no real avail.
  • The reason that my code at best only displayed one result from the XML List is because I instantiate a TextField outside of the loop that draws the var i from the XML's many nodes. To correctly display a textfield for each node, I need to instantiate the TextField for each var i. Like this :

    function callThumbsW():void {
    for (var i:Number = 0; i < my_totalW; i++) {
    
     var thumb_urlW = my_imagesW[i].thumb;
     var book = my_imagesW[i].TITLE;
    
     var textHolder:TextField = new TextField;
     container_mcW.addChild(textHolder);
    

    This causes instant gratification.

ASP.NET MVC Deployed project not working: Inheritance System.web.mvc.viewpage fails?

Hi,

i have a MVC project which runs perfectly local. When I deploy to the production server I receive a compilation error:

BC30456: 'Title' is not a member of 'ASP.views_home_index_aspx'.

It makes me think that the inheritance of System.Web.ViewPage(of T) fails somehow... The project is deployed under http://server/ProjectName. The website at http://server/ works fine when deployed....

Can somebody assist? Thanks

UPDATE
Does everybody notice: "not a member of 'ASP.views_home_index_aspx'. ?
Shouldn't this be "not a member of 'ProjectName.views_home_index_aspx'. ?

From stackoverflow
  • Have you got the MVC DLL in your projects BIN folder.

    It is installed on your machine at C:\Program Files\Microsoft ASP.NET\ASP.NET MVC 1.0\Assemblies

    EDIT: Does the class ASP.views_home_index_aspx inherit from System.Web.Mvc.ViewPage ?

    EDIT 2: Every page in a .net web application and/or MVC site is compiled into a class. The class names are generated from the location of the file. So views_home_index_aspx is the compiled class that represents your aspx file at views/home/index.aspx . It has converted the "/" and "." to underscores.

    So your error is saying that, the compiled class that your page generates does not contain the Title member you are trying to access.

    Is this a big error that your page throws with a stack trace? or do you get the error in visual studio. Can you post some code?

    Ropstah : Yes it's there. I'm using a websetup deployment project and the assembly is found as dependency so it's automatically included. :(
    Ropstah : You're getting close I think. I have /views/home/index.aspx. This page has an inherits attribute which says: "System.Web.Mvc.ViewPage(Of IEnumerable(Of Models.Project))". However I cannot find the class views_home_index_aspx anywhere....
  • Best go through these posts just in case its something you have missed.

    Ropstah : Thanks for the urls, but both sites don't mention anything related to this issue...

Concurrency between windows and Web app C# asp.net

Hi, I am wondering if there is a best practice in regards to concurrency between asp.net and a windows app using the same db? I have a db with items their quantity, any of these items can be sold with different quantities from a website shopping cart or store location. updating the item quantity when user adds the item to their shopping cart seems to be a problematic approach.

Thanks

From stackoverflow
  • not knowing the business rules regarding how an item can be reserved in a basket (such as basket expiry) can you not maintain 'reserved' and 'sold' counts?

    Ok so based on what you say. I'd think perhaps a compensation based system rather than a transaction based system for handling this. Yes you have transactions on sale but thw reserve you don't

    Sammy : The database is an SQL 2008 and is setup to be almost identical to NorthWind db, I ended up adding an extra field to the Items table "InSessionCount" which will be a nullable int. when the user "any user" checks out the item, we put the selected quantity in the InSessionCount, if the transaction is approved, we modify the quantity row else we reset the InSessionCount field to null and the order is cancelled.
  • I would suggest introducing a Gateway into your system. The Gateway would be a single application (or part of one of your existing applications: the winforms app or the web app) that acts as the intermediary to the DB for both the windows app and the web app. This way, you only have one point of failure between db requests and the db itself. Design that Gateway to manage concurrency and then you dont have to worry about other processes writing to your db.

    If i was in your position i might select the web app to be the gateway. Create a set of services/repositories to interface with the db and have the UI layer of the web app access those services. Then expose those services via web services (or WCF services) to your windows app for it to access the db instead of it accessing the db directly. This way you have decoupled your system and created a single point of entry to the data store. You'll probably solve a whole lot more problems other than concurrency with this approach.

Connection refused after some time on threaded process in tcp socket requests (c/linux)

I'm trying to make process that takes number of requests each second, on each request new thread is created. Each thread then opens socket connection to address (http port) sends HEAD requests, gets response and closes socket.
Problem I'm having comes when i put more then 3 requests per second, after some time i get error in send() part of function, i keep getting Connection Refused. If I input more requests per second i get errors earlier. If i put only 2 requests per second i don't get errors at all. I suspect that I'm running out of some resource but i can't find which.

Here is basic structure of code

//declarations

socketfd = socket(servinfo->ai_family,servinfo->ai_socktype,servinfo->ai_protocol);

arg = fcntl(socketfd, F_GETFL, NULL)) < 0);
arg |= O_NONBLOCK;
fcntl(socketfd, F_SETFL, arg)

if((conn = connect(socketfd, servinfo->ai_addr, servinfo->ai_addrlen)) < 0)
{
 if(errno == EINPROGRESS)
 {
  do
  {
            tv.tv_sec = CONNECT_TIMEOUT;
   tv.tv_usec = 0;
   FD_ZERO(&myset);
   FD_SET(socketfd, &myset);
   if((res = select(socketfd+1, NULL, &myset, NULL, &tv) > 0)) 
   {
    if( (arg = fcntl(socketfd, F_GETFL, NULL)) < 0) { 
     perror("fcntl get 2");
    } 
    arg &= (~O_NONBLOCK); 
    if( fcntl(socketfd, F_SETFL, arg) < 0) {
     perror("fcntl set 2");
    }
    char szBuf[4096];

    std::string htmlreq = "HEAD / HTTP/1.1\r\nHost:";
    htmlreq += info->hostName;
    htmlreq += "\r\n\r\n";

    if((conn = send(socketfd,htmlreq.c_str(),htmlreq.size(),0)) == -1 && errno != EINTR)
    {
     perror("send");
     close(socketfd);
     return;
    }

    if((conn = recv(socketfd,szBuf,sizeof(szBuf)+1,0)) < 0 && errno != EINTR)
    {
     perror("recv");
     close(socketfd);
     return ;
    }

    close(socketfd);

    // do stuff with data
    break;
   }
   else
   {
                //timeout
    break;
   }
  }while(1);
 }
 else
 {
  perror("connect");
  close(socketfd);
  return; 
 }
}

I removed some error checking from start, what i get as output is "Send: Connection Refused" after some time. I'd appreciate some pointers to what part could be causing problems, platform is ubuntu linux. I'd also be glad to post other parts of code if needed. Tnx in advance.

From stackoverflow
  • The resource you're probably running out of is on the server you're connecting to. The connection is being refused by the computer you're connecting to because it's either:

    1. Configure to limit the number of connections per second ( based on some criteria )
    2. Or the server you're connecting to is under too much load for some reason and can't take any more connections.

    Since you always get the error on the third connection it could be that the server you're connecting to limits the number of connections on a per IP basis.

    Edit1

    You're trying to do a non-blocking connect? Now that I look at it closer it sounds like your problem is with the select, as in select is returning that the socket is readable before it's actually connected and then you're calling send. One of the things to watch out for on non-blocking connects is that the socket becomes both readable and writeable on error. Which means you need to check for both after select returns otherwise you may be missing whatever the actual error is and seeing the send error instead.

    This is from Stevens UNP:

    FD_ZERO(&rset);
    FD_SET(sockfd, &rset);
    wset = rset;
    tval.tv_sec = nsec;
    tval.tv_usec = 0;
    
    if ( (n = Select(sockfd+1, &rset, &wset, NULL,
         nsec ? &tval : NULL)) == 0) {
     close(sockfd);  /* timeout */
     errno = ETIMEDOUT;
     return(-1);
    }
    
    if (FD_ISSET(sockfd, &rset) || FD_ISSET(sockfd, &wset)) {
     len = sizeof(error);
     if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &error, &len) < 0)
      return(-1);   /* Solaris pending error */
    } else
     err_quit("select error: sockfd not set");
    
    done:
    Fcntl(sockfd, F_SETFL, flags); /* restore file status flags */
    
    if (error) {
     close(sockfd);  /* just in case */
     errno = error;
     return(-1);
    }
    return(0);
    
    Robert S. Barnes : You're not checking for readability during the select which may mean you're missing a select error, see above.
  • There are quite a few problems in your code.

    First you set the socket to non blocking. I don't understand why you do this. The connect function has an internal timeout and so won't block.

    Another problem of your code is that the first if statement will skip the instruction block if the connection immediately succeeds ! Which may happen.

    You apparently want to first send the HEAD message. There is no real need to make this one non blocking unless you expect the remote server or the network to be very slow and want a time out on it. In this case the select with non blocking socket would make sens.

    Once you send the HEAD message, you expect some data in response that you collect with the recv function. Be aware that this function call may return before the whole data sent is received. You need an independent way to determine that all the data sent has been received. Would the server close the connection ? This would detected by the recv function returning 0.

    So the recv should be wrapped into a loop where you append to received data to some buffer or a file and quit when recv returns 0. Use a non blocking socket if you want to add a timeout on this recv operation which may indeed block.

    But first try without timeouts to be sure it works at full speed without blocking as your current version.

    I suspect the initial connect is slow because of name and IP adresse resolution, and gets faster in subsequent calls because data is cached.

    Robert S. Barnes : The connect function can take a very long time to timeout ( 10 or 11 minutes on Linux iirc ) and you often don't want to wait that long. You should read up on non-blocking connects and why they're used.

How can I restore process state after a crash?

What's a good way to persist state when restarting a crashed process?

I have a supervisor in an OTP application what watches several "subsystem" gen_servers.

For example, one is a "weather" subsystem that generates a new weather state every 15 minutes and handles queries for the current state of the weather. (Think the lemonade stand game)

If that gen_server crashes, I want it to be restarted, but it should be be restarted with the most recent weather state, not some arbitrary state hardcoded in init(). It wouldn't make sense for the simulation state to suddenly go from "hail storm" to "pleasant and breezy" just because of the crash.

I hesitate to use mnesia or ETS to store the state after every update because of the added complexity; is there an easier way?

From stackoverflow
  • As long as it just has to be during runtime a would suggest the usage of ETS. The value is by far greater than the complexity. The API is simple and if you're working with named tables the access is simple too. You only have to create the table before your gen_server is started by the supervisor.

    Two - more complex - alternatives:

    • Build a pair of processes, one for the job to do, one for the state maintenance. Due to the simplicity of the second one it would be really reliable.
    • A real silly one could be the exchange of the child spec of the supervisor with the current state as argument each time the state is changing. (smile) No, just kidding.
  • is there an easier way?

    when process died it sends message to supervisor that containing State of process, so you can use this value to store in supervisor (in mnesia or supervisor's state) and when your server will start (in init) it have to send sync call to supervisor to get State value. I haven't real example, but i hope it makes sense.

    Anyway i don't really see problem to store State in mnesia.

    sorry my English :)