Monday, February 21, 2011

User Messages Database Schema?

This is probably very subjective and I have my own thoughts on this, but how would one go about constructing a database that supports user to user messages (one to one or one to many).

My original thought was to have a MESSAGE table and MESSAGE_PARTIES table

MESSAGE would include the following fields: -ID, Subject, Body, Created On, Parent MSG ID (for replies)

MESSAGE PARTIES fields would include: -ID, Message ID, Sender ID, Recipient ID, Sent On

Is this sound logic? I'm dying to know what the better/more efficient way is.

From stackoverflow
  • You're not quite right with MESSAGE PARTIES. Given your current setup, you're able to specify multiple senders and multiple dates (more precisely, you're able to specify multiple combinations of sender, recipient, and date). This is not like any messaging system I'm familiar with, and likely not what you intended (it also doesn't match your description).

    A more suitable layout would put the sender and "sent on" fields in the MESSAGE table, then just ID, Message ID, and Recipient ID in the MESSAGE PARTIES table.

Best book to learn java web programming (for an experienced perl developer)

I'm an experienced perl developer who commonly uses Catalyst/Moose etc for web development, and have some python/django knowledge. I'm interested in learning java with an eye on wicket/spring/hibernate and later on possibly moving towards groovy, scala or closure.. I'd rather not plough through all the basics.. What do you recommend book-wise to get going?

From stackoverflow
  • To learn the java web application architectural approach read Beginning Java EE 6 Platform with GlassFish 3: From Novice to Professional

    Tom : thanks for the recommendation - i shall check it out.
  • I wrote Java SE code for a year before I managed to understand the concepts behind Java EE. I only got my head around it when I read the Google App Engine starting guide.

    The most important thing to comprehend is the Servlet pattern and the JSP format. A servlet is a Java class bound to a specific URI by (most often) by XML.

    The Servlet class implements a method (doGet() or doPost()) accepting some parameters:

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        response.getWriter().println("Hello, World!");
    
    }
    

    Will yield "Hello, World!" when accessing the URI associated with this HttpServlet class.

    It's really the same principles as in PHP/Perl framework but with Java being a typed language the "You're not calling the Framework, the Framework is calling you" becomes more apparent.

    With regards to Hibernate/ORM libraries, no (?) Java frameworks are bundled with an ORM library as such. There are several independent implementations of the Java Persistence API with Java Persistence Annotations (JPA) being the most recent (and hottest) standard. JPA would be the persistence implementation most closely mimicking the Perl/PHP ORM method of defining a User or BlogPost class as a model. DataNucleus (a JPA implementation) has migrations built in.

    Tom : Thanks, good tip on the GAE guide. I did follow that and it got me started but I feel like I need something to get me moving on from there.

URLLoader handler in child movie not being called.

Hi I am writing a flex application that has a MainMovie that loads flex programs (ChildMovie) depending on what the user selects in the MainMovie. below is some pseudocode to help me describe my problem hopefully.

class MainMovie{

  private var request:URLRequest = new URLRequest();

  public function callPHPfile(param:String, loader:URLLoader,   
             handlerFunction:Function):void {

    var parameter:URLVariables=new URLVariables();
    parameter.param = param;
    request.method = URLRequestMethod.POST;
    request.data = parameter;
    request.url = php file on server;
    loader.addEventListener(Event.COMPLETE, handlerFunction);
    loader.load(request);
  }

}

Class ChildMovie {

   private var loaderInChild:URLLoader = new URLLoader();

   public function handlerInChild(e:Event):void {
      process data....
      loaderInChild.removeEventListerner(Event.COMPLETE, handlerInChild);
   }  



   private function buttonClickHandler(e:Event):void{
      Application.application.callPHPfile(param, loaderInChild, handlerInChild)
   }
}

I can see that the callPHPfile function is being executed and received xml data from in httpFox, the problem is that the code in the handlerInChild function is not being executed. What am I doing wrong here?

From stackoverflow
  • It was a runtime error. I forgot that i uninstalled flash player debugger in firefox and it didn't show. in the handlerInChild function, there is a line

    var data:XML = loader.data;
    

    it should be

    var data:XML = XML(loader.data);
    

    and the code will run as expected.

Mysql incremental Backup

Hello Everyone,

Can anyone help me to take incremental backup in mysql.

i had some idea about that but it is not cleared in my mind ,

please give solutions in steps

Thanks in advance!!!

Riddhi

From stackoverflow

Is it possible to add a single row to a Django form?

I have a form along the lines of:

class aForm(forms.Form):
  input1 = forms.CharField()
  input2 = forms.CharField()
  input3 = forms.CharField()

What I'm hoping to do is add an additional input3 to the form when the user clicks an "add another input3".

I've read a bunch of ways that let me add new forms using formsets, but I don't want to append a new form, I want to just add a new input3.

Is this possible?

From stackoverflow
  • I would define input3 in your form definition, not require it, and then hide it by default. The user can then show the input using JavaScript.

    If you want to allow the user to add an undefined amount of additional inputs, I would look further into formsets.

  • Perhaps something like this:

    from django import forms
    from django.utils.datastructures import SortedDict
    def some_view(request):
        data = {}
    
        # Using session to remember the row count for simplicity
        if not request.session.get('form_rows', None):
            request.session['form_rows'] = 3
    
        # If posted with add row button add one more row
        if request.method == 'POST' and request.POST.get('rows', None):
                request.session['form_rows'] += 1
                data = request.POST
    
        # Create appropriate number of form fields on the fly
        fields = SortedDict()
        for row in xrange(1, request.session['form_rows']):
            fields['value_{0}'.format(row)] = forms.IntegerField()
    
        # Create form class
        MyForm = type('MyForm', (forms.BaseForm,), { 'base_fields': fields })
    
        form = MyForm(initial=data)
    
        # When submitted...
        if request.method == 'POST' and not request.POST.get('rows', None):
            form = MyForm(request.POST)
            if form.is_valid():
                # do something
        return render_to_response('some_template.html', {
            'form':form,
        }, context_instance=RequestContext(request))
    

    With template:

    <form action="" method="post">
        {{ form }}
        <input type="submit" />
        <input type="submit" value='Add' name='rows' />
    </form>
    

    This is over simplified but it works.

    You could easily modify this example so you can make request using AJAX and just replace old form with new one.

  • for adding dynamic fields overwrite the init method.

    Something like this:

    class aForm(forms.Form):
      input1 = forms.CharField()
      input2 = forms.CharField()
    
      def __init__(self, addfields=0, *args, **kwargs):
        super(aForm, self).__init__(*args, **kwargs)
    
        #add new fields
        for i in range(3,addfields+3)
           self.fields['input%d' % i] = forms.CharField()
    

how to delete specific number of rows using jquery provided by argument

i have a sample code. This will delete entire row if nor args provided. If provided it will delete the given rows.

function deleteTableRows(tableID)
{
        rowsToDel = document.getElementById('getrows').value;
        if(document.getElementById(tableID) !== undefined)
        {
                var tbl = document.getElementById(tableID);
                var deleteAll = false;
                if(rowsToDel ==null || rowsToDel == "")
                {
                        rowsToDel = tbl.rows.length;
                        deleteAll = true;
                }
                if(deleteAll)
                {
                        while(rowsToDel > 0)
                        {
                                tbl.deleteRow(rowsToDel - 1);
                                rowsToDel = tbl.rows.length;
                        }
                }
                else
                {
                        while(rowsToDel > 0)
                        {
                                tbl.deleteRow(rowsToDel - 1);
                                rowsToDel = rowsToDel - 1;
                        }
                }
        }
}

How to do this in jquery

From stackoverflow
  • See a working example

    function deleteTableRows(table, rowsToDelete) {
        table = $(table);
        var rows = table.find('> tbody > tr');
        rows.slice(-(rowsToDelete || rows.length)).remove();
    }
    

    Moved the rowsToDelete parameter inside the function to remove the external dependency on the #getrows element.

    Also, changed the table parameter so we can pass the DOM element, or a selector, or a jQuery wrapped object to select which table.

Looking For An API That Will Feed Me Soccer Stats

Hello, I am looking for an API that will feed me soccer stats from leagues like the EPL, Bundesliga, Serie A, and La Liga such as personal player information (name, height, weight, dob, etc.), player statistics (goals, assists, minutes played), as well as results from games.

If anyone knows of a service (maybe even sites like premierleague.com have API's that aren't being advertised) I would be interested.

From stackoverflow
  • http://stats.com/ may have what you need; They have the data at least, I know nothing about their APIs other than what their marketing blurb says about it: pull and push, and HTML, XML, CSV...

How to guarantee two related models get saved?

How do I guarantee data only gets saved when the related objects are both filled with data?

class A(models.Model):
    title = models.CharField(max_length=255)
    slug = models.SlugField()

class B(A):
    author = models.CharField(max_length=255)
    url = models.URLField()

I insert data by accessing model B:

b = B()
b.title = 'title'
b.slug = 'slug'
b.author = 'author'
b.url = 'www.google.com'
b.save()

If an error occurs in model B then model A still gets saved. How can I prevent model A from saving when model B doesn't get saved?

From stackoverflow
  • Database transactions?

  • Depending on your environment, transactions are probably the answer

  • Override B's save method (as described in the docs), have it call A's full_clean method. if it raises an exception, just don't save the model.

    rotrotrot : Well that's not the problem. If B raises an exception A still gets saved.
    Ofri Raviv : Then call B's full_clean.

how to remove duplicates from an array without sorting

Hello, i have an array which might contain duplicate objects. I wonder if it's possible to find and remove the duplicates in the array: - without sorting (strict requirement) - without using a temporary secondary array - possibily in O(N), with N the nb of the elements in the array

In my case the array is a Lua array, which contains tables:

t={
{a,1},
 {a,2},
 {b,1},
 {b,3},
 {a,2}
} 

In my case, t[5] is a duplicate of t[2], while t[1] is not.

From stackoverflow
  • Iterate the array, stick every value in a hash, checking if the it exists first. If it does remove from original array (or don't write to the new one). Not very memory efficient, but only 0(n) since you are only iterating the array once.

    Valerio Schiavoni : One of the requirements was "- without using a temporary secondary array". I guess I should have written "- without using a temporary secondary storage", but maybe it's good enough.
  • Can't be done in O(n) but ...

    what you can do is

    • Iterate thru the array
    • For each member search forward for repetitions, remove those.

    Worst case scenario complexity is O(n^2)

  • To summarize, you have the following options:

    • time: O(n^2), no extra memory - for each element in the array look for an equal one linearly
    • time: O(n*log n), no extra memory - sort first, walk over the array linearly after
    • time: O(n), memory: O(n) - use a lookup table (edit: that's probably not an option as tables cannot be keys in other tables as far as I remember)

    Pick one. There's no way to do what you want in O(n) time with no extra memory.

    Judge Maygarden : Tables can be used as keys in other tables.
    Valerio Schiavoni : tables can used as keys but the value used to compare if 2 tables are equals is their memory reference and not the values they store.

debugging list in visual studio 2010

Hi everybody,

All my colegas and I are facing a hangup problem with visual studio 2010 while debugging.

Every time i try to watch in a list, by clicking the '+' symbol into the watch windows, VS2010 hangs up.

Any ideas to solve the problem ?

THx

From stackoverflow
  • Is the list of fixed content and each element having simple properties?

    If not, e.g. items are generated as needed, item properties are calculated dynamically, then you might be hitting problems with needing to run application code while otherwise stopped in the debugger. This is particularly a problem if locks and concurrency are involved (e.g. property is waiting on a lock held by a thread that is blocked by the debugger).

Good/Simple shopping cart example using asp.net mvc and jquery

Is there a Good/Simple shopping cart example using asp.net mvc and jquery? Any suggestion...

From stackoverflow

Error "Invalid resource directory name" when trying to create android app with phonegap in eclipse.

I followed the tutorial here but when I create the project in Eclipse, i get an error "invalid resource directory name. Resource: "drawable-hdpi" path "/HelloAndroid/res" type "Android AAPT Problem"

From stackoverflow
  • I believe you have the wrong platform set. Right click on the Project name in Eclipse and go to properties and then click on Android and select at least Android 1.6.

    a.meservy : That solved it, thanks for that!

Solr - multifaceting syntax

I'm having a hard time constructing the URL for a query that has more than one multifacet. I'm following the sample here:

http://www.craftyfella.com/2010/01/faceting-and-multifaceting-syntax-in.html

For instance, take a look at the eBay screendump, how would the URL look like if you select 'Sony' and 'LG' in the 'Brand' section and then select 'LCD' in the 'Type' section?

Assume BRAND and TYPE are defined in schema.xml.

This URL would work if you select 'Sony' and 'LG' in the 'Brand' section:

...&facet=on&facet.field={!ex=BRAND}BRAND&fq={!tag=BRAND}BRAND:Sony%20OR%20LG

But what if you need to have selections from both 'Brand' and 'Type'? I tried this but it does not give me what I want:

...&facet=on&facet.field={!ex=BRAND}BRAND&fq={!tag=BRAND}BRAND:Sony%20OR%20LG&facet.field={!ex=TYPE}TYPE&fq={!tag=TYPE}TYPE:LCD

Any help is appreciated.

From stackoverflow
  • When you specify fq twice, only documents matching both filters will be kept. It is like having one fq with AND for the conditions. Maybe it is not what you want. If you want to keep documents having one or the other filter, you will have to use only one fq and combined the condition with OR.

    UPDATE
    After re-thinking, it makes probably more sense to have an AND between the BRAND and the TYPE filters.

    Also, do not forget to specify again in which field you apply the second condition of the Brand fq:

    fq=BRAND:Sony+OR+BRAND:LG
    

    Finally, you can specify the same exclusion for both facet.field, given:

    ...&facet=on&facet.field={!ex=bt}BRAND&facet.field={!ex=bt}TYPE&fq={!tag=bt}BRAND:Sony+OR+BRAND:LG+OR+TYPE:LCD
    
    hungster : Thanks. You are right.

Tree view visible in win XP but not in Windows 7

hello every one.....

i have a problem in .net web application... i have created a tree view which runs perfect on windows XP but as i try to run this application on windows7 the tree view is not displayed/visible . i could not able to find the solution so please give me the solution...

thanks in advance....

From stackoverflow
  • If it's a web application and "runs perfect" on XP, my assumption would be that you mean it works when you view it from a browser in XP - I'd assume that you're hosting it on a different machine. That being the case, there are a huge potential list of concerns...

    • you could be using a custom web control (say, an ActiveX control) that works in earlier IE but doesn't run under IE8's stricter security
    • you could have a markup/standards compatibility problem
    • you could have something installed on the XP machine (an IE plugin) that's not on the win7 machine (or doesn't work under IE8)

    It's important to identify what the real culprit is. I would guess that it's the differing browsers, not the differing OS - is your WinXP machine running IE7 (or even 6)? Does it still work in XP if you upgrade to IE8? Does it work in a non-IE browser (Firefox, Opera, Chrome) on either OS?

    Ultimately there's not enough to go on in your question to solve the problem, but there are plenty of avenues to investigate.

Calling stored procedure ignoring output parameters

I need to call MySql procedure as a plain text. Procedure has output parameter.
I'm not interested in returned data. What do I need to pass as output parameter to ignore it?

PS:

I know that using of SqlParameters is good and safe, but it is not my case.

From stackoverflow
  • Is this what you are looking for?

    SqlConnection mySqlConnection = ConnectDB();
    SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
    mySqlCommand.CommandText =
       @" 
          SQL QUERY HERE
       ";
    mySqlConnection.Open();
    mySqlCommand.ExecuteNonQuery();
    mySqlConnection.Close();
    
    Orsol : Not exact. I need to call "MyStoredProcedure @outputParam"

live streaming in iPhone

Hello,

Will the ALAC format support live streaming in iPhone ? the ALAC audio recording format is streamed to Server machine? so will i be able to play the audio chunk data, does ALAC format support?

Thank You.

From stackoverflow
  • Assuming you mean "Apple Lossless" audio...

    I don't see why it wouldn't, but I don't know the details. You'll probably need to embed it in a transport stream instead of a MPEG 4 container (but then, I don't know how the HTTP live streaming works either).

    I don't think streaming lossless audio is sensible, though.

HTML-Two elements next to each, one absolute width and the other relative

I have an 'iframe' next to a 'form'. The form needs to have absolute width (width:450px), and the width of iframe will be relative as it will be whatever is left from the form. So for the iframe I will need something equivalent to 'width: 100% - 450px'. How can I achieve that?

Thanks in advance.

From stackoverflow
  • You can use jQuery to "query" for the current page and element dimensions, so some math and update the sizes accordingly.

    http://api.jquery.com/width/

    Lee : Thanks Andrew, this is just what I need.

How to Reload the Same layout on View Flipper in Android?

I have an Linear Layout inside the View Flipper. When i fling/swipe the layout the same layout reloads the same layout with the animations slide_left_out and slide_right_in. I just have only one layout view. it has the values the image view and text view. When i swipe the view it just change the next value to that views. Any Idea?

From stackoverflow
  • How did you add the swipe/fling functionality? In other words, when the screen is "flung", that's where your code has to come in and "flip" the viewflipper to a different layout.

    AFAIK There isn't a built-in way to fling the viewflipper without having to write some code to handle the fling and manually change the viewflipper layout (index).

    EDIT:

    Basic Gesture Detection

    Flipping Views using ViewVlipper.setDisplayedChild()

    Praveen Chandrasekaran : can you explain with some example code?
    Brad Hein : That part of my code is copywritten but I added two links with detailed samples (possibly better than my own code :)

Using two different Core Data Models in the same iPhone app. How can I do it?

I am trying to use two different Core Data Models in a iPhone application, I created and correctly set up the first Core Data Model that uses SQLite as persistent object store. This one works very well and the pre-populated default store loads correctly in a Table View.

Now I want to create a different Core Data Model with a different pre-populated SQLite default store to load it in a different Table View in the same iPhone application. How can I do this task? I read the Core Data documentation and downloaded the sample codes but I did not find anything about this task.

Any sample code useful to solve this problem will be appreciated.

Thank you in advance, Pier

From stackoverflow
  • You can do it two different ways:

    • You can set up a separate entire core data stack, effectively just copying the template code you already have in your AppDelegate.

    • You can add the second Core Data sqlite file into the existing core data stack. This will let you access both Entities (not tables, this is an object graph not a database) in the same stack. To do that you add a second -addPersistentStore... call in your -persistentStoreCoordinator method and make sure your -managedObjectModel method is doing a merge of the models in your bundle.

    Update

    Set it up anywhere you want. You can set it up in the AppDelegate and then do a dependency injection and push down the second stack to whoever needs reference to it.

    Generally I would not create the stack in the UIViewController as it is not its responsibility.

    Pier : Thank you very much, but I did not understand where do I set up the separate entire core data stack, using the template code that I have in my AppDelegate? Maybe in the table view controller where I want to load the data of the second Core Data Stack ?

how to query last inserted Guid in hibernate

hi can any body tell me how i can get the last in serted id in hibernate like in my sql i used the query like this:=="SELECT LAST_INSERT_ID()"

how i can represent this in hibernate

thanks in advance

From stackoverflow
  • Why you need this is unclear but it should be possible using a native query. Something like that:

    Integer lastId = (Integer) session.createSQLQuery("SELECT LAST_INSERT_ID()")
        .uniqueResult();  
    
  • thanks actually i got the solution inthis way

    lSession.flush(); long lAddGUID = lObjAddressTable.getUserGUID(); pObjAddressDetails.setUserGUID(lAddGUID); if(0 != lAddGUID ){ lRetVal = true; }

    but i have another doubt

    can u tell me how i can update my data from a table with 2 where condition and i have no primary key even if the primary key is there i am not using that one thanks

nCover + MSTest + CruiseControl = Zero Coverage

Hi,

I use CruiseControl.net, MSTest 3.5 and nCover 1.5.8. I am new to nCover and want to integrate it in CruiseControl.

The problem is that I get a 0% coverage result but it should be 100%. My demo app calls just one method and in my mstest project this method is tested. in my cruiseControl server all works fine without ncover and i can see the mstest results (passes with ok)

now i want to through in nCover. in my cruiseConttrol server I call a nant script that does this (simplified):

<target name="nCover">
  <exec program="C:\Programme\NCover\ncover.console.exe" 
       workingdir="C:\temp" 
       commandline="//a CCTestApp //x coverage.xml C:\MSTest.exe /testcontainer:UnitTests.dll /resultsfile:mstestResult.trx /nologo" />
</target>

Running this in cruisecontrol seems to work and i can see the ncover result. but the result is 0% coverage

any ideas?

bye bembi

From stackoverflow
  • I got it!

    If using MSTest you have to set the /noisolation flag for mstest in order to get it working! this flag prevents mstest from starting another thread which ncover can't handle.

  • You can also set the //coverall flag on NCover, which will allow it to handle process isolation under MSTest.

    : //coverall isn't avaliable for ncover 1.5.8

using regular expression in watin

I'm using regular expression in watin.

I have something like: ie.Button(Find.ByName(new Regex(input))).Click(); but I wan't to click on the second or third button that match and not the first one.

How can I do this?

From stackoverflow
  • Try this:

    ie.Button(Find.ByName(new Regex(input)) && Find.ByIndex(1 /* or 2 */)).Click();
    
  • Try this:

        ButtonCollection buttonCol = ie.Buttons;
        buttonCol = buttonCol.Filter(Find.ByName(new Regex(input)));
        buttonCol[1].Click();
        buttonCol[2].Click();
    

problems with cookies

i'm using restful-authentication plugin with rails 2.3.8

i've problems with cookies store

i've put a logger instruction in this function for check the cookie:

 def send_remember_cookie!
      cookies[:auth_token] = {
        :value   => @current_user.remember_token,
        :expires => @current_user.remember_token_expires_at }  
      logger.error "--------------#{cookies[:auth_token].keys}"   
    end

But when i launch the program i receive this error:

undefined method `keys' for nil:NilClass

why?

How can i set the cookie?

thanks

From stackoverflow
  • The cookies object is an instance ApplicationController::CookieJar. It's almost like a Hash but the behavior of the [] and []= methods are not symmetric. The setter sets the cookie value for sending to the browser. The getter retrieves the value which comes back form the browser. Hence when you access it in your code having just set the outgoing value the incoming value will be unset. There some more info on this here

    Also did you intentionally mean to say cookie[:auth_token].keys or did you mean cookie.keys?

Difference Between Parameter And Argument?

is there a difference between a parameter and an argument, or are they simply synonyms?

From stackoverflow
  • Argument is often used in the sense of "actual argument" vs. "formal parameter".

    The formal parameter is what's given in the function declaration/definition/prototype, the actual argument is what's passed when calling the function, an instance of a formal parameter, if you will.

    That being said, they're often used interchangably, or depending on language/community, and I've also heard "actual parameter" &c.

    So here, x and y would be formal parameters:

    int foo(int x, int y) {
        ...
    }
    

    Whereas here, in the function call, 5 and z are the actual arguments:

    foo(5, z);
    
    Jake Petroules : Speaking of terminology, what is the "&c" you used? Does that mean "and vice versa" or something like that?
    danlei : "&" is a ligature of "e" and "t", so it means "et", which is latin for "and". The "c" stands for "cetera", which means "(the) other(s)" (Nom. pl. n.). So you can substitute it with something like "and (the) other things", or "and so on".
  • Generally, the parameters are what are used inside the function and the arguments are the values passed when the function is called. Unless you take the opposite view.

    double sqrt(double x)
    {
        ...
        return x;
    }
    
    void other(void)
    {
         double two = sqrt(2.0);
    }
    

    Under my thesis, x is the parameter to sqrt() and 2.0 is the argument.

    The terms are often used at least somewhat interchangeably.

  • They are often used interchangeably in text, but in most standards the distinction is that an argument is an expression passed to a function, where a parameter is a reference declared in a function declaration.

  • Depends on what is the context of the question. If this is about C++ standard, yes they have different definitions in the standard.

Enumerable LINQ extensions are hidden on strings... why and how ?

Possible Duplicate:
Why doesn’t VS 2008 display extension methods in Intellisense for String class

Hi all.

Yesterday I noticed that Enumerable LINQ exstensions are hidden on strings (I mean hidden from the intellisense).

We all know string is an IEnumerable<char>, so automatically it should get Enumerable extensions, and actually compiles and works if you use them, but why .NET developers decided to hide them from intellisense?

And lastly, how we can hide extension methods from a specific type ?

P.S. sorry for my poor english...

EDIT: I forgot to say I'm targeting .net 3.5 on VS 2008

EDIT2: Here 2 images of what happen:

Intellisense on string:

Intellisense on string

Intellisense on IEnumerable:

Intellisense on enumerable

From stackoverflow
  • Not on my copy of Visual Studio (that's 2010, with ReSharper installed):

    alt text

    Perhaps you forgot the using System.Linq; at the top? Or maybe ReSharper is adding them, not sure...

    digEmAll : I edited my question. I'm using VS2008 and I have "using System.Linq" at the top.

how to call winmain function through a main function

I am using dev c++ and i need to call a function which has some butons and edit boxes created using windows.h through another program which uses graphics functions and both files exist in a project and i am unable to do it..can any one help me please...

From stackoverflow
  • From what I gather, you have a function that creates some GUI components and needs to be called from two different programs. If this is the case, one option is to create a separate .DLL project that makes a run-time library that can be shared with the other two programs.

UIImageView animation with stop on final frame

I'm using UIImageView's animationImages to show some frames over a second. I want to show the animation then have it rest on the final frame. In OS 3.1.3, this worked fine for that:

[self setAnimationRepeatCount:1];
[self setAnimationDuration:1];
[self startAnimating];
// auto set the last image in the frame
[self setImage:[UIImage imageNamed:[NSString stringWithFormat:@"frame-%d_29.png", self.frameSet]]];

When the animation was done it would display the image. No such luck with OS 4. I've tried setting an NSTimer and setting the static frame when that finishes, but there's a noticable flicker sometimes with that method. Any solution?

From stackoverflow
  • Edit

    Even better than the previous solution is simply to switch the order of the start and set:

    [self setImage:[UIImage imageNamed:[NSString stringWithFormat:@"frame-%d_29.png", self.frameSet]]];
    [self startAnimating];
    

    After messing around a bit more, I found that the NSTimer solution actually works if you set the delay to 29/30ths of a second, i.e. ~0.97:

    - (void)doAnimation
    {
        [self setAnimationRepeatCount:1];
        [self setAnimationDuration:1];
        [self startAnimating];
        [NSTimer scheduledTimerWithTimeInterval:0.97f
                                         target:self
                                       selector:@selector(onTimer:)
                                       userInfo:nil
                                        repeats:NO];
    }
    
    - (void)onTimer:(NSTimer *)theTimer
    {
        [self stopAnimating];
        [self setImage:[UIImage imageNamed:[NSString stringWithFormat:@"frame-%d_29.png", self.frameSet]]];
    }
    

set focus on any item of listview in android

I have a listview which contains textviews as its elements.

  1. Now i want the first item of the list to be automatically focused when i launch the application
  2. How can i set the focus on any item of the list when i click on the some other view for example a button?
From stackoverflow
  • ListView has a setSelected method that takes the index of the item in the list.

    sarvesh : Hi but selected listitem is same as focused listitem?

Workflow 4 CodeActivity not throwing TimeoutException

I am new to Windows Workflow and trying to write a Long Running process.
I am also trying to limit how long this process can run for.
I am calling WorkflowInvoker.Invoke to trigger my Workflow passing it a small timespan for testing.

If I try this certain activities, this seems to work perfectly.
But If I use a CodeActivity, it seems to ignore my timeout entirely.

Why is this? And how do I cause my CodeActivity to timeout if it takes too long?

An example working with a Delay Activity:
(In this example the TimeOutException is thrown)

Activity wf = new Sequence()
{
    Activities =
    {
        new Delay() 
        { 
            Duration = TimeSpan.FromSeconds(10) 
        },
    }
};

try
{
    WorkflowInvoker.Invoke(wf, TimeSpan.FromSeconds(5));
}
catch (TimeoutException ex)
{
    Console.WriteLine(ex.Message);
}

An example trying to use a CodeActivity:
(In this example the TimeOutException is not thrown)

public class LongActivity : CodeActivity
{
    protected override void Execute(CodeActivityContext context)
    {
        Thread.Sleep(TimeSpan.FromSeconds(10));
    }
}

Activity wf = new Sequence()
{
    Activities =
    {
        new LongActivity()
    }
};

try
{
    WorkflowInvoker.Invoke(wf, TimeSpan.FromSeconds(5));
}    
catch (TimeoutException ex)
{
    Console.WriteLine(ex.Message);
}
From stackoverflow
  • The workflow runtime can only take action when it is in charge and if your activity takes 10 seconds to execute, or sleep, the runtime can't do anything about it. It won't schedule any new activities though because there is no remaining time left and would throw a TimeoutException instead.

    Normally when you have long running work you would use an asynchronous activity, either an AsyncCodeActivity or a NativeActivity with a bookmark so the runtime is in control and can abort the workflow.

How to left or right justify a column header in a JTable

Hi All,

I searched and couldn't find an answer for this. By default column headers in a JTable are centered. How do I make certain column headers left or right justified instead?

TIA

From stackoverflow
  • TableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setHorizontalAlignment(SwingConstants.RIGHT);
    table.getColumn(id).setHeaderRenderer(renderer);
    

    Or, if you don't have the column names available:

    table.getColumnModel().getColumn(index).setHeaderRenderer(renderer);
    
    Dan Howard : I get an error because I don't seem to have an ID. I use table.getColumn(0).setHeaderRenderer(renderer); for column 1 and table.getColumn(1).setHeaderRenderer(renderer); for column 2
    Dan Howard : this works: table.getColumn(table.getColumnName(1)).setHeaderRenderer(renderer); thanks

what does core mean in iphone libraries?

There's Core Data, Core Audio, Core Animation, etc... does core just mean that it's the basic library of that whole general category?

From stackoverflow
  • It's just the naming that Apple used to indicate their purpose built libraries.

    Nothing special, just marketing really. It sounds a lot better to say they have "CoreData" than "a new data library".

Which RDBMS has the richest super-set of ANSI-SQL?

Back in 1989, when I used to program with Oracle 5.2.3 on UNIX and VAX/VMS platforms, I considered SQL*PLUS as having the richest super-set of built-in functions. ORACLE*FORMS also had the ability to embed SQL statements within triggers. That was then, 21 years ago. At present, which other RDBMS' have come close, have the same, or more functionality than Oracle's SQLPLUS, DB2?.. SQL-Server?.. T-SQL?.. MySQL?.. etc?

From stackoverflow
  • It's hard to tell what is "richest". All systems have some proprietary things which the other systems don't support, including, but not limited to:

    • MODEL clause in Oracle
    • CROSS APPLY in SQL Server
    • DISTINCT ON in PostgreSQL
    • ON DUPLICATE KEY UPDATE in MySQL
    Frank Computer : @Quassnoi: OK, apart from those proprietary directives, which has the most comprehensive library of built-in functions, e.g. NVL(..), TODATE(..),SOUNDEX, DECODE, ENCRYPT, etc?
    Quassnoi : @Frank: I really don't know how to count this. In terms of "the maximal number of recognized built-in functions", most probably it will be `PostgreSQL`.
    Frank Computer : @Quassnoi: OK, not so much max, rather functionally useful!.. would you agree that Oracle was the pioneer in offering a robust super-set of SQL and continues to provide the richest set?
    Hao : @Frank Computer: "would you agree that Oracle was the pioneer in offering a robust super-set of SQL and continues to provide the richest set?" That question is now different from your original question "At present, which other RDBMS' have come close, have the same, or more functionality than Oracle's SQLPLUS?". That makes the original question a very subjective one
  • DB2 has a complete Java virtual machine available for server side processing stored procedures, you don't get much more "complete" than that.

    CouchDB uses JavaScript, can't get much more flexible and complete that that either.

How to debug a WCF service connected with multiple clients - .NET

Hello

I've written a WCF service with a duplex contract which asynchronously calls back the clients. I have some issues when multiple clients get connected and i dono how to debug the service. Any insights on this?

Thank you.

NLV

From stackoverflow
  • A bit more info on what your problem is would be helpful, but to get you started try enabling diagnostics. Add the following to your service config and set "initializeData" to set where the log file is written. Opening the file should launch Microsoft Service Trace Viewer. You can do the same on the client side. If you have both a service log and client log in Trace Viewer go to Menu -> Add and select the other file. You will then get the message interactions matched up in the graph tab.

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      ...
      <system.diagnostics>
        <trace autoflush="true" />
        <sources>
          <source name="System.ServiceModel"
                  switchValue="Verbose">
            <listeners>
              <add name="sdt"
                  type="System.Diagnostics.XmlWriterTraceListener"
                  initializeData="D:\wcfLog.svcLog"  />
            </listeners>
          </source>
        </sources>
      </system.diagnostics>
    </configuration>
    

    More info here: Tracing

Can you use sketchflow controls/styles in a WPF application?

I really love the sketchy-ness of the Sketchflow buttons and controls, and would love to use those controls/styles in my own WPF app, can this be done in anyway? Perhaps just reference the Sketchflow binaries?

From stackoverflow
  • Hey, the Sketchflow Application uses the "SketchStyle.xaml" for all of the Sketch-Styles. You can find this xaml-file when you create a new Sketchflow-Application with Blend.

    And from this xaml-file you can copy the styles. You just have to copy all the style into the app.xaml of your Application or your ResourceDictionary. And than you can just use them, for example for your buttons, with:

    <Button Content="My Button" Style="{DynamicResource Button-Sketch}"/>
    

    I hope this helped you.

    Mark : thanks a lot for the advice :)
  • I believe this should work if you do the following:

    • Add SketchStyles.xaml to your wpf project (easiest way is to find it by creating a wpf SketchFlow project and copying it from there)
    • Reference Microsoft.Expression.Prototyping.SketchControls.dll in your project (found here on my system: C:\Program Files (x86)\Microsoft SDKs\Expression\Blend.NETFramework\v4.0\Libraries)
    • Add a directory named "Fonts"
    • In that directory, add the 3 fonts found in a SketchFlow project
    • To make the default Sketch font work, open SketchStyles.xaml in xaml editing mode, and find the line with "Buxton Sketch", it will have a reference to your old project, it should be changed to look like this: < FontFamily x:Key="FontFamily-Sketch">Fonts/#Buxton Sketch< /FontFamily>
    • Last, edit app.xaml in xaml editing mode and make sure it looks like this:

    < Application.Resources>

    < !-- Resources scoped at the Application level should be defined here. -->
    < ResourceDictionary>
        < ResourceDictionary.MergedDictionaries>
            < ResourceDictionary Source="/Microsoft.Expression.Prototyping.SketchControls;component/ScrollViewerStyles.xaml"/>
            < ResourceDictionary Source="SketchStyles.xaml"/>
        < /ResourceDictionary.MergedDictionaries>
    < /ResourceDictionary>
    

    < /Application.Resources>

    Mark : thanks so much, every step worked perfectly!