Tuesday, May 3, 2011

Delete a Web that doesn't exist.

While setting up a test environment I was attempting to set up many different types of sites for testing various things when I ran into a strange bug in SharePoint.

I was creating a subsite under a blank site template and saw the option for "News Site" so I selected it and got an error saying that the Publishing Feature was not enabled at the site collection level.

Fine. So, I went and activated it and then attempted to create the site again and I got the error:

The Web site address "/mpsite/news" is already in use

Ok, so the site must have been created anyway so I try to visit the URL and get:

The webpage cannot be found

Fine. So, obviously it errored in the middle of the site creation so I'll just delete it via STSADM. Wrong:

There is no top-level Web site named "http://server/mpsite/news/".

So, the site is listed in the sites and workspaces list, but doesn't really exist and can't actually be deleted.

How do I get rid of it from the Sites and Workspaces listing?

From stackoverflow
  • Have you tried http://server/mpsite/news/_layouts/deleteweb.aspx ?

    Or maybe the "Content and structure" (http://server/mpsite/_layouts/sitemanager.aspx) link from site actions?

    webwires : Cool, going directly to the deleteweb.aspx worked ... never would have guessed, good advice.
  • You've run into one of the lovely undocumented "features" of SharePoint - site templates get applied after the site gets created in a seperate, descrete step. This means that potentially, a site can "exist" (as far as the content database is concerned) without template, which leaves you with a site you can't browse to, but still sorta "exists" in SharePoint purgatory (I've actually written a couple of hacks that involve relying on this "feature").

    It looks to me like you may have run into one such situation - when you went to go create your site, I'm guessing that you got the error before the template was applied to your news site.

    The way I've fixed similar problems in the past has been to use SharePoint Designer to delete the sites - since it looks straight into the content database for what does and doesn't exist, it might do the trick for deleting your rouge news site.

    Hope this helps!

Stackoverflow-like login system in Rails?

What's the best (easy) way to implement a login/authentication system on a Rails web-app that looks and works like the Stackoverflow system?

I realize that it's basicly OpenID, but Stackoverflow handles integration with multiple providers.

Is there a easy way to this on Rails? Or do we have to hack restfull_auth or authlogic to do that?

From stackoverflow
  • Ryan has a decent railscast about this.

  • http://rubyforge.org/projects/ruby-openid/

    This may provide you with a solution. Also look at http://leancode.com/openid-for-rails/ for some resources and recommendations for OpenID on rails.

    This also looks promising, although I haven't seen the documentation. You might want to check it out.

  • Stackoverflow doesn't really do anything special for specific providers. It just takes an OpenId and then transfers the browser to the url processes it.

    You might want to check out this blog entry on integrating OpenId into your rails application:

    http://www.danwebb.net/2007/2/27/the-no-shit-guide-to-supporting-openid-in-your-applications

  • I believe StackOverflow uses the OpenID Selector, which for the visual effect is all HTML and Javascript, so you should be able to easily apply it to your Rails app that already uses a Ruby OpenID library.

    Javier : Does the Ruby OpenID library support account providers like Google and Yahoo (as does OpenID Selector)?
    rubenfonseca : As far as I tested it, it works with all the major openID providers, including google and yahoo!
  • Hi, I've just implemented what you're looking for in an example application:

    http://openid-example.joontos.ch

    (check out the link to the source code)

    rubenfonseca : excellent example! thank you!
    piemesons : @Javier its gone :-(

Hosting CLR versus using ClrCreateManagedInstance - what are the benefits?

I have successfully implemented interop beftween Win32 application and managed .Net dll as described here. But I also read here that it is possible to host the entire CLR inside of the unmanaged process.

So my question is: why would you do that? It is somewhat more complex than just use an object - what benefits you gain for this price of increased complexity?

Edit: what I understood from 2 first answers, is that you get the possibility to customize the CLR for your needs - meaning if you're writing a simple business app, you'll never need to host. Hosting is for system-heavy stuff, like browser or SQL Server.

From stackoverflow
  • You may have a legacy application and want to allow 3rd parties to the use the facilities of .net from within your application but particularly in a controlled manner such as controlling where assemblies are loaded from. Here is an example.

    Sergey Aldoukhov : Good link, thanks. Still, my question was more around of why you need more control.
  • Microsoft SQL Server uses it extensivly to replace the security, assembly loading, memory management, thread management and what not. A good book about this subject is "Customizing the Microsoft .NET Framework Common Language Runtime".

  • Hosting the CLR is generally not something you do to interop between managed code and Win32. there are generally 3 methods of interop:

    • Runtime Callable Wrapper (RCW) - call a COM object from .NET
    • COM Callable Wrapper (CCW) - make a .NET object appear as a COM object
    • P/Invoke

    These have been supported since the first version of .NET. The whole point of hosting the CLR is to allow you to deeply embed .NET code inside an unmanaged application. For example, there is a module that can host .NET in Apache on Win32 allowing it run .aspx pages.

    Similarly, the SQL Server wanted a way for people to write extended stored procedures and functions with managed code. In the past you could write these in C/C++, but if they hosted the CLR they could actually allow people to write these with C#. The work to get the CLR into a state were it could be safely embedded really pushed out the timelines, and so things like control over memory and security were born. SQL Server has some serious stability requirements and you can't have .NET rocking the boat.

    The hosting API changed significantly from .NET 1.x to 2.x but has been more stable since the 2.0 CLR has lived through .NET 3.0, 3.5 etc.

XmlInclude or SoapInclude

I am developing a webservice that returns arrays of classes I define within the webservice. When I test it, I get: "System.InvalidOperationException: The type WebSite+HostHeader was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically."

Here is part of the code:

[WebService(Namespace = "http://WebSiteInfo.Podiumcrm.com/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class WebSite : System.Web.Services.WebService { public class WebSiteEntry { public string SiteName = ""; public string Comment = ""; public string IISPath = ""; public int SiteID = 0; public ArrayList HostHeaders;

    public WebSiteEntry()
    {
    }
}
public class HostHeader
{
    public string IPAddress = "";
    public int Port = 0;
    public string URL = "";

    public HostHeader()
    {
    }
}


[WebMethod(EnableSession = true)]
[TraceExtension(Filename = @"C:\DotNetLogs\WebSiteServices.log")]
public WebSiteEntry[] WebSites()
{...}

}

When I try: [WebService(Namespace = "http://WebSiteInfo.Podiumcrm.com/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [XmlInclude(typeof(WebSiteEntry))] [XmlInclude(typeof(WebSiteProperty))] [XmlInclude(typeof(HostHeader))]

public class WebSite : System.Web.Services.WebService {...}

I get: The type or namespace name 'XmlInclude' could not be found (are you missing a using directive or an assembly reference?)

Points the the person who can give me the incantation that both compiles and executes!

Thanks...

From stackoverflow
  • For shits and giggles, add the [Serializable] attribute to your HostHeader class:

    [Serializable]
    public class HostHeader
    {    
        private string _ipAddress = "";
        private int _port = 0;
        private string _url = "";
    
        public string IpAddress { get { return _ipAddress; } set { _ipAddress = value; } }
    
        public int Port { get { return _port; } set { _port = value; } }
    
        public string Url { get { return _url; } set { _url = value; } }
    
        public HostHeader()
        {
        }
    }
    

    That should ensure that your class is XML Serializable.

    alexdej : Actually, the XmlSerializer ignores this attribute.
  • From the error you are receiving:

    The type or namespace name 'XmlInclude' could not be found (are you missing a using directive or an assembly reference?)

    It appears that you are missing the System.Xml.Serialization Namespace. You can fully qualifying the XmlInclude type, like this:

    System.Xml.Serialization.XmlInclude(typeof(WebSiteProperty))
    

    or add the namespace via the using directive:

    using System.Xml.Serialization
    

WPF WindowsFormsHost VS2008 Toolbox has grayed out all the Windows Forms controls

I'm trying to use WindowsFormsHost in a WPF app so I can use some Windows Forms components.

<Grid>
    <WindowsFormsHost>

    </WindowsFormsHost>
</Grid>

This all works ok with no errors, but when I go to drag a Windows Forms component from the toolbox in VS2008, they're all grayed out. In a way this makes sense as only the WPF components are available. But how do you drop a Windows Forms component onto a WindowsFormsHost if they're all grayed out and unavailable?

From stackoverflow
  • I don't think WPF designer supports Windows Forms components. You need to specify these in the XAML or in code. A simple example of how to add a WinForms button into a WPF application. Note that the button isn't visible on the design surface.

    <Window x:Class="DataTemplateBind.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:forms="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
        Title="Window1" Height="300" Width="300">
    
        <WindowsFormsHost Height="200" Name="windowsFormsHost1" Width="258" >
            <forms:Button Text="Waaa :("></forms:Button>
        </WindowsFormsHost>
    </Window>
    

    Note the added xmlns:forms namespace which isn't there by default.

    Mitch : Thanks Mikko, that did it. I was at the end of a long day and the frustration was setting in!

how to extract formating part from a string

How does one extract only the formatting part from a string. For example: if I have a string = "Warning: the error {0} has occurred. {1, 9} module has {2:0%} done." I would like to extract {0}, {1,9} and {2:0%} out into a sting array. Is there a regular expression or something that can be done other than my way of looping the string with Substring indexof '{' and '}' alternately?

From stackoverflow
  • Will some variant of "\{[^}]+\}" not work? Run it through finding the matches and substring'ing out from start to end of the match.

  • new Regex(@"\{[0-9:,% .]+\}");
    

    You may have to tweak/tune it to account for any additional formatting options that you haven't provided in your example.

  • In Java, the Matcher class takes a regex and will return all matching sub-strings.

    For example:

    String str = "Warning: the error {0} has occurred. {1, 9} module has {2:0%} done.";
    
    Matcher matcher = pattern.matcher( "{.*}");
    while (matcher.find()){
        String matched = matcher.group()
        \\do whatever you want with matched
    }
    
  • The following code is different from other answers in that it uses non-greedy matching (".*?"):

        private static void Main(string[] args) {
            const string input = "Warning: the error {0} has occurred. {1, 9} module has {2:0%} done.";
            const string pattern = "{.*?}"; // NOTE: "?" is required here (non-greedy matching).
            var formattingParts = Regex.Matches(input, pattern).Cast<Match>().Where(item => item.Success).Select(item => item.Groups[0].Value);
            foreach (var part in formattingParts) {
                Console.WriteLine(part);
            }
        }
    
    Terry_Brown : +1 I'd started writing something with named matches to help extract each part individually, but the above stopped me - really nice solution
    Colin Burnett : Except doing [^}] in between { and } prevents it from being greedy. Likewise on [0-9:,% .] that Jordan proposed. Ethan's is the only greedy one that will match "{0} ... {1}" from beginning to end.

How to programatically modify assemblyBinding in app.config?

I am trying to change the bindingRedirect element at install time by using the XmlDocument class and modifying the value directly. Here is what my app.config looks like:


<configuration>
    <configSections>
        <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">            
            ...
        </sectionGroup>      
    </configSections>
    <runtime>
      <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
        <dependentAssembly>
          <assemblyIdentity name="MyDll" publicKeyToken="31bfe856bd364e35"/>
          <bindingRedirect oldVersion="0.7" newVersion="1.0"/>
        </dependentAssembly>
     </assemblyBinding>
    </runtime>    
...
</configuration>

I then try to use the following code to change 1.0 to 2.0

    private void SetRuntimeBinding(string path, string value)
    {
        XmlDocument xml = new XmlDocument();


        xml.Load(Path.Combine(path, "MyApp.exe.config"));
        XmlNode root = xml.DocumentElement;

        if (root == null)
        {
            return;
        }

        XmlNode node = root.SelectSingleNode("/configuration/runtime/assemblyBinding/dependentAssembly/bindingRedirect/@newVersion");

        if (node == null)
        {
            throw (new Exception("not found"));
        }

        node.Value = value;

        xml.Save(Path.Combine(path, "MyApp.exe.config"));

    }

However, it throws the 'not found' exception. If I back the path up to /configuration/runtime it works. However once I add assemblyBinding, it does not find the node. Possibly this has something to do with the xmlns? Any idea how I can modify this? ConfigurationManager also does not have access to this section.

From stackoverflow
  • Modifying Configuration Settings at Runtime By UsualDosage

    This article will demonstrate how to add, delete, and update key value pairs in an App.config file.

    http://www.codeproject.com/KB/cs/modconfigruntime.aspx

    esac : Not helpful. I already know how to modify it programatically at runtime. My problem is that it works for other areas, just not for assemblyBinding element.
  • I think the right Xpath syntax is:

    /configuration/runtime/assemblyBinding/dependentAssembly/bindingRedirect@newVersion

    (you have a slash too many).

    Or if this doesn't work you could select the bindingRedirect element (using SelectSingleNode):

    /configuration/runtime/assemblyBinding/dependentAssembly/bindingRedirect

    Then modify the attribute newVersion of this element.

    esac : Already been down this path, it complains of invalid token with bindingRedirect@newVersion. Second case, it complains that it could not find the path specified.
  • I found what I needed. The XmlNamespaceManager is required as the assemblyBinding node contains the xmlns attribute. I modified the code to use this and it works:

        private void SetRuntimeBinding(string path, string value)
        {
            XmlDocument doc = new XmlDocument();
    
            try
            {
                doc.Load(Path.Combine(path, "MyApp.exe.config"));
            }
            catch (FileNotFoundException)
            {
                return;
            }
    
            XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable);
            manager.AddNamespace("bindings", "urn:schemas-microsoft-com:asm.v1");
    
            XmlNode root = doc.DocumentElement;
    
            XmlNode node = root.SelectSingleNode("//bindings:bindingRedirect", manager);
    
            if (node == null)
            {
                throw (new Exception("Invalid Configuration File"));
            }
    
            node = node.SelectSingleNode("@newVersion");
    
            if (node == null)
            {
                throw (new Exception("Invalid Configuration File"));
            }
    
            node.Value = value;
    
            doc.Save(Path.Combine(path, "MyApp.exe.config"));
        }
    
    esac : Just a note, I throw exceptions as this is part of an Setup Project and that is how the installer is notified of any errors. It would be better to have the method return true or false if the modification was made.
  • Sounds like you've got your configuration file tweak working now, but I thought you might still be interested in how to adjust binding redirects at run time. The key is to use the AppDomain.AssemblyResolve event, and the details are in this answer. I prefer it over using the configuration file, because my version number comparison can be a bit more sophisticated and I don't have to tweak the configuration file during every build.

  • awesome thread, saved me a ton of time.

Recommend a Java wizard library?

I'm looking for a wizard library/framework for Java, but it seems all the ones I can find are abandoned and/or lacking in enough documentation to use quickly. Here's the ones I've found, and all appear to be no longer maintained.

I tried using SwingLab's Wizard, but I ran into an issue that was not explained in the documentation and I received no response from the maintainer. I'm hoping someone else knows of a good replacement before I need to re-invent the wheel.

Edit: It appears that the current state of Java does not provide such a framework, and I'll roll my own. Thankfully my needs are extremely limited (a 2 pane wizard).

From stackoverflow
  • A couple of ideas:

    • Have you seen this article about creating dialogs using the java swing api?

    • There is also NSIS (Nullsoft Scriptable Install System) is a professional open source system to create Windows installers. It is designed to be as small and flexible as possible and is therefore very suitable for internet distribution.

  • There is one in the JFace library (that powers Eclipse) here. But it is for SWT rather than Swing.

  • If you're writing a web application, Spring Web Flow would be an excellent choice. It comes with a lot of nice features out of the box like support for the back button and is very extensible as you'd expect.

    Kissaki : Wizard: A step by step guide for the user. Also see http://en.wikipedia.org/wiki/Wizard_%28software%29
  • I ran into the same problem about a year ago, and developed CJWizards to fit my need. It's more general-purpose than the other wizards I've found.

    The project is a bit stale because I haven't needed it recently, but I'd be happy to help anyone who uses it get going.

    It supports bi-directional navigation (so the user can go back, fix something, then move forward again, maintaining the answers they provided on the first pass), and makes it substantially easier to design wizards that branch (when compared with other wizard frameworks I've seen).

    The dialog layout is separated into a few layers, so you can add wrapper content, such as the navigation bar on the left of this screenshot to all the steps, or stick in a logo, move the buttons, etc. according to your needs.

    Each page of the dialog is essentially a JPanel that you add named widgets to -- the framework looks for named widgets, and monitors them for data which is stored in a map of (widgetName, value).

  • I've tried three frameworks before to come into JWF (Java Wizard Framework, the first you enlisted).

    It's definitely the clearest and the simplest to use. However, it lacks documentation but if you look at the example provided in the release jar you can use it without any pain.

Deciding Factor for Asynchronous Programming

What could be the deciding factor to use the methods asynchronously.

One factor i can understand is independent and parallel execution so as to save time and uses the available resources.

What could be the other factors ???

Any help is highly appreciated.

From stackoverflow
  • Providing feedback and allowing for call cancellation - you can cancel a call at any time gracefully.

  • Slow input, doing it asynchronously allows you to do processing (Also allows you to respond to user events) while you wait for the input to complete. Most networking functions can be implemented this way (Through callbacks, etc).

  • Providing responsiveness and feedback in the user interface, in order to keep the users happy and buying more software.

    Maghis : +1 for buying more software:)
    • Allow the user to do other tasks (or cancel) during the execution
    • Allow the software to do other tasks during the execution
      • Eg. Using processor time while waiting for network or file system
      • Communication with external processes or devices which need immediate response to not run into a timeout. (Eg. Network response, external devices)

    It's good praxis to not bind two different time consuming tasks synchronously together, eg. network communication and Database access.

    On the other hand, software does not get faster if everything is asynchronous. It just allows using resources while waiting for others.

  • Allowing the UI to remain responsive during long running processes is a big plus. Some users tend to end task once they see that dreaded "Not Responding" in the applications title bar. I'd much rather display a progress bar in order to distract the user :).

  • One thing to remember is that once you jump the hurdle of asynchronous programming, you can do more than two things at once.

    In other words, going from synchronous programming to asynchronous programming can be daunting. However, once you're there, you can fire off many things asynchronously and improve your program's efficiency.

Java vs Javascript Regex problem

Hello,
I am having a problem with my regular expression: <a.*href=[\"'](.*?)[\"'].*>(.*?)</a>. It is, as you can probably tell, supposed to take all the links from a string of HTML and return the link text in group 2, and the link target in group 1. But I am having a problem. If I try it in Javascript (using http://www.regextester.com/, with all the flags on), it works fine, but in Java, like this:

Pattern myPattern = Pattern.compile("<a.*href=[\"'](.*?)[\"'].*>(.*?)</a>", Pattern.CASE_INSENSITIVE);
Matcher match = myPattern.matcher(htmlData);
while(match.find()) {
 String linkText = match.group(2);
 String linkTarget = match.group(1);
}

I don't get all the matches I expect. With regex tester, I get many more and it works exactly like it is supposed to, but with the Java version, it just get 1 or 2 links per page.
Sorry if this is obvious, but I am new to regular expressions.
Thanks,
Isaac Waller

Edit: I think it might be something wrong with my regex. See, from this Apache indexof page:

<tr><td valign="top"><img src="/icons/sound2.gif" alt="[SND]"></td><td><a href="Bryan%20Adams%20-%20Here%20I%20Am.mp3">Bryan Adams - Here I Am.mp3</a></td><td align="right">27-Aug-2008 11:48  </td><td align="right">170K</td></tr>
<tr><td valign="top"><img src="/icons/sound2.gif" alt="[SND]"></td><td><a href="Cars%20-%20Drive.mp3">Cars - Drive.mp3</a></td><td align="right">26-Aug-2008 19:04  </td><td align="right">149K</td></tr>
<tr><td valign="top"><img src="/icons/sound2.gif" alt="[SND]"></td><td><a href="Cock%20Robin%20-%20When%20Your%20Heart%20Is%20Weak.mp3">Cock Robin - When Your Heart Is Weak.mp3</a></td><td align="right">26-Aug-2008 19:04  </td><td align="right">124K</td></tr>
<tr><td valign="top"><img src="/icons/sound2.gif" alt="[SND]"></td><td><a href="Colbie%20Caillat%20-%20Bubbly.mp3">Colbie Caillat - Bubbly.mp3</a></td><td align="right">27-Aug-2008 11:49  </td><td align="right">215K</td></tr>

<tr><td valign="top"><img src="/icons/sound2.gif" alt="[SND]"></td><td><a href="Colbie%20Caillat%20-%20The%20Little%20Things.mp3">Colbie Caillat - The Little Things.mp3</a></td><td align="right">27-Aug-2008 11:49  </td><td align="right">176K</td></tr>
<tr><td valign="top"><img src="/icons/sound2.gif" alt="[SND]"></td><td><a href="Coldplay%20-%20Violet%20Hill.mp3">Coldplay - Violet Hill.mp3</a></td><td align="right">27-Aug-2008 11:49  </td><td align="right">136K</td></tr>
<tr><td valign="top"><img src="/icons/sound2.gif" alt="[SND]"></td><td><a href="Corrs%20-%20Radio.mp3">Corrs - Radio.mp3</a></td><td align="right">26-Aug-2008 19:04  </td><td align="right">112K</td></tr>
<tr><td valign="top"><img src="/icons/sound2.gif" alt="[SND]"></td><td><a href="Corrs%20-%20What%20Can%20I%20Do.mp3">Corrs - What Can I Do.mp3</a></td><td align="right">26-Aug-2008 19:04  </td><td align="right">146K</td></tr>
<tr><td valign="top"><img src="/icons/sound2.gif" alt="[SND]"></td><td><a href="Counting%20Crows%20-%20Big%20Yellow%20Taxi.mp3">Counting Crows - Big Yellow Taxi.mp3</a></td><td align="right">26-Aug-2008 19:04  </td><td align="right">135K</td></tr>

<tr><td valign="top"><img src="/icons/sound2.gif" alt="[SND]"></td><td><a href="Curtis%20Stigers%20-%20I%20Wonder%20Why.mp3">Curtis Stigers - I Wonder Why.mp3</a></td><td align="right">26-Aug-2008 19:03  </td><td align="right">213K</td></tr>
<tr><td valign="top"><img src="/icons/sound2.gif" alt="[SND]"></td><td><a href="Cyndi%20Lauper%20-%20Time%20After%20Time.mp3">Cyndi Lauper - Time After Time.mp3</a></td><td align="right">26-Aug-2008 19:03  </td><td align="right">193K</td></tr>
<tr><td valign="top"><img src="/icons/sound2.gif" alt="[SND]"></td><td><a href="David%20Bowie%20-%20Absolute%20Beginners.mp3">David Bowie - Absolute Beginners.mp3</a></td><td align="right">26-Aug-2008 19:04  </td><td align="right">155K</td></tr>
<tr><td valign="top"><img src="/icons/sound2.gif" alt="[SND]"></td><td><a href="Depeche%20Mode%20-%20Enjoy%20The%20Silence.mp3">Depeche Mode - Enjoy The Silence.mp3</a></td><td align="right">26-Aug-2008 19:03  </td><td align="right">230K</td></tr>
<tr><td valign="top"><img src="/icons/sound2.gif" alt="[SND]"></td><td><a href="Dido%20-%20White%20Flag.mp3">Dido - White Flag.mp3</a></td><td align="right">27-Aug-2008 11:48  </td><td align="right">158K</td></tr>

I should get:
1: Bryan%20Adams%20-%20Here%20I%20Am.mp3
2: Bryan Adams - Here I Am.mp3
and many more like that. With Regex tester, I get all the results I want. With Java, I get none.

From stackoverflow
  • You have to escape the backslash characters and the quotation marks:

    Pattern myPattern = Pattern.compile("<a.*href=[\\\"'](.*?)[\\\"'].*>(.*?)</a>", Pattern.CASE_INSENSITIVE);
    

    However, that might not be your real problem. The backslashes are not really needed in the pattern. There are some other possible issues with the pattern.

    You are using a greedy match before the href property, which means that it will match from the start of the first link on the line to the href property of the last link on the line. Make the match non-greedy by changing it from ".*" to ".*?". The same goes for the match after the href property, it has to be non-greedy or it will match up to the end of the last link on the line.

    The . character does not match line breaks, so if there are line breaks in the link code or in the text in the link, the link will not be matched. You can use [\W\w] instead of . to match any character.

    So, removing the backslashes, making the matches non-greedy and allowing line breaks would make the pattern:

    Pattern myPattern = Pattern.compile("<a[\\W\\w]*?href=[\"'](.*?)[\"'][\\W\\w]*?>([\\W\\w]*?)</a>", Pattern.CASE_INSENSITIVE);
    

    Edit:
    I forgot to escape the backslashes in the [\W\w] codes in the string.

    Isaac Waller : I think you use 3 slashes instead of 2, but it did not work regardless. Sorry.
    Alan Moore : Isaac said he's using the DOTALL modifier (along with all of the other modifiers), so his dots are already matching newlines. Come to think of it, if he had left that out, he probably wouldn't have noticed anything wrong; all of the links in the sample text are separated from each other by at least one newline.
  • Don't all of the full-stop/wildcard matches need to be ungreedy?

    <a.*?href=[\"'](.*?)[\"'].*?>(.*?)</a>
    

    I'm not a java developer so I don't know the escaping rules for patterns.

Libraries / tutorials for manipulating video in java

I need to do some simple video editing within a Java application, but the frameworks I've found (JMF and FMJ) appear to be quite stale, and thus far I haven't found any evidence that either can actually edit video. The type of operations I need are: cropping, redacting sections, and extracting clips.

I've never worked with video in any real capacity before, so I may just be misunderstanding what FMJ/JMF do, but I am still concerned by the age of the most recent releases of those tools.

What do people use to do this sort of thing? What keywords should I be using to get more relevant results?

(The specific format of video is not particularly important to me -- anything common is just fine.)

From stackoverflow
  • You may take a look on Xuggler. Also some alternatives to JMF were covered in Wikipedia.

    rcreswick : Thanks! I found FMJ on that wikipedia article earlier, but somehow overlooked the xuggle link!
  • GStreamer has some Java bindings.

UTF8 or UTF-8?

Which of the two is correct terminology?

From stackoverflow
  • UTF-8

  • I believe according to the Unicode Consortium, it's UTF-8.

  • It's definitely UTF-8. UTF8 is only used commonly in places where a dash is not allowed (programming language indentifiers) or because people are too lazy.

  • Also UTF-8 (great and thorough explanation of UTF-8)

  • Following the RFC standard the answer is UTF-8

    http://www.ietf.org/rfc/rfc3629

  • That depends on where you use it...

    The name of the encoding is UTF-8.

    A dash is not valid to use everywhere, so for example in .NET framework the property of the System.Text.Encoding class that returns an instance of the UTF8Encoding class that handles the UTF-8 encoding is named UTF8.

How do I get js2-mode to use spaces instead of tabs in Emacs?

I am using js2-mode to edit Javascript in Emacs, but I can't seem to get it to stop using tabs instead of spaces for indentation. My other modes work fine, just having issues w/ js2.

From stackoverflow
  • Do you have

    (setq-default indent-tabs-mode nil)
    

    in your .emacs? It works fine for me in emacs 23.0.60.1 when I do that. js2-mode uses the standard emacs function indent-to, which respects indent-tabs-mode, to do its indenting.

  • The above solution only works if you want to use spaces for all modes. I need to use tabs to space my python files and spaces for javascript. Is there a way to modify the js2-mode's use of indent-to such that js2-mode uses spaces for indentation?

    Jouni K. Seppänen : Then don't set indent-tabs-mode via setq-default in all modes but via setq in a mode-specific hook.

iPhone friendly websites with ASP.NET MVC

Are there any resources or guidance out there on how to make iPhone friendly web applications?

In my case specifically, I'd like to use ASP.NET MVC, but since that all runs on the server, I know it'll boil down to just markup/css/javascript considerations.

edit: as I find other resources not mentioned here, I will update the question text :-)

From stackoverflow
  • Scot Hanselman had a great presentation at Mix 09. Click here link.

    Also look at the Mobile Device Browser File=>LINK. It is open source at codeplex.

    "What is the Mobile Device Browser Definition File?

    The Mobile Device Browser Definition File contains capability definitions for individual mobile devices and browsers. At run time, ASP.NET uses this .browser file, along with the information in the HTTP request header, to determine what type of device/browser has made the request and what the capabilities of that device are. This information is exposed to the developer through the Request.Browser property and allows them to tailor the presentation of their web page to suit the capabilities of the target device." - Codeplex

  • The definitive resource is Apple's Safari Dev Center.

Mysql Dropping Connection

I am on Instant Ruby on Rails Mysql version 5.0.27, developing a system and all was going ok (sort of). Now the database keeps dropping. I found some comments that the userid needs to be root and password blank, I had changed the password, so I changed it back. Views run fine displaying and making changes than 500 Internal error, log says the Mysql connection dropped. Any clues??

From stackoverflow
  • check mysql log. what does it say?

  • ActiveRecord::StatementInvalid (Mysql::Error: Lost connection to MySQL server during query: SELECT * FROM events WHERE (events.id = 1) ): followed by alot of falldown errors

Are there any articles or advice on creating a C++ chat server with a C# client?

My current class is planning on creating a basic networked game, but we have decided to take on the task of making a C++ server with a C# client. I understand this is probably a difficult task, but I was wondering if there is any advice on making this happen.

I am sorry I do not have any more information than this. We are just getting started and just want to make sure this is possible within the time span we have.

From stackoverflow
  • If it is running all in one windows domain, you might consider DCOM. Otherwise, I'd go for web services (SOAP toolkit for C++) or maybe REST.

  • This works fine. C# and C++ both support TCP and UDP network connections, in many flavors. Either would work fine for the client or server.

    The main issues you'll need to watch for are deciding how to transmit your data, and making sure that any packets you pass through the wire are serialized/deserialized the same way.

    This would be simpler if you were to use the same language (or at least libraries) on both sides, ie: if you used C++/CLI for the server, and stuck with some of the same managed .NET tools for working with data transmission.

  • It's really not a big issue - as long as you come up with a good protocol. The bits on the wire don't care what language was used to write the program that interprets them.

    By protocol I mean you need a clear understanding of who should do what when, what to say, and what to expect back.

    For example, an echo server and its client might expect that

    • the client speaks first
    • there's a well understood identifier to mark the end of the client's input
    • the client will wait for the server to respond before speaking again
    • there's a well understood identifier to mark the end of the server's output.

    And so on. A different client that sent the message length before the message instead of using a end of input identifier wouldn't work with the original server, because of protocol incompatibilities.

    Protocols can be flexible, but you have to account for that flexibility in the protocol itself.

  • As everyone's said, this isn't an issue at all if your chat protocol is well-designed. Only if you were using hacks like using BinaryFormatter to directly serialize CLR objects onto the wire would you have a problem...

    I would recommend you use existing protocols (e.g. IRC) and/or libraries to the extent you're allowed.

  • For a chat program, try using a chat protocol.

    Examine XMPP and see if you can use it, or a cut down version. Starting from what others have figured out is never a bad idea. At the very least you can see what you don't like about it. :)

Is the MVC (Model View Controller) paradigm a better way to develop or just a new complex one?

I was trying to use RoR or ASP.NET MVC but at my first impression it seems to me that MVC is a drastic way to change the programming paradigm. Is this just my resistance to changes or it is really weird? Some times i feel really lost! Any suggestion or I just have to turn back and program in the old fashion way?

From stackoverflow
  • MVC isn't particularly new. It dates from 1979 (reference), so it's old enough to drink.

    In general, MVC forces a form of encapsulation upon you; that is, your View needs to be largely independent of your Model. Once you get used to it, you will find it useful; that said, for your individual needs, other paradigms may be more appropriate. MVC isn't the end-all, be-all; but it IS a useful way to look at some problems.

  • MVC is neither new nor particularly complex. MVC is a standard paradigm that has been around for a long time. I remember it being one of the highlighted patterns in my Software Engineering classes 10 or so years ago. MVC, once you understand it, provides a very clean, testable implementation for your project. It's certainly different than WebForms -- and knowing WebForms can actually be a hindrance in learning ASP.NET MVC -- but I'm not planning to go back. I only expect ASP.NET MVC to get better and better as we see the same sort of controls built up for it that there are for WebForms.

  • What is your basis for comparison? If you're used to perl / CGI, then maybe it is a bit more complex!

    In web terms, MVC (or Model-Template-View as preferred by Django, to separate from the original Smalltalk MVC) tends to allow for better separation of concerns in your application. In my (and many others) experience, this leads to more extensible, well-tested code that is easier to maintain.

    Some suggestions for going forward. It's hard to make specific recommendations without knowing a bit more about your background, and learning can be such a personal thing anyway:

    • RoR - Sam Ruby has a new book out. There are various screen-casts.
    • Django - I would recommend that as well, since those are the two web frameworks that have the least friction out of the ones that I've used.

    Sorry, I've been off the MS platform for a few years, so I can't offer any advice on ASP.NET.

  • It only feels drastic because its new. It's actually not that bad.

    Taking a look at a real life application may help.

    Check out http://www.nerddinner.com/ for a decent example, as well as a free chapter in the Professional ASP.NET MVC 1.0 book that covers the code.

  • Change is hard, for all of us. In the DOS days we used the MTF Menu-Table-Form pattern.

    MVC has been around for a long time now and there is a flavor for all major languages used in internet programming.

    Once you use MVC for a while you will probably not want to go back. It provides for code separation and reuse. I have used RoR, Django and ASP.NET MVC and the MVC pattern made my development.

    I would encourage you to keep at it! Buy a book or find a mentor.

  • A more highly factored / layered design is always harder to wrap your head around initially - the payoff only comes once that happens. The advantage is that now you have clearly defined places where to put what; while being forced to stick to a predetermined separation of concerns seems onerous at first, the predictability of the code structure it makes things much easier to maintain later.

  • Well, it is certainly popular. If you are doing RoR, don't fight the paradigm, go with it, that is the whole point of RoR.

    If you are in a position of defining your paradigm, the fact of the matter is that MVC tends to just be MV. A Controller according to some advocates of the pattern is intended more in the case of multiple views, which is almost always not the case in a given project (although the data may ultimately end up being viewed very differently in a different context within the enterprise). Depending on the GUI though, a separate controller can help the testability of the code (were the controller acts as the class under test, and the GUI component just hits the methods under test in the most minimal way possible).

    MVC originated with the SmallTalk crowd, which more recently got into a Morphic pattern (where the object displays itself via an inner class which subclasses the relevant GUI components). That isn't a difficult way to do HTML stuff for sure, because the html can't effectively be given to designers.

    Personally if I really am going from scratch, I prefer a Presentation pattern (I've seen it called that, but I can't find the reference now) where the view and data binding is put into a presentation class. The power of the pattern comes if the the presentation of the whole screen is made up of different presentations of portions of the data. In plain boring business apps (the kind I tend to write) bits of data (say an address) tend to get displayed on a lot of screens, so it helps to be able to chunk and reuse the gui presentation components.

    But these days, you really need to think carefully if you need to do it from scratch, at least in good old boring data display and manipulation applications. There is a lot out there, and if you use a tool, you should go with its pattern. Fighting the tool is counterproductive.

What is a good way using LINQ To SQL to update multiple tables through a view?

I have a view and it's composed of two tables. I want to edit a value in each table through the view and save those changes but LINQ is throwing an error about not being able to edit two values on the same view.

Does anyone know of a good workaround?

Thanks

From stackoverflow
  • SQLServer doesn't support updating columns from multiple tables on a view. You may be able to get around this by separating the column changes so that you only update the columns on one table, submit your changes, update the changes on the other table, and then submit changes again. You could also use a stored procedure to update the individual tables independently in the same transaction. This stored procedure could be added as a method on your data context using the designer. Assuming that it returns the same schema as the view when it completes, it could return an object of the same type as the view.

    Reference

    Updatable Views You can modify the data of an underlying base table through a view, as long as the following conditions are true:

    Any modifications, including UPDATE, INSERT, and DELETE statements, must reference columns from only one base table. The columns being modified in the view must directly reference the underlying data in the table columns. The columns cannot be derived in any other way, such as through the following: An aggregate function: AVG, COUNT, SUM, MIN, MAX, GROUPING, STDEV, STDEVP, VAR, and VARP. A computation. The column cannot be computed from an expression that uses other columns. Columns that are formed by using the set operators UNION, UNION ALL, CROSSJOIN, EXCEPT, and INTERSECT amount to a computation and are also not updatable. The columns being modified are not affected by GROUP BY, HAVING, or DISTINCT clauses. TOP is not used anywhere in the select_statement of the view together with the WITH CHECK OPTION clause.

  • While @tvanfosson's is answer is absolutely correct, if you are using LINQ-to-SQL, you can instead reference both tables directly in your code, get your collection of objects, update them, and push them back. Upon issuing the update command, my understanding is that LINQ-to-SQL will place all the commands in a transaction and handle it for you.

  • A third option is to create an INSTEAD OF trigger, where you write the code to split the updated values into two different queries.

SWT layout problem - padding for labels possible ?

I am using GridLayout in my SWT GUI app. I have the following GridData defined for each grid cell. The grid cell itself is just a label.

    GridData gridData = new GridData();
    gridData.horizontalAlignment = GridData.FILL;
    gridData.grabExcessHorizontalSpace = true;
    gridData.grabExcessVerticalSpace = true;
    gridData.heightHint = 25;
    gridData.widthHint = 25;
    gridData.verticalAlignment = GridData.VERTICAL_ALIGN_CENTER;
    gridData.verticalIndent = 10;

And I create each lable element like this -

    Label l = new Label(shell, SWT.BORDER);
    l.setAlignment(SWT.CENTER);
    l.setText("some text");
    l.setLayoutData( gridData );

Now My problem is in spite of using verticalAlignment property, verticalIndent property and setAlignment on the label itself, I am not able to get the text align vertically centered with respect to the grid cell area ( 25 x 25 ). I think I am missing something. How can I achieve the vertically centered alignment in a grid cell ?

From stackoverflow
  • There is no setVerticalAlignment() on a Label and if you set the height, using the heightHint in the LayoutData, that becomes the size of the control and effectively stopping you from setting it in the middle. A workaround would be to put the Label into a composite with the size you want and then center the control. E.g.

    Composite labelCell = new Composite(shell, SWT.BORDER);
    GridData gridData = new GridData();
    gridData.heightHint = 250;
    gridData.widthHint = 250;
    labelCell.setLayoutData(gridData);
    labelCell.setLayout(new GridLayout());
    Label l = new Label(labelCell , SWT.NONE);
    l.setText("some text");
    l.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true));
    

Open-source US- state status display

I was wondering if anyone knew of an Open-source project for displaying numbers for the US states.

Specifically, you always see these graphics with California in dark grey, Montana in green, etc. Based on some sort of criteria.

I'm thinking of building one for a site I maintain, but I was hoping I might not have to reinvent the wheel.

http://upload.wikimedia.org/wikipedia/commons/7/70/World_map_of_Energy_consumption_1979-1981.svg

Something like the above, but for the US, and you can define your own criteria?

From stackoverflow

Draw arrow on canvas tag

Hello,

I want to draw an arrow using the canvas tag, javascript. I've made it using the quadratic function, but I'm having problems to calculate the angle of rotation of the arrow...

Anyone have a clue on this?

Thank you

From stackoverflow
  • You can push your matrix, rotate it, draw your arrow and then pop the matrix.

  • You can do:

    ctx.save();
    ctx.translate(xOrigin, yOrigin);
    ctx.rotate(angle);
     // draw your arrow, with its origin at [0, 0]
    ctx.restore();
    

css selector rules --ruleset for all elements within a selector?

With at-rules, it's possible to have a ruleset for elements during that at-rule event (like printing, mobile devices, etc.) But what about just for a specific selector?

I am working on a sub page of a larger site, and I have to use the master stylesheet for any of my pages. Sometimes a style rule just gets trumped by a rule from the master style sheet. To overcome this, I end up having to add "#mypage #content blah blah" before all of my rules to ensure my css is more specific. It gets messy very fast. What I'd prefer to do is something like:

@#mypage {
       div {
           border: 1px solid #000;
           }
       div p {
           color: #00f;
           }
       }

so that any rules I make up are contained to the id of the section of the page I am working on.

Oh, I forgot to mention, I can't (as far as I understand) use @namespace, as my page is within a template frame (hence the need for the master stylesheet), so if I just say @namespace (my-page-url) my stylesheet would overwrite the master stylesheet.

Am I missing something simple?


Clarification:

Sorry, I guess in my attempt to stay simple I was too vague...

I am developing the content of a page which will be placed inside of a more generic template (masthead, sidebar navigation, etc) which has a global style sheet and I have no control over any of that content.

I have some liberty with the stylesheet for just my section. I don't want any my rules to accidentally overwrite the global stylesheet, and I want to avoid having to use really long selectors for my rules to avoid the global stylesheet overwriting my stylesheet. For example, if I want to say

"all tables have a black border"

I risk putting a black border around some table in the sidebar. However, if I say

"all tables within the div #content have a black border"

this only works as long as they don't have a more specific rule.

Now, I can go through each rule and add a long train of selectors to ensure that each of my rules works and only for my section, but that's not really attractive or fun to do. I was hoping that I could nest all of my rules inside of a larger rule, like in my example above, so that I can have a main rule:

#content {

and place all of my style rules inside of that:

p { border: pink; }

so that I only have to declare my specificity once and it covers every rule inside that main rule.

From stackoverflow
  • You can ovveride the other stylesheet with the "!important" declaration:

    div {
        border: 1px solid #000 !important;
        }
    div p {
        color: #00f !important;
        }
    

    More info: http://www.w3.org/TR/CSS2/cascade.html#important-rules

  • From what I've read the following rule fits the bill, is only one level deep, and is frankly typical of most websites I've seen and used:

    #content div {
      ... your rules ...
    }
    

    That would only effect divs which are under the element with the id of content.

    There's no way to "group" these rules as so:

    #content {
      div {
        ... your rules ...
      }
    }
    

    That would be nice, but alas, it's not the way it was written.

    Anthony : I agree about staying away from important rules, at least when possible. But my question is still not answered, unfortunately. I know I can put an id selector before EVERY rule. What I am wondering is if I can put an id selector before a group of rules so that those rules only get applied to those rules, but for all of them.
    altCognito : Ah, I see you've updated the question, I'll read the update.
    altCognito : Ok, so let me know if that solution is what you want or why the css rules would have to be even more specific than that.
  • Not a perfect solution, since it uses PHP-based server-side processing, but this might be good enough for you:

    http://www.shauninman.com/archive/2007/06/27/css_server_side_pre_processor

  • A very similar question (with a rather poor title) was asked a while ago.

    The most popular answer was Shaun Inman's server-side preprocessor (which has now been superseded by CSSCacheer).

    My suggestion was Sass.

    In either case, this is somewhat of a deficiency in vanilla CSS.