Sunday, May 1, 2011

Aggregate multiple arrays into one array (Linq)

I'm having trouble aggregating multiple arrays into one "big array", I think this should be possible in Linq but I can't get my head around it :(

consider some method which returns an array of some dummyObjects

public class DummyObjectReceiver 
{
  public DummyObject[] GetDummyObjects  { -snip- }
}

now somewhere I have this:

public class Temp
{
  public List<DummyObjectReceiver> { get; set; }

  public DummyObject[] GetAllDummyObjects ()
  {
    //here's where I'm struggling (in linq) - no problem doing it using foreach'es... ;)
  }
}

hope it's somewhat clear what I'm trying to achieve (as extra I want to order this array by an int value the DummyObject has... - but the orderby should be no problem,... I hope ;)

From stackoverflow
  • You use the SelectMany method to flatten the list of array returning objects into an array.

    public class DummyObject {
     public string Name;
     public int Value;
    }
    
    public class DummyObjectReceiver  {
    
     public DummyObject[] GetDummyObjects()  {
      return new DummyObject[] {
       new DummyObject() { Name = "a", Value = 1 },
       new DummyObject() { Name = "b", Value = 2 }
      };
     }
    
    }
    
    public class Temp {
    
     public List<DummyObjectReceiver> Receivers { get; set; }
    
     public DummyObject[] GetAllDummyObjects() {
      return Receivers.SelectMany(r => r.GetDummyObjects()).OrderBy(d => d.Value).ToArray();
     }
    
    }
    

    Example:

    Temp temp = new Temp();
    temp.Receivers = new List<DummyObjectReceiver>();
    temp.Receivers.Add(new DummyObjectReceiver());
    temp.Receivers.Add(new DummyObjectReceiver());
    temp.Receivers.Add(new DummyObjectReceiver());
    
    DummyObject[] result = temp.GetAllDummyObjects();
    
    AnthonyWJones : +1. I missed the "multiple" aspect in my now deleted answer.
    Calamitous : exactly what I was looking for :) extra thanks for including orderby! (still can only +1)

Hibernate criteria _ how to use criteria to return only one element of an object instead the entire object

Hello,

I'm trying to get only the list of id of object bob for example instead of the list of bob. It's ok with a HQL request, but I would know if it's possible using criteria ?

An example :

final StringBuilder hql = new StringBuilder();
hql.append( "select bob.id from " )
    .append( bob.class.getName() ).append( " bob " )
    .append( "where bob.id > 10");

final Query query = session.createQuery( hql.toString() );
return query.list();
From stackoverflow

Loading an existing database into WWW SQL Designer?

I've used WWW SQL Designer several times to design databases for applications. I'm now in charge of working on an application with a lot of tables (100+ mysql tables) and I would love to be able to look at the relations between tables in a manner similar to what WWW SQL Designer provides. It seems that it comes with the provisions to hook up to a database and provide a diagram of its structure, but I've not yet been able to figure out exactly how one would do that.

From stackoverflow
  • Can you just export the sql query that builds your existing tables, and run that in WWW SQL Designer? Most database management software has that option...

  • Looking at the interface of the designer, I guess that when you run it on your own PHP/MySQL server, you should be able to import existing database with "Import from DB" button in Save/Load dialog.

  • You could use VISIO to import the database, it will diagram it for you.

  • btw, have you tried SchemaBank? They are web-based and support MySQL fairly well. It eats your sql dump and generates the tables and relationships for you.

  • http://code.google.com/p/database-diagram/

    This takes a SQL structure (SQL dump) and shows a diagram :)

    Paul Wicks : Very cool. Now it just needs to work with a few more sql types and do a better job of arranging the diagram

Crystal Reports - inconsistent formatting

We have a c# windows service generating reports from Crystal 11 RPT files.

This morning the service was restarted as normal, generated a couple of reports correctly then seems to have changed the line spacing in the headers of a table in one particular report, so the headers didn't fit correctly. The width of the text also changed, and some words wrapped where they would not normally wrap.

Some 20 reports were generated incorrectly then, roughly half an hour later, the reports went back to looking like normal.

Other RPT files were not affected.

The problem has not happened on previous days, so is not simply connected to the time.

Some of the reports had no rows in the table which was screwed up, so it's not simply a matter of data not fitting in the table either.

Can anyone help suggest an explanation for this, or is it just the kind of madness one expects from a product as hopeless as Crystal?

From stackoverflow
  • Did you change your default printer or other printer settings for the printer being used by the report? If the printer that is selected in the report for printing is not found, the report will print to the default printer. This may cause the page settings to change based on the sizes and fonts supported by the printer.

    LordSauce : Hi Huzefa - thanks for your reply - nothing was changed on the server generating reports.

ASP.NET MVC - jQuery Sortable

I have a list of menu items which can be sorted. I have the sort working which is based on this link.

However, I'm not sure how to save the order of the menu items to the database? I'm using nhibernate.

View Code

<h3>Sort Main Menus</h3>
<% using(Html.BeginForm()) { %>
    <p>You can drag the items into a different order</p>
    <p></p>
    <div id="items">
        <% foreach (var mainMenusList in ViewData.Model) 
           {%>
             <%Html.RenderPartial("MainMenuEditor", mainMenusList, new ViewDataDictionary(ViewData) { { "mainMenuName", "mainMenu" } });%>     
           <%} 
        %>
    </div>
    <input type="submit" value="Save changes" />
 <% } %>

 <script type="text/javascript">
    $(function() 
    {
        $("#items").sortable({ axis: "y" });
    });
</script>

MainMenuEditor Code

