Friday, May 6, 2011

Int in a simulated memory array of uchar

In C, in an Unix environment (Plan9), I have got an array as memory.

uchar mem[32*1024];

I need that array to contain different fields, such as an int (integer) to indicate the size of memory free and avaliable. So, I've tried this:

uchar* memp=mem;
*memp=(int)250; //An example of size I want to assign.

I know the size of an int is 4, so I have to force with casting or something like that, that the content of the four first slots of mem have the number 250 in this case, it's big endian.

But the problem is when I try to do what I've explained it doesn't work. I suppose there is a mistake with the conversion of types. I hopefully ask you, how could I force that mem[0] to mem[3] would have the size indicated, representated as an int and no as an uchar?

Thanks in advance

From stackoverflow
  • Like this:

    *((int*) memp) = 250;
    

    That says "Even though memp is a pointer to characters, I want you treat it as a pointer to integers, and put this integer where it points."

    Polar Geek : Ok, thanks, it does work. And I've got the point.
    Polar Geek : But, if I want to assign a pointer to another part of mem (the array of unsigned chars),at the beginning to nil. Could I do something like this?: *((void*) memp) = nil; It doesn't compile. :(
    ephemient : It is never possible to dereference a (void *) pointer.
    leander : Be careful when attempting to write things other than char/uchar to a uchar array, unless you know the address is aligned properly (i.e. for a 32-bit system, usually aligned to a 4-byte boundary). Many modern processors can handle unaligned writes (with a performance penalty -- and note that the compiler may assume the worst and use slower instructions to make the write), but some still can't -- see e.g. smaller processors like the early ARMs. You also may have aliasing issues to worry about...
  • Cast pointer to int, not unsigned char again!

    int * memp = (int *)mem;
    * memp = 250; //An example of size I want to assign.
    
  • Have you considered using a union, as in:

    union mem_with_size {
      int   size;
      uchar mem[32*1024];
    };
    

    Then you don't have to worry about the casting. (You still have to worry about byte-ordering, of course, but that's a different issue.)

  • As others have pointed out, you need to cast to a pointer to int. You also need to make sure you take alignment of the pointer in consideration: on many architectures, an int needs to start at a memory location that is divisible by sizeof(int), and if you try to access an unaligned int, you get a SIGBUS. On other architectures, it works, but slowly. On yet others, it works quickly.

    A portable way of doing this might be:

    int x = 250;
    memcpy(mem + offset, &x, sizeof(x));
    

    Using unions may make this easier, though, so +1 to JamieH.

How to solve lazy initialization exception using JPA and Hibernate as provider

I am working on a project for a customer who wants to use lazy initialization. They always get "lazy initialization exception" when mapping classes with the default lazy loading mode.

@JoinTable(name = "join_profilo_funzionalita", joinColumns = {@JoinColumn(name =    "profilo_id", referencedColumnName = "profilo_id")}, inverseJoinColumns = {@JoinColumn(name = "funzionalita_id", referencedColumnName = "funzionalita_id")})
//@ManyToMany(fetch=FetchType.EAGER) - no exceptions if uncommented
@ManyToMany 
private Collection<Funzionalita> funzionalitaIdCollection;

Is there a standard pattern using JPA classes to avoid this error?

Snippets are welcome, thanks a lot for your time.

From stackoverflow
  • OpenSessionInView is one pattern to deal with this problem. Some info here:

    http://www.hibernate.org/43.html

    What kind of application are you writing? If you're not dealing with remoting (no web services, no AJAX-based web client) then OSIV may work very nicely. Otherwise things get complicated quickly...

  • LazyInitializationException means that you are calling the collection after the hibernate session has closed, or after the object has been detached from the session.

    You need to either re-attach the object to hibernate session, change the place where you are calling the collection, or move the boundary of where the session gets closed to a higher layer.

  • There are many ways to pre-fetch properties, so they are there after session is closed:

    1. Just call appropriate getter. After field is fetched into bean it is there after session is closed.
    2. You may initialize field in EJBQL query , look for JOIN FETCH keyword.
  • Using JBoss Seam solves the problem LazyInitailizationException and not only. Seam does not close the hibernate session after each request but it binds to the conversation (Open session in Conversation) so you can really use the dirty checking in the long conversations like wizards (no merge only flash). View rendering phase is executed in a separate transaction so there is no problem if the commit fails as in OpenSessionInView.

Are there any good oracle podcasts?

Are there any good oracle podcasts around? The only ones I've found is produced by oracle corp, and as such are little more than advertising pieces pushing their technology of the moment.

I'm specifically interested in Database technologies.

From stackoverflow
  • Here's a list: http://www.oracle.com/podcasts/index.html

  • Oracle Podcast Center


    Green Enterprise Podcasts

    Host: Paul Salinger, VP Marketing

    Listen to discussions with customers, partners, and Oracle green experts, exploring topics that can help Oracle customers better understand how Oracle products can support their sustainability initiatives and enable a green enterprise.


    Oracle AppCasts

    Host: Cliff Godwin, SVP, Applications Technology

    Tune into "Live with Cliff" to hear from application technology experts, product and industry experts, and customers about what's saving Oracle customers time and money when using Oracle E-Business Suite, PeopleSoft, and JD Edwards applications.


    Oracle Customer SuccessCasts

    Tune into Oracle Customer SuccessCasts, where customers describe how Oracle helps them to run their businesses more successfully.


    Oracle Database Podcasts

    Tune into this podcast series to get the latest information on Oracle Database from Oracle technical experts.


    Oracle Fusion Middleware Radio

    Host: Rick Schultz, VP, Product Marketing for Oracle Fusion Middleware & Security Products

    Tune into this podcast series about Oracle Fusion Middleware to hear about Oracle's middleware product strategy and explore what middleware means to your business—growth, agility, insight, and reduced risk.


    Oracle Magazine Feature Casts

    Tune into conversations with Oracle Magazine editors, authors, and Oracle subject matter experts about featured articles in Oracle Magazine. Go beyond print with additional insight into Oracle products, technologies, customers, and more.


    Oracle PartnerNetwork (OPN) PartnerCast

    Tune in and learn how to grow your business with Oracle, exclusively for Oracle PartnerNetwork members.


    Oracle Technology Network Arch2Arch Podcast

    Host: Bob Rhubart, Manager, Architect Community, OTN

    Listen in as architects and other experts from across the Oracle community discuss the topics, tools, and technologies that drive the evolution of software architecture.


    Oracle Technology Network TechCasts

    Host: Justin Kestelyn, OTN Editor-in-Chief

    Tune into "fireside chats" with experts about new tools, technologies, and trends in application development.


    Oracle@Work

    Through Oracle@Work Video Podcasts you'll learn how Oracle customers from aerospace and automotive to travel and television address business and technical issues with the latest Oracle technology and applications solutions. Oracle@Works play like short television news magazine pieces shot on location, world wide. See Oracle customers in action, first hand, with Oracle@Work Video Podcasts.


    Profit Online Executive Briefing Audiocasts

    Every month, Profit Online presents conversations with Oracle executives, customers, and partners, discussing developments in their businesses and trends in their industries. Tune into and stay up to date on how IT and business leaders are expanding into new markets, improving business processes, and creating the future of the enterprise.


    Reference: Oracle Podcasts

  • Asking for an "Oracle podcast" that isn't going to be a product marketing focused is too broad. It's almost like asking for a "Microsoft Podcast." Anything you get is going to be broad and shallow. An introduction, nothing in depth.

    What are you looking for? DB, Middleware, Linux/OS, ERP, CRM, BI, Information Security, Identify Management, Integration, PL/SQL etc. . . . For what kind of audience? Developer, Sysadmin, DBA, Apps DBA (very diff believe it or not), Technology Manager, Accountant, Finance Director, White Hat security specialist, etc.

    Matthew Watson : Fair comment, I have updated the query slightly. Although, I haven't been able to find many non Oracle corp endorsed podcasts of any Oracle technology.

