Monday, February 21, 2011

How to map these classes with Hibernate?

Suppose I've these 2 classes:

class A{

    B ref1 = null; //Can both be null
    B ref2 = null;

}

class B{

    ..
}

I'm omitted the getters and setters for ref1 and ref2. Of course I want to add ids... Anyway what I want is to have hibernate handle automatic persistence of these two references... and to have automatic deletion of B objects. I thought of using one-to-one between each property ref* of A and B. But I got lost :) Can you give suggestions? I want to use SchemaExport.

Thank you.

From stackoverflow
  • you can achieve this behaviour by using the Cascade property of the OneToOne-Annotation. so with Hibernate Annotations / JPA Annotations youd have something like:

    @Entity
    public class AClass{
        @Id
        @GeneratedValue
        private long id;
        @OneToOne(cascade={Cascade.ALL, Cascade.DELETE_ORPHANS})
        private BClass b_1;
        @OneToOne(cascade={Cascade.ALL, Cascade.DELETE_ORPHANS})
        private BClass b_2;
    }
    
    @Entity
    public class BClass{
        private String someField;
    }
    

    in an XML-mapping the association should look something like this:

    <hibernate-mapping>
        <class name="AClass">
            <one-to-one cascade="all,delete-orphans" name="b_1" class="BClass" />
            <one-to-one cascade="all,delete-orphans" name="b_2" class="BClass" />
        </class>
    </hibernate-mapping>
    

    This should give you the wanted behaviour in cascading persistence operations onto the BClasses and delete any nonreferenced BClass Objects from the persistence layer.

    Have Fun!

    Frank

    gotch4 : thanks but I was looking for xml based mapping...
    gotch4 : moreover are you sure that it is safe to use one-to-one isn't it one to many for A?
    smeg4brains : well that depends on the data model, if you have one and only one reference from one AClass to one BClass it works, even if there are 2 fields holding BClasses in AClass. they just shouldnt be referencing the same instance
  • Hi,

    You have a @OneToMany relationship. But you have to adapt ORM to your model because of There is no @OneToTwo relationship available.

     <hibernate-mapping>
         <class name="ClassAa">
             <list name="classBbList">
                 <key column="CLASS_AA_ID" not-null="true"/>
                 <list-index column="CLASS_BB_INDEX"/>
                 <one-to-many class="ClassBb"/>
             </list>
         </class>
     <hibernate-mapping>
    

    Now your ClassAa looks like

    public class ClassAa {
    
        private ClassBb classBb1;
        private ClassBb classBb2;
    
        private List<ClassBb> classBbList = new ArrayList<ClassBb>();
    
        public void setClassBb1(ClassBb classBb1) {
            // You can use index 0 to store your classBb1
            if(getClassBbList().size == 0)
                getClassBbList().add(classBb1);
            else
                getClassBbList().set(0, classBb1);
        }
    
        public ClassBb getClassBb1() {
            if(getClassBbList().size() == 0)
                return null;
    
            return getClassBbList().get(0);
        }
    
        public void setClassBb2(ClassBb classBb2) {
            // You can use index 1 to store your classBb2
            switch(getClassBbList().size()) {
                case 0:
                    getClassBbList().add(null);
    
                    getClassBbList().add(classBb2);
                break;
                case 1:
                    getClassBbList().add(classBb2);
                break;
                case 2:
                    getClassBbList().set(1, classBb2);
                break;
            }
        }
    
        public ClassBb getClassBb2() {
            if(getClassBbList().size() < 2)
                return null;
    
            return getClassBbList().get(1);
        }
    
        public List<ClassBb> getClassBbList() {
            return this.classBbList;
        }
    
        public void setClasBbList(List<ClassBb> classBbList) {
            this.classBbList = classBbList;
        }
    
    }
    

    regards,

ColdFusion executing unwanted SQL statements

I have an application that loads a vast amount of data from twitter. We have began to notice some performance issues and so I setup SQL Profiler for the applications database. I have noticed the following SQL statement are being executed but do not appear anywhere in my code. Therefore, I am assuming that either SQL Server 2005 or ColdFusion 8 are adding these statements in for some reason.

  1. SET TRANSACTION ISOLATION LEVEL READ COMMITTED
  2. SET FMTONLY ON select Title from Links where 1=2 SET FMTONLY OFF
  3. exec [sys].sp_datatype_info_90 -9,@ODBCVer=4
  4. EXEC sp_executesql N'set implicit_transactions off select USER_NAME() select usertype,type,name from systypes where usertype>=257'
  5. EXEC sp_execute 16,'iTunes Store'
  6. exec sp_unprepare 28
  • I do not have any cftransaction's in my code
  • All my queries are being ran from cfqueries. (no stored procedures)
  • I am never running an execute or exec statement anywhere in my code
  • All these statements are being ran from my database user account specifically set up for my web application
  • The statements in #5 and #6 are replicated with many different numbers
  • The statement in #5 is replicated with many different strings

Why are these statements being added, are they needed, and if not how can I stop them?

From stackoverflow
  • It's by no means abnormal to see statements appear in profiler that you don't actually explicitly send yourself from the code.

    But that's the key point - you don't explicitly send them, but they are done implicitly as a result of the actions you are performing/how you're doing them.

    e.g. if you opened a recordset in VB6 then iterate round it, you'd see (e.g.) sp_cursor calls going through profiler - now these aren't being explicitly called by the code, but is as a result of ADO advancing through the connected recordset.

    I hope I've made some sort of sense

  • 1,2,3,4 can be accounted for in "normal" ColdFusion code - assuming you are on version 8 or 9. It does all sorts of mucking around in the backend to ensure the database server is capable and ready to return information automatically that ColdFusion requests as part of CFQUERY, even though it may not be explicitly called for in your actual query.

    http://www.forta.com/blog/index.cfm/2007/7/6/ColdFusion-8-Can-Return-Identity-Values

    I have no idea what 5 and 6 are doing.

    Also, are you using the Adobe provide MS SQL Driver or are you using the MS JDBC SQL Driver? There are some differences between using the two drivers:

    http://cfsearching.blogspot.com/2008/03/cf8-ms-jdbc-12-driver-and-for-my-next.html