<div>
 <input type="hidden" name="<%= ViewData["mainMenuName"] + ".index" %>" value="<%= ViewData.Model.Id %>" />
 <% var fieldPrefix = string.Format("{0}[{1}].", ViewData["mainMenuName"], ViewData.Model.Id); %>
 <%= Html.Hidden(fieldPrefix + "MainMenuID", ViewData.Model.Id) %>
 <%= Html.TextBox(fieldPrefix + "Name", ViewData.Model.MainMenuName, new { size = "30"})%></div>
From stackoverflow
  • I think you need a <form>-tag, and submit that form you your controller. The controller needs to pass the data to the model, and the model will make that the data is saved in the database.

    Roslyn : Thanks. That's it working now.

Emacs ESS Mode - Tabbing for Comment Region

I am using the Emacs-Speaks-Statistics (ESS) mode for Emacs. When editing R code, any comment lines (those starting with #) automatically get tabbed to the far right when I create a new line above it. How should I change my .emacs.el file to fix this?

For example, I have:

# Comment

Now, after putting my cursor at the beginning of the line and pressing Enter, I get:

                                # Comment

Thanks for any hints.

From stackoverflow
  • Either

    (setq ess-fancy-comments nil)
    

    if you never want to indent single-# comments, or

    (add-hook 'ess-mode-hook 
              (lambda () 
                (local-set-key (kbd "RET") 'newline)))
    

    if you want to change the behavior of Enter so it doesn't indent.

    aL3xa : This is just sublime! Thanks!!!
    Martin Mächler : Rather I think you should use "#" for end-of-line comments, and these are nicely indented to the same column on purpose --> nice code "listing". For the other comments, really do get in to the habit of using "##" (much more than "###"): These indent as other "statements" within that block of code
  • Use '###' if you don't want the comments indented. According to the manual,

    By default, comments beginning with ‘###’ are aligned to the beginning of the line. Comments beginning with ‘##’ are aligned to the current level of indentation for the block containing the comment. Finally, comments beginning with ‘#’ are aligned to a column on the right (the 40th column by default, but this value is controlled by the variable comment-column,) or just after the expression on the line containing the comment if it extends beyond the indentation column.

Escaping HTML entities in the URL of a rails remote_function

Some content in my page is loaded dynamically with the use of this code :

javascript_tag( remote_function( :update => agenda_dom_id, :url => agenda_items_url(options), :method => :get ) )

When it outputs in the browser, it comes out as this :

new Ajax.Updater('agenda', 'http://localhost:3000/agenda_items?company=43841&amp;history=true', {asynchronous:true, evalScripts:true, method:'get'})

The & character in the URL is replaced by &amp; and so the second parameter of the request is discarded.

I made different tests and it looks as if Rails tries to make the HTML entities conversion as soon as it detects that the code is in a script tag. And trying to hardcode the link or the javascript tag didn`t change anything.

Anybody encountered this problem before?

From stackoverflow
  • All javascript characters are escaped (see the source of remote_function). That has some consequences. However in your case I don't see any problem, I have similar cases where this just works.

    Can you describe the problem you have with it?

    PS. I have posted I lighthouse ticket because I have a case where I need to insert javascript: https://rails.lighthouseapp.com/projects/8994/tickets/2500-remote_function-does-not-allow-dynamically-generation-of-url#ticket-2500-2

  • The problem is with the URL that gets generated :

    http://localhost:3000/agenda_items?company=43841&amp;history=true
    

    The history parameter won't get sent correctly since the & character is replaced by a &amp;.

    The funny thing is that when I try it with a link_to_remote instead of the remote_link or when I output the remote_function directly on the page (and not in a script tag), it works as expected and doesn't escape the & character with its HTML entity.

    I'm on Rails 2.1.1 and Firefox. Maybe it has been fixed in the latest version of Rails but switching is not an option right now.

  • I'm on Rails 2.3.2 and I don't have any problem when & is replaced by & amp;

    If you need to fix this in your situation, you could patch the remote_ function update and add a :escape_ url option and set that to false. Put the code below somewhere in your rails environment where it gets loaded.

    module ActionView
    class Base
     def remote_function(options)
      javascript_options = options_for_ajax(options)
    
      update = ''
      if options[:update] && options[:update].is_a?(Hash)
        update  = []
        update << "success:'#{options[:update][:success]}'" if options[:update][:success]
        update << "failure:'#{options[:update][:failure]}'" if options[:update][:failure]
        update  = '{' + update.join(',') + '}'
      elsif options[:update]
        update << "'#{options[:update]}'"
      end
    
      function = update.empty? ?
        "new Ajax.Request(" :
        "new Ajax.Updater(#{update}, "
    
      url_options = options[:url]
      url_options = url_options.merge(:escape => false) if url_options.is_a?(Hash)
      function << (options[:escape_url] == false ? "'#{url_for(url_options)}'" : "'#{escape_javascript(url_for(url_options))}'") ## Add this line to the rails core
      function << ", #{javascript_options})"
    
      function = "#{options[:before]}; #{function}" if options[:before]
      function = "#{function}; #{options[:after]}"  if options[:after]
      function = "if (#{options[:condition]}) { #{function}; }" if options[:condition]
      function = "if (confirm('#{escape_javascript(options[:confirm])}')) { #{function}; }" if options[:confirm]
    
      return function
    end 
    end
    

    end

  • Use the :with option (which must be a valid query string and is not escaped like the :url), like so

    url, query_string = agenda_items_url(options).split('?')
    javascript_tag( remote_function( :update => agenda_dom_id, :url => url, :with => query_string, :method => :get ) )
    

    I'm assuming agenda_items_url is your own helper function and it is outputting the full url without escaping it first.

  • Guys, it's just a default behavior of url_for in views... C'mon, pass :escape => false along with URL params and enjoy unescaped stuff :)