XSL Conversion XML->XML outputs only text?

Hi I have following XAML code which is the output from XamlWriter.Save():

<StackPanel Name="itemStack" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:mm="clr-namespace:MindManager;assembly=MindManager">
  <mm:Item Width="Auto" Height="Auto">
    <Border BorderThickness="10,10,10,10" Name="border1" Height="Auto">
      <DockPanel>
        <DockPanel LastChildFill="True" Name="dockPanel1" Height="33" DockPanel.Dock="Top">
          <Button Name="deleteItemButton" Width="26" Height="21.638" FlowDirection="LeftToRight" DockPanel.Dock="Right" Grid.IsSharedSizeScope="False">x</Button>
          <TextBox Name="tagsTextBox" Height="19">1</TextBox>
        </DockPanel>
        <TextBox TextWrapping="Wrap" MinLines="5" AcceptsReturn="True" AcceptsTab="True" HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Disabled" AutoWordSelection="True" Name="contentTextBox" Width="Auto" MinWidth="600" Height="Auto" MinHeight="80">2</TextBox>
      </DockPanel>
    </Border>
  </mm:Item>
  <mm:Item Width="Auto" Height="Auto">
    <Border BorderThickness="10,10,10,10" Name="border1" Height="Auto">
      <DockPanel>
        <DockPanel LastChildFill="True" Name="dockPanel1" Height="33" DockPanel.Dock="Top">
          <Button Name="deleteItemButton" Width="26" Height="21.638" FlowDirection="LeftToRight" DockPanel.Dock="Right" Grid.IsSharedSizeScope="False">x</Button>
          <TextBox Name="tagsTextBox" Height="19">3</TextBox>
        </DockPanel>
        <TextBox TextWrapping="Wrap" MinLines="5" AcceptsReturn="True" AcceptsTab="True" HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Disabled" AutoWordSelection="True" Name="contentTextBox" Width="Auto" MinWidth="600" Height="Auto" MinHeight="80">4</TextBox>
      </DockPanel>
    </Border>
  </mm:Item>
</StackPanel>

I want to convert it to simpler XML with the following XSL:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl" xmlns:mm="clr-namespace:MindManager;assembly=MindManager">  
  <xsl:output method="xml" indent="yes"/>
    <xsl:template match="/StackPanel">
      <mindcontainer>
        <xsl:for-each select="mm:Item">
          <minditem>
            <xsl:value-of select="/tagsTextBox"/>
            <xsl:value-of select="/contentTextBox"/>
          </minditem>
        </xsl:for-each>
      </mindcontainer>
    </xsl:template>
</xsl:stylesheet>

I want the output to have the following format:

<mindcontainer>
 <minditem>
   content of tagsTextBox
   content of contentTextBox
 </minditem>
 <minditem>
   content of tagsTextBox
   content of contentTextBox
 </minditem>
</mindcontainer>

But the problem is that all I get from it is:

  x
  1

2







  x
  3

4

One can see that there is only text, there are not text, also the filter doesn't work the x is the label of the close button which I do not want to be outputted.

This is the code Iam using to perform the transform:

    XmlWriterSettings settings = new XmlWriterSettings();
    settings.Indent=true;

    StringBuilder sb = new StringBuilder();
    using (XmlWriter wr = XmlWriter.Create(sb, settings))
    {
        XamlWriter.Save(scrollViewer1.Content, wr);
    }

    settings.ConformanceLevel = ConformanceLevel.Auto;
    using (XmlReader rd = XmlReader.Create(new StringReader(sb.ToString())))
    {
        XslCompiledTransform trans = new XslCompiledTransform();
        trans.Load("output.xsl");

        trans.Transform(rd, XmlWriter.Create("mindstore.xms", settings));
    }