Search Server 2010 - reference error

Hello,

Im running Search Server 2010 from a virtual machine and it works good so far. On my development machine (win xp 32bit), the thought is to query the search server with a web service. Problem is that when i try to start the site, i get the following error:

Could not load file or assembly 'Microsoft.Office.Server.Search' or one of its dependencies. An attempt was made to load a program with an incorrect format. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.BadImageFormatException: Could not load file or assembly 'Microsoft.Office.Server.Search' or one of its dependencies. An attempt was made to load a program with an incorrect format.

I copied the dll-file from virtual server after the installation of Search Server. Added it as a reference and its there in the bin-catalog. Compiles with no errors. The site is not a sharepoint site, but a EPiServer Site.

Any help is most appreciated.

/Mattias

From stackoverflow
  • Apparently the correct way to add the reference is via WEB reference...

Learning about Data Oriented Design

http://gamesfromwithin.com/data-oriented-design

I'm a bit fan of the article above. Where can I learn more about this? Anyone suggest a textbook, series of articles, or source code base to read?

From stackoverflow

Error While Debugging

Hi, I have one web application. while i debug the solution the rendering makes too slow and if i close the browser page i got one error like this

WebDev.WebServer.exe has encountered a problem and needs to close. We are sorry for the inconvenience.

I got one information from attched proess is that this .exe file related to asp.net development server- port(port number).

How it can be resolved? please help me..

From stackoverflow
  • You cannot close the browser that opens when you are running debug for an ASP.NET program.

    It renders slower because you are debugging it. This means the compiler has injected a lot of extra code need to make the application work with the debugger. There is no getting around this.

Is it possible to modify Adobe Air's WebKit settings in the mx:HTML component?

Adobe Air's (read: Flex) mx:HTML component uses WebKit to render webpages. As such, does anyone know of a way to tweak WebKit's settings via the Air application (or a Flex API)? For example, I'd like to set WebKit's "enable-private-browsing" setting from "false" to "true".

From stackoverflow
  • That would be very interesting. Sadly, judging by the source code of the HTML component and the AIR documentation, it doesn't seem that there's any way to do so.

    Maybe something to propose to the Flex/AIR team on JIRA for the next version.

    Huuuze : I've logged a ticket here: http://bugs.adobe.com/jira/browse/SDK-25585 Let's see what happens.
  • Since it's not possible, I've logged a ticket here: bugs.adobe.com/jira/browse/SDK-25585 Let's see what happens.

How can I return a specific node when there are different selection criteria/depths with xpath?

Given the following XML,

<root>
    <property>
        <programs>
            <program>1</program>
            <program>5</program>
        </programs>
        <tool>
        </tool>
    </property>
    <property>
        <tool>
            <programs>
                <program>1</program>
                <program>2</program>
            </programs>
        </tool>
    </property>
</root>

how would I write an XPath expression to return a collection containing the "property" nodes when program=1? I think I want to write something like "give me all the property nodes when self or a descendant contains programs[program=1]", but can't get it to just give me the "property" nodes...

