Saturday, March 27, 2010

jQuery: Targeting elements added via *non-jQuery* AJAX before any Javascript events fire? Beyond the scope of live()?

Programmer Question

Working on a Wicket application that adds markup to the DOM after onLoad via Wicket's built-in AJAX for an auto-complete widget. We have an IE6 glitch that means I need to reposition the markup coming in, and I am trying to avoid tampering with the Wicket javascript... blah blah blah... here's what I'm trying to do:




  1. New markup arrives in the DOM (I
    don't have access to a callback)

  2. Somehow I know this, so I fire my
    code.



I tried this, hoping the new tags would trigger onLoad events:



 $("selectorForNewMarkup").live("onLoad", function(){ //using jQuery 1.4.1
//my code
});


...but have become educated that onLoad only fires on the initial page load. Is there another event fired when elements are added to the DOM? Or another way to sense changes to the DOM?



Everything I've bumped into on similar issues with new markup additions, they have access to the callback function on .load() or similar, or they have a real javascript event to work with and live() works perfectly.



Is this a pipe dream?



Find the answer here

Adding values to a C# array

Programmer Question

Probably a really simple one this - I'm starting out with C# and need to add values to an array, for example:



int[] terms;

for(int runs = 0; runs < 400; runs++)
{
terms[] = value;
}


For those who have used PHP, here's what I'm trying to do in C#:



$arr = array();
for ($i = 0; $i < 10; $i++) {
$arr[] = $i;
}


Thanks,
Ross



Find the answer here

gpg error - connection already closed?

Programmer Question

omg... hope someone can help me because I am so lost as to what to try next.... I don't know what is causing the error to happen, and I don't see how to figure it out... Keep going between the pgloader.conf examples and what I have, and I don't understand why I keep getting the 'connection already closed' error? The first few lines of my fr.conf is at the very end...



I'd really appreciate / love some guidance here... Been trying to get this thing going all morning, and am even getting stuck just on this part...



Running this command at the command line:



/usr/bin/pgloader -c /var/mybin/pgconfs/fr.conf


Yields this in the pgloader.log (with the process just hanging)



more /tmp/pgloader.log
27-03-2010 12:22:53 pgloader INFO Logger initialized
27-03-2010 12:22:53 pgloader INFO Reformat path is ['/usr/share/python-support/pgloader/reformat']
27-03-2010 12:22:53 pgloader INFO Will consider following sections:
27-03-2010 12:22:53 pgloader INFO fixed
27-03-2010 12:22:54 fixed INFO fixed processing
27-03-2010 12:22:54 pgloader INFO All threads are started, wait for them to terminate
27-03-2010 12:22:57 fixed ERROR connection already closed
27-03-2010 12:22:57 fixed INFO closing current database connection

[pgsql]
host = localhost
port = 5432
base = frdb
user = username
pass = password


[fixed]
table = fr
format = fixed
filename = /var/www/fr.txt
...


So, maybe a python issue? Any idea how to fix it?



Traceback (most recent call last):
File "/usr/lib/python2.6/threading.py", line 525, in __bootstrap_inner
self.run()
File "/usr/lib/pymodules/python2.6/pgloader/pgloader.py", line 847, in run
self.terminate()
File "/usr/lib/pymodules/python2.6/pgloader/pgloader.py", line 874, in terminate
self.db.close()
File "/usr/lib/pymodules/python2.6/pgloader/db.py", line 103, in close
self.dbconn.close()


Find the answer here

Python: How to transfer varrying length arrays over a network connection

Programmer Question

Hi,



I need to transfer an array of varying length in which each element is a tuple of two integers. As an example:



path = [(1,1),(1,2)]
path = [(1,1),(1,2),(2,2)]


I am trying to use pack and unpack, however, since the array is of varying length I don't know how to create a format such that both know the format. I was trying to turn it into a single string with delimiters, such as:



msg = 1&1~1&2~
sendMsg = pack("s",msg) or sendMsg = pack("s",str(msg))


on the receiving side:



path = unpack("s",msg)


but that just prints 1 in this case. I was also trying to send 4 integers as well, which send and receive fine, so long as I don't include the extra string representing the path.



sendMsg = pack("hhhh",p.direction[0],p.direction[1],p.id,p.health)



on the receive side:



x,y,id,health = unpack("hhhh",msg)


The first was for illustration as I was trying to send the format "hhhhs", but either way the path doesn't come through properly.



Thank-you for your help. I will also be looking at sending a 2D array of ints, but I can't seem to figure out how to send these more 'complex' structures across the network.



Thank-you for your help.



Find the answer here

Is this an example of polymorphism?

Programmer Question

I'm working on a homework assignment (a project), for which one criterion is that I must make use of polymorphism in a way which noticeably improves the overall quality or functionality of my code.



I made a Hash Table which looks like this:



public class HashTable<E extends Hashable>{
...
}


where Hashable is an interface I made that has a hash() function.



I know that using generics this way improves the quality of my code, since now HashTable can work with pretty much any type I want (instead of just ints or Strings for example). But I'm not sure if it demonstrates polymorphism.



I think it does, because E can be any type that implements Hashable. In other words HashTable is a class which can work with (practically) any type.



But I'm not quite sure - is that polymorphism? Perhaps can I get some clarification as to what exactly polymorphism is?



Thanks in advance!



Find the answer here

Friday, March 26, 2010

Do you need Visual Studio 2010 to manage a 2010 build agent?

Programmer Question


<p>we are considering TFS2010 but need to confirm some information as we're still using TFS2008 and vs2008. the question is whether we can still manage our builds using the 2008 client. </p>

<p>please advise.</p>

<p>thanks!</p>



Find the answer here

How can I figure out if an ASP.NET application contains 32bit code/component

Programmer Question


<p>We have an ASP.NET 3.5 application which we need to run on 64bit, but when we do the performance is worst than when we enable 32 bit on the App Pool. It seems like there is something we use in the project which requires 32 bit, but we cannot find what.</p>



Find the answer here

How to search for 3 lettered words in a column - MySQL?

Programmer Question


<p>I have a 'Title' column with abbreviations (Ceo, Cio,..) which I have to capitalize. What is the most efficient way of finding 3 lettered words and capitalizing them?</p>

<p>Sample data :</p>

<pre><code>Title
-----------------------
Vp - business, Cio, Ceo
E Vp, Cfo
Ceo
Cio
Vp
</code></pre>

<p>Thank you so much!</p>



Find the answer here

Multi-site WCF Service

Programmer Question


<p>I have implemented a WCF service that will be used at Site A with 5 computers in the LAN accessing the service.</p>

<p>What I would like to do is have an elevated user/administrator be able to use one of the 5 machines and query an identical service at Site B (also with 5 computers) that they will need to connect to by bypassing the LAN firewall.Accessing data from Site A to Site B (and vica-versa) need only be read-only</p>

<p>Is there a standardised way to acheive this using WCF?</p>



Find the answer here

How can you see what functions and variables are currently defined in javascript?

Programmer Question


<p>There's a function in PHP where you can get a list of the user defined functions that are currently defined, is there something similar in JS?</p>



Find the answer here

Thursday, March 25, 2010

ModelBindingContext ModelName

Programmer Question

Can anyone explain where the ModelName gets populated from?



Looked in MSDN documentation and no explaination here.
I am creating a custom model binder and within it I get null for the following:
var result = bindingContext.ModelName);



Find the answer here

Sending the array of arbitrary length through a socket. Endianness.

Programmer Question

Hi everyone,



I'm fighting with socket programming now and I've encountered a problem, which I don't know how to solve in a portable way.
The task is simple : I need to send the array of 16 bytes over the network, receive it in a client application and parse it. I know, there are functions like htonl, htons and so one to use with uint16 and uint32. But what should I do with the chunks of data greater than that?



Thank you.



Find the answer here

Why does the "choose files" button not work in Wordpress 2.5 when trying to upload photos?

Programmer Question

I've got Wordpress 2.5 installed on my website. It works well, but I can't get the photo uploader to work. When I'm writing a post, I click on the "Add media" button. In the "Choose File" tab, I see the "Choose files to upload" button. When I click on it, nothing happens. I searched the net and found nothing helpful. One page vaguely mentioned having the latest Flash player. I verified and confirmed that I have the latest player. Any ideas?