From stackoverflow
  • In XPath/XSLT 1.0, to select (or match) an element that's in a namespace, you must declare a namespace prefix and use that prefix in your expressions (or patterns). Don't be fooled by the fact that <StackPanel> and other elements don't use prefixes in the input XML. It's using a default namespace, as determined by this default namespace declaration:

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    

    So you need a corresponding declaration in your stylesheet (as you did for the "mm" namespace), except that you need to pick a namespace prefix to use. Any prefix will do (just as you didn't actually have to use "mm").

    <xsl:stylesheet version="1.0"
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      ...>
    

    Then, in your stylesheet, you need to update your expressions and patterns to use the prefix you chose ("x" in my example above):

    <xsl:template match="/x:StackPanel">
    

    The reason you're seeing the output you're getting is that your template rule isn't ever getting invoked (because the name doesn't match). Instead, the built-in template rules for each of the XPath node types is getting invoked. For the root node and element nodes, it's to just keep processing children. For text nodes, it's to copy them through. Thus, the behavior you're seeing is the same behavior you'd get with any empty stylesheet (that has no template rules): a dump of all the text nodes in the input document.

    It can be a pain to have to prefix every name test in every expression or pattern. That's why XSLT 2.0 introduced a feature called xpath-default-namespace, which makes it possible for XPath expressions and XSLT patterns to use a default namespace, just like elements can in XML. In that case, all you'd have to change is to add one line:

    <xsl:stylesheet version="2.0"
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
      xpath-default-namespace="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      ...>
    

    But that's only if you you're using an XSLT 2.0 processor. (MSXML, for example, doesn't support XSLT 2.0.)

    Before I leave you, I see some more issues in your stylesheet (which you, no doubt, would have discovered next):

            <xsl:value-of select="/tagsTextBox"/>
            <xsl:value-of select="/contentTextBox"/>
    

    Starting an expression with "/" means "start from the document/root node". So these expressions are looking for a <tagsTextBox> document element and a <contentTextBox> document element, respectively. Based on what I see in your sample input document, I think what you meant to write is this:

            <xsl:value-of select=".//x:TextBox[@Name = 'tagsTextBox']"/>
            <xsl:value-of select=".//x:TextBox[@Name = 'contentTextBox']"/>
    

    Hope this helps! Let me know if anything needs further explanation.

  • You problems are in the XSLT, at the very least:

    1. You need to put your matching expressions in the right namespaces as they are to match. E.g.

      ... xml:xaml='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
      <xsl:template match='/xaml:StackPanel'>...
      
    2. The value-of expressions (match /tagsTextBox and /contentText) Boxseem to be intended to match within the StackPanel, but:

      • Also lack namespace qualification
      • Are matching immediate children of the document root, rather than descendent nodes of the current content node. Likely you need:

        <xsl:value-of select='descendent::xaml:TextBox'/>
        

    And possibly more.

Lazy choices in Django form

I have a Django my_forms.py like this:

class CarSearchForm(forms.Form):  
    # lots of fields like this
    bodystyle = forms.ChoiceField(choices=bodystyle_choices())

Each choice is e.g. ("Saloon", "Saloon (15 cars)"). So the choices are computed by this function.

def bodystyle_choices():  
    return [(bodystyle.bodystyle_name, '%s (%s cars)' %  
          (bodystyle.bodystyle_name, bodystyle.car_set.count()))  
          for bodystyle in Bodystyle.objects.all()]

My problem is the choices functions are getting executed every time I merely import my_forms.py. I think this is due to the way Django declares its fields: in the class but not in a class method. Which is fine but my views.py imports my_forms.py so the choices lookups are done on every request no matter which view is used.

I thought that maybe putting choices=bodystyle_choices with no bracket would work, but I get:

'function' object is not iterable

Obviously I can use caching and put the "import my_forms" just in the view functions required but that doesn't change the main point: my choices need to be lazy!

From stackoverflow
  • Try using a ModelChoiceField instead of a simple ChoiceField. I think you will be able to achieve what you want by tweaking your models a bit. Take a look at the docs for more.

    I would also add that ModelChoiceFields are lazy by default :)

  • Another solution is to move the bodystyle field to the class constructor:

    class CarSearchForm(forms.Form):
      def __init__(self, *args, **kwargs):
        super(CarSearchForm, self).__init__(*args, **kwargs)
        self.fields['bodystyle'] = forms.ChoiceField(choices=bodystyle_choices())
    
    Tom Viner : I think I will keep the class definition part, but have self.fields['bodystyle'].choices = bodystyle_choices() in the constructor.
  • You can use the "lazy" function :)

    from django.utils.functional import lazy
    
    class CarSearchForm(forms.Form):  
        # lots of fields like this
        bodystyle = forms.ChoiceField(choices=lazy(bodystyle_choices, tuple)())
    

    very nice util function !

Generate a commutative hash based on three sets of numbers?

I need to generate a commutative hash based on three sets of "score" structs.

Each score has a "start", an "end" and a "number".

Both start and end are usually huge numbers (8-9 digits) but number is just from 1 to 4.

I need them to be commutative so the order does not matter. I'm using XOR at the moment but it seems to be giving bad results.

Since I'm working with large large datasets, I'd prefer a performance-friendly solution. Any suggestions? Thanks =]

 public static int getCustomHash(cnvRegion c1, cnvRegion c2, cnvRegion c3)
 {
  int part1 = (c1.startLocation * c2.startLocation * c3.startLocation);
  int part2 = (c1.endLocation * c2.endLocation * c3.endLocation);
  int part3 = (c1.copyNumber + c2.copyNumber + c3.copyNumber)*23735160;
  return part1 ^ part2 ^ part3;
 }