From stackoverflow
  • property[.//programs/program=1]
    

    Selects the property elements that contain descendant programs elements that contain a child program element who's value is 1.

    end-user : Aha! I knew there had to be a way to do it. "That was easy!" Thx
    Tomalak : You mean `property[.//programs/program=1]`. `//` starts at the root, which would lead to *every* property node being returned as long as there is a `program=1` anywhere in the document. `.//` starts at the context node.
    Mads Hansen : Doh! Thanks, Tomalak. I've corrected the answer

How to log information from inside <CFScript>

HI ,

I am learning to use <cfscript>.

Is there any way I can log some messages or values inside the <cfscript>?

like outside <cfscript> I can use <cflog>, Is there any way or Tag something like that, i can use to print the messages in log file inside >

Thanks

From stackoverflow
  • Unfortunately there isn't. However, what you can do is map a UDF to cflog:

    <cffunction name="doCFLog">
       <cflog attributeCollection=arguments>
    </cffunction>
    

    inside your cfscript call the doCFLog function with the same attributes as you would cflog

    eg. doCFLog(text='sometext', type='warning',application='yes', file='mylog');

    Note: its not a good idea to call your methods/udf etc the same name as an existing function or tag, hence not calling the function "cflog" or "log"

  • ColdFusion 9 added the "writeLog" function which allows you to do this. http://help.adobe.com/en_US/ColdFusion/9.0/CFMLRef/WS48D04B65-0694-44e9-9E35-F9D7C9152B6C.html

    CFUser : Thanks Terry for info
    Stephen Moretti : Knew I'd seen something in CF9... typically couldn't see it when I looked. Thanks for the reminder Terry.

int array to IEnumerable<MyTestObj> ?

I have a MVC that posts an array of int, and I want to convert that array of int's to IEnumerable<MyTestObj>, how is that done? I cant use myintArr.AsEnumerable() it seems.

From stackoverflow
  • You need something along the lines of the following (depending how you create the object):

    myIntArr.Select(i => new MyTestObj(i));
    // or...
    myIntArr.Select(i => (MyTestObj)i);
    // or...
    myIntArr.Select(i => new MyTestObj { SomeProperty = i });
    
  • you did not clarify exactly what T you need ... but here's a try:

    IEnumerable<MyTestObj> dataStore = /* my magic dataStore */;
    IEnumerable<int> arrayOfIds = /* my magic array of ids */;
    
    IEnumerable<MyTestObj> objects = dataStore.Where(element => arrayOfIds.Contains(element.Id));
    

    this is not really efficient! you should rather go for a dictionary, like:

    IDictionary<int, MyTestObj> dataStore = /* my magic dataStore */;
    IEnumerable<int> arrayOfIds = /* my magic array of ids */;
    
    IEnumerable<MyTestObj> objects = from id in arrayOfIds
                                     where dataStore.ContainsKey(id)
                                     select dataStore[id];
    

    if you just need IEnumerable<int>, you don't need to do anything at all, cause int[] is already IEnumerable<int>

  • I'm a little confused. I am assuming that you have something like this for an action:

    public ActionResult MyAction(int [] postedValues)

    If that's the case then postedValues would already be IEnumerable. Not sure what problem you are having. It this isn't what you were asking then look at wither Mehrdad's or Andreas's answers.

  • I may be missing the point here, but doesn't an array support IEnumerable? In other words just use your array as it is (assuming you want an enumerable of int).

    If you want an enumerable collection of some other object I think the other answers address that, but it's not clear (to me at least) what it is you are trying to acheive.

Why does crypt/blowfish generate the same hash with two different salts?

This question has to do with PHP's implementation of crypt(). For this question, the first 7 characters of the salt are not counted, so a salt '$2a$07$a' would be said to have a length of 1, as it is only 1 character of salt and seven characters of meta-data.

When using salt strings longer than 22 characters, there is no change in the hash generated (i.e., truncation), and when using strings shorter than 21 characters the salt will automatically be padded (with '$' characters, apparently); this is fairly straightforward. However, if given a salt 20 characters and a salt 21 characters, where the two are identical except for the final character of the 21-length salt, both hashed strings will be identical. A salt 22 characters long, which is identical to the 21 length salt except for the final character, the hash will be different again.

Example In Code:

$foo = 'bar';
$salt_xx = '$2a$07$';
$salt_19 = $salt_xx . 'b1b2ee48991281a439d';
$salt_20 = $salt_19 . 'a';
$salt_21 = $salt_20 . '2';
$salt_22 = $salt_21 . 'b';

var_dump(
    crypt($foo, $salt_19), 
    crypt($foo, $salt_20), 
    crypt($foo, $salt_21), 
    crypt($foo, $salt_22)
);

Will produce:

string(60) "$2a$07$b1b2ee48991281a439d$$.dEUdhUoQXVqUieLTCp0cFVolhFcbuNi"
string(60) "$2a$07$b1b2ee48991281a439da$.UxGYN739wLkV5PGoR1XA4EvNVPjwylG"
string(60) "$2a$07$b1b2ee48991281a439da2.UxGYN739wLkV5PGoR1XA4EvNVPjwylG"
string(60) "$2a$07$b1b2ee48991281a439da2O4AH0.y/AsOuzMpI.f4sBs8E2hQjPUQq"

Why is this?

EDIT:

Some users are noting that there is a difference in the overall string, which is true. In salt_20, offset (28, 4) is da$., while in salt_21, offset (28, 4) is da2.; however, it is important to note that the string generated includes the hash, the salt, as well as instructions to generate the salt (i.e. $2a$07$); the part in which the difference occurs is, in fact, still the salt. The actual hash is unchanged as UxGYN739wLkV5PGoR1XA4EvNVPjwylG.

Thus, this is in fact not a difference in the hash produced, but a difference in the salt used to store the hash, which is precisely the problem at hand: two salts are generating the same hash.

Rembmer: the output will be in the following format:

"$2a$##$saltsaltsaltsaltsaltsaHASHhashHASHhashHASHhashHASHhash"
//                            ^ Hash Starts Here, offset 28,32

where ## is the log-base-2 determining the number of iterations the algorithm runs for

Edit 2:

In the comments, it was requested that I post some additional info, as the user could not reproduce my output. Execution of the following code:

var_dump(
    PHP_VERSION, 
    PHP_OS, 
    CRYPT_SALT_LENGTH, 
    CRYPT_STD_DES, 
    CRYPT_EXT_DES, 
    CRYPT_MD5, 
    CRYPT_BLOWFISH
);

Produces the following output:

string(5) "5.3.0"
string(5) "WINNT"
int(60)
int(1)
int(1)
int(1)
int(1)

Hope this helps.

From stackoverflow
  • Looks like the outputs are actually different. (da$, vs da2) for result of salt_20 and salt_21.

    Dereleased : Actually, that part is actually still the salt of the hash, not the hash itself. The hash is only the last 32 characters. I have edited the question to reflect the fact that the salt is prepended to the string in order to make the question more clear.
    Harley Green : Maybe you can post some information about your php version, host OS, and the values of the following php constants: - CRYPT_SALT_LENGTH - CRYPT_STD_DES - CRYPT_EXT_DES - CRYPT_MD5 - CRYPT_BLOWFISH When I run the code you posted I get the following: `string(13) "$2yymq4BO0Z3w" string(13) "$2yymq4BO0Z3w" string(13) "$2yymq4BO0Z3w" string(13) "$2yymq4BO0Z3w" `
    Dereleased : You are getting encryption using STD_DES - notice how only the first two characters of the given salt are considered. Internal support for Blowfish (if not supported by your host OS) was not added until PHP 5.3, so if you have an older version it would revert to the default method, which on your setup appears to be STD_DES. See http://php.net/manual/en/function.crypt.php for more info.
    Harley Green : I would venture then that the crypt function has some internal mechanism for manipulating the salt once it is received, either some expansion or contraction function to make it the right size for the given encryption algorithm (perhaps treating it as base64 and when decoding if it does not have the correct number of bytes to read in it pads it regardless of the last several bytes). I've not taken the time to dig through the latest php source code to look at this, but if you are really curious that's where you should start!
    Dereleased : Problem solved!
  • After some experimentation, I have come to the conclusion that this is due to the way the salt is treated. The salt is not considered to be literal text, but rather to be a base64 encoded string, such that 22 bytes of salt data would actually represent a 16 byte string (floor(22 * 24 / 32) == 16) of salt. The "Gotcha!" with this implementation, though, is that, like Unix crypt, it uses a "non-standard" base64 alphabet. To be exact, it uses this alphabet:

    ./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz$
    

    The 65th character, '$', is the padding character.

    Now, the crypt() function appears to be capable of taking a salt of any length less than or equal to its maximum, and silently handling any inconsistencies in the base64 by discarding any data that doesn't make up another full byte. The crypt function will fail completely if you pass it characters in the salt that are not part of its base64 alphabet, which just confirms this theory of its operation.

    Take an imaginary salt '1234'. This is perfectly base64 consistent in that it represents 24 bits of data, so 3 bytes, and does not carry any data that needs to be discarded. This is a salt whose Len Mod 4 is zero. Append any character to that salt, and it becomes a 5 character salt, and Len Mod 4 is now 1. However, this additional character represents only six bits of data, and therefore cannot be transformed into another full byte, so it is discarded.

    Thus, for any two salts A and B, where

       Len A Mod 4 == 0 
    && Len B Mod 4 == 1  // these two lines mean the same thing
    && Len B = Len A + 1 // but are semantically important separately
    && A == substr B, 0, Len A
    

    The actual salt used by crypt() to calculate the hash will, in fact, be identical. As proof, I'm including some example PHP code that can be used to show this. The salt constantly rotates in a seminon-random way (based on a randomish segment of the whirlpool hash of the current time to the microsecond), and the data to be hashed (herein called $seed) is simply the current Unix-Epoch time.

    $salt = substr(hash('whirlpool',microtime()),rand(0,105),22);
    $seed = time();
    for ($i = 0, $j = strlen($salt); $i <= $j; ++$i) {
        printf('%02d = %s%s%c',
            $i,
            crypt($seed,'$2a$07$' . substr($salt, 0, $i)),
            $i%4 == 0 || $i % 4 == 1 ? ' <-' : '',
            0x0A
        );
    }
    

    And this produces output similar to the following

    00 = $2a$07$$$$$$$$$$$$$$$$$$$$$$.rBxL4x0LvuUp8rhGfnEKSOevBKB5V2. <-
    01 = $2a$07$e$$$$$$$$$$$$$$$$$$$$.rBxL4x0LvuUp8rhGfnEKSOevBKB5V2. <-
    02 = $2a$07$e8$$$$$$$$$$$$$$$$$$$.WEimjvvOvQ.lGh/V6HFkts7Rq5rpXZG
    03 = $2a$07$e89$$$$$$$$$$$$$$$$$$.Ww5p352lsfQCWarRIWWGGbKa074K4/.
    04 = $2a$07$e895$$$$$$$$$$$$$$$$$.ZGSPawtL.pOeNI74nhhnHowYrJBrLuW <-
    05 = $2a$07$e8955$$$$$$$$$$$$$$$$.ZGSPawtL.pOeNI74nhhnHowYrJBrLuW <-
    06 = $2a$07$e8955b$$$$$$$$$$$$$$$.2UumGVfyc4SgAZBs5P6IKlUYma7sxqa
    07 = $2a$07$e8955be$$$$$$$$$$$$$$.gb6deOAckxHP/WIZOGPZ6/P3oUSQkPm
    08 = $2a$07$e8955be6$$$$$$$$$$$$$.5gox0YOqQMfF6FBU9weAz5RmcIKZoki <-
    09 = $2a$07$e8955be61$$$$$$$$$$$$.5gox0YOqQMfF6FBU9weAz5RmcIKZoki <-
    10 = $2a$07$e8955be616$$$$$$$$$$$.hWHhdkS9Z3m7/PMKn1Ko7Qf2S7H4ttK
    11 = $2a$07$e8955be6162$$$$$$$$$$.meHPOa25CYG2G8JrbC8dPQuWf9yw0Iy
    12 = $2a$07$e8955be61624$$$$$$$$$.vcp/UGtAwLJWvtKTndM7w1/30NuYdYa <-
    13 = $2a$07$e8955be616246$$$$$$$$.vcp/UGtAwLJWvtKTndM7w1/30NuYdYa <-
    14 = $2a$07$e8955be6162468$$$$$$$.OTzcPMwrtXxx6YHKtaX0mypWvqJK5Ye
    15 = $2a$07$e8955be6162468d$$$$$$.pDcOFp68WnHqU8tZJxuf2V0nqUqwc0W
    16 = $2a$07$e8955be6162468de$$$$$.YDv5tkOeXkOECJmjl1R8zXVRMlU0rJi <-
    17 = $2a$07$e8955be6162468deb$$$$.YDv5tkOeXkOECJmjl1R8zXVRMlU0rJi <-
    18 = $2a$07$e8955be6162468deb0$$$.aNZIHogUlCn8H7W3naR50pzEsQgnakq
    19 = $2a$07$e8955be6162468deb0d$$.ytfAwRL.czZr/K3hGPmbgJlheoZUyL2
    20 = $2a$07$e8955be6162468deb0da$.0xhS8VgxJOn4skeI02VNI6jI6324EPe <-
    21 = $2a$07$e8955be6162468deb0da3.0xhS8VgxJOn4skeI02VNI6jI6324EPe <-
    22 = $2a$07$e8955be6162468deb0da3ucYVpET7X/5YddEeJxVqqUIxs3COrdym
    

    The conclusion? Twofold. First, it's working as intended, and second, know your own salt or don't roll your own salt.

    Harley Green : Base64 gotchas... My guess was correct.
    Dereleased : Indeed. Might have been more apparent if it used a standard base64 alphabet, but oh well, life goes on.

Is there any difference between type casting & type conversion?

Is there any difference between type casting & type conversion in c++.

From stackoverflow
  • One of the major differences occurs when you work with strings. You cannot say (int)"234" and get the integer 234. Type casting generally only works on primitive numeric data types.

  • Generally, casting refers to an explicit conversion, whether it's done by C-style cast (T(v) or (T)v) or C++-style cast (static_cast, const_cast, dynamic_cast, or reinterpret_cast). Conversion is generally a more generic term used for any time a variable is converted to another:

    std::string s = "foo"; // Conversion from char[] to char* to std::string
    int i = 4.3; // Conversion from float to int
    float *f = reinterpret_cast<float*>(&i); // (illegal) conversion from int* to float*
    
    Passionate programmer : so there is no difference right
    DevSolar : The difference is that a cast is *explicit*. The C++ keywords can be grep'ed. Both the C and C++ cast show that the conversion was done on purpose and with the consent of the programmer. An implicit conversion could be intended, or by mistake.
  • Type casting means that you take a string of bits and interpret them differently. Type conversion means that you transform a string of bits from a configuration useful in one context to a configuration useful in another.

    For example, suppose I write

    int x=65;
    char c=(char) x;
    char* s=(char*) x;
    

    c will now contain the character 'A', because if I reinterpret the decimal number 65 as a character, I get the letter 'A'. s will not we a pointer to a character string residing at memory location 65. This is almost surely a useless thing to do, as I have no idea what is at that memory location.

    itoa(x, s, 10);
    

    is a type conversion. That should give me the string "65".

    That is, with casts we are still looking at the same memory location. We are just interpreting the data there differently. With conversions we are producing new data that is derived from the old data, but it is not the same as the old data.

  • While we are reading an integer

    int i=parseInt.Integer(readLine(str));

    Here we are entering a value, the JVM consider that as string after that it will be converted to Int. This is called as Type casting.

    float f=7.9; int i=(int)f; Here we are casting the float value to integer value. this is called Type Casting.

Compiling a C library so it can be used in an iPhone static library

I've never done this before, so I'm not sure where to even start. I have a few projects where I want to use the liblio library, both on the iPhone and OS X. I've put the installation instructions in a gist.

Here are my questions, and I'll try and edit these questions as I figure them out.

  1. Do I want to use make install to compile these files? I feel like all the compilation should be done within XCode.
  2. It looks like there are a lot of platform specific settings during compilation. How do I control this from XCode?
  3. It seems like I should be able to add all the .h/.m files to my XCode project and compile them myself. Is this missing something?

For the record, I'm aware of a few LibLO libraries created for use on the iPhone. I may break down and use one, but I'd prefer to learn how to do this myself.

From stackoverflow
  • Yes, if you want to compile these projects from within XCode, you need to add the .c/.h files and then setup them accordingly. XCode has support for passing argument to the compiler of course, so it is indeed possible.

    From the gist snippet, it looks like the installation instructions are GNU standard instructions, ie. configure; make; make install. You could try playing with arguments to configure (which, btw, creates the Makefile on the spot) and see what options you have for compiling to a different target platform.

    However, it may not be worth all the trouble to convert the Makefile's to a pure XCode project. Another approach, which I think I would start with, is to hack the created Makefile until you are able to compile an iPhone friendly lib-file. After that you can tell XCode to run 'make ...' as part of your projects build steps. Then, once you understand the issues, it may be easier to include them in your XCode project proper.

    kubi : It was really much easier than I thought it would be. Add the .h/.c files to the project and clean up a few little things (bad paths to header files, preproccessor macros that are inexplicably wrapping the wrong code, etc). Maybe I got lucky with an easy project, but it didn't take that much effort.
    Martin Wickman : Nice work! Thats the beauty of C, it works everywhere... eventually :-)
  • I have not tried this myself, but Building autoconf-configured libraries for iPhone OS might have some useful information for you.

    kubi : oh awesome. I'll give that a try this evening.