Find the answer here

Saving/Associating slider values with a pop-up menu

Programmer Question

Hi,



Following on from a question I posted yesterday about GUIs, I have another problem I've been working with. This question related to calculating the bending moment on a beam under different loading conditions.



On the GUI I have developed so far, I have a number of sliders (which now work properly) and a pop-up menu which defines the load case. I would like to be able to select the load case from the pop-up menu and position the loads as appropriate, in order to define each load case in turn. The output that I need is an array defining the load case number (the rows) and a number of loading parameters (the itensity and position of the loads, which are controlled by the sliders).



The problem I am having is that I can produce this array (of the size I need) and define the loading for one load case (by selecting the pop-up menu) using the sliders, but when I change the popup menu again, the array only keeps the loading for the load case selected by the pop-up menu.



Can anyone suggest an approach I can take with (specifically to store the variables from each load case) or an example that illustrates a similar solution to the problem?



The probem may be a bit vague, so please let me know if anything needs clearing up.



Many Thanks,
James



Find the answer here

Using a version control system as a data backend

Programmer Question

I'm involved in a project that, among other things, involves storing edits and changes to a large hierarchical document (HTML-formatted text). We want to include versioning of textual changes and of structural changes.



Currently we're maintaining the tree of document sections in a relational database, but as we start working on how to manage versioning of structural changes, it's clear that we're in danger of having to write a lot of the functionality that a version control system provides.



We don't want to reinvent the wheel. Is it possible that we could use an existing version control system as the data store, at least for the document itself? Presumably we could do so by writing out new versions to the filesystem, and keeping that directory under version control (and programmatically doing commits and so forth) but it would be better if we could directly interact with the repository via code.



The VCS that we are most familiar with is Subversion, but I'm not thrilled with how Subversion represents changes to the directory structure -- it would be nice if we could see that a particular revision included moving a section from Chapter 2 to Chapter 6, rather than just seeing a new version of the tree. This sounds more like the way a system like Mercurial handles changes to the structure.



Any advice? Do VCS's have public APIs and so forth? The project is in Java (with Spring) if it matters.



Find the answer here

Wednesday, March 24, 2010

XmlSerializer equivalent of IExtensibleDataObject

Programmer Question

With DataContracts you can derive from IExtensibleDataObject to allow round-tripping to work without losing any unknown additional data from your XML file.



I can't use DataContract because I need to control the formatting of the output XML. But I also need to be able to read a future version of the XML file in the old version of the app, without losing any of the data from the XML file.



e.g.



XML v1:



<Person>
<Name>Fred</Name>
</Person>


XML v2:



<Person>
<Name>Fred</Name>
<Age>42</Age>
</Person>


If reading an XML v2 file from v1 of my app, deserializing and serializing it again turns it into an XML v1 file. i.e. the "Age" field is erased.



Is there anything similar to IExtensibleDataObject that I can use with XmlSerializer to avoid the Age field disappearing?



Find the answer here

When giving DataSource to a BindingSource shows only the cachedList Items.

Programmer Question

I have a BindingSource on a form with MyObject Datasource. I Open another form and passing MyObject where i give its EntitySetObject reference to another BindingSource.
Everything ok.



Deleting an Entity on EntitySetObject reference and closing the form with EndEdit(). OK.
Back in the "First" form i add one Entity in MyObject.EntitySetObject and again opening the form. But i have noticed that when giving the datasource to the BindingSource i have 2 items in cachedlist and 3 entities. Control now shows only the 2 cached items.



Any Idea?



Find the answer here

why the hell does x,y = zip(*zip(a,b)) work in Python?

Programmer Question

OK I love Python's zip() function. Use it all the time, it's brilliant. Every now and again I want to do the opposite of zip(), think "I used to know how to do that", then google python unzip, then remember that one uses this magical * to unzip a zipped list of tuples. Like this:



x = [1,2,3]
y = [4,5,6]
zipped = zip(x,y)
unzipped_x, unzipped_y = zip(*zipped)
unzipped_x
Out[30]: (1, 2, 3)
unzipped_y
Out[31]: (4, 5, 6)


What on earth is going on? What is that magical asterisk doing? Where else can it be applied and what other amazing awesome things in Python are so mysterious and hard to google?



Find the answer here

Tuesday, March 23, 2010

Storing an object to use in multiple classes

Programmer Question

I am wondering the best way to store an object in memory that is used in a lot of classes throughout an application.



Let me set up my problem for you:



We have multiple databases, 1 per customer. We also have a master table and each row is detailed information about the databases such as database name, server IP it's located and a few config settings.



I have an application that loops through those multiple databases and runs some updates on them. The settings I mentioned above are updated each loop iteration into memory. The application then runs through series of processes that include multiple classes using this data. The data never changes during the processes, only during the loop iteration.



The variables are related to a customer, so I have them stored in a customer class. I suppose I could make all of the members shared or should I use a singleton for the customer class? I've never actually used a singleton, only read they are good in this type of situation. Are there better solutions to this type of scenario?



Also, I could have plans for this application to be multithreaded later.



Sorry if this is confusing. If you have questions, let me know and I will answer them.



Thanks for your help.



Find the answer here

How can I get a set of radio buttons to accept NULL (nothing checked)?

Programmer Question

I'm working on a Rails application where I have some a set of two radio buttons where users can click "yes" or "no". The MySQL DB column created by the ActiveRecord migration is a tinyint.



If the user doesn't click either radio button I want MySQL to store NULL. (The column allows NULL.) And when they come back to edit the data, neither button should be checked.



What's happening is that ActiveRecord is storing 0 and then when I come back the "No" button is checked.



Rails 2.3.5