From stackoverflow
  • Thomas Wang has a discussion of hash functions here.

    • See the knuth's method, and the 64 to 32-Bit mix functions.

    Paul Hsieh also has a page on integer hashing, which describes his "SuperFastHash" function which got mixed feedback.

    EDIT

    Because you want your custom hash to be commutative (I assume between the cnvRegion params) you could probably write something like this:

    public int hash6432shift(long key)
    {
       key = (~key) + (key << 18); // key = (key << 18) - key - 1;
       key = key ^ (key >>> 31);
       key = key * 21; // key = (key + (key << 2)) + (key << 4);
       key = key ^ (key >>> 11);
       key = key + (key << 6);
       key = key ^ (key >>> 22);
       return (int) key;
    }
    
    public static int getCustomHash(cnvRegion c1, cnvRegion c2, cnvRegion c3)
    {
        int part1 = (c1.startLocation ^ c2.startLocation ^ c3.startLocation);
        int part2 = (c1.endLocation ^ c2.endLocation ^ c3.endLocation);
        int part3 = (c1.copyNumber ^ c2.copyNumber ^ c3.copyNumber);
    
        int hash1 = hash6432shift(((long)part1 << 0x20) | part2);
        return hash6432shift(((long)hash1 << 0x20) | part3);
    }
    

    However, in the end the task of finding a hash function that is both fast and provides good collision resistance is very dependent of the data you are processing.

    Let me give you an example:

    Let's say that the values you are hashing are large, 10 digit numbers, and they represent a UNIX timestamp (the time elapsed in seconds since 01/01/1970). In this case, hashing a lot of timestamps that occur within a limited time span - say over a month is simply a matter of eliminating the portion that doesn't change, and using only the portion of the timestamp that changes a lot. This is the same as saying that you are eliminating the portions that have low entropy.

    v1 = 1241536920   // 5/5/2009 3:22:00 PM
    v2 = 1241529720   // 5/5/2009 1:22:00 PM
    v3 = 1241270520   // 5/2/2009 1:22:00 PM
    v4 = 1242825720   // 5/20/2009 1:22:00 PM
    

    It is pretty clear that we could safely eliminate the first 3-4 digits and only use the remaining digits as the hash. Also, if these values usually occurred within a few minutes of each other you can also drop the last 2-3 digits.

    In this manner, you're left with only 4 digits that you can use as a hash with a pretty good collision resistance for our case example.

    My point is that hash functions can be highly optimized if you know the statistical distribution of the values your are trying to hash.

    DarkAmgine : I'm having a hard time understanding the crypto language, and the information doesnt seem to apply to my case (getting a COMMUTATIVE hash from THREE sources).
    DarkAmgine : so I was looking at the hashes that my original code generated and was surprised to see it fairly evenly distributed from -2147483648 to +2147483647 Turns out I'm just getting a lot of collisions because there's just too many data for using int. Thanks
    Miky Dinescu : Well, in that case you'll probably have to try Int64.. :)
    DarkAmgine : by the way, do you know what ">>>" means? c# doesn't seem to like it...
    DarkAmgine : nevermind, i used >> and it worked.
    Miky Dinescu : In Java, the ">>>" is an unsigned right shift and it is the same thing as doing a right shift on an UInt32 in C#. (Java doesn't have unsigned types)
  • First, I think the requirements are not quite clear. If you hash three datasets c1, c2 and c3. Then if you switch, c1.copyNumber and c2.copyNumber and hash again. Should that give the same result or not? If you switch c1.startLocation with c1.endLocation. Should that result in the same hash or not?

    I'm going to assume that you'd like to have different hash results in both cases and that the only permutation that should not change the hash result are permutations of the datasets c1, c2, c3.

    If that is the case then I'd propose to first hash the three datasets independently to smaller values. I.e. h1 = H(c1) h2 = H(c2) h3 = H(c3) where H can be any hash function (e.g., CRC32, Adler32, SHA1 etc) depending on how hard you want to avoid collisions.

    The next step would be to compute a commutative hash of h1, h2, h3. If you want to avoid collisions unless h1, h2, h3 are permuted then the following works. Compute the polynomial

    • P(x) = (x-h1)(x-h2)(x-h3)

    then hash the polynomial (rsp. its coefficients) with any good hash function. I.e. that would be

    • H(h1+h2+h3 || h1 * h2 + h1 * h3 + h2 * h3 || h1 * h2 * h3), where || is concatenation.

    If you want to avoid any unecessary collision at all cost then the coefficients should be computed as multiprecision integers and a collision resistant hash function such as SHA1 should be used. Because of the unique factorisation property of polynomials if follows that the coefficents of the polynomial are different if h1, h2 and h3 are different. But it seems that avoiding collisions at all cost is overkill in your case.

    So rather than computing a polynomial P(x) symbolically one could just evaluate it at a arbitrary value R. I.e. if h1, h2, h3 are just 32-bit values then computing the following might be enough: (some C type pseudocode follows. I'm don't know what C# uses for 64-bit integers)

    const long long R = SOME_RANDOM_64_BIT_CONSTANT;
    long long hash0 = (R - h1) * (R - h2) * (R - h3);
    int hash = (int) (hash0 >> 32);
    

    I'm 64-bit multiplication here, because they are fast enough on modern CPUs and I'm using the upper 32-bit of hash0 rather than the lower 32 bit because the lower 32 bits are somewhat biased. I.e., the least significant bit is much more likely to be 0 than 1.

Can I 'open source' the sources to my site and still copyright the contents?

I have put up the sources of my site on GitHub for easy maintenance. While the majority of the content is in a wordpress database, there are a few html files which contain some content. Since these files are in a open source repository, I was wondering if I can enforce a copyright on them.

From stackoverflow
  • Open Source does not mean that you will not have any copyright. Mostly, it is about transparency by distributing the source so that the receiver can have a look and modify the program should need be, should he want to. What happens to the derivative work depends on the exact clauses of the license. There are quite a few licenses you can choose from like MIT, BSD, GPL, Creative Commons etc. Choose one that fits your needs the best.

    sandesh247 : @dirkgently: "Open Source does not mean that you will not have any copyright." I don't know how I missed that. Thanks.
  • Sure you can. The right to retain copyright is completely independent of the availability of the source code. Open-source, closed-source, freeware, or shareware, it is simply a mark of intellectual property. If you observe many (most?) of the projects on such project hosting sites as SourceForge and CodePlex, or even articles on CodeProject, the author(s) have declared copyright. Creations released into the public domain cannot have be copyrighted of course (or their copyright has expired), but this is only a subset of the much wider open source category.

    I would recommend that you just place your appropiate copyright notice in each file that you own (whether they interact with WordPress does not matter of course) and additionally place the full notice in a separate file (Readme or Copyright is standard), including explicit attribution to all the authors (team or individuals).

    As a side note, the wikipedia article on copyright law should give you a good idea of more precisely what copyright entails internationally and in various countries/regions. Finally, it's worth just observing that the Perens' principle states that open source material should have very relaxed or even no copyright restrictions. Of course, this is only a principle, and in reality most authors want to put some limited restrictions on their creations, as the widely used GPL (and to a lesser degree LGPL) licenses provide, while others (such as the BSD I believe) license practically allow any use as far as distribution and derivative works go, as far as I know.

    Jon Rimmer : You may want to check GitHub's policy on storing non Open Source licensed content in a public repository though. While you would retain copyright, you might be in violation of their terms and conditions (I only speculating here though, I have never used GitHub).
    Noldorin : @Jon: Yeah, you have a fair point. I haven't used GitHub either, so it's worth checking into. I know there are no problems with SourceForge, CodePlex, Launchpad, among other hosts, but they do all have their own rules to varying degrees.
    sandesh247 : @Jon: Thanks for the advice, I'll make sure.

Restrict Windows shell extension to folder/drive

Hey guys,

I'm working on a shell extension that is supposed to display extended properties of files (mostly .jpgs) stored on a virtual drive (think of it as an external harddrive).

Is it possible to register the shell extension in a way that it only kicks in for files of a specific folder/drive (in my case the external harddrive) and leaves the handling of jpgs in other folder to the Windows default shell extension?

Regards,

Sebastian

From stackoverflow
  • As far as I have understood the shell extension registration in the registry, there is no such thing as "limit it to a certain folder". Your extension would have to be registered globally, and implemented in a way that simply displays no additional context menu items when not appropriate.

    In the registry, shell extensions are bound to file types in the CLASSES_ROOT key. The whole process is designed to be file-centric. So file type resolution is the best you can get. Looking at it, everything else (like path/drive/drive type of a given file) would be too volatile to make basing an extension registration on it a sensible thing.

dashed line in Jfreechart

hi,

Does anybody knows how to draw a vertical dashed line in Jfreechart at some given coordinates ?

Thanks

From stackoverflow
  • Example 5 shows a series of dashed lines for a chart. Set your stroke thus:

    plot.getRenderer().setSeriesStroke(
        0, 
        new BasicStroke(
            2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND,
            1.0f, new float[] {6.0f, 6.0f}, 0.0f
        )
    

    and you'll need to set your dataset to simply reference the coordinates of your vertical line.

How to validate currency value using JavaScript?

I have some input fields in a page and i want to validate if they contain currency values such as $100 or with euro.

Any one have an idea or example?

From stackoverflow
  • a regex can validate that for you:

    /[\$£¥]\d+(\.\d\d)?/
    

    (but with the euro sign in there too)

    this one I've given won't be the most robust way to do it. You could alter to your preference. An alternative is to try something like this:

    var myString = "$55.32",
        currency = parseFloat(myString.replace(/^[^\d\.]*/, ''))
        valid = !isNaN(currency)
    ;
    

    It strips away any non-number or . characters from the start and then parses it as a float.

  • The problem here is threefold:

    1. There are a lot of currency symbols;
    2. Currencies share the same symbol (does $ mean Australian or US dollars for example); and
    3. Locale differences in writing numbers (eg 3,000.00 in English is 3'000,00 in German).

    My advice? Just take numbers and forget about the currency symbol. If however detecting the currency is the whole point then either select that separately or you'll need to implement at least a subset of the above list of currencies plus the locale differences.

LINQ to XML - How does it work?

My question is essentially a simple one, though I'm looking for as in-depth an answer possible here: how does LINQ to XML work behind the scenes?

Now, I have had a fair amount of experience working with LINQ to XML for various applications, so it's interfaces is nothing strange to me, but I am quite clueless as to how the internals operate. Now, I do have some understanding of generally how LINQ providers work (implementing IQueryable and IQueryProvider and utilising the visitor pattern, in essence). However, I haven't been able to discover anything about the LINQ provider for LINQ to XML - even messing around with Reflector didn't get me anywhere, though perhaps I was missing the obvious. Most interestingly, I wasn't able to find any evidence of a LINQ provider (implementation of IQueryProvider) within the System.Xml.Linq assembly/namespace.

From observing the LINQ to XML model, it has struck me as a rather unique form of LINQ in that LINQ queries and the associated syntax don't seem quite so integral to the technology, and it rather seems to be based more around a queryable DOM model that provides a lot of useful extension methods. So really, what I would firstly like to know is, does LINQ to XML even have a query provider in the standard sense (that LINQ to SQL has for example), or is it essentially a framework with extension methods on top of which you can use LINQ to Objects to facilitate usage. In addition, I'm also curious how the parsing/conversion from XML code to the DOM hierarchy is done - is XDocument qutie similar to the old XmlDocument in this sense? Does it use an XmlReader or such behind the scenes to parse and interpret the document upon load?

This is very much an open ended question, so any sort of information regarding how LINQ to XML operates behind the scenes would be most welcome. My intention here is primarily to build up a picture of how this specific LINQ technology was designed so that I might subsequently attempt to emulate it myself for a format with similar structure to XML.

From stackoverflow
  • LINQ to XML is really just LINQ-to-Objects, that work on objects representing XML. So when you write a LINQ query to retrieve nodes from an XDocument (for example), you are actually just invoking extension methods that returns IEnumerable<T>'s, and invoking the standard query operators as they are defined for IEnumerable<T>.

    So, one could say that LINQ-to-XML mostly consists of the XElement family of XML-representing classes and the many extension methods that are provided for those, in order to make queries easier.

    This is also explained here.

    Noldorin : Yeah, this is pretty much what I was suspecting. Thanks for the info.

Android: Enable/Disable Auto Sync and Background Data

I want to develop an application that disable the Background Data (new feature in Android 1.5) and Auto Sync and then enable GPRS/EDGE connection and vice versa.

I figured out how to enable/disable GPRS/EDGE by changing the APN settings. (weird solution. However; Android developers couldn't think a user may want to disable GPRS/EDGE) But, I couldn't find a way to enable/disable Auto Sync and Background data.

I investigated the Android code and as I understood, the Sync operation is an intend. So, I wanted to reach with putExtra to the intend and trigger the enabling/disabling. But; I couldn't find the correct keyword. Or may be I am totally wrong. SO, I need some advice.

If you could tell me how can I do or where should I look, I would be very happy. Thank you.

From stackoverflow
  • In my HTC dreams, there is a checkbox to disable the auto sync. I can look for the menu arborescence if you wish so you can find what the callback function is in the android source code. But I am pretty sure auto synch cannot completely be disable. Unchecking auto sync will prevent sync from being performed on a timed basis, but it will occur everytime you run an app with synch capabilities if any network data connection is available.

    Good luck anyway.

    EDIT :

    There are two ways to get the info you desire.

    First, I thing you can use the code in ndroid-sources/packages/apps/Settings/src/com/android/settings/Utils.java to create an activity that will list all the keys of the intent then find the one you want.

    The other way is to write a nice mail to guy who made the Toogle Setting app (http://smartphoneandroid.com/2008/12/28/toggle-setting-perfect-app-for-android-phone.html) since he obviously found a solution to your problem. His email adress is written in the app sheet on the android market. I won't write it here, but if you do not have access to real android phone, I can mail it to you on a yopmail adress.

    Omer : If you can find the callback function, I will be very happy. I dig for this information. However; I couldn't find anything. On the other hand, I know that I can not prevent the third party applications to use GPRS/EDGE. But, my main aim is to disable the sync with Google server only. Because; As I observed if auto sync is on, Google sync uses most of my data plan.
  • Background data is a secure setting, so cannot be changed by user applications. But bear in mind, it's just a setting - it's not enforced. Apps are meant to read it and respect it but I bet some don't.

    Omer : If I can find out to disable auto sync only, Background Data may not be a problem.

tomcat polling issue

Hi

I am not sure if anyone else encountered this issue,

I have a java app that polls data from an external provider every second, it works fine and polls data as required -this is a console app

I have written a jsp service that does the same, it is basically returning the same data that the console app writes to the console, instead, it is just writing that data to a web page.

The problem now is that the webpage is getting updated every 8.04 seconds, i have checked the tomcat console and it is connecting to the app on the every 8th attempt. is there a way i can solve this polling issue?

It might be a small question but your help would be greatly appreciated.

Many Thanks,

From stackoverflow
  • Could it be caching each request? It would depend on how your Tomcat service is configured or what library you are using to access the Tomcat server. you could try and append a

    "?time="+System.currentTimeMillis()

    to the end of your URL and see if the behavior has changed.

Finding Directed Acyclic Graph (DAG) Minimal Elements (Vertices) with XSLT/XPath?

I have an XML file that encodes a directed acyclic graph (DAG) that represents a partial order. Such graphs are useful for things like specifying dependencies and finding critical paths. For the curious, my current application is to specify component dependencies for a build system, so vertices are components and edges specify compile-time dependencies. Here is a simple example:

<?xml version="1.0"?>
<dag>
    <vertex name="A">
        <directed-edge-to vertex="C"/>
    </vertex>
    <vertex name="B">
        <directed-edge-to vertex="C"/>
        <directed-edge-to vertex="D"/>
    </vertex>
    <vertex name="C">
        <directed-edge-to vertex="E"/>
    </vertex>
    <vertex name="D">
        <directed-edge-to vertex="E"/>
    </vertex>
    <vertex name="E">
        <directed-edge-to vertex="G"/>
    </vertex>
    <vertex name="F">
        <directed-edge-to vertex="G"/>
    </vertex>
    <vertex name="G"/>
</dag>

This DAG may be drawn like this:

I'd like to apply an XSLT stylesheet that produces another XML document that contains only the vertices that correspond to minimal elements of the partial order. That is, those vertices that have no incoming edges. The set of minimal vertices for the example graph is {A, B, F}. For my build dependency application, finding this set is valuable because I know that if I build the members of this set, then everything in my project will be built.

Here is my current stylesheet solution (I'm running this with Xalan on Java using Apache Ant's xslt task). A key observation is that a minimal vertex will not be referenced in any directed-edge-to element:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:xalan="http://xml.apache.org/xslt"
                exclude-result-prefixes="xalan">
    <xsl:output method="xml" indent="yes" xalan:indent-amount="4"/>

    <xsl:template match="dag">
        <minimal-vertices>
            <xsl:for-each select="//vertex">
                <xsl:if test="not(//vertex/directed-edge-to[@vertex=current()/@name])">
                    <minimal-vertex name="{@name}"/>
                </xsl:if>
            </xsl:for-each>
        </minimal-vertices>
    </xsl:template>
</xsl:stylesheet>

Applying this stylesheet produces the following output (which I believe is correct):

<?xml version="1.0" encoding="UTF-8"?>
<minimal-vertices>
    <minimal-vertex name="A"/>
    <minimal-vertex name="B"/>
    <minimal-vertex name="F"/>
</minimal-vertices>

The thing is, I'm not completely satisfied with this solution. I'm wondering if there is a way to combine the select of the for-each and the test of the if with XPath syntax.

I want to write something like:

<xsl:for-each select="//vertex[not(//vertex/directed-edge-to[@vertex=current()/@name])]">

But that does not do what I want because the current() function does not reference the nodes selected by the outer //vertex expression.

Thusfar, my solution uses XPath 1.0 and XSLT 1.0 syntax, though I'm open to XPath 2.0 and XSLT 2.0 syntax as well.

Here's the Ant build script if you like:

<?xml version="1.0"?>
<project name="minimal-dag" default="default">
    <target name="default">
        <xslt in="dag.xml" out="minimal-vertices.xml" style="find-minimal-vertices.xsl"/>
    </target>
    <target name="dot">
        <xslt in="dag.xml" out="dag.dot" style="xml-to-dot.xsl"/>
    </target>
</project>

The dot target generates Graphviz Dot language code for rendering the graph. Here is xml-to-dot.xsl:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:xalan="http://xml.apache.org/xslt"
                exclude-result-prefixes="xalan">
    <xsl:output method="text"/>

    <xsl:template match="dag">
        digraph {
        rankdir="BT";
        node [style="filled", fillcolor="cyan", fontname="Helvetica"];
        <xsl:apply-templates select="//directed-edge-to"/>
        }
    </xsl:template>

    <xsl:template match="directed-edge-to">
        <xsl:value-of select="concat(ancestor::vertex/@name, '->', @vertex, ';')"/>
    </xsl:template>
</xsl:stylesheet>
From stackoverflow
  • You can take advantage of XPath's implicit existential quantification on the = operator:

    <xsl:for-each select="//vertex[not(@name = //vertex/directed-edge-to/@vertex)]">
    

    When you use any of the six comparison operators (=, !=, <, <=, >, and >=) to compare a node-set, the expression will return true if any node in the node-set satisfies the condition. When comparing one node-set with another, the expression returns true if any node in the first node-set satisfies the condition when compared with any node in the second node-set. XPath 2.0 introduces six new operators that don't perform this existential quantification (eq, ne, lt, le, gt, and ge). But in your case, you'll want to use "=" to get that existential quantification.

    Note of course, that you'll still want to use the not() function as you were doing. Most of the time, it's good to avoid the != operator. If you used it here instead of not(), then it would return true if there are any @vertex attributes that are not equal to the @name value, which is not your intention. (And if either node-set is empty, then it would return false, as comparisons with empty node-sets always return false.)

    If you want to use eq instead, then you'd have to do something like you did: separate out the conditional from the iteration so you could bind current(). But in XPath 2.0, you can do this within an expression:

    <xsl:for-each select="for $v in //vertex
                          return $v[not(//directed-edge-to[@vertex eq $v/@name])]">
    

    This is useful for when your condition isn't a simple equality comparison (and thus can't be existentially quantified using "="). For example: starts-with(@vertex, $v/@name).

    XPath 2.0 also has an explicit way of performing existential quantification. Instead of the for expression above, we could have written this:

    <xsl:for-each select="//vertex[not(some $e in //directed-edge-to
                                       satisfies @name eq $e/@vertex)]">
    

    In addition to the "some" syntax, XPath 2.0 also supplies a corresponding "every" syntax for performing universal quantification.

    Rather than using for-each, you could also use template rules, which are more modular (and powerful):

    <xsl:stylesheet version="1.0"
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    
      <xsl:template match="/">
        <minimal-vertices>
          <xsl:apply-templates/>
        </minimal-vertices>
      </xsl:template>
    
      <!-- Copy vertex elements that have no arrows pointing to them -->
      <xsl:template match="vertex[not(@name = //directed-edge-to/@vertex)]">
        <minimal-vertex name="{@name}"/>
      </xsl:template>
    
    </xsl:stylesheet>
    

    Again, in this case, we're relying on the existential quantification of =.

    XSLT 1.0 prohibits use of the current() function in patterns, i.e., in the match attribute, but XSLT 2.0 allows it. In that case, current() refers to the node currently being matched. So in XSLT 2.0, we could also write this (without having to use a for expression):

    <xsl:template match="vertex[not(//directed-edge-to[@vertex eq current()/@name])]">
    

    Note that this pattern is essentially the same as the expression you tried to use in for-each, but whereas it doesn't do what you want in for-each, it does do what you want in the pattern (because what current() binds to is different).

    Finally, I'll add one more variation that in some ways simplifies the logic (removing not()). This also goes back to using XSLT 1.0:

    <xsl:stylesheet version="1.0"
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    
      <xsl:template match="/">
        <minimal-vertices>
          <xsl:apply-templates/>
        </minimal-vertices>
      </xsl:template>
    
      <!-- By default, copy vertex elements -->
      <xsl:template match="vertex">
        <minimal-vertex name="{@name}"/>
      </xsl:template>
    
      <!-- But strip out vertices with incoming arrows -->
      <xsl:template match="vertex[@name = //directed-edge-to/@vertex]"/>
    
    </xsl:stylesheet>
    

    If you don't like the whitespace being output, add an empty rule for text nodes, so they'll get stripped out (overriding the default rule for text nodes, which is to copy them):

    <xsl:template match="text()"/>
    

    Or you could just be more selective in what nodes you apply templates to:

    <xsl:apply-templates select="/dag/vertex"/>
    

    Which approach you take is partially dependent on taste, partially dependent on the wider context of your stylesheet and expected data (how much the input structure might vary, etc.).

    I know I went way beyond what you were asking for, but I hope you at least found this interesting. :-)

    Greg Mattes : Great Answer! Thanks for all of the variations and clear explanations. Hopefully this answer will help lots of people in the future! (this could have been broken into several answers)
    Evan Lenz : I'm glad you found it helpful. Thanks for the vote. I'm still learning how to use this website. Should I have provided separate responses?
    Greg Mattes : Providing separate answers or one answer with several variations is a matter of taste. Independent answers allow independent voting. For example, maybe I would have accepted an answer that uses apply-templates as the best response, but the community might have preferred an answer using for-each. Other alternatives could have been down-voted. My accepted answer would be shown first and the community answer second when sorting by votes. Comments could be addressed to particular solutions.
    Evan Lenz : Makes perfect sense. Thanks for the tips!
  • One such XPath 1.0 expression is:

            /*/vertex[not(@name = /*/vertex/directed-edge-to/@vertex)]

    Then just put it into an XSLT stylesheet like that:

    <xsl:stylesheet version="1.0"
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
     <xsl:output omit-xml-declaration="yes" indent="yes"/>
    
        <xsl:template match="/">
          <minimal-vertices>
           <xsl:for-each select=
           "/*/vertex[not(@name = /*/vertex/directed-edge-to/@vertex)]"
           >
            <minimal-vertex name="{@name}"/>
           </xsl:for-each>
          </minimal-vertices>
        </xsl:template>
    </xsl:stylesheet>
    

    When this stylesheet is applied on the originally-provided XML document:

    <dag>
        <vertex name="A">
         <directed-edge-to vertex="C"/>
        </vertex>
        <vertex name="B">
         <directed-edge-to vertex="C"/>
         <directed-edge-to vertex="D"/>
        </vertex>
        <vertex name="C">
         <directed-edge-to vertex="E"/>
        </vertex>
        <vertex name="D">
         <directed-edge-to vertex="E"/>
        </vertex>
        <vertex name="E">
         <directed-edge-to vertex="G"/>
        </vertex>
        <vertex name="F">
         <directed-edge-to vertex="G"/>
        </vertex>
        <vertex name="G"/>
    </dag>
    

    The wanted result is produced:

    <minimal-vertices>
      <minimal-vertex name="A" />
      <minimal-vertex name="B" />
      <minimal-vertex name="F" />
    </minimal-vertices>
    

    Do note: A solution for traversing full (maybe cyclic) graphs is available in XSLT here.

    Greg Mattes : Thanks! This is a great answer too, it's very focused on the question that I asked. It was a tough decision, but I accepted Evan's answer because of the breadth of his answer. I am curious about why you prefer the /*/ syntax to //, is there any advantage with the extra character?
    Dimitre Novatchev : @greg-mattes THe "//" abbreviation should be avoided whenever possible as it is very expensive, causing the whole subtree rooted at the context node to be searched. "//" at the top level causes the whole XML document to be searched. It is very important *not* to use "//" whenever the structure of the XML document is known at the time of writing the XPath expression.
    Greg Mattes : So /*/ is better in general because it limits the search to a single level because * means "selects all element children of the context node" (http://www.w3.org/TR/xpath#path-abbrev) rather than all descendants which could be a large search? In this particular example it shouldn't make a difference, but it's a good point to keep in mind. Thanks again.
    Evan Lenz : I agree with Dimitre about the use of "//". And you're right that performance isn't much of a consideration for this particular data. However, another reason to use /*/vertex, or, even better, /dag/vertex, is that it makes your intentions more explicit. "*" implies that the document element's name may vary, and "//" implies that elements might appear as deeper descendants. You can save people reading your code from having to wonder such things by making your intentions more explicit. "//" is still useful, of course, when it's necessary, i.e. when it actually is your intention.

Why does Clang complain about all my autoreleased objects?

I have the following function:

- (NSString *)urlEncodedValue {
NSString *result = (NSString *)CFURLCreateStringByAddingPercentEscapes(
       kCFAllocatorDefault, 
       (CFStringRef)self, 
       NULL, 
       CFSTR("?=&+/\r\n"), 
       kCFStringEncodingUTF8
);

return [result autorelease];

}

Why is Clang giving me the following complaints?

  • 1 Call to function 'CFURLCreateStringByAddingPercentEscapes' returns a Core Foundation object with a +1 retain count (owning reference)
  • 2 Object sent -autorelease message
  • 3 Object returned to caller as an owning reference (single retain count transferred to caller)
  • 4 Object over-autoreleased: object was sent -autorelease but the object has zero (locally visible) retain counts

To the best of my knowledge, this conforms to Apple's guidelines regarding memory management and object ownership. Do I have to explicitly release the object? This error has come up 19 times in my project, all under similar circumstances. What am I doing wrong?

From stackoverflow
  • I've found the answer to my own question, posting it here if anyone else stumbles across the issue. I was using checker-0.198, checker-0.204 reports no such issue. Seems it was a temporary regression.

How do I dynamically create an Expression<Func<MyClass, bool>> predicate?

Hi all,

How would I go about using an Expression Tree to dynamically create a predicate that looks something like...

(p.Length== 5) && (p.SomeOtherProperty == "hello")

So that I can stick the predicate into a lambda expression like so...

q.Where(myDynamicExpression)...

I just need to be pointed in the right direction.

Thanks.

Edit: Sorry folks, I left out the fact that I want the predicate to have multiple conditions as above. Sorry for the confusion.

From stackoverflow
  • Original

    Like so:

        var param = Expression.Parameter(typeof(string), "p");
        var len = Expression.PropertyOrField(param, "Length");
        var body = Expression.Equal(
            len, Expression.Constant(5));
    
        var lambda = Expression.Lambda<Func<string, bool>>(
            body, param);
    


    Updated

    re (p.Length== 5) && (p.SomeOtherProperty == "hello"):

    var param = Expression.Parameter(typeof(SomeType), "p");
    var body = Expression.AndAlso(
           Expression.Equal(
                Expression.PropertyOrField(param, "Length"),
                Expression.Constant(5)
           ),
           Expression.Equal(
                Expression.PropertyOrField(param, "SomeOtherProperty"),
                Expression.Constant("hello")
           ));
    var lambda = Expression.Lambda<Func<SomeType, bool>>(body, param);
    
    Hovito : Thanks, but stupidly I forgot to mention that I'd like the predicate to read like... (p.Length == 5) && (p.SomeOtherProperty == "hello"). In other words, how do I chain the conditions? Sorry for not having been clear
    Hovito : Thanks alot for the update. Seems to be what I was looking for. Thanks
  • You could instantiate the expression and look at it with an Expression Tree visualizer. There is one in the Visual studio samples - you can compile it and then put it in a specific folder.

    That will give you a nice little tree that shows you how an expression is made up. Then you could construct such an expression with the static methods of the Expression object.

  • To combine several predicates with the && operator, you join them together two at a time.

    So if you have a list of Expression objects called predicates, do this:

    Expression combined = predicates.Aggregate((l, r) => Expression.AndAlso(l, r));
    
    Marc Gravell : Actually, you mean Expression.AndAlso. Expression.And is the bitwise and - i.e. where 2 & 1 = 3
    Daniel Earwicker : Thanks, corrected it.
  • Use the predicate builder.

    http://www.albahari.com/nutshell/predicatebuilder.aspx

    Its pretty easy!

Astar-like algorithm with unknown endstate

A-star is used to find the shortest path between a startnode and an endnode in a graph. What algorithm is used to solve something were the target state isn't specifically known and we instead only have a criteria for the target state?

For example, can a sudoku puzzle be solved with an Astar-like algorithm? We dont know how the endstate will look like (which number is where) but we do know the rules of sudoku, a criteria for a winning state. Therefore I have a startnode and just a criteria for the endnode, which algorithm to use?

From stackoverflow
  • A* requires a graph, a cost function for traversal of that graph, a heuristic as to whether a node in the graph is closer to the goal than another, and a test whether the goal is reached.

    Searching a Sudoku solution space doesn't really have a traversal cost to minimize, only a global cost ( the number of unsolved squares ), so all traversals would be equal cost, so A* doesn't really help - any cell you could assign costs one move and moves you one closer to the goal, so A* would be no better than choosing the next step at random.

    It might be possible to apply an A* search based on the estimated/measured cost of applying the different techniques at each point, which would then try to find a path through the solution space with the least computational cost. In that case the graph would not just be the solution states of the puzzle, but you'd be choosing between the techniques to apply at that point - you'd know an estimate of the cost of a transition, but not where that transition 'goes', except that if successful, it's one step closer to the goal.

    mizipzor : Yes, I can see now that sudoku was a bad example. Assuming you obey the rules of sudoku, for any given game you will end up in the same state using the same number of moves. Although the core of the question was whether an astar could be applied if we only knew a criteria for the endstate, rather than the exact endstate itself, sudoku was just an example of such a problem. Maybe I should rephrase the question. Good answer though. :)
  • Yes, A* can be used when a specific goal state cannot be identified. (Pete Kirkham's answer implies this, but doesn't emphasise it much.)

    When a specific goal state can't be identified, it's sometimes harder to come up with a useful heuristic lower bound on the remaining cost needed to complete a partial solution -- and the efficiency of A* depends on choosing an effective heuristic. But it doesn't mean it can't be applied. Any problem that can be solved on a computer can be solved using a breadth-first search, plus an array of flags indicating whether a state has been seen before; which is the same as A* with a heuristic lower bound that is always zero. (Of course, this is not the most efficient algorithm for solving many problems.)

  • You dont have to know the exact target endstate. It all comes down to the heuristic function, when it returns 0 you could assume to have found (at least) one of the valid endstates.

    So during the a*, instead of checking if current_node == target_node, check if current_node.h() returns 0. If so, it should be infinitely close and/or overlapping the goal/endstate.