Buttons to fill width when using TableLayout

Hello,

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content" android:layout_height="wrap_content">
    <TableLayout android:id="@+id/TableLayout01"
        android:layout_height="wrap_content" android:layout_width="fill_parent">
        <TableRow android:id="@+id/TableRow01" android:layout_width="wrap_content"
            android:layout_height="wrap_content">
            <Button android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:text="Settings"
                android:id="@+id/btnSettings"></Button>
            <Button android:text="@+id/Button01" android:id="@+id/Button01"
                android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
            <Button android:text="@+id/Button02" android:id="@+id/Button02"
                android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
        </TableRow>
        <TableRow android:id="@+id/TableRow02" android:layout_width="wrap_content"
            android:layout_height="wrap_content">
            <Button android:text="@+id/Button03" android:id="@+id/Button03"
                android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
            <Button android:text="@+id/Button04" android:id="@+id/Button04"
                android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
            <Button android:text="@+id/Button05" android:id="@+id/Button05"
                android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
        </TableRow>
    </TableLayout>
</ScrollView>

I have a table having 2 rows each row having 3 buttons. How can I make the buttons to fill the space equally. In HTML I would give them 33% width.

Also do you know any way I can create a view having 4 image buttons in a row as a grid layout, similar to the launcher.

From stackoverflow
  • Try adding android:stretchColumns="*" to your <TableLayout> tag.

  • Set the TableRow layout_width to fill_parent and set a layout_weight of 1 on each button.

    The layout_weight works sort of like a percentage. If all of your items get the same number, they take the same percent of space. If one button has a weight of 2, and another has a weight of 1, then the first will take up twice as much space.

    If you haven't done so already, ready through the common layouts page of the dev guide for a good intro to layouts.