Form code (I'm using Haml):



        = f.radio_button( :model_attribute, true )
Yes

= f.radio_button( :model_attribute, false )
No


(In retrospect it probably would have been better to use a single checkbox, but it would be difficult to change that now.)



Find the answer here

htaccess Redirect 301 problem .. all redirects with one string fail to redirect and 404

Programmer Question

So I have moved a website and am trying to 301 redirect everything, which I do quite often so this is a weird problem but probably something stupid I'm not seeing.



ALL of my redirects are working fine, except any redirect that the first string starts with "/Dining" or "/dining" are failing. For example, this redirect works fine-



Redirect 301 /healthfitness/teeth.cfm /healthcare/pretty-teeth


...as well as 100s of others.



But all of these are failing (many more than I'm showing)-



Redirect 301 /Dining/diningreviews/vawines.cfm /shopping/wines-2004
Redirect 301 /Dining/diningathome/carrotcake.cfm /home-garden/carrot-cake-2003
Redirect 301 /Dining/diningathome/oldvarolls.cfm /home-garden/virginia-rolls-2003
Redirect 301 /Dining/diningathome/pumpkincake.cfm /home-garden/pumpkin-cake-2003


The top of my .htaccess file looks like this-



RewriteEngine On
RewriteBase /

#uploaded files
RewriteRule ^(.*/)?files/$ index.php [L]
RewriteCond %{REQUEST_URI} !.*wp-content/plugins.*
RewriteRule ^(.*/)?files/(.*) wp-content/blogs.php?file=$2 [L]

# add a trailing slash to /wp-admin
RewriteCond %{REQUEST_URI} ^.*/wp-admin$
RewriteRule ^(.+)$ $1/ [R=301,L]

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule . - [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-.*) $2 [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L]
RewriteRule . index.php [L]

<IfModule mod_security.c>
<Files async-upload.php>
SecFilterEngine Off
SecFilterScanPOST Off
</Files>
</IfModule>

#Everything below here are Redirect 301s


Find the answer here

Capturing system command output as a string

Programmer Question

Perl and PHP do this with backticks. For example:



$output = `ls`;


This code returns a directory listing into the variable $output. A similar function, system("ls"), returns the operating system return code for the given command. I'm talking about a variant that returns whatever the command prints to stdout. (There are better ways to get the list of files in a directory; the example code is an example of this concept.)



How do other languages do this? Is there a canonical name for this function? (I'm going with "backtick"; though maybe I could coin "syslurp".)



Find the answer here

Does a version control database storage engine exist?

Programmer Question

I was just wondering if a storage engine type existed that allowed you to do version control on row level contents. For instance, if I have a simple table with ID, name, value, and ID is the PK, I could see that row 354 started as (354, "zak", "test")v1 then was updated to be (354, "zak", "this is version 2 of the value")v2 , and could see a change history on the row with something like select history (value) where ID = 354.



It's kind of an esoteric thing, but it would beat having to keep writing these separate history tables and functions every time a change is made...



Find the answer here

Monday, March 22, 2010

Number Sequence in MySQL

Programmer Question

In Python if I wanted a sequence from 0 - 9 (inclusive) I would use xrange(0,10) . Is there a way I can do this in MySQL?



Find the answer here

open source project requirements

Programmer Question

I know it's a very common question, but I don't see a previous one to be asked, since I'm interested in the basic steps, nothing in particular.



It's the first time I want to license one of my projects, and it turns out, I don't know much about it. Let's say I want to use the MIT License. Do I just take the definition and paste it into my files? Does it need to be in ALL the files, or just one? or?



I don't want any fancy rights so MIT has been recommended to me, do you suggest something else? I'm looking for impartial opinions. Thanks.



What other aspects must I take into account?
It's PHP, btw.



Find the answer here

Easiest way to generate P/Invoke code?

Programmer Question

I am an experienced .Net programer, but have not compiled a C/C++ program in my life. Now I have this C-dll, headers and documentation (3rd party, not from Win API), from which I need to call about ten methods.



I was thinking of using Platform Invoke. I found these three tools that would create the code for me:





and possibly





Pinvoker seems to have a bit different approach than the Interop assistant and the Wizard. Swig I just found when checking that this question has not been asked here.



What are the pros and cons of these tools?



What would be the best = easiest and safest way for me to produce the P/Invoke code given that I don't know much about C/C++?



Find the answer here

Foreach over a collection of IEnumerables

Programmer Question

I have 3 IEnumerables that I want to iterate over. I want to do something like this:



IEnumerable<Car> redCars = GetRedCars();
IEnumerable<Car> greenCars = GetGreenCars();
IEnumerable<Car> blueCars = GetBlueCars();

foreach(Car c in (redCars + greenCars + blueCars)) {
c.DoSomething();
}

...


The best way I can think of is:



...
List<Car> allCars = new List();
allCars.AddRange(redCars);
allCars.AddRange(greenCars);
allCars.AddRange(blueCars);
foreach(car in allCars) {
...
}
...


Is there a more concise way to do this? Seems like combinding IEnumberables should be trivial.



Find the answer here

Why are lists useful?

Programmer Question

What would you use a list for that you couldn't use an array of objects for?



Find the answer here

Sunday, March 21, 2010

What's a good 3D modelling editor, other than Blender, that can be used within Unity 3D?

Programmer Question

Unity 3D is an amazing tool for quickly creating good-looking, fun games. Unfortunately, its not intended to be used for actually designing your characters or complex levels.



Blender is the general low-budget answer for this, but is difficult to understand when compared to proprietary programs, say, 3DS Max. What else is out there?



Find the answer here

How to determine orientation of Windows Phone 7?

Programmer Question

How can you tell whether the device is oriented vertically (portrait) or horizontally (landscape)?



Is there an API that simplifies this or do you have to make the determination "by hand" using the accelerometer?



Find the answer here

Python: speed up removal of every n-th element from list.

Programmer Question

I'm trying to solve this programming riddle and although the solution (see code below) works correctly, it is too slow for succesful submission.




  • Any pointers as how to make this run
    faster (removal of every n-th element from a list)?

  • Or suggestions for a better algorithm to calculate the same; seems I can't think of anything
    else than brute-force for now...



Basically, the task at hand is:




GIVEN:
L = [2,3,4,5,6,7,8,9,10,11,........]
1. Take the first remaining item in list L (in the general case 'n'). Move it to
the 'lucky number list'. Then drop every 'n-th' item from the list.
2. Repeat 1

TASK:
Calculate the n-th number from the 'lucky number list' ( 1 <= n <= 3000)


My original code (it calculated the 3000 first lucky numbers in about a second on my machine - unfortunately too slow):



"""
SPOJ Problem Set (classical) 1798. Assistance Required
URL: http://www.spoj.pl/problems/ASSIST/
"""

sieve = range(3, 33900, 2)
luckynumbers = [2]

while True:
wanted_n = input()
if wanted_n == 0:
break

while len(luckynumbers) < wanted_n:
item = sieve[0]
luckynumbers.append(item)
items_to_delete = set(sieve[::item])
sieve = filter(lambda x: x not in items_to_delete, sieve)
print luckynumbers[wanted_n-1]


EDIT: thanks to the terrific contributions of Mark Dickinson, Steve Jessop and gnibbler, I got at the following, which is quite a whole lot faster than my original code (and succesfully got submitted at http://www.spoj.pl with 0.58 seconds!)...



sieve = range(3, 33810, 2)
luckynumbers = [2]

while len(luckynumbers) < 3000:
if len(sieve) < sieve[0]:
luckynumbers.extend(sieve)
break
luckynumbers.append(sieve[0])
del sieve[::sieve[0]]

while True:
wanted_n = input()
if wanted_n == 0:
break
else:
print luckynumbers[wanted_n-1]


Find the answer here

Analyze kernel dump of hanged windows server

Programmer Question

I have a production server that is hanging for around five minutes once or twice a week. During this time it responds to pings but nothing else. After shooting in the dark for a while ( upgrading drivers and firmwares, changing network parameters etc ) we took a kernel dump during such hang. We have send it to Microsoft support. But in the mean time I am trying to look at it. The output of the !locks command is as follow



5: kd> !locks
**** DUMP OF ALL RESOURCE OBJECTS ****
KD: Scanning for held locks.......

Resource @ Ntfs!NtfsData (0xfffffade5ad9bfa0) Shared 1 owning threads
Contention Count = 16
Threads: fffffade70af8bf0-01<*>
KD: Scanning for held locks.......

Resource @ 0xfffffade6a6e7800 Shared 2 owning threads
Contention Count = 4114
NumberOfSharedWaiters = 71
NumberOfExclusiveWaiters = 1
Threads: fffffade69e98530-01<*> fffffade76007040-01<*> fffffade6a076840-01 fffffade6a045bf0-01
fffffade72317040-01 fffffade70af77a0-01 fffffade6a05c040-01 fffffade7a3d2040-01
<lines removed>
fffffade6936e4a0-01 fffffade6b530bf0-01 fffffade6ed36bf0-01 fffffade6b95e040-01
fffffade6fbf6040-01
Threads Waiting On Exclusive Access:
fffffade6a9ddbf0

KD: Scanning for held locks........................................

Resource @ 0xfffffade6abab640 Shared 1 owning threads
Contention Count = 115580
NumberOfSharedWaiters = 2
NumberOfExclusiveWaiters = 2
Threads: fffffadfdb3fb040-01<*> fffffade70af8040-01 fffffade70af8bf0-01
Threads Waiting On Exclusive Access:
fffffade69e98530 fffffade76007040

KD: Scanning for held locks........................

Resource @ 0xfffffade69e0acf0 Exclusively owned
Contention Count = 4
NumberOfExclusiveWaiters = 4
Threads: fffffade70afa040-01<*>
Threads Waiting On Exclusive Access:
fffffade6ecc0bf0 fffffade6bbb9040 fffffade6ecafbf0 fffffade6fb9ebf0

KD: Scanning for held locks.......................

Resource @ 0xfffffade755b0ec0 Exclusively owned
Threads: fffffade76007040-01<*>
KD: Scanning for held locks.

Resource @ 0xfffffade6fdd63c0 Exclusively owned
Threads: fffffade72317040-01<*>

Resource @ 0xfffffade7788c2e0 Exclusively owned
Threads: fffffade7a3d2040-01<*>

Resource @ 0xfffffade71c3f030 Exclusively owned
Threads: fffffade7a920a30-01<*>
KD: Scanning for held locks.

Resource @ 0xfffffade75ebef80 Exclusively owned
Threads: fffffade6ecc5040-01<*>

Resource @ 0xfffffade74529030 Exclusively owned
Threads: fffffade7a978770-01<*>
KD: Scanning for held locks.

Resource @ 0xfffffade7cdfae70 Exclusively owned
Threads: fffffade727e69f0-01<*>

Resource @ 0xfffffade8e69e030 Exclusively owned
Threads: fffffade765230c0-01<*>

Resource @ 0xfffffade7dfa6030 Exclusively owned
Threads: fffffade82d248c0-01<*>

Resource @ 0xfffffade6aa52540 Exclusively owned
Threads: fffffade75428760-01<*>

Resource @ 0xfffffade5be9b930 Exclusively owned
Threads: fffffade70af8bf0-01<*>
KD: Scanning for held locks.

Resource @ 0xfffffade6eeaf3f0 Exclusively owned
Threads: fffffade6b6615a0-01<*>
KD: Scanning for held locks.

Resource @ 0xfffffade7db22030 Exclusively owned
Threads: fffffade6fbf6040-01<*>
118264 total locks, 17 locks currently held


What does this tell me? What should I do next?
Thanks.



Find the answer here

Try-Catch or Check Length? C# XNA

Programmer Question

I was just wondering which would be cheaper, using a try catch block for index out of bounds or checking the length of a multi dimensional array and comparing values?



I have a feeling it's the length, since I can store the length in a variable and then just do if's which are relatively cheap. I'm just not sure how expensive try-catch is.



Thanks!



Find the answer here

Friday, March 19, 2010

can bind successfully to the ldap server, but needs to know how to find user w/i AD

Programmer Question

I create a login form to bind to the ldap server, if successful, it creates a session (which the user's username is stored within), then I go to another page that has session_start(); and it works fine.



What I want to do now, is add code to test if that user is a member of a specific group.



So in theory, this is what I want to do



if(username session is valid) {
search ldap for user -> get list of groups user is member of

foreach(group they are member of) {
switch(group) {
case STAFF:
print 'they are member of staff group';
$access = true;
break;

default:
print 'not a member of STAFF group';
$access = false;
break;
}

if(group == STAFF) {
break;
}

}

if($access == TRUE) {
// you have access to the content on this page
} else {
// you do not have access to this page
}
}


How do I do a ldap_search w/o binding? I don't want to keep asking for their password on each page, and I can't pass their password thru a session.



Any help is appreciated.



Find the answer here

C++ read registry string value in char*

Programmer Question

I'm reading a registry value like this:



char mydata[2048];
DWORD dataLength = sizeof(mydata);
DWORD dwType = REG_SZ;

..... open key, etc
ReqQueryValueEx(hKey, keyName, 0, &dwType, (BYTE*)mydata, &dataLength);


My problem is, that after this, mydata content looks like: [63, 00, 3A, 00, 5C, 00...], i.e. this looks like a unicode?!?!.



I need to convert this somehow to be a normal char array, without these [00], as they fail a simple logging function I have. I.e. if I call like this: WriteMessage(mydata), it outputs only "c", which is the first char in the registry. I have calls to this logging function all over the place, so I'd better of not modify it, but somehow "fix" the registry value. Here is the log function:



void Logger::WriteMessage(const char *msg)
{
time_t now = time(0);
struct tm* tm = localtime(&now);
std::ofstream logFile;

logFile.open(filename, std::ios::out | std::ios::app);

if ( logFile.is_open() )
{
logFile << tm->tm_mon << '/' << tm->tm_mday << '/' << tm->tm_year << ' ';
logFile << tm->tm_hour << ':' << tm->tm_min << ':' << tm->tm_sec << "> ";
logFile << msg << "\n";
logFile.close();
}
}


Find the answer here

Is read-only auto-imlemented property possible?

Programmer Question

Hello.
I found a topic on MSDN that talks that yes, this is possible.



I did a test that seems to break this statement:



using System;



namespace Test
{
class Program
{
static void Main(string[] args)
{
Foo f = new Foo("1");
Console.WriteLine(f.Bar); // prints 1
f.Test("2");
Console.WriteLine(f.Bar);// successfully prints 2
}
}

class Foo
{
public Foo(string b)
{
this.Bar = b;
}

public string Bar { get; private set; }

public void Test(string b)
{
// this would be impossible for readonly field!
// next error would be occur: CS0191 or CS0191
// A readonly field cannot be assigned to (except in a constructor or a variable initializer)
this.Bar = b;
}
}
}


Where am I wrong?



Find the answer here

Learning C bit manipulation

Programmer Question

I didn't know any better name for a title of the question.



For ex: on one of my previous questions one answered ((a)-(b))&0x80000000) >> 31 - this is kind of a too advanced for me and i can't really get what it means. I am not looking just for an answer of that, but i need someone to tell me some books/sites/whatever where i can learn this cool "advanced" tricks in C - and learn how and where to use them respectively too.



Find the answer here

Thursday, March 18, 2010

Should I use an ArrayList or IList

Programmer Question

Im using the .NET framework 1.1 and Im hoping someone could help me implement a dynamic array of objects?



A watered-down example of the object I wish use is below.



Class CarObj
{
public string CarName;
public string CarYear;
}


Should I use an ArrayList or do you think it would be better to make a CarList class to implement an IList interface? Is there a performance benefit for one over another?



Find the answer here

Can you configure Windows to open JAR files like ZIP files without a 3rd party tool?

Programmer Question

I'd like to be able to examine the contents of a JAR file without having to install Winzip or some other tool and without having to rename the file. Windows Explorer can open ZIP files just fine; is there some registry setting I can use to let it treat JARs like ZIPs?



Find the answer here

SSIS task failed event handler

Programmer Question

Is there any way in SSIS to identify which particular task has failed? My requirement is on file source task failure I need to send an email.



Find the answer here

Lawler's Algorithm Implementation Assistance

Programmer Question

Here is my implemenation of Lawler's algorithm in PHP (I know... but I'm used to it):



<?php    

$jobs = array(1, 2, 3, 4, 5, 6);
$jobsSubset = array(2, 5, 6);
$n = count($jobs);
$processingTimes = array(2, 3, 4, 3, 2, 1);
$dueDates = array(3, 15, 9, 7, 11, 20);
$optimalSchedule = array();
foreach ($jobs as $j) {
$optimalSchedule[] = 0;
}
$dicreasedCardinality = array();
for ($i = $n; $i >= 1; $i--) {

$x = 0;
$max = 0;

// loop through all jobs
for ($j = 0; $j < $i; $j++) {

// ignore if $j already is in the $dicreasedCardinality array
if (false === in_array($j, $dicreasedCardinality)) {

// if the job has no succesor in $jobsSubset
if (false === isset($jobs[$j+1])
|| false === in_array($jobs[$j+1], $jobsSubset)) {

// here I find an array index of a job with the maximum due date
// amongst jobs with no sucessor in $jobsSubset
if ($x < $dueDates[$j]) {

$x = $dueDates[$j];
$max = $j;

}

}

}

}

// move the job at the end of $optimalSchedule
$optimalSchedule[$i-1] = $jobs[$max];

// decrease the cardinality of $jobs
$dicreasedCardinality[] = $max;
}

print_r($optimalSchedule);


Now the above returns an optimal schedule like this:



Array
(
[0] => 1
[1] => 1
[2] => 1
[3] => 3
[4] => 2
[5] => 6
)


Which doesn't seem right to me. The problem might be with my implementation of the algorithm because I am not sure I understand it correctly. I used this source to implement it:



http://www.google.com/books?id=aSiBs6PDm9AC&pg=PA166&dq=lawler%27s+algorithm+code&lr=&hl=sk&cd=4#v=onepage&q=&f=false



The description there is a little confusing. For example, I didn't quite get how is the subset D defined (I guess it is arbitrary).



Could anyone help me out with this? I have been trying to find some sources with simpler explanation of the algorithm but all sources I found were even more complicated (with math proofs and such) so I am stuck with the link above.



Yes, this is a homework, if it wasn't obvious.



I still have few weeks to crack this but I have spent few days already trying to get how exactly this algorithm works with no success so I don't think I will get any brighter during that time.



Find the answer here

fortran 90 user defined type, passing by value ?

Programmer Question

I have an issue in Fortran 90.



I have a user-defined type, and when I call one of the MPI subroutines the data looks to be passed by value (not address, as I thought it should). The output arguments aren't modified. It seems to be specific to the MPI calls. I tried the same thing in a simple test, and I can change the passed in values in the calling scope. I'm not sure why this is, because I thought Fortran always passes by address. Any idea what could be going on?



Just to be clear, the commented snippet shows how the calls are made. In the first call, c%NSubDomains is an output argument and should be modified in the calling scope, but is not. When I call with an array rather than a member of a user-defined type it works, in the uncommented snippet.



! ! This doesn't work output values aren't modified ??
! call MPI_Dims_create(c%NProcs,c%NDims,c%NSubDomains,iErr)

nsubs(:)=0
call MPI_Dims_create(c%NProcs,c%NDims,nsubs,iErr)
c%NSubDomains=nsubs


Find the answer here

Tuesday, March 16, 2010

Multi-threading mechanisms to run some lengthy operations from winforms code and communication with GUI

Programmer Question

What do I want to achieve: I want to perform some time consuming operations from my MDI winforms application (C# - .NET).



An MDI child form may create the thread with the operation, which may take long time (from 0.1 seconds, to even half hour) to complete. In the meantime I want the UI to respond to user actions, including manipulation of data in some other MDI child form. When the operation completes, the thread should notify the MDI child that the calculations are done,
so that the MDI child can perform the post-processing.



How can I achieve this:
Should I use explicit threading (i.e., create explicit threads), thread pools? Or simply just propose your solution. Should I create foreground or background threads?



And how does the thread communicates with the GUI, according the solution you propose?



If you know of a working example that handles a similar situation, please make a note.



Find the answer here

Where should addins for Office 2010 put their Options GUI? (and how?)

Programmer Question

Up until Office 2007 it was common for addins to add a tab page to the main Options dialog (Tools|Options) where users could configure the addin's settings. While this essentially still works in Office 2010 the way it is implemented seems like a backwards-compatibility clutch similar to the "COM-Addins" tab on the new ribbon where buttons went that in previous versions would have been placed on a toolbar:



In order to get at an addin's Options page you now have to go to Files|Options then switch to the Add-ins page and look for the "Add-In Options" button, click it and then select the relevant addin's tab. I find it hard to believe that this is the way things are supposed to be, or is it? Surely there should be some way to put my addin options directly on the File|Options dialog?



Where can I find a document describing best-practices for addin developers that explains where to put my addin's Options page (and how) in Office 2010?



Find the answer here

Code Golf - π day

Programmer Question

The Challenge



The shortest code by character count to display a representation of a circle of radius R using the *character, followed by an approximation of π.



Input is a single number, R.



Since most computers seem to have almost 2:1 ratio you should only output lines where y is odd. This means that when R is odd you should print R-1 lines. There is a new testcase for R=13 to clarify.



eg.



Input
5
Output Correct Incorrect

3 ******* 4 *******
1 ********* 2 *********
-1 ********* 0 ***********
-3 ******* -2 *********
2.56 -4 *******
3.44


Edit: Due to widespread confusion caused by odd values of R, any solutions that pass the 4 test cases given below will be accepted



The approximation of π is given by dividing twice the number of * characters by R².

The approximation should be correct to at least 6 significant digits.

Leading or trailing zeros are permitted, so for example any of 3, 3.000000, 003 is accepted for the inputs of 2 and 4.



Code count includes input/output (i.e., full program).



Test Cases



Input
2
Output
***
***
3.0

Input
4
Output
*****
*******
*******
*****
3.0

Input
8
Output
*******
*************
***************
***************
***************
***************
*************
*******
3.125

Input
10
Output
*********
***************
*****************
*******************
*******************
*******************
*******************
*****************
***************
*********
3.16


Bonus Test Case



Input
13
Output

*************
*******************
*********************
***********************
*************************
*************************
*************************
*************************
***********************
*********************
*******************
*************
2.98224852071


Find the answer here

How to parse the file name and rename in Matlab

Programmer Question

I am reading a .xls file and then procesing it inside and rewriting it in the end of my program. I was wondering if someone can help me to parse the dates
as my input file name is like file_1_2010_03_03.csv



and i want my outputfile to be



newfile_2010_03_03.xls



is there a way to incorporate in matlab program so i do not have to manually write the command

xlswrite('newfile_2010_03_03.xls', M);
everytime and change the dates as i input files with diff dates

like
file_2_2010_03_04.csv.



Maybe i was not clear>
I am using uigetfile to input 3 diff files in format
file_1_2010_03_03.csv,file_2_2010_03_03.csv,file_3_2010_03_03.csv



Now i am processing the file inside my program and writing 4 output files
with names newfileX_3_2010_03_03.xls,newfileXY_3_2010_03_03.xls,newfileXZ_3_2010_03_03.xls,
newfileYZ_3_2010_03_03.xls



so my dates are not current date , but i need that from the input file and append that to newname for my xlswrite.



so was wondering if there is a way i can write a generic



xlswrite ('xxx ' M);
which will pick the name i want instead of me having 2 modify the name' xxx' everytime i input a new file



Thanks



Thanks



Find the answer here

errors from localhost to real site

Programmer Question

hi, i was working on the localhost and every thing was just fine, but when i upload to my site it get alot of errors



why is that ?



(sorry for my bad english)



Find the answer here

Sunday, March 14, 2010

How can I easily keep consistent UI settings in C# Winform application?

Programmer Question

I have a lot of different UserControls and would like to maintain consistent UI settings (mainly colors and fonts). My first try was this:



public class UISettings
{
//...
public void SetupUserControl(ref UserControl ctrl)
{
ctrl.BackColor = this.BackColor;
}
}


to be called in every control like this:



settings.SetupUserControl(ref this);


As this is read-only it cannot be passed by ref argument so this does not work. What are other options to keep consistent UI without manually changing properties for every item?



Find the answer here

Visual Studio support for coding directly in IL?

Programmer Question

For the longest time I've been curious to code in Intermediate Language just as an academic endeavour and to gain a better understanding of what's "happening under the hood".



Does anybody provide Visual Studio support for *IL in the form of: project templates, IntelliSense integration, and those kind of RAD features?



Edits: I don't mean restricted to out of the box support. For example, I can download Visual Studio extensions to support Python, COBOL, etc. Want the same for *IL.



There is a stand-alone Intermediate Assembler tool.



Find the answer here

Capturing Standard Output from an IronRuby Script using the DLR APIs

Programmer Question

I have a very simple test.rb file:



puts "Hello World"


I want to execute this file within c#, eg:



var runtime = Ruby.CreateRuntime();
runtime.ExecuteFile("C:\test.rb");


How can I capture the "Hello World"?



Find the answer here

How to make OSX application that just runs opens some file type and runs arbitrary Ruby code?

Programmer Question

It's trivial to make a program executable from shell - just put #!/usr/bin/ruby on top, chmod +x it and done. Unfortunately OSX won't let me associate file type with such scripts - it requires its .apps instead. This sort of distinction doesn't seem to exist on other operating systems.



What's the simplest way of making such .app, which would merely execute some arbitrary Ruby code?



Find the answer here

Migrating MachineKey from iis6 on old server to iis7 on new server

Programmer Question

I am migrating our hosting environment to a totally new data center with new boxes and hardware and software... the whole deal.



Our website cookies are encrypted using the machineKey, so when I make a request to my domain and point it to the new web server (by overriding the local hosts file), I get an error because the cookie cannot be decrypted, since the Machine Key is different. I'd like to avoid any problems a frequent user might have when they arrive at the new server for the first time.



To the best of my knowledge, at this point I think I need to set the same MachineKey from our current servers on our new servers. This way when past visitors with a cookie arrive at our website served by the new server, the cookie will be decrypted properly with the MachineKey it was encrypted with and then log them in properly.



My question is where do I find my MachineKey value (in IIS 6 win2k3 server) so I can use that value to set it statically on my new servers? I've pulled up my machine.config file, but it doesn't specify the key, it only specifies a configSection where the key can be defined. It's not in my web.config for the app or elsewhere.



I did find this great article on some MachineKey and Web Garden woes (which could explain some other bugs I've been experiencing with regard to the machineKey).



Update
I am back to this issue and am still faced with a similar problem. I have the MachineKey auto-generated on the IIS6 server but I need to get that exact key so I can set it explicitly and not have it auto-generated anymore.



Any help is appreciated...



Find the answer here

Saturday, March 13, 2010

how to put jcheckbox to table cell?

Programmer Question

Hello, I cannot put jChceckBox to jTable cell. More likely I can put checkBox to table, but when I run module with that table, the cell where should be checkBox shows text "true" or "false". The behaviors of that cell are the same like checkbox, but it shows text value instead of checkbox.



Here is the code.



DefaultTableModel dm = new DefaultTableModel();
dm.setDataVector(new Object[][]{{"dd", "Edit", "Delete"},
{"dd","Edit", "Delete"}},
new Object[]{"Include","Component", "Ekvi"});
jTable1 = new javax.swing.JTable();

jTable1.setModel(dm);


JCheckBox chBox=new JCheckBox();
jTable1.getColumn("Include").setCellEditor(new DefaultCellEditor(chBox));
jScrollPane1.setViewportView(jTable1);


Find the answer here

Why dont Android applications provide an "Exit" option?

Programmer Question

Is there something in the Android developer guidelines that disuadea developers from providing the option to "exit" (stop running) an application from within the application itself?



I love multitasking and all but it's not clear to me why:




  • the vast majority of apps don't have their own Exit functions and hence just keep running forever

  • don't give you a choice about running when you turn on the phone - they just do by default



Both of these things lead to memory usage constantly increasing and your device running with this performance burden all of the time despite the fact that you may only want certain apps to run some of the time.



Am I missing something?



Find the answer here

MSSQL 2005: Rename DB Server Instance Name?

Programmer Question

Hi,



Can somebody tell me how to rename the DB server instance name and a DB name
in MSSQL 2005?



Right Now I Have



SERVER/OLDNAME



-- oldnameDB



I want to change the server instance and also change the db name.



I have tried:



EXEC sp_renamedb 'oldName', 'newName'



and that has changed the dbname as it appers in the tree directory.
But, when I do "select @@servername" it is the old name. Also,
the MDF and LDF files are still the old name.



How do change instance and db names as a clean sweep across the server?



Thanks.



Find the answer here

How to provide stl like container with public const iterator and private non-const iterator?

Programmer Question

Hello,



I have a class that includes a std::list and wish to provide public begin() and end() for const_iterator and private begin() and end() for just plain iterator.



However, the compiler is seeing the private version and complaining that it is private instead of using the public const version.



I understand that C++ will not overload on return type (in this case const_iterator and iterator) and thus it is choosing the non-const version since my object is not const.



Short of casting my object to const before calling begin() or not overloading the name begin is there a way to accomplish this?



I would think this is a known pattern that folks have solved before and would like to follow suit as to how this is typically solved.



class myObject {
public:
void doSomethingConst() const;
};

class myContainer {
public:
typedef std::list<myObject>::const_iterator const_iterator;
private:
typedef std::list<myObject>::iterator iterator;

public:
const_iterator begin() const { return _data.begin(); }
const_iterator end() const { return _data.end(); }
void reorder();
private:
iterator begin() { return _data.begin(); }
iterator end() { return _data.end(); }
private:
std::list<myObject> _data;
};

void myFunction(myContainer &container) {
myContainer::const_iterator itr = container.begin();
myContainer::const_iterator endItr = container.end();
for (; itr != endItr; ++itr) {
const myObject &item = *itr;
item.doSomethingConst();
}
container.reorder(); // Do something non-const on container itself.
}


The error from the compiler is something like this:



../../src/example.h:447: error: `std::_List_iterator<myObject> myContainer::begin()' is private
caller.cpp:2393: error: within this context
../../src/example.h:450: error: `std::_List_iterator<myObject> myContainer::end()' is private
caller.cpp:2394: error: within this context


Thanks.



-William



Find the answer here

How to implement Open Flash Chart 2 on Symfony

Programmer Question

I'm trying to use Open Flash Chart 2 on my symfony project by including the ofc2 library on one of my controller's action.



Unfortunately it doesn't work. When i call the action it prints nothing :'(



There is a plugin for this, but it uses an outdated version of OFC.



Anyone have had any success showing Open Flash Chart 2 on their site?



Here's how my controller's actions file looks:



<?php

class chartActions extends sfActions{

public function executeTestChartData(sfWebRequest $request){
$this->getResponse()->setHttpHeader('Content-Type','text/plain');

include('/cidat/lib/php-ofc-library/open-flash-chart.php');

$title = new title( date("D M d Y") );

$bar = new bar();
$bar->set_values( array(9,8,7,6,5,4,3,2,1) );

$chart = new open_flash_chart();
$chart->set_title( $title );
$chart->add_element( $bar );

$output = $chart->toPrettyString();

return $this->renderText($output);
}
}

?>


Thanks in advance,



Vic



Find the answer here

Friday, March 12, 2010

Session bug using facebook-connect-with-authlogic in Rails

Programmer Question

I'm trying to follow this article: http://ryanbigg.com/2010/03/testing-facebook, but I'm stuck. I think the problem is with my session, in that the current_usermethod comes up with nil for session[:facebook_session].



According to the original authlogic, it says to use the active_record_store for sessions:



# config/environment.rb
config.action_controller.session_store = :active_record_store
# db/schema includes
create_table "sessions", :force => true do |t|
t.string "session_id", :null => false
t.text "data"
t.datetime "created_at"
t.datetime "updated_at"
end


The article calls for the use of cookies. I'm confused; can I use cookies and the active record sessions? I'm also confused by the use of cattr_accessor :current_user from within the User model -- current_user still goes in the application controller, right?



Please help.



Find the answer here

MathML or OMML to PNG w/ .NET?

Programmer Question

Are there any libraries which take MathML (or, even more preferably, OMML) and outputs a .PNG file?



I am putting together an export process for .docx files and, as a part of this process, I'd like to extract equations and render them as .PNG files. Word 2007 does this natively when you save a document for the web, but so far, I have not been able to find a way to do this programmatically (if anyone has an answer for that, it would be even better). So the next best thing is to take the OMML and use the Microsoft provided XSL stylesheets and transform them to MathML.



Unfortunately, I haven't been able to find any (working) rendering libraries for either MathML or OMML.



If there aren't any pure .NET libraries for this, I'll settle for just about anything that I can call from a commandline to output a .PNG from either MathML or OMML.



Find the answer here

Can't instantiate COM component in C# - error 80070002

Programmer Question

I'm attempting to instantiate a Windows Media Player COM object on my machine:



Guid mediaPlayerClassId = new Guid("47ac3c2f-7033-4d47-ae81-9c94e566c4cc");
Type mediaPlayerType = Type.GetTypeFromCLSID(mediaPlayerClassId);
Activator.CreateInstance(mediaPlayerType); // <-- this line throws


When executing that last line, I get the following error:



System.IO.FileNotFoundException was caught
Message="Retrieving the COM class factory for component with CLSID {47AC3C2F-7033-4D47-AE81-9C94E566C4CC} failed due to the following error: 80070002."
Source="mscorlib"
StackTrace:
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean fillCache)
at System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.Activator.CreateInstance(Type type)
at MyStuff.PreviewFile(String filePath) in F:\Trunk\PreviewHandlerHosting\PreviewHandlerHost.cs:line 60
InnerException:


This same code works on other developer machines and end user machines. For some reason, it only fails on my machine. What could be the cause?



Find the answer here

C/C++ packing signed char into int

Programmer Question

hello



I have need to pack four signed bytes into 32-bit integral type.
this is what I came up to:



int32_t byte(int8_t c) { return (unsigned char)c; }

int pack(char c0, char c1, ...) {
return byte(c0) | byte(c1) << 8 | ...;
}


is this a good solution? Is it portable (not in communication sense)?
is there a ready-made solution, perhaps boost?



issue I am mostly concerned about is bit order when converting of negative bits from char to int. I do not know what the correct behavior should be.



Thanks



Find the answer here

CSS filters - sometimes working, sometimes not?

Programmer Question

I'm on the verge of pulling my hair out over this.



Here I have a block of perfectly functioning CSS:



#admin .block.mode.off
{
opacity: 0.25;
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(opacity=25)";
filter: progid:DXImageTransform.Microsoft.Alpha(opacity=25);
}


Meanwhile... Internet Explorer 8 couldn't care less about my filter declarations here:



#admin .drop .tabs
{
margin-bottom: 12px;
}
#admin .drop .tab
{
margin-right: 4px;
}
#admin .drop .tab.off
{
cursor: pointer;
opacity: 0.5;
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(opacity=50)";
filter: progid:DXImageTransform.Microsoft.Alpha(opacity=50);
}
#admin .drop .tab.off:hover
{
text-shadow: 0px 0px 4px #fff;
}
#admin .drop .tab.on
{
cursor: default;
text-shadow: 0px 0px 4px #fff;
-ms-filter: "progid:DXImageTransform.Microsoft.Glow(color=#fff, strength=4)";
filter: progid:DXImageTransform.Microsoft.Glow(color=#fff, strength=4);
}


My document shows in IE8 Standards, and I am assuming the developer tools are a load of tuna, because the functioning block shows up in its CSS tab as:



filter: progid:DXImageTransform.Microsoft.Alpha(opacity=25); opacity: 0.25


Does anyone have any ideas?



Find the answer here

Update a list from another list

Programmer Question

I have a list of users in local store that I need to update from a remote list of users every once in a while. Basically:




  1. If a remote user already exists locally, update its fields.

  2. If a remote user doesn't already exist locally, add the user.

  3. If a local user doesn't appear in the remote list, deactivate or delete.

  4. If a local user also appears in the remote list, update its fields.



Just a simple case of syncing the local list. Is there a better way to do this in pure Java than the following? I feel gross looking at my own code.



public class User {
Integer id;
String email;
boolean active;

//Getters and Setters.......

public User(Integer id, String email, boolean active) {
this.id = id;
this.email = email;
this.active = active;
}

@Override
public boolean equals(Object other) {
boolean result = false;
if (other instanceof User) {
User that = (User) other;
result = (this.getId() == that.getId());
}
return result;
}

}




public static void main(String[] args) {

//From 3rd party
List<User> remoteUsers = getRemoteUsers();

//From Local store
List<User> localUsers =getLocalUsers();

for (User remoteUser : remoteUsers) {
boolean found = false;
for (User localUser : localUsers) {
if (remoteUser.equals(localUser)) {
found = true;
localUser.setActive(remoteUser.isActive());
localUser.setEmail(remoteUser.getEmail());
//update
}
break;
}
if (!found) {
User user = new User(remoteUser.getId(), remoteUser.getEmail(), remoteUser.isActive());
//Save
}
}

for(User localUser : localUsers ) {
boolean found = false;
for(User remoteUser : remoteUsers) {
if(localUser.equals(remoteUser)) {
found = true;
localUser.setActive(remoteUser.isActive());
localUser.setEmail(remoteUser.getEmail());
//Update
}
break;
}
if(!found) {
localUser.setActive(false);
// Deactivate
}
}
}


Find the answer here

How are *.XIB, *.m and *.h files related?

Programmer Question

How/where in the code does the nib file get related to its *.m and *.h files?



Find the answer here

Links to official style guides

Programmer Question

C++ has several types of styles: MFC, Boost, Google, etc. I would like to examine these styles and determine which one is best for my projects, but I want to read from the official style guidebook. Does anyone have an official guide that they typically use?



Here are two that I found. I bet there are more:





Note: This is NOT a discussion about which styleis best..only a call for official style guides that people currently use. Please refrain from bashing other style guides that you don't like.



Side question: Is there a good tool that can examine source code and tell if it matches a given style guide?



Find the answer here

Returning currently displayed index of an array Javascript...

Programmer Question

I have a simple array with x number of items. I am displaying them individually via a link click... I want to update a number that say 1 of 10. when the next one is displayed i want it to display 2 of 10 etc...



I have looked all around and my brain is fried right now... I know its simple I just cant get it out.



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Page Title</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" charset="utf-8"/>
<script type="text/javascript">
var quotations = new Array()
quotations[0]= "1"
quotations[1]= "2"
quotations[2]= "3"
quotations[3]= "4"
quotations[4]= "5"
quotations[5]= "6"
quotations[6]= "7"

numQuotes = quotations.length;
curQuote = 1;

function move( xflip ) {
curQuote = curQuote + xflip;
if (curQuote > numQuotes)
{ curQuote = 1 ; }
if (curQuote == 0)
{ curQuote = numQuotes ; }
document.getElementById('quotation').innerHTML=quotations[curQuote - 1];
}
var curPage = //this is where the current index should go
</script>

</head>

<body>
<div id="quotation">
<script type="text/javascript">document.write(quotations[0]);</script>
</div>
<div>
<p><a href="javascript();" onclick="move(-1)">GO back</a>
<script type="text/javascript">document.write(curPage + " of " + numQuotes)</script>
<a href="javascript();" onclick="move(1)">GO FORTH</a></p>

</div>
</body>

</html>


Find the answer here

The provided URI scheme 'https' is invalid; expected 'http'. Parameter name: via

Programmer Question

I am trying to make a WCF service over basicHttpBinding to be used over https. Here's my web.config:



  <service behaviorConfiguration="MyServices.PingResultServiceBehavior"
name="MyServices.PingResultService">
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="defaultBasicHttpBinding"
contract="MyServices.IPingResultService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>


...



<bindings>
<basicHttpBinding>
<binding name="defaultBasicHttpBinding">
<security mode="Transport">
<transport clientCredentialType="None"/>
</security>
</binding>
</basicHttpBinding>
</bindings>


...









I am connecting using WCFStorm which is able to retrieve all the meta data properly, but when I call the actual method I get:



The provided URI scheme 'https' is invalid; expected 'http'.
Parameter name: via



Any ideas?



Find the answer here

Thursday, March 11, 2010

I have a following gcc compilation warning

Programmer Question

symbol.h:179: note: expected ‘uintptr_t *’ but argument is of type ‘PRECEDENCE’



The corresponding code is :



176 void            symbol_SetCount(SYMBOL, unsigned long);
177 unsigned long symbol_GetCount(SYMBOL);
178
179 size_t symbol_Ordering(uintptr_t*, SYMBOL);
180
181 void symbol_CheckIndexInRange(int);
182 void symbol_CheckNoVariable(SYMBOL);


SYMBOL is defined as:



typedef size_t SYMBOL


Any effort will be highly appreciated.



Find the answer here

How can I *prevent* Apache2 from setting the Content-Type header?

Programmer Question

I have a CGI script that prints the following on stdout:



print "Status: 302 Redirect\n";
print "Server: Apache-Coyote/1.1\n";
print "Location: $redirect\n";
print "Content-Length: 0\n";
print "Date: $date\n\n";


Where $redirect and $date are reasonable values. What Apache2 actually sends also includes a Content-Type: header (text/plain). I've commented out the DefaultType in the server configuration file.



I'm trying to debug a downstream problem that arises when no Content-Type: header is sent. So what magic incantation do I have to perform to prevent Apache2 from adding the content type header?



Find the answer here

Python HTML sanitizer / scrubber / filter

Programmer Question

Does anyone have experience using a Python HTML sanitizer / scrubber / filter?



I'm looking for a module that will remove any HTML tags from a string that are not found in a whitelist. Of course I've Googled it but haven't found anything definitive.



Thanks,
Everett



Find the answer here

How can I verify that web pages are being gzipped?

Programmer Question

I plan to configure weblogic's gzip servlet filter (using weblogicx-gzip.jar) to gzip my web pages.



How can I verify that the pages are being sent to the client gzipped?



Find the answer here

C: How to convert a string of ints into actual ints and store them in an array?

Programmer Question

I have a string "14 22 33 48". I need to insert each of the values in the string into the respective location in the array:



int matrix[5];


so that



matrix[0] = 14;
matrix[1] = 22;
matrix[2] = 33;
matrix[3] = 48;


How do I do this?



Find the answer here

Wednesday, March 10, 2010

Django subprocess

Programmer Question

I'm really sorry if this is a duplicate, but I have been searching, and haven't been able to find the answer.



In Django I want to do something like (see the comments):



# we have a file in our database...
v = create_file_entry(clean_data, ip_address)
# next, start a *background process* to upload the file somewhere else...
p = Process(target=upload_file, args=(filepath,v))
p.start()
p.join()
# ...we don't care about the result of the process, or
# wait for it to finish, just redirect the user to success *immediately*
return HttpResponseRedirect('/success/')


I want the code to start the upload_file process, and then redirect the user to the success page immediately, while the upload_file process runs in the background (it's slow). I thought a subprocess might do this.



Unfortunately the code above seems to wait for the upload_file process to finish before heading before redirecting the user to the success page, which is not what I need.



Note that upload_file is a Python function in my views.py file. I've heard about popen - I guess I could convert def upload_file into a stand-alone Python script and run it from the command line - would that start running and then immediately redirect the user, as I want? Or should I be using some kind of thread/process?



Find the answer here

Is it better to swap classes or swap content in jQuery

Programmer Question

I was wondering which of these two scenario's works best for swapping between 2 stated. Let's say for temporary disable a button.



I think the first and most easy way is just to have both pieces of html already in place. And when clicked the a class of none is swapped, like this:



css:
.none{display:none;}

html init:
<div class"somecss none">but1</div>
<div class"somecss">but1</div>

html changed:
<div class"somecss none">but1</div>
<div class"somecss">but1</div>


The second scenario i can think of is swapping the whole piece of html using javascript. I think the code is clear on that one. You just have an if-statement and just insert the html code required for the state.



Pros, cons



In the first scenario you have more DOM elements i assume, esp when the html of both of the containers is large. There is however not much to do in javascrip.



In the second scenario the DOM is minimal, but however the is a little more javascript needed.



Which of these 2 scenario's you think is the best and why?



And maybe you know of another solution i was not aware of, i would like to hear that.



Thank you and have a great day!



Find the answer here

run function at ready and keyup event

Programmer Question

Is there another in jquery to run a function at page load and at a keyup event instead of the way I'm doing it?



$(function() {
totalQty();
$("#main input").keyup(function() {
totalQty();
});
});



Find the answer here

How can you pass JSON Object of option parameters to open a new window?

Programmer Question

the window.open() object has some funky parameter list...



is there a way to do something like window.open({options..});



Thoughts?



Find the answer here

How can I make gcc understand alternate signatur syntax ?

Programmer Question

I'm trying to use a delegate library in gcc (http://www.codeproject.com/KB/cpp/ImpossiblyFastCppDelegate.aspx) but the "preferred syntax" is not recognized by gcc 4.3. I.e. howto make compiler understand the
template < RET_TYPE (ARG1, ARG2) > syntax instead of template ??



TIA
/Rob



Find the answer here

Tuesday, March 9, 2010

remove values from an array php

Programmer Question

I have a array of links and i have another array which contains certain values i would like to filter in the list
eg:



http://www.liquidshredder.co.uk/shop%3Fkw%3Dsurfboards%26fl%3D330343%26ci%3D3889610385%26network%3Ds
http://www.bournemouth-surfing.co.uk/index.php%3FcPath%3D32
http://www.stcstores.co.uk/wetsuit-range-sizing--pricing-info-1-w.asp
http://www.kingofwatersports.com/wetsuit-sale-c227.html
http://www.uk.best-price.com/search/landing/query/bodyboards/s/google/altk/Surf%2Band/koid/1944273223/
http://www.surfinghardware.co.uk/Results.cfm%3Fcategory%3D20%26kw%3Dbodyboards%26fl%3D11407%26ci%3D3326979552%26network%3Ds
http://www.teste.co.uk/adtrack/baod.html
http://www.teste.co.uk/bodyboards/
www.sandskater.co.uk/
www.sandskater.co.uk/bodyboards/+Bodyboards&sa=X&ei=GwSWS-KaGM24rAeF-vCKDA&ved=0CBMQHzAKOAo
http://www.extremesportstrader.co.uk/buy/water/bodyboarding/
www.extremesportstrader.co.uk/buy/water/bodyboarding/+Bodyboards&sa=X&ei=GwSWS-KaGM24rAeF-vCKDA&ved=0CBYQHzALOAo
www.circle-one.co.uk/+Bodyboards&sa=X&ei=GwSWS-KaGM24rAeF-vCKDA&ved=0CBkQHzAMOAo
http://www.teste.co.uk/bodyboards/p1
http://www.teste.co.uk/bodyboards/p2
http://www.amazon.co.uk/s/%3Fie%3DUTF8%26keywords%3Dbodyboards%26tag%3Dgooghydr-21%26index%3Daps%26hvadid%3D4764625891%26ref%3Dpd_sl_2lyzsfw1ar_e
http://www.teste.co.uk/bodyboards/p3
www.extremesportstrader.co.uk/buy/water/


and i would like to remove all the instances of "http://www.teste.co.uk"?



i tried the below code but it doesn't work :(



$remove=array("teste.co.uk","127.0.0.1","localhost","wikipedia.org","gmail.com","answers.yahoo.com");

foreach ($list[0] as $key=>$clean)
{
if (in_array($clean,$remove))
{
unset($list[0][$key]);
}

echo $clean;
echo '<br>';
}


Find the answer here

Do browsers support autocomplete for ajax loaded login forms at all?

Programmer Question

My problem is, that the browsers' (IE&FF) autocomplete does not work for my login form.



I have a webapp with CakePHP & jQuery. To allow visitors to login/register unobtrusively. The login form is inside a div, which is loaded via AJAX. (This enables logging in without a page reload.)



The browsers do recognize it as a login field, as they prompt me to save the credentials when clicking login. And they really do save the username/password, as they appear between the saved ones in the browser settings. But the saved username/password is never entered automatically. They do not appear pre-entered when the page loads. When I start typing in the username, the username appears as a suggestion, but even when you select it, the password is not entered next to it. Why? How can I get this working?



That you can test it yourself, here is a simple AJAX login form:



http://gablog.eu/test/ajaxlogin.html



It loads the following login form, if you go to the url below, autocomplete will work for just the plain form, so it is not a problem with the form itself, but rather that it is AJAX loaded:
http://gablog.eu/test/loginform.html



The layout:



<div id="user-bar">
<script type="text/javascript">
$(function() {
$("#user-bar").load('loginform.html').html();
});
</script>
</div>


The view loaded (when not logged in):



<form id="form-login" action="" onsubmit="login(); return false;">
<input type="text" id="username" name="username"/>
<input type="password" id="password" name="password"/>
<input type="submit" value="Login"/>
<div id="login-error" class="error-message"></div>
</form>

<script type="text/javascript">
function login() {
$.post('/ajax/login', $("#form-login").serialize(), function(data) {
if (data.success) {
$("#user-bar").load('userbar.html').html();
} else {
$("#login-error").html(data.message);
}
}, "json");
}
</script>


To clarify: I do not want to use AJAX autocomplete, I want the browser's autocomplete to work for my login form. This is an issue between my form and the browser. jQuery submission seems to play a minor role, as the usernames/passwords are saved. They are just not auto-entered for ajax loaded HTML elements! (The test site does not use jQuery submission.) Related question: http://stackoverflow.com/questions/1622628/browser-autocomplete-saved-form-not-work-in-ajax-request



Find the answer here

Loading xml into a xdoc, and then initializing an object

Programmer Question

My object looks like:



public class Template
{
public string Title {get;set;}
public string Body {get;set;}
}


xml that is stored in /files/test.xml in a web application (at the root):



<nodes>
<template name="someKey">
<node name="title">soem title</node>
<node name="body">some body text here</node>
</template>
</nodes>


So I can load the document like:



XDocument doc = XDocument.Load(HttpContext.Current.Server.MapPath("~/files/test.xml"));


Now how would I load the object from the xml? (say for the template with name = somekey



Find the answer here

LinkWithin

Related Posts with Thumbnails