What are good rules of thumb for python imports?

I am a little confused by the multitude of ways in which you can import modules in python.

import X
import X as Y
from A import B

I have been reading up about scoping and namespaces but I would like some practical advice on what is the best strategy, under which circumstances and why. Should imports happen at a module level or a method/function level? In the __init__.py or in the module code itself?

My question is not really answered by this post although it is obviously related.

From stackoverflow
  • I would normally use import X on module level. If you only need a single object from a module, use from X import Y.

    Only use import X as Y in case you're otherwise confronted with a name clash.

    I only use imports on function level to import stuff I need when the module is used as the main module, like:

    def main():
      import sys
      if len(sys.argv) > 1:
         pass
    

    HTH

  • Maybe the (old) article Importing Python Modules by The Effbot will be of some help.

    Nowadays a little more confusion is added by even more import options. See especially Absolute and Relative Imports in 2.5.

  • In production code in our company, we try to follow the following rules.

    We place imports at the beginning of the file, right after the main file's docstring, e.g.:

    """
    Registry related functionality.
    """
    import wx
    # ...
    

    Now, if we import a class that is one of few in the imported module, we import the name directly, so that in the code we only have to use the last part, e.g.:

    from RegistryController import RegistryController
    from ui.windows.lists import ListCtrl, DynamicListCtrl
    

    There are modules, however, that contain dozens of classes, e.g. list of all possible exceptions. Then we import the module itself and reference to it in the code:

    from main.core import Exceptions
    # ...
    raise Exceptions.FileNotFound()
    

    We use the import X as Y as rarely as possible, because it makes searching for usage of a particular module or class difficult. Sometimes, however, you have to use it if you wish to import two classes that have the same name, but exist in different modules, e.g.:

    from Queue import Queue
    from main.core.MessageQueue import Queue as MessageQueue
    

    As a general rule, we don't do imports inside methods -- they simply make code slower and less readable. Some may find this a good way to easily resolve cyclic imports problem, but a better solution is code reorganization.

  • The import X as Y is useful if you have different implementations of the same module/class.

    With some nested try..import..except ImportError..imports you can hide the implementation from your code. See lxml etree import example:

    try:
      from lxml import etree
      print("running with lxml.etree")
    except ImportError:
      try:
        # Python 2.5
        import xml.etree.cElementTree as etree
        print("running with cElementTree on Python 2.5+")
      except ImportError:
        try:
          # Python 2.5
          import xml.etree.ElementTree as etree
          print("running with ElementTree on Python 2.5+")
        except ImportError:
          try:
            # normal cElementTree install
            import cElementTree as etree
            print("running with cElementTree")
          except ImportError:
            try:
              # normal ElementTree install
              import elementtree.ElementTree as etree
              print("running with ElementTree")
            except ImportError:
              print("Failed to import ElementTree from any known place")
    
  • I generally try to use the regular import modulename, unless the module name is long, or used often..

    For example, I would do..

    from BeautifulSoup import BeautifulStoneSoup as BSS
    

    ..so I can do soup = BSS(html) instead of BeautifulSoup.BeautifulStoneSoup(html)

    Or..

    from xmpp import XmppClientBase
    

    ..instead of importing the entire of xmpp when I only use the XmppClientBase

    Using import x as y is handy if you want to import either very long method names , or to prevent clobbering an existing import/variable/class/method (something you should try to avoid completely, but it's not always possible)

    Say I want to run a main() function from another script, but I already have a main() function..

    from my_other_module import main as other_module_main
    

    ..wouldn't replace my main function with my_other_module's main

    Oh, one thing - don't do from x import * - it makes your code very hard to understand, as you cannot easily see where a method came from (from x import *; from y import *; my_func() - where is my_func defined?)

    In all cases, you could just do import modulename and then do modulename.subthing1.subthing2.method("test")...

    The from x import y as z stuff is purely for convenience - use it whenever it'll make your code easier to read or write!

  • Others have covered most of the ground here but I just wanted to add one case where I will use import X as Y (temporarily), when I'm trying out a new version of a class or module.

    So if we were migrating to a new implementation of a module, but didn't want to cut the code base over all at one time, we might write a xyz_new module and do this in the source files that we had migrated:

    import xyz_new as xyz
    

    Then, once we cut over the entire code base, we'd just replace the xyz module with xyz_new and change all of the imports back to

    import xyz
    
    Just Some Guy : You beat me to it.
  • DON'T do this:

    from X import *
    

    unless you are absolutely sure that you will use each and every thing in that module. And even then, you should probably reconsider using a different approach.

    Other than that, it's just a matter of style.

    from X import Y
    

    is good and saves you lots of typing. I tend to use that when I'm using something in it fairly frequently But if you're importing a lot from that module, you could end up with an import statement that looks like this:

    from X import A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P
    

    You get the idea. That's when imports like

    import X
    

    become useful. Either that or if I'm not really using anything in X very frequently.

    John Fouhy : 'from X import *' does have its uses -- e.g. with pyparsing.
    Jason Baker : I agree. But in general, it's not a good habit to get into. Nothing annoys me more than having to track down what function came from what module because there are a lot of from x import * type statements.
  • Let me just paste a part of conversation on django-dev mailing list started by Guido van Rossum:

    """ [...] For example, it's part of the Google Python style guides[1] that all imports must import a module, not a class or function from that module. There are way more classes and functions than there are modules, so recalling where a particular thing comes from is much easier if it is prefixed with a module name. Often multiple modules happen to define things with the same name -- so a reader of the code doesn't have to go back to the top of the file to see from which module a given name is imported.

    """

    source: http://groups.google.com/group/django-developers/browse_thread/thread/78975372cdfb7d1a

    1: http://code.google.com/p/soc/wiki/PythonStyleGuide#Module_and_package_imports

  • When you have a well-written library, which is sometimes case in python, you ought just import it and use it as it. Well-written library tends to take life and language of its own, resulting in pleasant-to-read -code, where you rarely reference the library. When a library is well-written, you ought not need renaming or anything else too often.

    import gat
    
    node = gat.Node()
    child = node.children()
    

    Sometimes it's not possible to write it this way, or then you want to lift down things from library you imported.

    from gat import Node, SubNode
    
    node = Node()
    child = SubNode(node)
    

    Sometimes you do this for lot of things, if your import string overflows 80 columns, It's good idea to do this:

    from gat import (
        Node, SubNode, TopNode, SuperNode, CoolNode,
        PowerNode, UpNode
    )
    

    The best strategy is to keep all of these imports on the top of the file. Preferrably ordered alphabetically, import -statements first, then from import -statements.

    Now I tell you why this is the best convention.

    Python could perfectly have had an automatic import, which'd look from the main imports for the value when it can't be found from global namespace. But this is not a good idea. I explain shortly why. Aside it being more complicated to implement than simple import, programmers wouldn't be so much thinking about the depedencies and finding out from where you imported things ought be done some other way than just looking into imports.

    Need to find out depedencies is one reason why people hate "from ... import *". Some bad examples where you need to do this exist though, for example opengl -wrappings.

    So the import definitions are actually valuable as defining the depedencies of the program. It is the way how you should exploit them. From them you can quickly just check where some weird function is imported from.

  • I'm with Jason in the fact of not using

    from X import *
    

    But in my case (i'm not an expert programmer, so my code does not meet the coding style too well) I usually do in my programs a file with all the constants like program version, authors, error messages and all that stuff, so the file are just definitions, then I make the import

    from const import *
    

    That saves me a lot of time. But it's the only file that has that import, and it's because all inside that file are just variable declarations.

    Doing that kind of import in a file with classes and definitions might be useful, but when you have to read that code you spend lots of time locating functions and classes.

how to get item data immediately after inserting

Hi

I have a form that allows users to insert items in the database. I call Scope_Identity() to get last identity value inserted. This works ok. When inserting the item a passowrd is randomly generated which is also saved in my database. I need to retrieve this password as well, immediately after the item is inserted. How do I do this?

From stackoverflow
  • Execute a query to get the password based on the ID which you have just received by calling Scope_Identity().

    What technologies are you using?

    Anelim : Thanks for your help. I just thought there may be another way.
  • pseudo code:

    insert into sometable
    declare @ID int  
    set @ID = Scope_Identity()
    select password from passwordtable where id = @ID
    
  • Presumably you can get a reference to the new password before the insert takes place, which I think would be the best approach - this would prevent the need to do an INSERT followed by a SELECT to read out the password - removes the second step.

    e.g. Say you use NEWID() to generate a password, you'd do:

    DECLARE @Pwd VARCHAR(36)
    DECLARE @NewId INTEGER
    SELECT @Pwd = CAST(NEWID() AS VARCHAR(36))
    
    INSERT MyTable (SomeField, Pwd)
    VALUES (@SomeValue, @Pwd)
    
    SELECT @NewId = SCOPE_IDENTITY()
    

    @Pwd and @NewId would be OUTPUT parameters (I'd do this as a sproc). IMO this would be preferrable to doing an unnecessary read if at all possible.

    (NB. I'm ignoring the points about actually how to store passwords/not in plain text)

  • IF you are using SQl Server 2008 you can use the output clause instead of scope identity. With the output clause you can output more than one field. an example of the code from Books online:

    DECLARE @MyTableVar table( ScrapReasonID smallint,
                               Name varchar(50),
                               ModifiedDate datetime);
    INSERT Production.ScrapReason
        OUTPUT INSERTED.ScrapReasonID, INSERTED.Name, INSERTED.ModifiedDate
            INTO @MyTableVar
    VALUES (N'Operator error', GETDATE());
    

Spring.net Using ProxyFactoryObject with Objects that use Constructor Injection

Hi, I've got an issue where i'm trying to call an object in spring.net through a ProxyFactoryObject. Now the the object that i'm calling in the factory has one constructor which takes in another object by reference through constructor injection. When i call the proxy from the c# code the correct target object is returned from the proxy but the items inside it that should be set to something through the initital constructor call are empty. Now i'm not sure why this is happening.

MY APP.CONFIG Objects section is below:

    <objects xmlns="http://www.springframework.net">

        <object name="MyMovieLister" id="MyMovieLister" type="SpringTestProgram.Classes.MovieLister, SpringTestProgram"  singleton="false">
            <!-- using cstor injection... -->
            <constructor-arg index="0" ref="MyMovieFinder"/>
            <constructor-arg index="1" value="2"/>
        </object>

        <object name="MyMovieFinder" id="MyMovieFinder" type="SpringTestProgram.Classes.MovieFinder, SpringTestProgram" singleton="false"/>

        <object id="MyBeforeAdvisor"
                type="Spring.Aop.Support.NameMatchMethodPointcutAdvisor, Spring.Aop">

            <property name="Advice">
                <object id="myBeforeAdvice"
                 type="SpringTestProgram.Classes.LoggingAdvice, SpringTestProgram"/>
            </property>

            <property name="MappedNames">
                <list>
                    <value>FindAll</value>
                </list>
            </property>
        </object>


        <object name="MovieWorkerProxy" type="Spring.Aop.Framework.ProxyFactoryObject, Spring.Aop">

             <property name="Target" ref="MyMovieLister" /> 

             <!--<property name="TargetSource">
                <object type="Spring.Aop.Target.PrototypeTargetSource, Spring.Aop">
                    <property name="TargetObjectName" value="MyMovieLister" />
                </object>
            </property>--> 

            <!--<property name="ObjectNames">
                <list>
                    <value>MyMovieLister</value>
                </list>
            </property>-->

            <property name="interceptorNames">
                <list>
                    <value>MyBeforeAdvisor</value>
                </list>
            </property>
        </object>      

    </objects>

And below is the c# code that i have to call this:

        IApplicationContext ctx = ContextRegistry.GetContext();
        MovieLister myMovieLister = ctx.GetObject("MovieWorkerProxy") as MovieLister;

        IList<string> myList = myMovieLister.FindMovies();

Now the actual implemention of the class is really not important but the only class that we are really concerned with here is listed below:

public class MovieLister 
{
    public MovieLister(IMovieFinder myMovieFinder, int i)
    {
        number = i;
        movieFinder = myMovieFinder;
    }

    public IList<string> FindMovies()
    {
        return movieFinder.FindAll();
    }

    private int number;
    private IMovieFinder movieFinder;         
}

Now i'm not sure why when i call the class above from my proxy factory do both of the fields that are set by the only constructor set to null ? Can anyone help......

From stackoverflow
  • Short answer: Make number and movieFinder a property, add the virtual keyword to the properties and the FindMovies method and use the properties instead of the fields directly.

    Longer answer: It has to do with the way the proxy is constructed, take a look at Erich Eichingers's blog on how Spring.NET creates proxies. Part 1, 2 and 3.

    And since you are proxying a class, take a look at the Spring.NET documentation, it indicates the problem with non virtual methods.

What is acessof undefined property Event and how do I resolve it? I use actionscript 3.0

public function assgn()
{
    var recA:Sprite = new Sprite();

    graphics.beginFill(0xFFF010);
    graphics.lineStyle(1);
    graphics.drawRect(0, 380, 50, 20);
    addChild(recA);

    recA.x = 300;
    recA.y = 300;
    recA.scaleX = 2;
    recA.scaleY = 2;
    recA.addEventListener(Event.ENTER_FRAME, moveRecA);
From stackoverflow
  • It looks to me like you might not have the correct import statements at the top of your Actionscript file. Try placing an import at the top of the file, as follows:

    package
    {
        import flash.events.Event;
        ...
        public class Xxxx
        {
            ...
            public function assgn()
            {
                var recA:Sprite = new Sprite();
    
                graphics.beginFill(0xFFF010);
                graphics.lineStyle(1);
                graphics.drawRect(0, 380, 50, 20);
                addChild(recA);
    
                recA.x = 300;
                recA.y = 300;
                recA.scaleX = 2;
                recA.scaleY = 2;
                recA.addEventListener(Event.ENTER_FRAME, moveRecA);
                ...
            }
    
            ...
        }
    }
    

overriding bool() for custom class

All I want is for bool(myInstance) to return False (and for myInstance to evaluate to False when in a conditional like if/or/and. I know how to override >, <, =)

I've tried this:

class test:
    def __bool__(self):
        return False

myInst = test()
print bool(myInst) #prints "True"
print myInst.__bool__() #prints "False"

Any suggestions?

(I am using Python 2.6)

From stackoverflow
  • test.__nonzero__()

  • Is this Python 2.x or Python 3.x? I think for Python 2.x you are looking to override __nonzero__() instead?

    class test:
        def __nonzero__(self):
            return False
    
  • If you want to keep your code forward compatible with python3 you could do something like this

    class test:
        def __bool__(self):
            return False
        __nonzero__=__bool__
    

javac -classpath problem with multiple dirs

I have

c:\sources with

A.java
B.java
com\pluto\B.class
Test.java

and

c:\packages with

com\pluto\oth\C.class

in Test.java there are references to B and C (correctly imported) but when I try to compile with (I'm in c:\sources)

javac -classpath \.;c:\packages Test.java 

the compiler tell me that it doesn't find B

but if I move B.java from c:\sources to another dir and then I compile with

javac -classpath .;c:\packages Test.java 

it does work!!

How must I set the current dir? . or \. and why do the first test fail?

... it seems as the compiler doesn't want to find a class file com/pluto/B.class and a source file with the same name B.java in the current dir where I'm compiling...

From stackoverflow
  • Use . to refer to the current directory. \. refers to the root directory of the current drive (for example C:\).

    Dave.Sol : . or .\ to refer to the current directory
  • javac -classpath c:\sources;c:\packages Test.java
    
    xdevel2000 : it doesn't still work...
    FractalizeR : You need to list source files here. Something can be wrong there

How to set the object context in another class using Objective-C??

Hi,

I have a main class and three other classes, now i need to give the reference of the other three objects that is created in their own classes to the main class object.How to do it ?

From stackoverflow
  • Set up attributes in the main class to hold pointers to the other classes and then use an init method to set them at the start or setters

    e.g. for classes A and B

    class Main : NSObject
    {
      A* anAObject;
      B* aBObject;
    }
    
    // implementation of init -needs to have memory management I've done the simplest
    initWithA:(A* anA) andB:(B* aB)
    {
       anObject = [anA retain];
       aBObject = [aB retain];
    }
    

Purging log files using EntLib

Does anyone know how to set EntLib in order to purge the log files generated by the rolling flat file trace listener?

I've seen the "MaximumLogFilesBeforePurge" option in a tutorial for entlib 2.0 but it seems it is not there anymore in 4.1

Thanks in advance!

From stackoverflow

VB6: how to add Inet component ?

basically i can't add Inet control in vb6 via drag and click from the general toolbar....where is it ?

From stackoverflow
  • Project (menu) --> Components --> Check "Microsoft Internet Transfer Controls 6.0" (MSINET.OCX). Now you should have the Inet icon on the toolbar.

Source Control - XCode - Visual Studio 2005/2008 / 2010

My apologies if this has been asked before, I wasnt quite sure if this question should be asked on a programming forum, as it more relates to programming environment than a particular technology, so please accept my (double) appologies if I am posting this in the wrong place, my logic in this case was if it effects the code I write, then this is the place for it.

At home, I do a lot of my development on a Mac Pro, I do development for the Mac, iPhone and Windows on this machine (Xcode & Visual Studio - (multiple versions installed in bootcamp, but generally I run it via Parallels)).

When visiting a client, I have a similar setup, but on my MacBook Pro.

What I want is a source control solution to install on the Mac Pro, that will support both XCode and multiple versions of visual studio, so that when I visit a client, I can simply grab the latest copy from source control via the MacBook Pro. Whilst visiting the client, he / she may suggest changes, and minor ones I would tend to make on site, so I need the ability to merge any modified code back into the trunk of the project / solution when I return home.

At the moment, I am using no source control at all, and rely on simply coping folders and overwriting them when I return from a client- thats my 'merge'!!!

I was wondering if anyone had any ideas of a source provider I could use, which would support both Windows and Mac development environments, and is cheap (free would be better).

From stackoverflow
  • You can use github (free if the projects are open source). You could also just host an SVN Repo on your desktop machine - however you won't be able to access it from the road unless you setup some port forwarding and static ip (via like dyn dns or something).

    SVN and GitHub will support any type of project (vs, xcode, etc).

  • I use Git ( http://git-scm.com ) when moving stuff back and forth between my Mac and PC.

    I have had a lot of success using DropBox ( http://www.dropbox.com ) to host a bare Git repository and then I clone that repository on my Mac and my PC, then I can create branches and push/pull all I want between the local copy and the origin in the drop box folder which will then get automatically synced to my other machine.

    The biggest benefit here is that I can propagate branches between the systems without commiting them to the main branch so everything I do is backed up and pushed to my other computer as soon as I push it to the repository.

    Also, DropBox lets me push and merge my changes even when not online and then will sync them up once i'm connected again.