input
stringlengths 51
42.3k
| output
stringlengths 18
55k
|
---|---|
Is there a Functional Programming library for .NET? <p>For example, in Java there is <a href="http://functionaljava.org/">Functional Java</a> and <a href="http://www.cs.chalmers.se/~bringert/hoj/">Higher-Order Java</a>. Both essentially give a small API for manipulating higher-order, curried functions, and perhaps a few new data types (tuples, immutable lists).</p>
| <p>have you looked into <a href="http://research.microsoft.com/fsharp/fsharp.aspx">F#</a>?</p>
<p>Also a neat blog post would be <a href="http://geekswithblogs.net/akraus1/articles/79880.aspx">here</a> that talks about how to use the new generic / lambda expressions built into c# 3.0.</p>
<p>If you just add using System.Linq to the top of your source file there are a LOT of nice new functions added to working with collections such as folding / filtering / etc.</p>
|
Is it the filename or the whole URL used as a key in browser caches? <p>It's common to want browsers to cache resources - JavaScript, CSS, images, etc. until there is a new version available, and then ensure that the browser fetches and caches the new version instead.</p>
<p>One solution is to embed a version number in the resource's filename, but will placing the resources to be managed in this way in a directory with a revision number in it do the same thing? Is the whole URL to the file used as a key in the browser's cache, or is it just the filename itself and some meta-data?</p>
<p>If my code changes from fetching <code>/r20/example.js</code> to <code>/r21/example.js</code>, can I be sure that revision 20 of <code>example.js</code> was cached, but now revision 21 has been fetched instead and it is now cached?</p>
| <p>Yes, any change in <em>any part</em> of the URL (excluding HTTP and HTTPS protocols changes) is interpreted as a different resource by the browser (and any intermediary proxies), and will thus result in a separate entity in the browser-cache.</p>
<p><strong>Update:</strong></p>
<p>The claim in <a href="http://www.thinkvitamin.com/features/webapps/serving-javascript-fast">this ThinkVitamin article</a> that Opera and Safari/Webkit browsers don't cache URLs with ?query=strings is <strong>false</strong>.</p>
<p>Adding a version number parameter to a URL is a perfectly acceptable way to do cache-busting.</p>
<p>What may have confused the author of the ThinkVitamin article is the fact that hitting Enter in the address/location bar in Safari and Opera results in different behavior for URLs with query string in them.</p>
<p>However, (<em>and this is the important part!</em>) Opera and Safari <strong>behave just like IE and Firefox</strong> when it comes to caching embedded/linked images and stylesheets and scripts in web pages - regardless of whether they have "?" characters in their URLs. (This can be verified with a simple test on a normal Apache server.)</p>
<p>(I would have commented on the currently accepted answer if I had the reputation to do it. :-)</p>
|
Samba, other non interactive accounts - noshell, nologin, or blank? <p>Conducting a user account cleanup accross Solaris and Redhat linux systems, many of which have a number of Samba shares. </p>
<p>What preference do people have for creating the local unix accounts for non interactive Samba users? In particular, the shell entry:</p>
<ol>
<li>noshell</li>
<li>nologin</li>
<li>blank</li>
</ol>
<p>And why?</p>
<p>JB</p>
| <p>I have seen the shell set to the <code>passwd</code> command so that logging in only gives an opportunity to change the password. This may or may not be appropriate in your non-interactive user case, but it has the upside of allowing people to change passwords without bothering an admin.</p>
|
Getting a full list of the URLS in a rails application <p>How do I get a a complete list of all the urls that my rails application could generate? </p>
<p>I don't want the routes that I get get form rake routes, instead I want to get the actul URLs corrosponding to all the dynmically generated pages in my application...</p>
<p>Is this even possible?</p>
<p>(Background: I'm doing this because I want a complete list of URLs for some load testing I want to do, which has to cover the entire breadth of the application)</p>
| <p>I was able to produce useful output with the following command:</p>
<pre><code>$ wget --spider -r -nv -nd -np http://localhost:3209/ 2>&1 | ack -o '(?<=URL:)\S+'
http://localhost:3209/
http://localhost:3209/robots.txt
http://localhost:3209/agenda/2008/08
http://localhost:3209/agenda/2008/10
http://localhost:3209/agenda/2008/09/01
http://localhost:3209/agenda/2008/09/02
http://localhost:3209/agenda/2008/09/03
^C
</code></pre>
<h3>A quick reference of the <code>wget</code> arguments:</h3>
<pre><code># --spider don't download anything.
# -r, --recursive specify recursive download.
# -nv, --no-verbose turn off verboseness, without being quiet.
# -nd, --no-directories don't create directories.
# -np, --no-parent don't ascend to the parent directory.
</code></pre>
<h3>About <code>ack</code></h3>
<p><code>ack</code> is like <code>grep</code> but use <code>perl</code> regexps, which are more complete/powerful.</p>
<p><code>-o</code> tells <code>ack</code> to only output the matched substring, and the pattern I used looks for anything non-space preceded by <code>'URL:'</code></p>
|
How do indicate the SQL default library in an IBM iSeries 2 connection string to an AS/400? <p>I'm connecting to an AS/400 stored procedure layer using the IBM iSeries Access for Windows package. This provides a .NET DLL with classes similar to those in the <code>System.Data</code> namespace. As such we use their implementation of the connection class and provide it with a connection string.</p>
<p>Does anyone know how I can amend the connection string to indicate the default library it should use?</p>
| <p>If you are connecting <strong>through .NET</strong>:</p>
<pre><code>Provider=IBMDA400;Data Source=as400.com;User Id=user;Password=password;Default Collection=yourLibrary;
</code></pre>
<p><em><strong>Default Collection</em></strong> is the parameter that sets the library where your programs should start executing.</p>
<p>And if you are connecting <strong>through ODBC from Windows</strong> (like setting up a driver in the control panel):</p>
<pre><code>DRIVER=Client Access ODBC Driver(32-bit);SYSTEM=as400.com;EXTCOLINFO=1;UID=user;PWD=password;LibraryList=yourLibrary
</code></pre>
<p>In this case <strong><em>LibraryList</em></strong> is the parameter to set, remember this is for ODBC connection.</p>
<p>There are two drivers from IBM to connect to the AS400, the older one uses the above connection string, if you have the newest version of the client software from IBM called "System i Access for Windows" then you should use this connection string:</p>
<pre><code>DRIVER=iSeries Access ODBC Driver;SYSTEM=as400.com;EXTCOLINFO=1;UID=user;PWD=password;LibraryList=yourLibrary
</code></pre>
<p>The last is pretty much the same, only the <strong><em>DRIVER</em></strong> parameter value changes.</p>
<p>If you are using this in a .NET application don't forget to add the <strong><em>providerName</em></strong> parameter to your XML tag and define the API used for connecting which would be OleDb in this case:</p>
<pre><code>providerName="System.Data.OleDb"
</code></pre>
|
MySql - Create Table If Not Exists Else Truncate? <p><strong>Here is the updated question:</strong></p>
<p>the current query is doing something like:<br></p>
<pre><code>$sql1 = "TRUNCATE TABLE fubar";
$sql2 = "CREATE TEMPORARY TABLE IF NOT EXISTS fubar SELECT id, name FROM barfu";
</code></pre>
<p>The first time the method containing this is run, it generates an error message on the truncate since the table doesn't exist yet.</p>
<p>Is my only option to do the <code>CREATE TABLE</code>, run the <code>TRUNCATE TABLE</code>, and then fill the table? (3 separate queries)</p>
<p><strong>original question was:</strong></p>
<p>
I've been having a hard time trying to figure out if the following is possible in MySql without having to write block sql:</p>
<pre><code>CREATE TABLE fubar IF NOT EXISTS ELSE TRUNCATE TABLE fubar
</code></pre>
<p>If I run truncate separately before the create table, and the table doesn't exist, then I get an error message. I'm trying to eliminate that error message without having to add any more queries.</p>
<p>This code will be executed using PHP.</p>
| <p>shmuel613, it would be better to update your original question rather than replying. It's best if there's a single place containing the complete question rather than having it spread out in a discussion.</p>
<p>Ben's answer is reasonable, except he seems to have a 'not' where he doesn't want one. Dropping the table only if it <strong>doesn't</strong> exist isn't quite right.</p>
<p>You will indeed need multiple statements. Either conditionally create then populate:</p>
<ol>
<li>CREATE TEMPORARY TABLE IF NOT EXISTS fubar ( id int, name varchar(80) )</li>
<li>TRUNCATE TABLE fubar</li>
<li>INSERT INTO fubar SELECT * FROM barfu</li>
</ol>
<p>or just drop and recreate</p>
<ol>
<li>DROP TABLE IF EXISTS fubar</li>
<li>CREATE TEMPORARY TABLE fubar SELECT id, name FROM barfu</li>
</ol>
<p>With pure SQL those are your two real classes of solutions. I like the second better.</p>
<p>(With a stored procedure you could reduce it to a single statement. Something like: TruncateAndPopulate(fubar) But by the time you write the code for TruncateAndPopulate() you'll spend more time than just using the SQL above.)</p>
|
Why learn Perl, Python, Ruby if the company is using C++, C# or Java as the application language? <p>I wonder why would a C++, C#, Java developer want to learn a dynamic language?</p>
<p>Assuming the company won't switch its main development language from C++/C#/Java to a dynamic one what use is there for a dynamic language?</p>
<p>What helper tasks can be done by the dynamic languages faster or better after only a few days of learning than with the static language that you have been using for several years?</p>
<h2>Update</h2>
<p>After seeing the first few responses it is clear that there are two issues.
My main interest would be something that is justifiable to the employer as an expense.
That is, I am looking for justifications for the employer to finance the learning of a dynamic language. Aside from the obvious that the employee will have broader view, the
employers are usually looking for some "real" benefit.</p>
| <p>A lot of times some quick task comes up that isn't part of the main software you are developing. Sometimes the task is one off ie compare this file to the database and let me know the differences. It is a lot easier to do text parsing in Perl/Ruby/Python than it is in Java or C# (partially because it is a lot easier to use regular expressions). It will probably take a lot less time to parse the text file using Perl/Ruby/Python (or maybe even vbscript <em>cringe</em> and then load it into the database than it would to create a Java/C# program to do it or to do it by hand.</p>
<p>Also, due to the ease at which most of the dynamic languages parse text, they are great for code generation. Sure your final project must be in C#/Java/Transact SQL but instead of cutting and pasting 100 times, finding errors, and cutting and pasting another 100 times it is often (but not always) easier just to use a code generator.</p>
<p>A recent example at work is we needed to get data from one accounting system into our accounting system. The system has an import format, but the old system had a completely different format (fixed width although some things had to be matched). The task is not to create a program to migrate the data over and over again. It is to shove the data into our system and then maintain it there going forward. So even though we are a C# and SQL Server shop, I used Python to convert the data into the format that could be imported by our application. Ultimately it doesn't matter that I used python, it matters that the data is in the system. My boss was pretty impressed.</p>
<p>Where I often see the dynamic languages used for is testing. It is much easier to create a Python/Perl/Ruby program to link to a web service and throw some data against it than it is to create the equivalent Java program. You can also use python to hit against command line programs, generate a ton of garbage (but still valid) test data, etc.. quite easily.</p>
<p>The other thing that dynamic languages are big on is code generation. Creating the C#/C++/Java code. Some examples follow:</p>
<p>The first code generation task I often see is people using dynamic languages to maintain constants in the system. Instead of hand coding a bunch of enums, a dynamic language can be used to fairly easily parse a text file and create the Java/C# code with the enums.</p>
<p>SQL is a whole other ball game but often you get better performance by cut and pasting 100 times instead of trying to do a function (due to caching of execution plans or putting complicated logic in a function causing you to go row by row instead of in a set). In fact it is quite useful to use the table definition to create certain stored procedures automatically.</p>
<p>It is always better to get buy in for a code generator. But even if you don't, is it more fun to spend time cutting/pasting or is it more fun to create a Perl/Python/Ruby script once and then have that generate the code? If it takes you hours to hand code something but less time to create a code generator, then even if you use it once you have saved time and hence money. If it takes you longer to create a code generator than it takes to hand code once but you know you will have to update the code more than once, it may still make sense. If it takes you 2 hours to hand code, 4 hours to do the generator but you know you'll have to hand code equivalent work another 5 or 6 times than it is obviously better to create the generator.</p>
<p>Also some things are easier with dynamic languages than Java/C#/C/C++. In particular regular expressions come to mind. If you start using regular expressions in Perl and realize their value, you may suddenly start making use of the Java regular expression library if you haven't before. If you have then there may be something else.</p>
<p>I will leave you with one last example of a task that would have been great for a dynamic language. My work mate had to take a directory full of files and burn them to various cd's for various customers. There were a few customers but a lot of files and you had to look in them to see what they were. He did this task by hand....A Java/C# program would have saved time, but for one time and with all the development overhead it isn't worth it. However slapping something together in Perl/Python/Ruby probably would have been worth it. He spent several hours doing it. It would have taken less than one to create the Python script to inspect each file, match which customer it goes to, and then move the file to the appropriate place.....Again, not part of the standard job. But the task came up as a one off. Is it better to do it yourself, spend the larger amount of time to make Java/C# do the task, or spend a much smaller amount of time doing it in Python/Perl/Ruby. If you are using C or C++ the point is even more dramatic due to the extra concerns of programming in C or C++ (pointers, no array bounds checking, etc.).</p>
|
Problem with Java 1.6 and Desktop.open() <p>I've been using Destop.open() to launch a .pdf viewer on Windows machines, both Vista and XP, and most of them work just fine. However, on one XP machine the call does not work, simply returning without throwing any exceptions, and the viewer does not launch. On that machine the file association is properly set up as far as I can tell: double-clicking a .pdf works, as does the "start xxx.pdf" command on the command prompt. I'm thinking it must be a Windows configuration issue, but can't put my finger on it.</p>
<p>Has anyone else seen this problem?</p>
| <p>This is a known problem with early versions of XP SP2, the ShellExecute function stopped accepting URIs; bring the XP machines patches up to date.</p>
<p>To view the exceptions make sure the Java Console is turned on:</p>
<pre><code>Control Panel->Java Control Panel->Advanced->Java Console.
</code></pre>
|
How do you authenticate against an Active Directory server using Spring Security? <p>I'm writing a Spring web application that requires users to login. My company has an Active Directory server that I'd like to make use of for this purpose. However, I'm having trouble using Spring Security to connect to the server.</p>
<p>I'm using Spring 2.5.5 and Spring Security 2.0.3, along with Java 1.6.</p>
<p>If I change the LDAP URL to the wrong IP address, it doesn't throw an exception or anything, so I'm wondering if it's even <em>trying</em> to connect to the server to begin with.</p>
<p>Although the web application starts up just fine, any information I enter into the login page is rejected. I had previously used an InMemoryDaoImpl, which worked fine, so the rest of my application seems to be configured correctly.</p>
<p>Here are my security-related beans:</p>
<pre><code> <beans:bean id="ldapAuthProvider" class="org.springframework.security.providers.ldap.LdapAuthenticationProvider">
<beans:constructor-arg>
<beans:bean class="org.springframework.security.providers.ldap.authenticator.BindAuthenticator">
<beans:constructor-arg ref="initialDirContextFactory" />
<beans:property name="userDnPatterns">
<beans:list>
<beans:value>CN={0},OU=SBSUsers,OU=Users,OU=MyBusiness,DC=Acme,DC=com</beans:value>
</beans:list>
</beans:property>
</beans:bean>
</beans:constructor-arg>
</beans:bean>
<beans:bean id="userDetailsService" class="org.springframework.security.userdetails.ldap.LdapUserDetailsManager">
<beans:constructor-arg ref="initialDirContextFactory" />
</beans:bean>
<beans:bean id="initialDirContextFactory" class="org.springframework.security.ldap.DefaultInitialDirContextFactory">
<beans:constructor-arg value="ldap://192.168.123.456:389/DC=Acme,DC=com" />
</beans:bean>
</code></pre>
| <p>I had the same banging-my-head-against-the-wall experience you did, and ended up writing a custom authentication provider that does an LDAP query against the Active Directory server.</p>
<p>So my security-related beans are:</p>
<pre><code><beans:bean id="contextSource"
class="org.springframework.security.ldap.DefaultSpringSecurityContextSource">
<beans:constructor-arg value="ldap://hostname.queso.com:389/" />
</beans:bean>
<beans:bean id="ldapAuthenticationProvider"
class="org.queso.ad.service.authentication.LdapAuthenticationProvider">
<beans:property name="authenticator" ref="ldapAuthenticator" />
<custom-authentication-provider />
</beans:bean>
<beans:bean id="ldapAuthenticator"
class="org.queso.ad.service.authentication.LdapAuthenticatorImpl">
<beans:property name="contextFactory" ref="contextSource" />
<beans:property name="principalPrefix" value="QUESO\" />
</beans:bean>
</code></pre>
<p>Then the LdapAuthenticationProvider class:</p>
<pre><code>/**
* Custom Spring Security authentication provider which tries to bind to an LDAP server with
* the passed-in credentials; of note, when used with the custom {@link LdapAuthenticatorImpl},
* does <strong>not</strong> require an LDAP username and password for initial binding.
*
* @author Jason
*/
public class LdapAuthenticationProvider implements AuthenticationProvider {
private LdapAuthenticator authenticator;
public Authentication authenticate(Authentication auth) throws AuthenticationException {
// Authenticate, using the passed-in credentials.
DirContextOperations authAdapter = authenticator.authenticate(auth);
// Creating an LdapAuthenticationToken (rather than using the existing Authentication
// object) allows us to add the already-created LDAP context for our app to use later.
LdapAuthenticationToken ldapAuth = new LdapAuthenticationToken(auth, "ROLE_USER");
InitialLdapContext ldapContext = (InitialLdapContext) authAdapter
.getObjectAttribute("ldapContext");
if (ldapContext != null) {
ldapAuth.setContext(ldapContext);
}
return ldapAuth;
}
public boolean supports(Class clazz) {
return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(clazz));
}
public LdapAuthenticator getAuthenticator() {
return authenticator;
}
public void setAuthenticator(LdapAuthenticator authenticator) {
this.authenticator = authenticator;
}
}
</code></pre>
<p>Then the LdapAuthenticatorImpl class:</p>
<pre><code>/**
* Custom Spring Security LDAP authenticator which tries to bind to an LDAP server using the
* passed-in credentials; does <strong>not</strong> require "master" credentials for an
* initial bind prior to searching for the passed-in username.
*
* @author Jason
*/
public class LdapAuthenticatorImpl implements LdapAuthenticator {
private DefaultSpringSecurityContextSource contextFactory;
private String principalPrefix = "";
public DirContextOperations authenticate(Authentication authentication) {
// Grab the username and password out of the authentication object.
String principal = principalPrefix + authentication.getName();
String password = "";
if (authentication.getCredentials() != null) {
password = authentication.getCredentials().toString();
}
// If we have a valid username and password, try to authenticate.
if (!("".equals(principal.trim())) && !("".equals(password.trim()))) {
InitialLdapContext ldapContext = (InitialLdapContext) contextFactory
.getReadWriteContext(principal, password);
// We need to pass the context back out, so that the auth provider can add it to the
// Authentication object.
DirContextOperations authAdapter = new DirContextAdapter();
authAdapter.addAttributeValue("ldapContext", ldapContext);
return authAdapter;
} else {
throw new BadCredentialsException("Blank username and/or password!");
}
}
/**
* Since the InitialLdapContext that's stored as a property of an LdapAuthenticationToken is
* transient (because it isn't Serializable), we need some way to recreate the
* InitialLdapContext if it's null (e.g., if the LdapAuthenticationToken has been serialized
* and deserialized). This is that mechanism.
*
* @param authenticator
* the LdapAuthenticator instance from your application's context
* @param auth
* the LdapAuthenticationToken in which to recreate the InitialLdapContext
* @return
*/
static public InitialLdapContext recreateLdapContext(LdapAuthenticator authenticator,
LdapAuthenticationToken auth) {
DirContextOperations authAdapter = authenticator.authenticate(auth);
InitialLdapContext context = (InitialLdapContext) authAdapter
.getObjectAttribute("ldapContext");
auth.setContext(context);
return context;
}
public DefaultSpringSecurityContextSource getContextFactory() {
return contextFactory;
}
/**
* Set the context factory to use for generating a new LDAP context.
*
* @param contextFactory
*/
public void setContextFactory(DefaultSpringSecurityContextSource contextFactory) {
this.contextFactory = contextFactory;
}
public String getPrincipalPrefix() {
return principalPrefix;
}
/**
* Set the string to be prepended to all principal names prior to attempting authentication
* against the LDAP server. (For example, if the Active Directory wants the domain-name-plus
* backslash prepended, use this.)
*
* @param principalPrefix
*/
public void setPrincipalPrefix(String principalPrefix) {
if (principalPrefix != null) {
this.principalPrefix = principalPrefix;
} else {
this.principalPrefix = "";
}
}
}
</code></pre>
<p>And finally, the LdapAuthenticationToken class:</p>
<pre><code>/**
* <p>
* Authentication token to use when an app needs further access to the LDAP context used to
* authenticate the user.
* </p>
*
* <p>
* When this is the Authentication object stored in the Spring Security context, an application
* can retrieve the current LDAP context thusly:
* </p>
*
* <pre>
* LdapAuthenticationToken ldapAuth = (LdapAuthenticationToken) SecurityContextHolder
* .getContext().getAuthentication();
* InitialLdapContext ldapContext = ldapAuth.getContext();
* </pre>
*
* @author Jason
*
*/
public class LdapAuthenticationToken extends AbstractAuthenticationToken {
private static final long serialVersionUID = -5040340622950665401L;
private Authentication auth;
transient private InitialLdapContext context;
private List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
/**
* Construct a new LdapAuthenticationToken, using an existing Authentication object and
* granting all users a default authority.
*
* @param auth
* @param defaultAuthority
*/
public LdapAuthenticationToken(Authentication auth, GrantedAuthority defaultAuthority) {
this.auth = auth;
if (auth.getAuthorities() != null) {
this.authorities.addAll(Arrays.asList(auth.getAuthorities()));
}
if (defaultAuthority != null) {
this.authorities.add(defaultAuthority);
}
super.setAuthenticated(true);
}
/**
* Construct a new LdapAuthenticationToken, using an existing Authentication object and
* granting all users a default authority.
*
* @param auth
* @param defaultAuthority
*/
public LdapAuthenticationToken(Authentication auth, String defaultAuthority) {
this(auth, new GrantedAuthorityImpl(defaultAuthority));
}
public GrantedAuthority[] getAuthorities() {
GrantedAuthority[] authoritiesArray = this.authorities.toArray(new GrantedAuthority[0]);
return authoritiesArray;
}
public void addAuthority(GrantedAuthority authority) {
this.authorities.add(authority);
}
public Object getCredentials() {
return auth.getCredentials();
}
public Object getPrincipal() {
return auth.getPrincipal();
}
/**
* Retrieve the LDAP context attached to this user's authentication object.
*
* @return the LDAP context
*/
public InitialLdapContext getContext() {
return context;
}
/**
* Attach an LDAP context to this user's authentication object.
*
* @param context
* the LDAP context
*/
public void setContext(InitialLdapContext context) {
this.context = context;
}
}
</code></pre>
<p>You'll notice that there are a few bits in there that you might not need.</p>
<p>For example, my app needed to retain the successfully-logged-in LDAP context for further use by the user once logged in -- the app's purpose is to let users log in via their AD credentials and then perform further AD-related functions. So because of that, I have a custom authentication token, LdapAuthenticationToken, that I pass around (rather than Spring's default Authentication token) which allows me to attach the LDAP context. In LdapAuthenticationProvider.authenticate(), I create that token and pass it back out; in LdapAuthenticatorImpl.authenticate(), I attach the logged-in context to the return object so that it can be added to the user's Spring authentication object.</p>
<p>Also, in LdapAuthenticationProvider.authenticate(), I assign all logged-in users the ROLE_USER role -- that's what lets me then test for that role in my intercept-url elements. You'll want to make this match whatever role you want to test for, or even assign roles based on Active Directory groups or whatever.</p>
<p>Finally, and a corollary to that, the way I implemented LdapAuthenticationProvider.authenticate() gives all users with valid AD accounts the same ROLE_USER role. Obviously, in that method, you can perform further tests on the user (i.e., is the user in a specific AD group?) and assign roles that way, or even test for some condition before even granting the user access at <em>all</em>.</p>
|
How do I efficiently search an array to fill in form fields? <p>I am looking for an efficient way to pull the data I want out of an array called $submission_info so I can easily auto-fill my form fields. The array size is about 120.</p>
<p>I want to find the field name and extract the content. In this case, the field name is <strong>loanOfficer</strong> and the content is <strong>John Doe</strong>.</p>
<pre><code>Output of Print_r($submission_info[1]):
Array (
[field_id] => 2399
[form_id] => 4
[field_name] => loanOfficer
[field_test_value] => ABCDEFGHIJKLMNOPQRSTUVWXYZ
[field_size] => medium
[field_type] => other
[data_type] => string
[field_title] => LoanOfficer
[col_name] => loanOfficer
[list_order] => 2
[admin_display] => yes
[is_sortable] => yes
[include_on_redirect] => yes
[option_orientation] => vertical
[file_upload_dir] =>
[file_upload_url] =>
[file_upload_max_size] => 1000000
[file_upload_types] =>
[content] => John Doe
)
</code></pre>
<p>I want to find the field name and extract the content. In this case, the field name is <strong>loanOfficer</strong> and the content is <strong>John Doe</strong>.</p>
| <p>You're probably best off going through each entry and creating a new associative array out of it.</p>
<pre><code>foreach($submission_info as $elem) {
$newarray[$elem["field_name"]] = $elem["content"];
}
</code></pre>
<p>Then you can just find the form fields by getting the value from $newarray[<em><field you're filling in></em>]. Otherwise, you're going to have to search $submission_info each time for the correct field.</p>
|
Distributed hierarchical clustering <p>Are there any algorithms that can help with hierarchical clustering?
Google's map-reduce has only an example of k-clustering. In case of hierarchical clustering, I'm not sure how it's possible to divide the work between nodes.
Other resource that I found is: <a href="http://issues.apache.org/jira/browse/MAHOUT-19">http://issues.apache.org/jira/browse/MAHOUT-19</a>
But it's not apparent, which algorithms are used.</p>
| <p>First, you have to decide if you're going to build your hierarchy bottom-up or top-down. </p>
<p>Bottom-up is called Hierarchical agglomerative clustering. Here's a simple, well-documented algorithm: <a href="http://nlp.stanford.edu/IR-book/html/htmledition/hierarchical-agglomerative-clustering-1.html" rel="nofollow">http://nlp.stanford.edu/IR-book/html/htmledition/hierarchical-agglomerative-clustering-1.html</a>.</p>
<p>Distributing a bottom-up algorithm is tricky because each distributed process needs the entire dataset to make choices about appropriate clusters. It also needs a list of clusters at its current level so it doesn't add a data point to more than one cluster at the same level.</p>
<p>Top-down hierarchy construction is called <a href="http://nlp.stanford.edu/IR-book/html/htmledition/divisive-clustering-1.html" rel="nofollow">Divisive clustering</a>. <a href="http://home.dei.polimi.it/matteucc/Clustering/tutorial_html/kmeans.html" rel="nofollow">K-means</a> is one option to decide how to split your hierarchy's nodes. This paper looks at K-means and Principal Direction Divisive Partitioning (PDDP) for node splitting: <a href="http://scgroup.hpclab.ceid.upatras.gr/faculty/stratis/Papers/tm07book.pdf" rel="nofollow">http://scgroup.hpclab.ceid.upatras.gr/faculty/stratis/Papers/tm07book.pdf</a>. In the end, you just need to split each parent node into relatively well-balanced child nodes.</p>
<p>A top-down approach is easier to distribute. After your first node split, each node created can be shipped to a distributed process to be split again and so on... Each distributed process needs only to be aware of the subset of the dataset it is splitting. Only the parent process is aware of the full dataset.</p>
<p>In addition, each split could be performed in parallel. Two examples for k-means:</p>
<ul>
<li><a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.101.1882&rep=rep1&type=pdf" rel="nofollow">http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.101.1882&rep=rep1&type=pdf</a></li>
<li><a href="http://www.ece.northwestern.edu/~wkliao/Kmeans/index.html" rel="nofollow">http://www.ece.northwestern.edu/~wkliao/Kmeans/index.html</a>.</li>
</ul>
|
How to communicate with a windows service from an application that interacts with the desktop? <p>With .Net what is the best way to interact with a service (i.e. how do most tray-apps communicate with their servers). It would be preferred if this method would be cross-platform as well (working in Mono, so I guess remoting is out?)</p>
<hr>
<h3>Edit:</h3>
<p>Forgot to mention, we still have to support Windows 2000 machines in the field, so WCF and anything above .Net 2.0 won't fly.</p>
| <p>Be aware that if you are planning to eventually deploy on Windows Vista or Windows Server 2008, many ways that this can be done today will not work. This is because of the introduction of a new security feature called "Session 0 Isolation". </p>
<p>Most windows services have been moved to run in Session 0 now in order to properly isolate them from the rest of the system. An extension of this is that the first user to login to the system no longer is placed in Session #0, they are placed in Session 1. And hence, the isolation will break code that does certain types of communication between services and desktop applications.</p>
<p>The best way to write code today that will work on Vista and Server 2008 going forward when doing communication between services and applications is to use a proper cross-process API like RPC, Named Pipes, etc. Do not use SendMessage/PostMessage as that will fail under Session 0 Isolation.</p>
<p><a href="http://www.microsoft.com/whdc/system/vista/services.mspx">http://www.microsoft.com/whdc/system/vista/services.mspx</a></p>
<p>Now, given your requirements, you are going to be in a bit of a pickle. For the cross-platform concerns, I'm not sure if Remoting would be supported. You may have to drop down and go all the way back to sockets: <a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.aspx">http://msdn.microsoft.com/en-us/library/system.net.sockets.aspx</a></p>
|
How do you maintain large t-sql procedures <p>I'm about to inherit a set of large and complex set of stored procedures that do monthly processing on very large sets of data.</p>
<p>We are in the process of debugging them so they match the original process which was written in VB6. The reason they decided to re write them in t-sql is because the vb process takes days and this new process takes hours.</p>
<p>All this is fine, but how can I make these now massive chunks of t-sql code(1.5k+ lines) even remotely readable / maintainable.</p>
<p>Any experience making t-sql not much of head ache is very welcome.</p>
| <p>First, create a directory full of .sql files and maintain them there. Add this set of .sql files to a revision control system. SVN works well. Have a tool that loads these into your database, overwriting any existing ones.</p>
<p>Have a testing database, and baseline reports showing what the output of the monthly processing should look like. Your tests should also be in the form of .sql files under version control.</p>
<p>You can now refactor your procs as much as you like, and run your tests afterward to confirm correct function.</p>
|
Resending invitation/action emails <p>I've got a web app that sends out emails in response to a user-initaited action. These emails prompt the recipient for a response (an URL is included related to the specific action.)</p>
<p>I've got some users asking for a "resend" feature to push that email again. </p>
<p>My objection is that if the original email ended up in a spam folder (or didn't make it all the first time), the same thing is likely to happen the second time. (I've confirmed that the emails haven't bounced; they were accepted by the recipient's mail server.)</p>
<p>So what does the community think: is the ability to resend and email invitation/notification useful or pointless?</p>
| <p>Definitely useful, at least from the user's point of view. By manually resending the email, they <em>know</em> that it has been sent and can check their spam folder immediately to catch the mail. Otherwise, they might not know about the mail and it will dissapear from their spam before they can catch it.</p>
|
Object Oriented Update Approach <p>I've been tasked with maintaining an application originally written in VB6. It has since been imported into VB .Net and to say the least the code is anything but Object Oriented. The code is riddled with classes which contain nothing more than Public Shared attributes(variables) and methods(functions), the result of which restricts the application from opening more than one project at a time.</p>
<p>A project consists of a XML file which contains general project settings, as well as the location to an Access database which contains other project related data. Over the years the format of the XML file has been modified, and an update and versioning strategy has been adopted. The chosen strategy performs an update upon open whenever an old version is encountered. Thus far, updates have only consisted of rearranging data within the XML file or making database schema changes and moving data from the XML file to the database.</p>
<p>Having quite a bit of background in OOP it's easy for me to see that a project should be a self contained object which other objects interact with. However, I fail to see how to apply the chosen update strategy in OOP.</p>
<p>The problem of implementing the chosen update strategy in OOP has kept me from using OOP as of yet. If anyone has experience with such a task, or recommendations on how to proceeded I'd appreciate any assistance you can provide.</p>
| <p>Build a class which reads the XML file in, and provides properties/methods/etc based upon the data in that file. When the class writes the XML file back out, have it format in the manner needed for the new version.</p>
<p>So, basically, the class will be able to read in the current version, plus all the older versions, but it will always write out the new version.</p>
<p>Data would be held in internal variables of the class, rather than having to scan the XML file every time you need something.</p>
<p>Adding a VERSION node to your XML file will also help in this case.</p>
|
How does the Java for each loop work? <pre><code>List<String> someList = new ArrayList<String>();
// add "monkey", "donkey", "skeleton key" to someList
</code></pre>
<pre><code>for (String item : someList) {
System.out.println(item);
}
</code></pre>
<p>What would the equivalent for loop look like without using the for each syntax?</p>
| <pre><code>for(Iterator<String> i = someList.iterator(); i.hasNext(); ) {
String item = i.next();
System.out.println(item);
}
</code></pre>
<p>Note that if you need to use <code>i.remove();</code> in your loop, or access the actual <code>iterator</code> in some way, you cannot use the <code>for( : )</code> idiom, since the actual <code>Iterator</code> is merely inferred.</p>
<p>As was noted by Denis Bueno, this code works for any object that <code>implements</code> the <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html"><code>Iterable interface</code></a>.</p>
<p>Also, if the right-hand side of the <code>for(:)</code> idiom is an <code>array</code> rather than an <code>Iterable</code> object, the internal code uses an int index counter and checks against array.length instead. See the <a href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.14.2">Java Language Specification</a>.</p>
|
Which language is useful to create a report for a valid C program <p>Can anyone suggest me a helpful programming language which can be used to create a tool which will analyse the given C program and generate a txt report or html report containing information about the given program (function list, variable list etc).
The program I intend to build is similar to doxygen but i want it for my personal use.</p>
| <p><a href="http://ctags.sourceforge.net/" rel="nofollow">ctags</a>, perhaps?</p>
<blockquote>
<p>Ctags generates an index (or tag) file of language objects found in source files that allows these items to be quickly and easily located by a text editor or other utility. A tag signifies a language object for which an index entry is available (or, alternatively, the index entry created for that object).</p>
</blockquote>
|
Most common cause of "java.lang.NullPointerException" when dealing with XMLs? <p>My strongest lead is that the code who deals with the incoming XMLs is actually receiving an invalid/incomplete file hence failing the DOM parsing. Any suggestions?</p>
| <p>Incomplete file is definitely the place to start looking. I'd print out the file right before the point you parse it to see what's getting sent to the parser. If it's incomplete it will be obvious. If it's invalid, you'll have a little searching to do.</p>
|
SQL Server 2005 Linked Server to DB2 Performance issue <p>I have a SQL Server 2005 machine with a JDE DB2 set up as a linked server.</p>
<p>For some reason the performance of any queries from this box to the db2 box are horrible.</p>
<p>For example. The following takes 7 mins to run from Management Studio</p>
<pre><code>SELECT *
FROM F42119
WHERE SDUPMJ >= 107256
</code></pre>
<p>Whereas it takes seconds to run in iSeries Navigator</p>
<p>Any thoughts? I'm assuming some config issue.</p>
| <p>In certain searches SQL Server will decide to pull the entire table down to itself and sort and search the data within SQL Server instead of sending the query to the remote server. This is usually a problem with collation settings. </p>
<p>Make sure the provider has the following options set:
Data Access,
Collation Compatible,
Use Remote Collation</p>
<p>Then create a new Linked Server using the provider and select the following provider options
Dynamic Parameters,
Nested Queries,
Allow In Process</p>
<p>After setting the options change the query slightly to get a new query plan.</p>
|
MVC C# custom MvcRouteHandler - How to? <p>Does anyone have experiences in providing a custom MvcRouteHandler? In my application I'd like to implement a globalization-pattern like <em>http://mydomain/en/about</em> or <em>http://mydomain/de/about</em>. </p>
<p>As for persistance, I'd like to have a cookie read as soon as a request arrives and if there is a language setting in this cookie apply it (so a user arriving at <em>http://mydomain/</em> would be transferred to <em>http://mydomain/en/</em> for example). If there is no cookie present, I'd like to get the first language the browser supports, apply this one and store it in this cookie.</p>
<p>I guess this can't be done with the standard routing mechanism mvc provides in it's initial project template. In a newsgroup I got the tip to have a look at the MvcRouteHandler and implement my own. But its hard to find a sample on how to do that.</p>
<p>Any ideas?</p>
| <p>I don't believe a custom route handler is required for what you are doing.</p>
<p>For your "globalized" URIs, a regular MVC route, with a constraint that the "locale" parameter must be equal to "en", "de", etc., will do. The constraint will prevent non-globalized URIs from matching the route.</p>
<p>For a "non-globalized" URI, make a "catch-all" route which simply redirects to the default or cookie-set locale URI.</p>
<p>Place the "globalized" route above the "catch-all" route in Global.asax, so that "already-globalized" URIs don't fall through to the redirection.</p>
<p>You would need to make a new route handler if you want a certain URI pattern to trigger something that is not an action on a controller. But I don't think that's what you're dealing with, here.</p>
|
AJAX - How to Pass value back to server <p>First time working with UpdatePanels in .NET. </p>
<p>I have an updatepanel with a trigger pointed to an event on a FormView control. The UpdatePanel holds a ListView with related data from a separate database.</p>
<p>When the UpdatePanel refreshes, it needs values from the FormView control so that on the server it can use them to query the database.</p>
<p>For the life if me, I can't figure out how to get those values. The event I'm triggering from has them, but I want the updatepanel to refresh asynchronously. How do I pass values to the load event on the panel?</p>
<p>Googled this ad nauseum and can't seem to get to an answer here. A link or an explanation would be immensely helpful..</p>
<p>Jeff</p>
| <p>make a javascript function that will collect the pieces of form data, and then sends that data to an ASHX handler. the ASHX handler will do some work, and can reply with a response.</p>
<p>This is an example I made that calls a database to populate a grid using AJAX calls. There are better libraries for doing AJAX (prototype, ExtJS, etc), but this is the raw deal. (I <strong><em>know</em></strong> this can be refactored to be even cleaner, but you can get the idea well enough)</p>
<p>Works like this...</p>
<ul>
<li>User enters text in the search box, </li>
<li>User clicks search button, </li>
<li>JavaScript gets form data, </li>
<li>javascript makes ajax call to ASHX, </li>
<li>ASHX receives request, </li>
<li>ASHX queries database,</li>
<li>ASHX parses the response into JSON/Javascript array, </li>
<li>ASHX sends response,</li>
<li>Javascript receives response, </li>
<li>javascript Eval()'s response to object,</li>
<li>javascript iterates object properties and fills grid</li>
</ul>
<p>The html will look like this... </p>
<pre><code><html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript" src="AjaxHelper.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtSearchValue" runat="server"></asp:TextBox>
<input id="btnSearch" type="button" value="Search by partial full name" onclick="doSearch()"/>
<igtbl:ultrawebgrid id="uwgUsers" runat="server"
//infragistics grid crap
</igtbl:ultrawebgrid>--%>
</div>
</form>
</body>
</html>
</code></pre>
<p>The script that fires on click will look like this...</p>
<pre><code>//this is tied to the button click. It takes care of input cleanup and calling the AJAX method
function doSearch(){
var eleVal;
var eleBtn;
eleVal = document.getElementById('txtSearchValue').value;
eleBtn = document.getElementById('btnSearch');
eleVal = trim(eleVal);
if (eleVal.length > 0) {
eleBtn.value = 'Searching...';
eleBtn.disabled = true;
refreshGridData(eleVal);
}
else {
alert("Please enter a value to search with. Unabated searches are not permitted.");
}
}
//This is the function that will go out and get the data and call load the Grid on AJAX call
//return.
function refreshGridData(searchString){
if (searchString =='undefined'){
searchString = "";
}
var xhr;
var gridData;
var url;
url = "DefaultHandler.ashx?partialUserFullName=" + escape(searchString);
xhr = GetXMLHttpRequestObject();
xhr.onreadystatechange = function() {
if (xhr.readystate==4) {
gridData = eval(xhr.responseText);
if (gridData.length > 0) {
//clear and fill the grid
clearAndPopulateGrid(gridData);
}
else {
//display appropriate message
}
} //if (xhr.readystate==4) {
} //xhr.onreadystatechange = function() {
xhr.open("GET", url, true);
xhr.send(null);
}
//this does the grid clearing and population, and enables the search button when complete.
function clearAndPopulateGrid(jsonObject) {
var grid = igtbl_getGridById('uwgUsers');
var eleBtn;
eleBtn = document.getElementById('btnSearch');
//clear the rows
for (x = grid.Rows.length; x >= 0; x--) {
grid.Rows.remove(x, false);
}
//add the new ones
for (x = 0; x < jsonObject.length; x++) {
var newRow = igtbl_addNew(grid.Id, 0, false, false);
//the cells should not be referenced by index value, so a name lookup should be implemented
newRow.getCell(0).setValue(jsonObject[x][1]);
newRow.getCell(1).setValue(jsonObject[x][2]);
newRow.getCell(2).setValue(jsonObject[x][3]);
}
grid = null;
eleBtn.disabled = false;
eleBtn.value = "Search by partial full name";
}
// this function will return the XMLHttpRequest Object for the current browser
function GetXMLHttpRequestObject() {
var XHR; //the object to return
var ua = navigator.userAgent.toLowerCase(); //gets the useragent text
try
{
//determine the browser type
if (!window.ActiveXObject)
{ //Non IE Browsers
XHR = new XMLHttpRequest();
}
else
{
if (ua.indexOf('msie 5') == -1)
{ //IE 5.x
XHR = new ActiveXObject("Msxml2.XMLHTTP");
}
else
{ //IE 6.x and up
XHR = new ActiveXObject("Microsoft.XMLHTTP");
}
} //end if (!window.ActiveXObject)
if (XHR == null)
{
throw "Unable to instantiate the XMLHTTPRequest object.";
}
}
catch (e)
{
alert("This browser does not appear to support AJAX functionality. error: " + e.name
+ " description: " + e.message);
}
return XHR;
} //end function GetXMLHttpRequestObject()
function trim(stringToTrim){
return stringToTrim.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}
</code></pre>
<p>And the ashx handler looks like this....</p>
<pre><code>Imports System.Web
Imports System.Web.Services
Imports System.Data
Imports System.Data.SqlClient
Public Class DefaultHandler
Implements System.Web.IHttpHandler
Private Const CONN_STRING As String = "Data Source=;Initial Catalog=;User ID=;Password=;"
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
context.Response.ContentType = "text/plain"
context.Response.Expires = -1
Dim strPartialUserName As String
Dim strReturnValue As String = String.Empty
If context.Request.QueryString("partialUserFullName") Is Nothing = False Then
strPartialUserName = context.Request.QueryString("partialUserFullName").ToString()
If String.IsNullOrEmpty(strPartialUserName) = False Then
strReturnValue = SearchAndReturnJSResult(strPartialUserName)
End If
End If
context.Response.Write(strReturnValue)
End Sub
Private Function SearchAndReturnJSResult(ByVal partialUserName As String) As String
Dim strReturnValue As New StringBuilder()
Dim conn As SqlConnection
Dim strSQL As New StringBuilder()
Dim objParam As SqlParameter
Dim da As SqlDataAdapter
Dim ds As New DataSet()
Dim dr As DataRow
'define sql
strSQL.Append(" SELECT ")
strSQL.Append(" [id] ")
strSQL.Append(" ,([first_name] + ' ' + [last_name]) ")
strSQL.Append(" ,[email] ")
strSQL.Append(" FROM [person] (NOLOCK) ")
strSQL.Append(" WHERE [last_name] LIKE @lastName")
'clean up the partial user name for use in a like search
If partialUserName.EndsWith("%", StringComparison.InvariantCultureIgnoreCase) = False Then
partialUserName = partialUserName & "%"
End If
If partialUserName.StartsWith("%", StringComparison.InvariantCultureIgnoreCase) = False Then
partialUserName = partialUserName.Insert(0, "%")
End If
'create the oledb parameter... parameterized queries perform far better on repeatable
'operations
objParam = New SqlParameter("@lastName", SqlDbType.VarChar, 100)
objParam.Value = partialUserName
conn = New SqlConnection(CONN_STRING)
da = New SqlDataAdapter(strSQL.ToString(), conn)
da.SelectCommand.Parameters.Add(objParam)
Try 'to get a dataset.
da.Fill(ds)
Catch sqlex As SqlException
'Throw an appropriate exception if you can add details that will help understand the problem.
Throw New DataException("Unable to retrieve the results from the user search.", sqlex)
Finally
If conn.State = ConnectionState.Open Then
conn.Close()
End If
conn.Dispose()
da.Dispose()
End Try
'make sure we have a return value
If ds Is Nothing OrElse ds.Tables(0) Is Nothing OrElse ds.Tables(0).Rows.Count <= 0 Then
Return String.Empty
End If
'This converts the table into JS array.
strReturnValue.Append("[")
For Each dr In ds.Tables(0).Rows
strReturnValue.Append("['" & CStr(dr("username")) & "','" & CStr(dr("userfullname")) & "','" & CStr(dr("useremail")) & "'],")
Next
strReturnValue.Remove(strReturnValue.Length - 1, 1)
strReturnValue.Append("]")
'de-allocate what can be deallocated. Setting to Nothing for smaller types may
'incur performance hit because of a forced allocation to nothing before they are deallocated
'by garbage collection.
ds.Dispose()
strSQL.Length = 0
Return strReturnValue.ToString()
End Function
ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
</code></pre>
|
PHP DOMDocument stripping HTML tags <p>I'm working on a small templating engine, and I'm using DOMDocument to parse the pages. My test page so far looks like this:</p>
<pre><code><block name="content">
<?php echo 'this is some rendered PHP! <br />' ?>
<p>Main column of <span>content</span></p>
</block>
</code></pre>
<p>And part of my class looks like this:</p>
<pre><code>private function parse($tag, $attr = 'name')
{
$strict = 0;
/*** the array to return ***/
$out = array();
if($this->totalBlocks() > 0)
{
/*** a new dom object ***/
$dom = new domDocument;
/*** discard white space ***/
$dom->preserveWhiteSpace = false;
/*** load the html into the object ***/
if($strict==1)
{
$dom->loadXML($this->file_contents);
}
else
{
$dom->loadHTML($this->file_contents);
}
/*** the tag by its tag name ***/
$content = $dom->getElementsByTagname($tag);
$i = 0;
foreach ($content as $item)
{
/*** add node value to the out array ***/
$out[$i]['name'] = $item->getAttribute($attr);
$out[$i]['value'] = $item->nodeValue;
$i++;
}
}
return $out;
}
</code></pre>
<p>I have it working the way I want in that it grabs each <block> on the page and injects it's contents into my template, however, it is stripping the HTML tags within the <block>, thus returning the following without the <p> or <span> tags:</p>
<pre><code>this is some rendered PHP! Main column of content
</code></pre>
<p>What am I doing wrong here? :) Thanks</p>
| <p>Nothing: nodeValue is the concatenation of the value portion of the tree, and will never have tags.</p>
<p>What I would do to make an HTML fragment of the tree under $node is this:</p>
<pre><code>
$doc = new DOMDocument();
foreach($node->childNodes as $child) {
$doc->appendChild($doc->importNode($child, true));
}
return $doc->saveHTML();
</code></pre>
<p>HTML "fragments" are actually more problematic than you'd think at first, because they tend to lack things like doctypes and character sets, which makes it hard to deterministically go back and forth between portions of a DOM tree and HTML fragments.</p>
|
php $_GET sort problem <p>here is the input i am getting from my flash file </p>
<p>process.php?Q2=898&Aa=Grade1&Tim=0%3A0%3A12&Q1=908&Bb=lkj&Q4=jhj&Q3=08&Cc=North%20America&Q0=1</p>
<p>and in php i use this code
foreach ($_GET as $field => $label)
{
$datarray[]=$_GET[$field];</p>
<pre><code>echo "$field :";
echo $_GET[$field];;
echo "<br>";
</code></pre>
<p>i get this out put</p>
<p>Q2 :898
Aa :Grade1
Tim :0:0:12
Q1 :908
Bb :lkj
Q4 :jhj
Q3 :08
Cc :North America
Q0 :1</p>
<p>now my question is how do i sort it alphabaticaly so it should look like this
Aa :Grade1
Bb :lkj
Cc :North America
Q0 :1
Q1 :908</p>
<p>and so on....before i can insert it into the DB</p>
| <pre><code>ksort($_GET);
</code></pre>
<p>This should <a href="http://php.net/manual/en/function.ksort.php" rel="nofollow">sort</a> the $_GET array by it's keys. <a href="http://php.net/manual/en/function.krsort.php" rel="nofollow">krsort</a> for reverse order.</p>
|
Determine if a function exists in bash <p>Currently I'm doing some unit tests which are executed from bash. Unit tests are initialized, executed and cleaned up in a bash script. This script usualy contains an init(), execute() and cleanup() functions. But they are not mandatory. I'd like to test if they are or are not defined.</p>
<p>I did this previously by greping and seding the source, but it seemed wrong. Is there a more elegant way to do this?</p>
<p>Edit: The following sniplet works like a charm:</p>
<pre><code>fn_exists()
{
type $1 | grep -q 'shell function'
}
</code></pre>
| <p>I think you're looking for the 'type' command. It'll tell you whether something is a function, built-in function, external command, or just not defined. Example:</p>
<pre class="lang-none prettyprint-override"><code>$ type foo
bash: type: foo: not found
$ type ls
ls is aliased to `ls --color=auto'
$ which type
$ type type
type is a shell builtin
$ type -t rvm
function
$ if [ -n "$(type -t rvm)" ] && [ "$(type -t rvm)" = function ]; then echo rvm is a function; else echo rvm is NOT a function; fi
rvm is a function
</code></pre>
|
How much success is there working on ASP.NET decompiled by Reflector? <p>I just finished a small project where changes were required to a pre-compiled, but no longer supported, ASP.NET web site. The code was ugly, but it was ugly before it was even compiled, and I'm quite impressed that everything still seems to work fine.</p>
<p>It took some editing, e.g. to remove control declarations, as they get put in a generated file, and conflict with the decompiled base class, but nothing a few hours didn't cure.</p>
<p>Now I'm just curious as to how many others have had how much success doing this. I would actually like to write a CodeProject article on defining, if not automating, the reverse engineering process. </p>
| <p>Due to all the compiler sugar that exists in the .NET platform, you can't decompile a binary into the original code without extremely sophisticated decompilers. For instance, the compiler creates classes in the background to handle enclosures. Automating this kind of thing seems like it would be a daunting task. However, handling expected issues just to get it to compile might be scriptable. </p>
|
OpenID providers - what stops malicious providers? <p>So I like the OpenID idea. I support it on my site, and use it wherever it's possible (like here!). But I am not clear about one thing. </p>
<p>A site that supports OpenID basically accepts any OpenID provider out there, right? How does that work with sites that want to reduce bot-signups? What's to stop a malicious OpenID provider from setting up unlimited bot IDs automatically?</p>
<p>I have some ideas, and will post them as a possible answer, but I was wondering if anyone can see something obvious that I've missed?</p>
| <p>You have confused two different things - identification and authorization. Just because you know who somebody is, it doesn't mean you have to automatically give them permission to do anything. Simon Willison covers this nicely in <a href="http://blog.simonwillison.net/post/57956829720/account" rel="nofollow">An OpenID is not an account!</a> More discussion on whitelisting is available in <a href="http://blog.simonwillison.net/post/57956830518/whitelisting" rel="nofollow">Social whitelisting with OpenID</a>.</p>
|
Can I make Perl ithreads in Windows run concurrently? <p>I have a Perl script that I'm attempting to set up using Perl Threads (use threads). When I run simple tests everything works, but when I do my actual script (which has the threads running multiple SQL*Plus sessions), each SQL*Plus session runs in order (i.e., thread 1's sqlplus runs steps 1-5, then thread 2's sqlplus runs steps 6-11, etc.).</p>
<p>I thought I understood that threads would do concurrent processing, but something's amiss. Any ideas, or should I be doing some other Perl magic?</p>
| <p>A few possible explanations:</p>
<ol>
<li><p>Are you running this script on a multi-core processor or multi-processor machine? If you only have one CPU only one thread can use it at any time.</p></li>
<li><p>Are there transactions or locks involved with steps 1-6 that would prevent it from being done concurrently?</p></li>
<li><p>Are you certain you are using multiple connections to the database and not sharing a single one between threads?</p></li>
</ol>
|
Good Linux (Ubuntu) SVN client <p>Subversion has a superb client on Windows (Tortoise, of course). Everything I've tried on Linux just - well - sucks in comparison....</p>
| <p><em>Disclaimer: A long long time ago I was one of the developers for RabbitVCS (previously known as NautilusSvn).</em></p>
<p>If you use Nautilus then you might be interested in <a href="http://rabbitvcs.org/">RabbitVCS</a> (mentioned earlier by Trevor Bramble). It's an unadulterated clone of TortoiseSVN for Nautilus written in Python. While there's still a lot of improvement to be made (especially in the area of performance) some people seem to be quite satisfied with it.</p>
<p>The name is quite fitting for the project, because the story it refers to quite accurately depicts the development pace (meaning long naps). If you do choose to start using RabbitVCS as your version control client, you're probably going to have to get your hands dirty.</p>
|
Designing a WPF map control <p>I'm thinking about making a simple map control in WPF, and am thinking about the design of the basic map interface and am wondering if anyone has some good advice for this. </p>
<p>What I'm thinking of is using a ScrollViewer (sans scroll bars) as my "view port" and then stacking everything up on top of a canvas. From Z-Index=0 up, I'm thinking:</p>
<ol>
<li>Base canvas for lat/long calculations, control positioning, Z-Index stacking.</li>
<li>Multiple Grid elements to represent the maps at different zoom levels. Using a grid to make tiling easier.</li>
<li>Map objects with positional data.</li>
<li>Map controls (zoom slider, overview, etc).</li>
<li>Scroll viewer with mouse move events for panning and zooming.</li>
</ol>
<p>Any comments suggestions on how I should be building this?</p>
| <p>If you're looking for a good start, you can use the foundation of code supplied by the <a href="http://www.codeplex.com/SharpMap/" rel="nofollow">SharpMap</a> project and build out from there. If I recall there were a few people already working on a WPF renderer for SharpMap, so you may also have some code to begin with.</p>
<p>I've personally used SharpMap in a C# 2.0 application that combined GIS data with real time GPS data, and it was very successful. SharpMap provided me the transformation suite to handle GIS data, along with the mathematical foundation to work with altering GIS information. It should be relatively straightforward to use the non-rendering code with a WPF frontend, as they already have presentation separated from the data.</p>
<p><em>(EDIT: added more details about how I used SharpMap)</em></p>
|
Different values of GetHashCode for inproc and stateserver session variables <p>I've recently inherited an application that makes very heavy use of session, including storing a lot of custom data objects in session. One of my first points of business with this application was to at least move the session data away from InProc, and off load it to either a stateserver or SQL Server.</p>
<p>After I made all of the appropriate data objects serializable, and changed the web.config to use a state service, everything appeared to work fine. </p>
<p>However, I found that this application does a lot of object comparisons using GetHashCode(). Methods that worked fine when the session was InProc no longer work because the HashCodes no longer match when they are supposed to. This appears to be the case when trying to find a specific child object from a parent when you know the child object's original hash code</p>
<p>If I simply change the web.config back to using inproc, it works again.</p>
<p>Anyone have any thoughts on where to begin with this?</p>
<p><hr /></p>
<p>EDIT: </p>
<p>qbeuek: thanks for the quick reply. In regards to:</p>
<blockquote>
<p>The default implementation of GetHashCode in Object class return a hash value based on objects address in memory or something similar. If some other identity comparison is required, you have to override both Equals and GetHashCode.</p>
</blockquote>
<p>I should have given more information on how they are using this. Basically, they have one parent data object, and there are several arrays of child objects. They happen to know the hash code for a particular object they need, so they are looping through a specific array of child objects looking for a hash code that matches. Once a match is found, they then use that object for other work.</p>
| <p>When you write</p>
<blockquote>
<p>does a lot of object comparisons using GetHashCode()</p>
</blockquote>
<p>i sense there is something horribly wrong with this code. The GetHashCode method does not guarantee, that the returned hash values should be in any way unique given two different objects. As far as GetHashCode is concerned, it can return 0 for all objects and still be considered correct.</p>
<p>When two object are the same (the Equals method returns true), they <strong>MUST</strong> have the same value returned from GetHashCode. When two objects have the same hash value, they <strong>can</strong> be the same object (Equals returns true) or be different objects (Equals returns false).</p>
<p>There are no other guarantees on the result of GetHashCode.</p>
<p>The default implementation of GetHashCode in Object class return a hash value based on objects address in memory or something similar. If some other identity comparison is required, you <strong>have to</strong> override both Equals and GetHashCode.</p>
|
Does DataGrid on CE 5.0 Compact Framework .NET support editing? <p>I am trying to get a DataGrid under CE 5.0 / .NET CF 2.0 that a user can edit. The document at <a href="http://msdn.microsoft.com/en-us/library/ms838165.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms838165.aspx</a> indicates that some environments do not support editing - </p>
<blockquote>
<p>As there is no native support for
editing in the DataGrid control, this
needs to be implemented manually</p>
</blockquote>
<p>Do I need to implement this ugly example - which doesn't work very well as shown?</p>
<p>The documentation is not clear about which .NET features are available on which platform.</p>
| <p>No, it is not directly editable. MSDN has samples for using the DataGrid, including suggestions for data editing, for both <a href="http://msdn.microsoft.com/en-us/library/ms229684.aspx" rel="nofollow">Pocket PC</a> and <a href="http://msdn.microsoft.com/en-us/library/ms229659.aspx" rel="nofollow">Smartphone</a> devices. Either one would be a reasonable start for a generic CE device, but the general strategy is to determine which cell is active and place a textbox over it for editing capability.</p>
<p>You might also look at <a href="http://www.ehartwell.com/InfoDabble/DataGrid_extensions_for_the_Compact_Framework" rel="nofollow">Eric Hartwell's extensions for the DataGrid</a> as well as the <a href="http://www.codeproject.com/KB/showcase/DotNetCompactGC.aspx" rel="nofollow">CF datagrid on CodeProject</a>.</p>
<p>Of course the usual suspects like Resco and ComponentOne also have commercial offerings.</p>
|
How to check if a String contains another String in a case insensitive manner in Java? <p>Say I have two strings,</p>
<pre><code>String s1 = "AbBaCca";
String s2 = "bac";
</code></pre>
<p>I want to perform a check returning that <code>s2</code> is contained within <code>s1</code>. I can do this with:</p>
<pre><code>return s1.contains(s2);
</code></pre>
<p>I am pretty sure that <code>contains()</code> is case sensitive, however I can't determine this for sure from reading the documentation. If it is then I suppose my best method would be something like:</p>
<pre><code>return s1.toLowerCase().contains(s2.toLowerCase());
</code></pre>
<p>All this aside, is there another (possibly better) way to accomplish this without caring about case-sensitivity?</p>
| <p>Yes, contains is case sensitive. You can use java.util.regex.Pattern with the CASE_INSENSITIVE flag for case insensitive matching:</p>
<pre><code>Pattern.compile(Pattern.quote(s2), Pattern.CASE_INSENSITIVE).matcher(s1).find();
</code></pre>
<p><strong>EDIT:</strong> If s2 contains regex special characters (of which there are many) it's important to quote it first. I've corrected my answer since it is the first one people will see, but vote up Matt Quail's since he pointed this out.</p>
|
Is there a specific name for the node that coresponds to a subtree? <p>I'm designing a web site navigation hierarchy. It's a tree of nodes. Nodes represent web pages.</p>
<p>Some nodes on the tree are special. I need a name for them.</p>
<p>There are multiple such nodes. Each is the "root" of a sub-tree with pages that have a distinct logo, style sheet, or layout. Think of different departments.</p>
<p><img src="http://img518.imageshack.us/img518/153/subtreesfe1.gif" alt="site map with color-coded sub-trees" /></p>
<p>What should I name this type of node?</p>
| <p>How about Root (node with children, but no parent), Node (node with children and parent) and Leaf (node with no children and parent)?</p>
<p>You can then distinguish by name and position within the tree structure (E.g. DepartmentRoot, DepartmentNode, DepartmentLeaf) if need be..</p>
<h2>Update Following Comment from OP</h2>
<p>Looking at your question, you said that "some" are special, and in your diagram, you have different nodes looking differently at different levels. The nodes may be different in their design, you can build a tree structure many ways. For example, a single abstract class that <em>can</em> have child nodes, if no children, its a leaf, if no parent, its a root but this can change in its lifetime. Or, a fixed class structure in which leafs are a specific class type that <em>cannot</em> have children added to them in any way.</p>
<p>IF your design does not need you to distinguish nodes differently depending on their position (relative to the root) it suggests that you have an abstract class used for them all.</p>
<p>In which case, it raises the question, <strong>how is it different?</strong> </p>
<p>If it is simply the same as the standard node everywhere else, but with a bit of styling, how about <em>StyledNode</em>? Do you even need it to be seperate (no style == no big deal, it doesn't render).</p>
<p>Since I don't know the mechanics of how the tree is architected, there could possibly be several factors to consider when naming.</p>
|
Is the syntax for the Wordpress style.css template element available anywhere? <p>I've recently embarked upon the <em>grand voyage</em> of Wordpress theming and I've been reading through the Wordpress documentation for how to write a theme. One thing I came across <a href="http://codex.wordpress.org/Theme_Development" rel="nofollow">here</a> was that the <code>style.css</code> file must contain a specific header in order to be used by the Wordpress engine. They give a brief example but I haven't been able to turn up any formal description of what must be in the <code>style.css</code> header portion. Does this exist on the Wordpress site? If it doesn't could we perhaps describe it here?</p>
<p>Thanks in advance!</p>
| <p>Based on <a href="http://codex.wordpress.org/Theme_Development">http://codex.wordpress.org/Theme_Development</a>:</p>
<p>The following is an example of the first few lines of the stylesheet, called the style sheet header, for the Theme "Rose":</p>
<pre><code>/*
Theme Name: Rose
Theme URI: the-theme's-homepage
Description: a-brief-description
Author: your-name
Author URI: your-URI
Template: use-this-to-define-a-parent-theme--optional
Version: a-number--optional
Tags: a-comma-delimited-list--optional
.
General comments/License Statement if any.
.
*/
</code></pre>
<p>The simplest Theme includes only a style.css file, plus images, if any. To create such a Theme, you must specify a set of templates to inherit for use with the Theme by editing the Template: line in the style.css header comments. For example, if you wanted the Theme "Rose" to inherit the templates from another Theme called "test", you would include Template: test in the comments at the beginning of Rose's style.css. Now "test" is the parent Theme for "Rose", which still consists only of a style.css file and the concomitant images, all located in the directory wp-content/themes/Rose. (Note that specifying a parent Theme will inherit all of the template files from that Theme â meaning that any template files in the child Theme's directory will be ignored.)</p>
<p>The comment header lines in style.css are required for WordPress to be able to identify a Theme and display it in the Administration Panel under Design > Themes as an available Theme option along with any other installed Themes. </p>
<p>The Theme Name, Version, Author, and Author URI fields are parsed by WordPress and used to display that data in the Current Theme area on the top line of the current theme information, where the Author's Name is hyperlinked to the Author URI. The Description and Tag fields are parsed and displayed in the body of the theme's information, and if the theme has a parent theme, that information is placed in the information body as well. In the Available Themes section, only the Theme Name, Description, and Tags fields are used.</p>
<p>None of these fields have any restrictions - all are parsed as strings. In addition, none of them are required in code, though in practice the fields not marked as optional in the list above are all used to provide contextual information to the WordPress administrator and should be included for all themes.</p>
|
What are the best practices for using html with xml based languages like svg? <p>From browsing on this site and elsewhere, I've learned that serving websites as xhtml at present <a href="http://hixie.ch/advocacy/xhtml" rel="nofollow">is considered harmful</a>.</p>
<p>Delivering xhtml and serving it as application/xhtml+xml isn't supported by the majority of people browsing at present, delivering xhtml as text/html is at best a placebo for myself, and at worst a recipe for breaking sites usually when you least need it happening.</p>
<p>So we end up back at html 4.01. If I instead serve my pages as html 4.01, is it possible to use SVG or any other xml-based language on the page?</p>
<p>If so, how?</p>
| <p>In HTML you won't be able to insert SVG directly. </p>
<p>You can embed SVG files with <code><object></code>/<code><embed></code> and in cutting-edge browsers (Opera, Safari) also <code><img></code> and CSS <code>background-image</code>.</p>
<p>You can put SVG in <code>data:</code> URI to avoid using external files.</p>
<p>Simple mathematical expressions can be written with help of Unicode and basic HTML/CSS (Opera 9.5 <a href="http://www.w3.org/TR/mathml-for-css/" rel="nofollow">supports large chunk of MathML via CSS</a>). For anything more complex you'll need to use images, like Wikipedia does.</p>
<p>HTML misinterprets namespace prefixes, so you won't be able to (properly) use other XML markup with HTML DOM. HTML5 has <code>data-*</code> attributes for application-specific markup additions. For metadata consider Microformats.</p>
<p>However if you want to embed XML only for non-browsers (robots), then you could use HTML-compatible XHTML subset and HTTP content negotiation to send proper XML with proper type to clients that understand it (<em>if</em> you thoroughly test page in both XML and HTML modes, then it won't be harmful). </p>
|
Where to find Java 6 JSSE/JCE Source Code? <p>Where can I download the JSSE and JCE source code for the latest release of Java? The source build available at <a href="https://jdk6.dev.java.net/">https://jdk6.dev.java.net/</a> does not include the javax.crypto (JCE) packages nor the com.sun.net.ssl.internal (JSSE) packages.</p>
<p>Not being able to debug these classes makes solving SSL issues incredibly difficult.</p>
| <p>there: <a href="http://openjdk.java.net/groups/security/">openjdk javax.net</a> in the security group </p>
<pre><code>src/share/classes/javax/net
src/share/classes/com/sun/net/ssl
src/share/classes/sun/security/ssl
src/share/classes/sun/net/www/protocol/https
</code></pre>
<p>also on this page:</p>
<pre><code>src/share/classes/javax/crypto
src/share/classes/com/sun/crypto/provider
src/share/classes/sun/security/pkcs11
src/share/classes/sun/security/mscapi
</code></pre>
<blockquote>
<p>These directories contain the core
cryptography framework and three
providers (SunJCE, SunPKCS11,
SunMSCAPI). <strong>SunJCE</strong> contains Java
implementations of many popular
algorithms, and the latter two
libraries allow calls made through the
standard Java cryptography APIs to be
routed into their respective native
libraries.</p>
</blockquote>
|
In Rails, after using find with :select, my objects don't save <p>Running something like:</p>
<p>@users = User.find(:first, :select => "name, lastname, salary")
for @user in @users do
@user.salary = 100000
@user.save
end</p>
<p>After this looking up in the Mysql table, the users aren't updated.</p>
| <p>ActiveRecord doesn't know the object's id, in order to save the data.
So include the id field in :select, like the example below:</p>
<p>@users = User.find(:first, :select => "id, name, lastname, salary")</p>
|
.NET library for processing HTML e-mails & stripping previous responses <p>Does anyone know of a .NET library that will process HTML e-mails and can be used to trim out the reply-chain? It needs to be able to accept HTML -or- text mails and then trim out everything but the actual response, removing the trail of messages that are not original content. I don't expect it to be able to handle responseswhen they're interleaved into the previous mail ("responses in-line") - that case can fail.</p>
<p>We have a home-built one based on SgmlReader and a series of XSL transforms, but it requires constant maintenance to deal with new e-mail clients. I'd like to find one I can buy... :)</p>
<p>Thanks,
Steve</p>
| <p>This does not answer much of your question, but the W3C's <a href="http://www.w3.org/Tools/html2things.html" rel="nofollow">Converting HTML to Other Formats</a> has a section on converting HTML to text. I hope it helps someone develop a full answer to your question!</p>
|
Mocking WebResponse's from a WebRequest <p>I have finally started messing around with creating some apps that work with RESTful web interfaces, however, I am concerned that I am hammering their servers every time I hit F5 to run a series of tests..</p>
<p>Basically, I need to get a series of web responses so I can test I am parsing the varying responses correctly, rather than hit their servers every time, I thought I could do this once, save the XML and then work locally.</p>
<p>However, I don't see how I can "mock" a WebResponse, since (AFAIK) they can only be instantiated by <strong>WebRequest.GetResponse</strong></p>
<p>How do you guys go about mocking this sort of thing? Do you? I just really don't like the fact I am hammering their servers :S I dont want to change the code <em>too</em> much, but I expect there is a elegant way of doing this..</p>
<h2>Update Following Accept</h2>
<p>Will's answer was the slap in the face I needed, I knew I was missing a fundamental point!</p>
<ul>
<li>Create an Interface that will return a proxy object which represents the XML.</li>
<li>Implement the interface twice, one that uses WebRequest, the other that returns static "responses".</li>
<li>The interface implmentation then either instantiates the return type based on the response, or the static XML.</li>
<li>You can then pass the required class when testing or at production to the service layer.</li>
</ul>
<p>Once I have the code knocked up, I'll paste some samples.</p>
| <p>I found this question while looking to do exactly the same thing. Couldn't find an answer anywhere, but after a bit more digging found that the .Net Framework has built in support for this.</p>
<p>You can register a factory object with <code>WebRequest.RegisterPrefix</code> which <code>WebRequest.Create</code> will call when using that prefix (or url). The factory object must implement <code>IWebRequestCreate</code> which has a single method <code>Create</code> which returns a <code>WebRequest</code>. Here you can return your mock <code>WebRequest</code>.</p>
<p>I've put some sample code up at
<a href="http://blog.salamandersoft.co.uk/index.php/2009/10/how-to-mock-httpwebrequest-when-unit-testing/">http://blog.salamandersoft.co.uk/index.php/2009/10/how-to-mock-httpwebrequest-when-unit-testing/</a></p>
|
How do I choose a CMS/Portal solution for a small website(s)? <p>I currently maintain 3 websites all revolving around the same concept. 2 of them are WinForms applications where the website gives a few basic details, and download links. The third is a web application to query data. I also have a forum (SMF/TinyPortal) that has been serving as a tech support/news hub for the three sites. The download traffic is decent, but I don't get a lot of hits on the support forums</p>
<p>I want to consolidate these three entities so that I don't have to duplicate announcements, upload data library updates to multiple locations, and also provide a unified look to the sites.</p>
<p>Fortunately my hosting account has both .NET and PHP support, so I've been looking into Drupal, Graffiti, DotNetNuke, Joomla, Community Server, and more. However, it has been hard for me to discern between what features included, supported, or just not part of the framework whatsoever.</p>
<p>Does anybody have a good evaluation of these projects (and others too) and can evaluate them for features/expandability/customization/etc.? I'm not necessarily looking for a "what's your favorite" but more of a feature set / target end user type evaluation.</p>
| <p>If you want to quickly compare features on CMS's, then take a look at <a href="http://www.cmsmatrix.org/" rel="nofollow">CMS Matrix</a> - has practically every cms known to man on there.</p>
<p><em>Edit</em>
To be a little more precise, from the site</p>
<blockquote>
<p>CMSMatrix is the number one content management system comparison site on the Internet. It allows users to evaluate over 950 content management systems in 135+ different categories.</p>
</blockquote>
|
How does gcc implement stack unrolling for C++ exceptions on linux? <p>How does gcc implement stack unrolling for C++ exceptions on linux? In particular, how does it know which destructors to call when unrolling a frame (i.e., what kind of information is stored and where is it stored)?</p>
| <p>See section 6.2 of the <a href="http://www.x86-64.org/documentation/abi.pdf" rel="nofollow">x86_64 ABI</a>. This details the interface but not a lot of the underlying data. This is also independent of C++ and could conceivably be used for other purposes as well.</p>
<p>There are primarily two sections of the ELF binary as emitted by gcc which are of interest for exception handling. They are <code>.eh_frame</code> and <code>.gcc_except_table</code>. </p>
<p><code>.eh_frame</code> follows the DWARF format (the debugging format that primarily comes into play when you're using gdb). It has exactly the same format as the <code>.debug_frame</code> section emitted when compiling with <code>-g</code>. Essentially, it contains the information necessary to pop back to the state of the machine registers and the stack at any point higher up the call stack. See the Dwarf Standard at dwarfstd.org for more information on this.</p>
<p><code>.gcc_except_table</code> contains information about the exception handling "landing pads" the locations of handlers. This is necessary so as to know when to stop unwinding. Unfortunately this section is not well documented. The only snippets of information I have been able to glean come from the gcc mailing list. See particularly <a href="http://gcc.gnu.org/ml/gcc-help/2010-09/msg00116.html" rel="nofollow">this post</a></p>
<p>The remaining piece of information is then what actual code interprets the information found in these data sections. The relevant code lives in libstdc++ and libgcc. I cannot remember at the moment which pieces live in which. The interpreter for the DWARF call frame information can be found in the gcc source code in the file gcc/unwind-dw.c</p>
|
How to edit sessions parameters on Oracle 10g XE? <p>default is 49</p>
<p>how to edit to higher?</p>
| <p>You will need to issue the following command (connected as a user that has alter system privileges, sys will do it)</p>
<p>alter system set sessions=<em>numberofsessions</em> scope=spfile;</p>
<p>Have you been getting an ORA-12516 or ORA-12520 error?
If so it's probably a good idea to increase the number of processes too</p>
<p>alter system set processes=<em>numberofprocesses</em> scope=spfile;</p>
<p>IIRC you'll need to bounce the database after issuing these commands.
This link <a href="http://www.oracle.com/technology/tech/php/pdf/underground-php-oracle-manual.pdf" rel="nofollow">http://www.oracle.com/technology/tech/php/pdf/underground-php-oracle-manual.pdf</a> has some good information about configuring XE.
I consulted it when I ran into similar issues using XE.</p>
|
How to embed audio/video on HTML page that plays on iPhone browser over GPRS <p>Although I don't have an iPhone to test this out, my colleague told me that embedded
media files such as the one in the snippet below, only works when the iphone is connected over the
WLAN connection or 3G, and does not work when connecting via GPRS.</p>
<pre><code><html><body>
<object data="http://joliclic.free.fr/html/object-tag/en/data/test.mp3" type="audio/mpeg">
<p>alternate text</p>
</object>
</body></html>
</code></pre>
<p>Is there an example URL with a media file, that will play in an iPhone browser
when the iphone connects using GPRS (not 3G)?</p>
| <p>The iPhone YouTube application automatically downloads lower quality video when connected via EDGE than when connected via Wi-Fi, because the network is much slower. That fact leads me to believe Apple would make the design decision to not bother downloading an MP3 over EDGE. The browser has no way to know in advance if the bit rate is low enough, and chances are, it won't be. So rather than frustrate the users with a sound file that takes too long to play (and prevents thems from receiving a call while downloading), it's better to spare them the grief and encourage them to find a Wi-Fi hotspot.</p>
|
Numbering Regex Submatches <p>Is there a canonical ordering of submatch expressions in a regular
expression? </p>
<p>For example: What is the order of the submatches in<br />
"(([0-9]{3}).([0-9]{3}).([0-9]{3}).([0-9]{3}))\s+([A-Z]+)" ?</p>
<pre><code>a. (([0-9]{3})\.([0-9]{3})\.([0-9]{3})\.([0-9]{3}))\s+([A-Z]+)
(([0-9]{3})\.([0-9]{3})\.([0-9]{3})\.([0-9]{3}))
([A-Z]+)
([0-9]{3})
([0-9]{3})
([0-9]{3})
([0-9]{3})
b. (([0-9]{3})\.([0-9]{3})\.([0-9]{3})\.([0-9]{3}))\s+([A-Z]+)
(([0-9]{3})\.([0-9]{3})\.([0-9]{3})\.([0-9]{3}))
([0-9]{3})
([0-9]{3})
([0-9]{3})
([0-9]{3})
([A-Z]+)
</code></pre>
<p>or</p>
<pre><code>c. somthin' else.
</code></pre>
| <p>They tend to be numbered in the order the capturing parens start, left to right. Therefore, option b.</p>
|
What are good grep tools for Windows? <p>Any recommendations on <a href="http://en.wikipedia.org/wiki/Grep">grep</a> tools for Windows? Ideally ones that could leverage 64-bit OS.</p>
<p>I'm aware of <a href="http://www.cygwin.com/">Cygwin</a>, of course, and have also found <a href="http://www.powergrep.com/">PowerGREP</a>, but I'm wondering if there are any hidden gems out there?</p>
| <p><a href="http://ss64.com/nt/findstr.html">FINDSTR</a> is fairly powerful, supports <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expressions</a> and has the advantages of being on all Windows machines already.</p>
<pre><code>c:\> FindStr /?
Searches for strings in files.
FINDSTR [/B] [/E] [/L] [/R] [/S] [/I] [/X] [/V] [/N] [/M] [/O] [/P] [/F:file]
[/C:string] [/G:file] [/D:dir list] [/A:color attributes] [/OFF[LINE]]
strings [[drive:][path]filename[ ...]]
/B Matches pattern if at the beginning of a line.
/E Matches pattern if at the end of a line.
/L Uses search strings literally.
/R Uses search strings as regular expressions.
/S Searches for matching files in the current directory and all
subdirectories.
/I Specifies that the search is not to be case-sensitive.
/X Prints lines that match exactly.
/V Prints only lines that do not contain a match.
/N Prints the line number before each line that matches.
/M Prints only the filename if a file contains a match.
/O Prints character offset before each matching line.
/P Skip files with non-printable characters.
/OFF[LINE] Do not skip files with offline attribute set.
/A:attr Specifies color attribute with two hex digits. See "color /?"
/F:file Reads file list from the specified file(/ stands for console).
/C:string Uses specified string as a literal search string.
/G:file Gets search strings from the specified file(/ stands for console).
/D:dir Search a semicolon delimited list of directories
strings Text to be searched for.
[drive:][path]filename
Specifies a file or files to search.
Use spaces to separate multiple search strings unless the argument is prefixed
with /C. For example, 'FINDSTR "hello there" x.y' searches for "hello" or
"there" in file x.y. 'FINDSTR /C:"hello there" x.y' searches for
"hello there" in file x.y.
Regular expression quick reference:
. Wildcard: any character
* Repeat: zero or more occurances of previous character or class
^ Line position: beginning of line
$ Line position: end of line
[class] Character class: any one character in set
[^class] Inverse class: any one character not in set
[x-y] Range: any characters within the specified range
\x Escape: literal use of metacharacter x
\<xyz Word position: beginning of word
xyz\> Word position: end of word
</code></pre>
<p>Example usage: <code>findstr text_to_find *</code> or to search recursively <code>findstr /s text_to_find *</code></p>
|
How can I find the location of a regex match in Perl? <p>I need to write a function that receives a string and a regex. I need to check if there is a match and return the start and end location of a match. (The regex was already compiled by <code>qr//</code>.)</p>
<p>The function might also receive a "global" flag and then I need to return the (start,end) pairs of all the matches.</p>
<p>I cannot change the regex, not even add <code>()</code> around it as the user might use <code>()</code> and <code>\1</code>. Maybe I can use <code>(?:)</code>.</p>
<p>Example: given "ababab" and the regex <code>qr/ab/</code>, in the global case I need to get back 3 pairs of (start, end).</p>
| <p>The built-in variables <code>@-</code> and <code>@+</code> hold the start and end positions, respectively, of the last successful match. <code>$-[0]</code> and <code>$+[0]</code> correspond to entire pattern, while <code>$-[N]</code> and <code>$+[N]</code> correspond to the <code>$N</code> (<code>$1</code>, <code>$2</code>, etc.) submatches.</p>
|
textboxes in Datarepeater dynamicly 'databound' <p>I need to know if it is possible to dynamically bind a textbox residing within a datarepeater to a 'dynamically' created BindingSource. I am using VB.net. The database I am using is a MySQL database. </p>
<p>I have to use the connection dynamicly due to the fact that the database my not permanently reside on the same server.</p>
<p>[edit]<br>
ok, so it seams that i am a dolt when asking questions. The app that i am making is not web based. it is a simple (i hope) app that connects to a MySQL database, accesses a table so i can edit/view it. Current setup is using the Add DataSource wizard. I have successfully connected to the dbase dynamicly using the mysql connector dll but without the textboxes set at design time to a datasource, i am unsure on how to 'link' them via the datarepeater.</p>
| <p>Your connection string should be defined in your Web.Config, and if you move your database to a different server, it's just a matter of modifying the web.config entry. As long as you keep the connection string name the same, the BindingSource object will pick up the new value from the config.<hr><strong>edit</strong><br><br>
In truth, the same concept should apply here as it does in the web app answer listed above.</p>
<p>All of your data objects should be hard-coded, and it's just the connection string (which you'll have to either ask the user for, or push out as update when the DB moves) which will get modified.</p>
<p>For example, create a App.Config file in your project. Have one of your configuration values be the connection string. This config value will be where you go to get the connection string whenever you need it. Then your wizard will be there to allow users to easily modify the connection.</p>
|
Automated integration testing a C++ app with a database <p>I am introducing automated integration testing to a mature application that until now has only been manually tested.</p>
<p>The app is Windows based and talks to a MySQL database.</p>
<p>What is the best way (including details of any tools recommended) to keep tests independent of each other in terms of the database transactions that will occur? </p>
<p>(Modifications to the app source for this particular purpose are not an option.)</p>
| <p>How are you verifying the results? </p>
<p>If you need to query the DB (and it sounds like you probably do) for results then I agree with Kris K, except I would endeavor to rebuild the DB after every test case, not just every suite.</p>
<p>This helps avoid dangerous <a href="http://xunitpatterns.com/Erratic%20Test.html" rel="nofollow">interacting tests</a></p>
<p>As for tools, I would recommend <a href="http://cppunit.sourceforge.net/doc/lastest/index.html" rel="nofollow">CppUnit</a>. You aren't really doing unit tests, but it shouldn't matter as the xUnit framework should give you the set up and teardown framework you'll need to automatically set up your <a href="http://xunitpatterns.com/Fixture%20Setup%20Patterns.html" rel="nofollow">test fixture</a></p>
<p>Obviously this can result in slow-running tests, depending on your database size, population etc. You may be able to attach/detach databases rather than dropping/rebuilding.</p>
<p>If you're interested in further research, check out <a href="http://www.xunitpatterns.com" rel="nofollow">XUnit Test Patterns</a>. It's a fine book and a good website for this kind of thing.</p>
<p>And thanks for automating :)</p>
<p>Nick</p>
|
Why do some conversions from wmv to flv with ffmpeg fail? <p>Ive been smashing my head with this for a while. I have 2 completely identical .wmv files encoded with wmv3 codec. I put them both through ffmpeg with the following command:</p>
<pre><code>/usr/bin/ffmpeg -i file.wmv -ar 44100 -ab 64k -qscale 9 -s 512x384 -f flv file.flv
</code></pre>
<p>One file converts just fine, and gives me the following output:</p>
<pre><code> FFmpeg version SVN-r11070, Copyright (c) 2000-2007 Fabrice Bellard, et al.
configuration: --prefix=/usr --incdir=/usr/include/ffmpeg --libdir=/usr/lib64 --shlibdir=/usr/lib64 --mandir=/usr/share/man --arch=x86_64 --extra-cflags=-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic --enable-liba52 --enable-libfaac --enable-libfaad --enable-libgsm --enable-libmp3lame --enable-libtheora --enable-libvorbis --enable-libxvid --enable-libx264 --enable-pp --enable-pthreads --disable-static --enable-shared --enable-gpl --disable-debug --disable-optimizations --disable-strip
libavutil version: 49.5.0
libavcodec version: 51.48.0
libavformat version: 51.19.0
built on Jun 25 2008 09:17:38, gcc: 4.1.2 20070925 (Red Hat 4.1.2-33)
Seems stream 1 codec frame rate differs from container frame rate: 1000.00 (1000/1) -> 29.97 (30000/1001)
Input #0, asf, from 'ok.wmv':
Duration: 00:14:22.3, start: 3.000000, bitrate: 467 kb/s
Stream #0.0: Audio: wmav2, 44100 Hz, stereo, 64 kb/s
Stream #0.1: Video: wmv3, yuv420p, 320x240 [PAR 0:1 DAR 0:1], 400 kb/s, 29.97 tb(r)
Output #0, flv, to 'ok.flv':
Stream #0.0: Video: flv, yuv420p, 512x384 [PAR 0:1 DAR 0:1], q=2-31, 200 kb/s, 29.97 tb(c)
Stream #0.1: Audio: libmp3lame, 44100 Hz, stereo, 64 kb/s
Stream mapping:
Stream #0.1 -> #0.0
Stream #0.0 -> #0.1
Press [q] to stop encoding
frame=25846 fps=132 q=9.0 Lsize= 88486kB time=862.4 bitrate= 840.5kbits/s
video:80827kB audio:6738kB global headers:0kB muxing overhead 1.050642%
</code></pre>
<p>While another file, fails:</p>
<pre><code>FFmpeg version SVN-r11070, Copyright (c) 2000-2007 Fabrice Bellard, et al.
configuration: --prefix=/usr --incdir=/usr/include/ffmpeg --libdir=/usr/lib64 --shlibdir=/usr/lib64 --mandir=/usr/share/man --arch=x86_64 --extra-cflags=-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic --enable-liba52 --enable-libfaac --enable-libfaad --enable-libgsm --enable-libmp3lame --enable-libtheora --enable-libvorbis --enable-libxvid --enable-libx264 --enable-pp --enable-pthreads --disable-static --enable-shared --enable-gpl --disable-debug --disable-optimizations --disable-strip
libavutil version: 49.5.0
libavcodec version: 51.48.0
libavformat version: 51.19.0
built on Jun 25 2008 09:17:38, gcc: 4.1.2 20070925 (Red Hat 4.1.2-33)
[wmv3 @ 0x3700940d20]Extra data: 8 bits left, value: 0
Seems stream 1 codec frame rate differs from container frame rate: 1000.00 (1000/1) -> 25.00 (25/1)
Input #0, asf, from 'bad3.wmv':
Duration: 00:06:34.9, start: 4.000000, bitrate: 1666 kb/s
Stream #0.0: Audio: 0x0162, 48000 Hz, stereo, 256 kb/s
Stream #0.1: Video: wmv3, yuv420p, 512x384 [PAR 0:1 DAR 0:1], 1395 kb/s, 25.00 tb(r)
File 'ok.flv' already exists. Overwrite ? [y/N] y
Output #0, flv, to 'ok.flv':
Stream #0.0: Video: flv, yuv420p, 512x384 [PAR 0:1 DAR 0:1], q=2-31, 200 kb/s, 25.00 tb(c)
Stream #0.1: Audio: libmp3lame, 48000 Hz, stereo, 64 kb/s
Stream mapping:
Stream #0.1 -> #0.0
Stream #0.0 -> #0.1
Unsupported codec (id=0) for input stream #0.0
</code></pre>
<p>The only difference I see is with the Input audio codec</p>
<p>Working:</p>
<pre><code>Stream #0.0: Audio: wmav2, 44100 Hz, stereo, 64 kb/s
</code></pre>
<p>Not working:</p>
<pre><code> Stream #0.0: Audio: 0x0162, 48000 Hz, stereo, 64 kb/s
</code></pre>
<p>Any ideas?</p>
| <p>It is in fact the audio format, which causes trouble. Audio formats are identified by its TwoCC (0x0162 here). You can look up the different TwoCCs here: <a href="http://wiki.multimedia.cx/index.php?title=TwoCC" rel="nofollow">http://wiki.multimedia.cx/index.php?title=TwoCC</a> and you'll find:</p>
<p>0x0162 Windows Media Audio Professional V9 </p>
<p>This codec isn't supported yet by ffmpeg and mencoder as far as I know. You can search at google for "<code>ffmpeg audio 0x0162</code>" and check for yourself. </p>
|
Using DateAdd in umbraco xslt to display next year's date <p>I'm trying to display the date for a year from now in an xslt file using umbraco like so:</p>
<pre><code><xsl:variable name="now" select="umbraco.library:CurrentDate()"/>
<xsl:value-of select="umbraco.library:DateAdd($now, 'year', 1)"/>
</code></pre>
<p>The value-of tag outputs today's date. How can I get the DateAdd to add a year to the current date?</p>
| <p>The constant 'year' is wrong. It expects just 'y'.</p>
<pre><code><xsl:variable name="now" select="umbraco.library:CurrentDate()"/>
<xsl:value-of select="umbraco.library:DateAdd($now, 'y', 1)"/>
</code></pre>
|
How do you overcome the svn 'out of date' error? <p>I've been attempting move a directory structure from one location to another in Subversion, but I get an <code>Item '*' is out of date</code> commit error. </p>
<p>I have the latest version checked out (so far as I can tell). <code>svn st -u</code> turns up no differences other than the mv commands.</p>
| <p>I sometimes get this with TortoiseSVN on windows. The solution for me is to <code>svn update</code> the directory, even though there are no revisions to download or update. It does something to the metadata, which magically fixes it.</p>
|
C#: Is Implicit Arraylist assignment possible? <p>I'd like to populate an arraylist by specifying a list of values just like I would an integer array, but am unsure of how to do so without repeated calls to the "add" method.</p>
<p>For example, I want to assign { 1, 2, 3, "string1", "string2" } to an arraylist. I know for other arrays you can make the assignment like:</p>
<pre><code>int[] IntArray = {1,2,3};
</code></pre>
<p>Is there a similar way to do this for an arraylist? I tried the addrange method but the curly brace method doesn't implement the ICollection interface.</p>
| <p>Depending on the version of C# you are using, you have different options.</p>
<p>C# 3.0 has collection initializers, detail at <a href="http://weblogs.asp.net/scottgu/archive/2007/03/08/new-c-orcas-language-features-automatic-properties-object-initializers-and-collection-initializers.aspx">Scott Gu's Blog</a></p>
<p>Here is an example of your problem.</p>
<pre><code>ArrayList list = new ArrayList {1,2,3};
</code></pre>
<p>And if you are initializing a collection object, most have constructors that take similar components to AddRange, although again as you mentioned this may not be an option.</p>
|
C#: Import/Export Settings into/from a File <p>What's the best way to import/export app internal settings into a file from within an app?</p>
<p>I have the Settings.settings file, winform UI tied to the settings file, and I want to import/export settings, similar to Visual Studio Import/Export Settings feature. </p>
| <p>If you are using the Settings.settings file, it's saving to the config file. By calling YourNamespace.Properties.Settings.Save() after updating your settings, they will be saved to the config files.</p>
<p>However, I have no idea what you mean by "multiple sets of settings." If the settings are user settings, each user will have its own set of settings. If you are having multiple sets of settings for a single user, you probably should not use the .settings files; instead you'll want to use a database.</p>
|
Any other tools/plugins like VisualAssist that will change my life (MSVS)? <p>I was introduced to VisualAssist a few years ago and for me there's no going back. Are there any other tools I'm missing out on?</p>
| <p>If you're a vim user, <a href="http://www.viemu.com" rel="nofollow">ViEmu</a> is indispensable. It's a plugin available for Visual Studio (SQL Server and Office as well, although it's sold separately) that transforms the editor into Vim.</p>
<p>Another plugin by the same company is <a href="http://www.codekana.com" rel="nofollow">Codekana</a>. In its current incarnation, it spruces up code structure considerably, and makes reading code much more pleasurable. Based on several chats with the author, he's planning on growing it into other areas as well.</p>
|
KVM/QEMU network TAP problems with libvirt <p>I'm trying to use libvirt with virsh to manage my kvm/qemu vms. The problem I have is with getting it to work with public IPs. The server is running ubuntu 8.04.</p>
<p>libvirt keeps trying to run it as:</p>
<pre><code>/usr/bin/kvm -M pc -m 256 -smp 3 -monitor pty -no-acpi \
-drive file=/opt/virtual-machines/calculon/root.qcow2,if=ide,boot=on \
-net nic,vlan=0,model=virtio -net tap,fd=10,vlan=0 -usb -vnc 127.0.0.1:0
</code></pre>
<p>Which boots, but does not have any network access (pings go nowhere). Running it without fd=10 makes it work right, with kvm creating the necessary TAP device for me and networking functioning inside the host. All the setup guides I've seen focus on setting up masquerading, while I just want a simple bridge and unfiltered access to the net (both the guests and host must use public IPs). </p>
<p>Running ifconfig on the host gives this, the bridge is manually setup in my /etc/network/interfaces file. :</p>
<pre><code>br0 Link encap:Ethernet HWaddr 00:1e:c9:3c:59:b8
inet addr:12.34.56.78 Bcast:12.34.56.79 Mask:255.255.255.240
inet6 addr: fe80::21e:c9ff:fe3c:59b8/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:3359 errors:0 dropped:0 overruns:0 frame:0
TX packets:3025 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:180646 (176.4 KB) TX bytes:230908 (225.4 KB)
eth0 Link encap:Ethernet HWaddr 00:1e:c9:3c:59:b8
inet6 addr: fe80::21e:c9ff:fe3c:59b8/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:6088386 errors:0 dropped:0 overruns:0 frame:0
TX packets:3058 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:680236624 (648.7 MB) TX bytes:261696 (255.5 KB)
Interrupt:33
</code></pre>
<p>Any help would be greatly appreciated.</p>
| <p>I followed the bridged networking guide at <a href="https://help.ubuntu.com/community/KVM">https://help.ubuntu.com/community/KVM</a> and have the following in /etc/network/interfaces:</p>
<pre><code>auto eth0
iface eth0 inet manual
auto br0
iface br0 inet static
address 192.168.0.10
network 192.168.0.0
netmask 255.255.255.0
broadcast 192.168.0.255
gateway 192.168.0.1
bridge_ports eth0
bridge_fd 9
bridge_hello 2
bridge_maxage 12
bridge_stp off
</code></pre>
<p>I have not changed any libvirt network settings and my kvm images are booted like:</p>
<pre><code>/usr/bin/kvm -M pc -no-kqemu -m 256 -smp 1 -monitor pty -boot c -hda \
/libvirt/apt.img -net nic,macaddr=00:16:3e:77:32:1d,vlan=0 -net \
tap,fd=11,script=,vlan=0 -usb -vnc 127.0.0.1:0
</code></pre>
<p>I then specify the static network settings in the kvm image as normal. Has all worked ok since I followed the guide.</p>
<p>I do have the following settings in my xml files in /etc/libvirt/qemu/ though under devices:</p>
<pre><code><interface type='bridge'>
<mac address='00:16:3e:77:32:1d'/>
<source bridge='br0'/>
</interface>
</code></pre>
|
Throwing exceptions in ASP.NET C# <p>Is there a difference between just saying <code>throw;</code> and <code>throw ex;</code> assuming <code>ex</code> is the exception you're catching?</p>
| <p><code>throw ex;</code> will erase your stacktrace. Don't do this unless you mean to clear the stacktrace. Just use <code>throw;</code></p>
|
Can regex capture and substitution be used with an Apache DirectoryMatch directive? <p>Does anyone know if it's possible to use regex capture within Apache's DirectoryMatch directive? I'd like to do something like the following:</p>
<pre><code><DirectoryMatch ^/home/www/(.*)>
AuthType Basic
AuthName $1
AuthUserFile /etc/apache2/svn.passwd
Require group $1 admin
</DirectoryMatch>
</code></pre>
<p>but so far I've had no success.</p>
<p>Specifically, I'm trying to create a group-based HTTP Auth for individual directories/vhosts on a server in Apache 2.0. </p>
<p>For example, Site A, pointing to /home/www/a will be available to all users in group admin and group a, site b at /home/www/b will be available to all users in group admin and group b, etc. I'd like to keep everything based on the directory name so I can easily script adding htpasswd users to the correct groups and automate this as much as possible, but other suggestions for solving the problem are certainly welcome.</p>
| <p>You could tackle the problem from a completely different angle: enable the perl module and you can include a little perl script in your httpd.conf. You could then do something like this:</p>
<pre><code><Perl>
my @groups = qw/ foo bar baz /;
foreach ( @groups ) {
push @PerlConfig, qq| <Directory /home/www/$_> blah </Directory> |;
}
</Perl>
</code></pre>
<p>That way, you could even read your groups and other information from a database or by simply globbing /home/www or whatever else tickles your fancy.</p>
|
Reporting Services Deployment <p>I need to create a repeatable process for deploying SQL Server Reporting Services reports. I am not in favor of using Visual Studio and or Business Development Studio to do this. The rs.exe method of scripting deployments also seems rather clunky. Does anyone have a very elegant way that they have been able to deploy reports. The key here is that I want the process to be completely automated.</p>
| <p>We use rs.exe, once we developed the script we have not needed to touch it anymore, it just works.</p>
<p>Here is the source (I slightly modified it by hand to remove sensitive data without a chance to test it, hope I did not brake anything), it deploys reports and associated images from subdirectories for various languages. Also datasource is created.</p>
<pre><code>'=====================================================================
' File: PublishReports.rss
'
' Summary: Script that can be used with RS.exe to
' publish the reports.
'
' Rss file spans from beginnig of this comment to end of module
' (except of "End Module").
'=====================================================================
Dim langPaths As String() = {"en", "cs", "pl", "de"}
Dim filePath As String = Environment.CurrentDirectory
Public Sub Main()
rs.Credentials = System.Net.CredentialCache.DefaultCredentials
'Create parent folder
Try
rs.CreateFolder(parentFolder, "/", Nothing)
Console.WriteLine("Parent folder created: {0}", parentFolder)
Catch e As Exception
Console.WriteLine(e.Message)
End Try
PublishLanguagesFromFolder(filePath)
End Sub
Public Sub PublishLanguagesFromFolder(ByVal folder As String)
Dim Lang As Integer
Dim langPath As String
For Lang = langPaths.GetLowerBound(0) To langPaths.GetUpperBound(0)
langPath = langPaths(Lang)
'Create the lang folder
Try
rs.CreateFolder(langPath, "/" + parentFolder, Nothing)
Console.WriteLine("Parent lang folder created: {0}", parentFolder + "/" + langPath)
Catch e As Exception
Console.WriteLine(e.Message)
End Try
'Create the shared data source
CreateDataSource("/" + parentFolder + "/" + langPath)
'Publish reports and images
PublishFolderContents(folder + "\" + langPath, "/" + parentFolder + "/" + langPath)
Next 'Lang
End Sub
Public Sub CreateDataSource(ByVal targetFolder As String)
Dim name As String = "data source"
'Data source definition.
Dim definition As New DataSourceDefinition
definition.CredentialRetrieval = CredentialRetrievalEnum.Store
definition.ConnectString = "data source=" + dbServer + ";initial catalog=" + db
definition.Enabled = True
definition.EnabledSpecified = True
definition.Extension = "SQL"
definition.ImpersonateUser = False
definition.ImpersonateUserSpecified = True
'Use the default prompt string.
definition.Prompt = Nothing
definition.WindowsCredentials = False
'Login information
definition.UserName = "user"
definition.Password = "password"
Try
'name, folder, overwrite, definition, properties
rs.CreateDataSource(name, targetFolder, True, definition, Nothing)
Catch e As Exception
Console.WriteLine(e.Message)
End Try
End Sub
Public Sub PublishFolderContents(ByVal sourceFolder As String, ByVal targetFolder As String)
Dim di As New DirectoryInfo(sourceFolder)
Dim fis As FileInfo() = di.GetFiles()
Dim fi As FileInfo
Dim fileName As String
For Each fi In fis
fileName = fi.Name
Select Case fileName.Substring(fileName.Length - 4).ToUpper
Case ".RDL"
PublishReport(sourceFolder, fileName, targetFolder)
Case ".JPG", ".JPEG"
PublishResource(sourceFolder, fileName, "image/jpeg", targetFolder)
Case ".GIF", ".PNG", ".BMP"
PublishResource(sourceFolder, fileName, "image/" + fileName.Substring(fileName.Length - 3).ToLower, targetFolder)
End Select
Next fi
End Sub
Public Sub PublishReport(ByVal sourceFolder As String, ByVal reportName As String, ByVal targetFolder As String)
Dim definition As [Byte]() = Nothing
Dim warnings As Warning() = Nothing
Try
Dim stream As FileStream = File.OpenRead(sourceFolder + "\" + reportName)
definition = New [Byte](stream.Length) {}
stream.Read(definition, 0, CInt(stream.Length))
stream.Close()
Catch e As IOException
Console.WriteLine(e.Message)
End Try
Try
'name, folder, overwrite, definition, properties
warnings = rs.CreateReport(reportName.Substring(0, reportName.Length - 4), targetFolder, True, definition, Nothing)
If Not (warnings Is Nothing) Then
Dim warning As Warning
For Each warning In warnings
Console.WriteLine(warning.Message)
Next warning
Else
Console.WriteLine("Report: {0} published successfully with no warnings", targetFolder + "/" + reportName)
End If
Catch e As Exception
Console.WriteLine(e.Message)
End Try
End Sub
Public Sub PublishResource(ByVal sourceFolder As String, ByVal resourceName As String, ByVal resourceMIME As String, ByVal targetFolder As String)
Dim definition As [Byte]() = Nothing
Dim warnings As Warning() = Nothing
Try
Dim stream As FileStream = File.OpenRead(sourceFolder + "\" + resourceName)
definition = New [Byte](stream.Length) {}
stream.Read(definition, 0, CInt(stream.Length))
stream.Close()
Catch e As IOException
Console.WriteLine(e.Message)
End Try
Try
'name, folder, overwrite, definition, MIME, properties
rs.CreateResource(resourceName, targetFolder, True, definition, resourceMIME, Nothing)
Console.WriteLine("Resource: {0} with MIME {1} created successfully", targetFolder + "/" + resourceName, resourceMIME)
Catch e As Exception
Console.WriteLine(e.Message)
End Try
End Sub
</code></pre>
<p>Here is the batch to call the rs.exe:</p>
<pre><code>SET ReportServer=%1
SET DBServer=%2
SET DBName=%3
SET ReportFolder=%4
rs -i PublishReports.rss -s %ReportServer% -v dbServer="%DBServer%" -v db="%DBName%" -v parentFolder="%ReportFolder%" >PublishReports.log 2>&1
pause
</code></pre>
|
How do I restore from a drop database command using a mysql binary log? <p>How can I restore a mysql database that was dropped using a "drop database" command? I have access to binary logs which should make this type of rollback possible.</p>
| <p>Documentation Sucks. It alludes to DROP DATABASE being recoverable, but only in odd conditions i'm not familiar with <a href="http://dev.mysql.com/doc/refman/5.0/en/binary-log.html">http://dev.mysql.com/doc/refman/5.0/en/binary-log.html</a> </p>
<p>According to Docs, binlogs are just a sequence of commands executed based on a given reference point. So that when you did "DROP DATABASE", instead of going "Oh, hes droppping the database, we should back up now just in case" it merely wrote a "DROP DATABASE" to the last binlog. Recovery is not as simple as playing the tape backwards. </p>
<p>What you need to do is recover the database from a last-known-good, and apply the binlogs that happened between that recover point and the DROP command.</p>
<p><a href="http://dev.mysql.com/doc/refman/5.0/en/recovery-from-backups.html">http://dev.mysql.com/doc/refman/5.0/en/recovery-from-backups.html</a></p>
<p>How one determines which binlogs to use tho, unclear. </p>
<p>There is nothing better than having full file system backups. And you should at least have these to fall back to.</p>
|
Polynomial time algorithm for finding a Hamiltonian walk in a graph <p>Is there a polynomial time algorithm for finding a Hamiltonian walk in a graph?</p>
<p>My algorithm is N factorial and is really slow.</p>
| <p>In general, as the (decision version of the) Hamiltonian Path problem is NP-complete, you cannot hope to get a polynomial-time algorithm for finding Hamiltonian paths. You can slightly speed it up with the usual N! → N<sup>2</sup>2<sup>N</sup> dynamic programming trick (compute hp[v][w][S] = "is there a path that has endpoints v and w and whose vertices are the subset S" for every subset S and every two vertices v and w in it using DP), but that's still exponential.</p>
<p>However, there are many special kinds of graphs for which Hamiltonian paths will always exist, and they can be found easily (see work of Posa, Dirac, Ore, etc.)</p>
<p>For instance, the following is true: <em>If every vertex of the graph has degree at least n/2</em>, then the graph has a Hamiltonian path. You can in fact find one in O(n<sup>2</sup>), or IIRC even O(n log n) if you do it more cleverly.<br/>
[Rough sketch: First, just connect all vertices in some "Hamiltonian" cycle, nevermind if the edges are actually in the graph. Now for every edge (v,w) of your cycle that is not actually in the graph, consider the rest of the cycle: v...w. As deg(v)+deg(w)>=n, there exist consecutive x,y in your list (in that order) such that w is a neighbour of x and v is a neighbour of y. [Proof: Consider {the set of all neighbours of w} and {the set of all successors in your list of neighbours of v}; they must intersect.] Now change your cycle [v...xy...wv] to [vy...wx...v] instead, it has at least one less invalid edge, so you'll need at most n iterations to get a true Hamiltonian cycle. More details <a href="http://cgm.cs.mcgill.ca/~perouz/cs251/documents/solutions6/solutions6.html">here</a>.]</p>
<p>BTW: if what you are looking for is just a walk that includes every <em>edge</em> once, it's called an Eulerian walk and for graphs that have it (number of vertices of odd degree is 0 or 2), one can quite easily be found in polynomial time (fast).</p>
|
Is there any reason to not ship the pdb's with your application? <p>Since you can use reflector to reverse-engineer a .Net app, is there any reason to NOT ship the pdb files with the app? If you do ship them with it, then your stack trace will include the line number with the problem, which is useful if it crashes.</p>
<p>Please only enter 1 reason per comment for voting.</p>
| <p>Shipping pdb does not give any additional convenience to user. So there are no reasons to ship pdb files with the app. Besides pdb file usually have large size.</p>
<p>Instead of shipping pdb files you should use local Microsoft Symbol Server for fast access to pdb files corresponding to error reports. <a href="http://msdn.microsoft.com/en-us/library/ms681417%28VS.85%29.aspx" rel="nofollow">Here</a> you can find detailed explanation how to use Symbol Server.</p>
|
Two Phase Commit/Shared Transaction <p>The scenario is this</p>
<p>We have two applications A and B, both which are running in separate database (Oracle 9i ) transactions</p>
<p>Application A - inserts some data into the database, then calls Application B
Application B - inserts some data into the database, related (via foreign keys) to A's data. Returns an "ID" to Application A
Application A - uses ID to insert further data, including the ID from B</p>
<p>Now, because these are separate transactions, but both rely on data from each others transactions, we need to commit between the calls to each application. This of course makes it very difficult to rollback if anything goes wrong. </p>
<p>How would you approach this problem, with minimal refactoring of the code. Surely this kind of this is a common problem in the SOA world?</p>
<p>------ Update --------</p>
<p>I have not been able to find anything in Oracle 9i, however Oracle 11g provides <a href="http://www.morganslibrary.org/reference/dbms%5Fxa.html" rel="nofollow">DBMS_XA</a>, which does exactly what I was after.</p>
| <p>You have three options:</p>
<ol>
<li><p>Redesign the application so that you don't have two different processes (both with database connections) writing to the database and roll it into a single app.</p></li>
<li><p>Create application C that handles all the database transactions for A and B.</p></li>
<li><p>Roll your own two phase commit. Application C acts as the coordinator. C signals A and B to ask if they're ready to commit. A and B do their processing, and respond to C with either a "ready" or a "fail" reply (note that there should be a timeout on C to avoid an infinite wait if one process hangs or dies). If both reply ready then C tells them to commit. Otherwise it sends a rollback signal.</p></li>
</ol>
<p>Note that you may run into issues with option 3 if app A is relying on foreign keys from app B (which you didn't state, so this may not be an issue). Oracle's read consistency would probably prevent this from being allowed, since app A's transaction will begin before app B. Just a warning.</p>
|
Is it possible to store and retrieve a boolean value in a varchar field using Java JDBC? <p>quick question: my customer has a situation where he has his database with a varchar field and the corresponding jdbc code is storing/retrieving a boolean.</p>
<p>I guess that the boolean values false and true are going to be translated to "0" and "1" but I would like to have a confirmation of this (I can't find the precise behavior specification online, maybe it depends on each driver, Oracle in this case).</p>
<p>I know I could experiment by myself, but I want to have a try at stackoverflow.com!</p>
<p>Thanks for your answer,</p>
<p>Eric.</p>
| <p>I agree with the answer that the semantics are highly database specific, which is why I think the important answer is that you <em>shouldn't</em> do this. A change in JDBC driver or something similar could cause the implicit behaviour to break.</p>
<p>Instead, If using raw JDBC, have the code take the boolean and convert it to an appropriate String ('true' or 'false' are obvious choices) and then set this value to the VARCHAR column. On read from the VARCHAR column do the reverse, throwing or handling the exception case where the String is not one of the boolean values as expected.</p>
|
How can I ban a whole company from my web site? <p>For reasons I won't go into, I wish to ban an entire company from accessing my web site. Checking the remote hostname in php using gethostbyaddr() works, but this slows down the page load too much. Large organizations (eg. hp.com or microsoft.com) often have blocks of IP addresses. Is there anyway I get the full list, or am I stuck with the slow reverse-DNS lookup? If so, can I speed it up?</p>
<p>Edit: Okay, now I know I can use the .htaccess file to ban a range. Now, how can I figure out what that range should be for a given organization?</p>
| <p>How about an .htaccess:</p>
<pre><code>Deny from x.x.x.x
</code></pre>
<p>if you need to deny a range say: 192.168.0.x then you would use</p>
<pre><code>Deny from 192.168.0
</code></pre>
<p>and the same applies for hostnames:</p>
<pre><code>Deny from sub.domain.tld
</code></pre>
<p>or if you want a PHP solution</p>
<pre><code>$ips = array('1.1.1.1', '2.2.2.2', '3.3.3.3');
if(in_array($_SERVER['REMOTE_ADDR'])){die();}
</code></pre>
<p>For more info on the htaccess method see <a href="http://httpd.apache.org/docs/1.3/mod/mod_access.html" rel="nofollow">this</a> page.</p>
<p>Now to determine the range is going to be hard, most companies (unless they are big corperate) are going to have a dynamic IP just like you and me.<br />
This is a problem I have had to deal with before and the best thing is either to ban the hostname, or the entire range, for example if they are on 192.168.0.123 then ban 192.168.0.123, unfortunatly you are going to get a few innocent people with either method.</p>
|
Annuity or Angle Operation Symbol in LaTeX <p>How do I set the symbol for the <em>angle</em> or <em>annuity</em> operation in LaTeX? Specifically, this is the actuarial <em>a</em> angle <em>s</em> = (1-v<sup>s</sup>)/i.</p>
| <p>I've looked at <a href="http://maths.dur.ac.uk/stats/courses/AMII/am.html">Life's Contingency's Package</a>, various Actuarial Outpost <a href="http://www.actuarialoutpost.com/actuarial_discussion_forum/showthread.php?t=113896">forum</a> <a href="http://www.actuarialoutpost.com/actuarial_discussion_forum/showthread.php?p=2200212">threads</a>, and the <a href="ftp://tug.ctan.org/pub/tex-archive/info/symbols/comprehensive/symbols-letter.pdf">Comprehensive Symbol List</a> for LaTeX, and combined the best into the following macros:</p>
<pre><code>\DeclareRobustCommand{\lcroof}[1]{
\hbox{\vtop{\vbox{%
\hrule\kern 1pt\hbox{%
$\scriptstyle #1$%
\kern 1pt}}\kern1pt}%
\vrule\kern1pt}}
\DeclareRobustCommand{\angle}[1]{
_{\lcroof{#1}}}
</code></pre>
<p>You can then use this macro for the problem's example by typing</p>
<pre><code> $a\angle{s}$
</code></pre>
<p>If you need a full set of actuarial symbols, you should use the <a href="http://maths.dur.ac.uk/stats/courses/AMII/am.html">Life's Contingency's Package</a> <code>lifecon</code>. Using <code>lifecon</code>, you can set the above by typing</p>
<pre><code> $a_{\lcroof{s}}$
</code></pre>
|
css help with box models <p>I need help with the css box models. I have a problem with my website ucare-ph.org . The logo (temporary) is covering the main copy. Now I know someone can tell me the code to fix this. But what I really need is a resource or resources in books or websites that can give me a better understanding of the box model. The syntax is very easy. But the relationship between the boxes is very difficult. And yes I have firebug and web dev for firefox. But its still trial and error. </p>
| <ul>
<li><a href="http://redmelon.net/tstme/box_model/" rel="nofollow">Interactive CSS Box Model</a></li>
<li><a href="http://www.brainjar.com/css/positioning/" rel="nofollow">CSS Positioning</a></li>
</ul>
<p>As to your site's logo, try setting <code>clear: both</code> on the content.</p>
|
App_Code folder issues <p>So I'm having a really weird issue with my App_Code folder on a new website I'm designing. </p>
<p>I have a basic class inside of a namespace in the App_Code folder. Everything works fine in the IDE when I setup the namespace and make an object from the class. It brings up the class summary on hover, and when you click on "go to deffinition" it goes to the class file.
And it also works fine localy.</p>
<p>However, when I load the site onto my server, I get this error message when I access that page: </p>
<p>Line 10: using System.Web.UI.WebControls;<br/>
Line 11: using System.Web.UI.WebControls.WebParts;<br/>
<strong>Line 12: using xxxx.xxxx</strong></p>
<p><strong>Compiler Error Message:</strong> CS0246: The type or namespace name 'xxxxxx' could not be found (are you missing a using directive or an assembly reference?)</p>
<p>I know for a fact that the class file is there. Anyone have any idea of whats going on?</p>
<p>Edits:</p>
<p>John, yes it is a 2.0 site.</p>
| <p>The problem that your classes are not compiled, You'll solve this issue simply by going to the properties of any class in the App_Code folder and change it's 'Build Action' property from "Content" to "Compile"</p>
<p>I was facing this problem and just found the solution..hope it helps any one, I'm sure you're not stuck with this problem since 2008 :D!</p>
|
Do anyone do test cases for pojos? <p>Is that needed?</p>
| <p>I write explicit tests for everything except simple getters and setters. </p>
<p>If the getter or setter only contains a return blah; or this.blah = blah; I don't think there is much value. The majority of times these are generated and I feel the time putting the tests together could be better spent elsewhere. </p>
|
How do you pass arguments to define_method? <p>I would like to pass an argument(s) to a method being defined using define_method, how would I do that?</p>
| <p>The block that you pass to define_method can include some parameters. That's how your defined method accepts arguments. When you define a method you're really just nicknaming the block and keeping a reference to it in the class. The parameters come with the block. So:</p>
<pre><code>define_method(:say_hi) { |other| puts "Hi, " + other }
</code></pre>
|
Can I display the list of all the system objects (semaphores, queues...) in VxWorks? <p>I would like to know what semaphores, messageQueues, etc... are active in my vxWorks 6.x system. I have access to this information via the debugger, but I would like access to it from the shell.</p>
<p>Is there a way?</p>
| <p>VxWorks 6.x provides a function called classShow() which will list all the objects of a specific class (e.g. semaphores, message queues, tasks, ...).
The following call will give you a list of objects for a given class:</p>
<pre><code>
classShow(objClassIdGet(classId), 1)
The classId types are:
1 windSemClass, /* Wind native semaphore */
2 windSemPxClass, /* POSIX semaphore */
3 windMsgQClass, /* Wind native message queue */
4 windMqPxClass, /* POSIX message queue */
5 windRtpClass, /* real time process */
6 windTaskClass, /* task */
7 windWdClass, /* watchdog */
8 windFdClass, /* file descriptor */
9 windPgPoolClass, /* page pool */
10 windPgMgrClass, /* page manager */
11 windGrpClass, /* group */
12 windVmContextClass, /* virtual memory context */
13 windTrgClass, /* trigger */
14 windMemPartClass, /* memory partition */
15 windI2oClass, /* I2O */
16 windDmsClass, /* device management system */
17 windSetClass, /* Set */
18 windIsrClass, /* ISR object */
19 windTimerClass, /* Timer services */
20 windSdClass, /* Shared data region */
21 windPxTraceClass, /* POSIX trace */
</code></pre>
|
How to reference a custom field in SQL <p>I am using mssql and am having trouble using a subquery. The real query is quite complicated, but it has the same structure as this:</p>
<pre><code>select
customerName,
customerId,
(
select count(*)
from Purchases
where Purchases.customerId=customerData.customerId
) as numberTransactions
from customerData
</code></pre>
<p>And what I want to do is order the table by the number of transactions, but when I use</p>
<pre><code>order by numberTransactions
</code></pre>
<p>It tells me there is no such field. Is it possible to do this? Should I be using some sort of special keyword, such as <code>this</code>, or <code>self</code>?</p>
| <p>use the field number, in this case:</p>
<pre><code>order by 3
</code></pre>
|
What time should I build to production? <p>My users use the site pretty equally 24/7. Is there a meme for build timing?</p>
<p>International audience, single cluster of servers on eastern time, but gets hit well into the morning, by international clients.</p>
<p>1 db, several web servers, so if no db, simple, whenever.</p>
<p>But when the site has to come down, when would you, as a programmer be least mad to see SO be down for say 15 minutes.</p>
| <p>If there's truly no good time from the users' perspective, then I'd suggest doing it when your team has the most time to recover from any build-related disaster.</p>
|
Entity Framework - Can you map the result type of an imported stored procedure to a custom entity type? <p>I already have an entity model in a separate dll that contains various objects that I need to use. I don't really want to create or duplicate entities using the EF designer. Instead I would like to configure it so that when I call a stored procedure it will map certain columns to specific properties.</p>
<p>I know you can do something VERY close to this using a custom DataContext in LinqToSql. The problem is you can't assign columns to complex property types. For example: I might have a columns returned that contain the address for a user. I would like to store the address details for the user in an Address object that is a property of a User object. So, Column STREET should map to User.Address.Street.</p>
<p>Any ideas?</p>
| <p>There are a couple of options here.</p>
<ol>
<li><p>You can create a "Complex Type" and map that to the procedure result. However, you have to do that in your EDMX; it's not supported by the designer. Read <a href="http://msdn.microsoft.com/en-us/library/bb738472.aspx" rel="nofollow">this article</a> for details. Note that Complex Types are not entity types <em>per se</em>, so this may or may not fit your needs. But you can find examples for <a href="http://msdn.microsoft.com/en-us/library/cc716733.aspx" rel="nofollow">stored procs which use "Address"</a>.</p></li>
<li><p>You can change the visibility of your procedure to private, and then write a public interface for it in any manually-written partial class file which does the mapping that you want. Or just overload the procedure.</p></li>
</ol>
|
In Classic asp, can I store a database connection in the Session object? <p>Can I store a database connection in the Session object?</p>
| <p>It is generally not recommended to do so, a connection string in the Application variable, with a nice helper function/class is a much preferred method. <strike>Here</strike> is some reference. <em>(Dead link removed because it now leads to a phishy site)</em></p>
|
Integrating with Google Docs <p>Has anyone integrated an "Open in Google Docs" in their web app yet? Gmail has this for opening attachments. How about any other sightings of this in a <em>non-google</em> web app?</p>
| <p>Google Docs does <a href="http://code.google.com/apis/documents/developers_guide_protocol.html" rel="nofollow">have an API</a> which allows you to search, upload, delete and retrieve documents from the Google Docs list of a specific user. You could conceivably use this to upload a document from your server and then retrieve the URL of that document (once it is imported), which you can then use to redirect the user. It wouldn't be <em>quite</em> as slick as Gmail's integration since you wouldn't be able to show that fancy "Importing your document..." page, but it might suffice.</p>
<p>As for other sightings, I am not aware of any.</p>
|
What's the easiest way to merge (server-side) a collection of PDF documents into one big PDF document in JAVA <p>I have 3 PDF documents that are generated on the fly by a legacy library that we use, and written to disk. What's the easiest way for my JAVA server code to grab these 3 documents and turn them into one long PDF document where it's just all the pages from document #1, followed by all the pages from document #2, etc.</p>
<p>Ideally I would like this to happen in memory so I can return it as a stream to the client, but writing it to disk is also an option.</p>
| <p>@J D OConal, thanks for the tip, the article you sent me was very outdated, but it did point me towards iText. I found this page that explains how to do exactly what I need:
<a href="http://java-x.blogspot.com/2006/11/merge-pdf-files-with-itext.html" rel="nofollow">http://java-x.blogspot.com/2006/11/merge-pdf-files-with-itext.html</a></p>
<p>Thanks for the other answers, but I don't really want to have to spawn other processes if I can avoid it, and our project already has itext.jar, so I'm not adding any external dependancies</p>
<p>Here's the code I ended up writing:</p>
<pre><code>public class PdfMergeHelper {
/**
* Merges the passed in PDFs, in the order that they are listed in the java.util.List.
* Writes the resulting PDF out to the OutputStream provided.
*
* Sample Usage:
* List<InputStream> pdfs = new ArrayList<InputStream>();
* pdfs.add(new FileInputStream("/location/of/pdf/OQS_FRSv1.5.pdf"));
* pdfs.add(new FileInputStream("/location/of/pdf/PPFP-Contract_Genericv0.5.pdf"));
* pdfs.add(new FileInputStream("/location/of/pdf/PPFP-Quotev0.6.pdf"));
* FileOutputStream output = new FileOutputStream("/location/to/write/to/merge.pdf");
* PdfMergeHelper.concatPDFs(pdfs, output, true);
*
* @param streamOfPDFFiles the list of files to merge, in the order that they should be merged
* @param outputStream the output stream to write the merged PDF to
* @param paginate true if you want page numbers to appear at the bottom of each page, false otherwise
*/
public static void concatPDFs(List<InputStream> streamOfPDFFiles, OutputStream outputStream, boolean paginate) {
Document document = new Document();
try {
List<InputStream> pdfs = streamOfPDFFiles;
List<PdfReader> readers = new ArrayList<PdfReader>();
int totalPages = 0;
Iterator<InputStream> iteratorPDFs = pdfs.iterator();
// Create Readers for the pdfs.
while (iteratorPDFs.hasNext()) {
InputStream pdf = iteratorPDFs.next();
PdfReader pdfReader = new PdfReader(pdf);
readers.add(pdfReader);
totalPages += pdfReader.getNumberOfPages();
}
// Create a writer for the outputstream
PdfWriter writer = PdfWriter.getInstance(document, outputStream);
document.open();
BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
PdfContentByte cb = writer.getDirectContent(); // Holds the PDF
// data
PdfImportedPage page;
int currentPageNumber = 0;
int pageOfCurrentReaderPDF = 0;
Iterator<PdfReader> iteratorPDFReader = readers.iterator();
// Loop through the PDF files and add to the output.
while (iteratorPDFReader.hasNext()) {
PdfReader pdfReader = iteratorPDFReader.next();
// Create a new page in the target for each source page.
while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
document.newPage();
pageOfCurrentReaderPDF++;
currentPageNumber++;
page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
cb.addTemplate(page, 0, 0);
// Code for pagination.
if (paginate) {
cb.beginText();
cb.setFontAndSize(bf, 9);
cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "" + currentPageNumber + " of " + totalPages,
520, 5, 0);
cb.endText();
}
}
pageOfCurrentReaderPDF = 0;
}
outputStream.flush();
document.close();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (document.isOpen()) {
document.close();
}
try {
if (outputStream != null) {
outputStream.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
</code></pre>
|
SQL Server sys.databases log_reuse_wait question <p>I was investigating the rapid growth of a SQL Server 2005 transaction log when I found that transaction logs will only truncate correctly - if the sys.databases "log_reuse_wait" column is set to 0 - meaning that nothing is keeping the transaction log from reusing existing space. </p>
<p>One day when I was intending to backup/truncate a log file, I found that this column had a 4, or ACTIVE_TRANSACTION going on in the tempdb. I then checked for any open transactions using DBCC OPENTRAN('tempdb'), and the open_tran column from sysprocesses. The result was that I could find no active transactions anywhere in the system.</p>
<p>Are the settings in the log_reuse_wait column accurate? Are there transactions going on that are not detectable using the methods I described above? Am I just missing something obvious?</p>
| <p>I still don't know why I was seeing the ACTIVE_TRANSACTION in the sys.databases log_reuse_wait_desc column - when there were no transactions running, but my subsequent experience indicates that the log_reuse_wait column for the tempdb changes for reasons that are not very clear, and for my purposes, not very relevant. Also, I found that running DBCC OPENTRAN, or the "select open_tran from sysprocess" code, is a lot less informative than using the below statements when looking for transaction information:</p>
<pre><code>select * from sys.dm_tran_active_transactions
select * from sys.dm_tran_session_transactions
select * from sys.dm_tran_locks
</code></pre>
|
What is your session management strategy for NHibernate in desktop applications? <p>I find it much more difficult to manage your session in a desktop application, because you cannot take advantage of such a clear bondary like HttpContext.
So how do you manage your session lifetime to take advantage of lazy loading but without having one session open for the entire application?</p>
| <p>Ayende has recently written <a href="http://msdn.microsoft.com/en-us/magazine/ee819139.aspx">a great article on the subject in MSDN</a>.</p>
|
Good asp.net (C#) apps? <p>Any suggestions for good open source asp.net (C#) apps out there which meet as many of the following:?</p>
<ol>
<li>Designed well and multi tiered</li>
<li>Clean & commented code</li>
<li>Good use of several design patterns</li>
<li>Web pages display properly in all common browsers</li>
<li>Produces valid html and has good use of css</li>
<li>Use of css themes. Prefer usage of css than tables</li>
<li>NOT dependent on third party components (grids, menus, trees, ...etc)</li>
<li>Has good unit tests</li>
<li>Web pages are not simplistic and look professional</li>
<li>Uses newer technologies like MVC, LINQ.. (not important)</li>
<li>(Anything else that matters which I couldn't think of right now)</li>
</ol>
| <p>I would have to agree with <a href="http://www.dotnetblogengine.net/" rel="nofollow">BlogEngine</a>. It implements a ton of different abilities and common needs in asp.net as well as allowing it to be fully customizable and very easy to understand. It can work with XML or SQL (your choice) and has a huge community behind it.</p>
<p>As for your requests (<strong>bold</strong> means yes):</p>
<ol>
<li><strong>Designed well and multi tiered</strong></li>
<li><strong>Clean & commented code</strong></li>
<li><strong>Good use of several design patterns</strong></li>
<li><strong>Web pages display properly in all common browsers</strong></li>
<li><strong>Produces valid html and has good use of css</strong></li>
<li><strong>Use of css themes. Prefer usage of css than tables</strong></li>
<li><strong>NOT dependent on third party components (grids, menus, trees, ...etc)</strong> - <em>kind of, still uses some custom dlls</em></li>
<li>Has good unit tests - <em>not sure</em></li>
<li><strong>Web pages are not simplistic and look professional</strong> - <em>yes, and there are TONS of free templates out there</em> </li>
<li>Uses newer technologies like MVC, LINQ.. (not important) - <em>not yet</em></li>
<li>(Anything else that matters which I couldn't think of right now) - <em>a ton more stuff like dynamic rss feeds, dynamic sitemaps, data references, etc.</em></li>
</ol>
<p>There is also a bunch more great open source projects available here: <a href="http://www.asp.net/community/projects/" rel="nofollow">http://www.asp.net/community/projects/</a></p>
<p>I know that <a href="http://www.asp.net/downloads/starter-kits/dotnetnuke/" rel="nofollow">dotNetNuke</a> is pretty popular as well, and the <a href="http://www.asp.net/downloads/starter-kits/classifieds/" rel="nofollow">Classified Program</a> is pretty easy to use.</p>
|
Word frequency algorithm for natural language processing <p>Without getting a degree in information retrieval, I'd like to know if there exists any algorithms for counting the frequency that words occur in a given body of text. The goal is to get a "general feel" of what people are saying over a set of textual comments. Along the lines of <a href="http://wordle.net/">Wordle</a>.</p>
<p>What I'd like:</p>
<ul>
<li>ignore articles, pronouns, etc ('a', 'an', 'the', 'him', 'them' etc)</li>
<li>preserve proper nouns</li>
<li>ignore hyphenation, except for soft kind</li>
</ul>
<p>Reaching for the stars, these would be peachy:</p>
<ul>
<li>handling stemming & plurals (e.g. like, likes, liked, liking match the same result)</li>
<li>grouping of adjectives (adverbs, etc) with their subjects ("great service" as opposed to "great", "service")</li>
</ul>
<p>I've attempted some basic stuff using Wordnet but I'm just tweaking things blindly and hoping it works for my specific data. Something more generic would be great.</p>
| <p>You'll need not one, but several nice algorithms, along the lines of the following.</p>
<ul>
<li>ignoring pronouns is done via a <a href="http://en.wikipedia.org/wiki/Stoplist">stoplist</a>.</li>
<li>preserving proper nouns? You mean, detecting named entities, like <em>Hoover</em> <em>Dam</em> and saying "it's one word" or compound nouns, like <em>programming</em> <em>language</em>? I'll give you a hint: that's tough one, but there exist libraries for both. Look for NER (Named entitiy recognition) and lexical chunking. <a href="http://opennlp.sf.net">OpenNLP</a> is a Java-Toolkit that does both.</li>
<li>ignoring hyphenation? You mean, like at line breaks? Use regular expressions and verify the resulting word via dictionary lookup.</li>
<li>handling plurals/stemming: you can look into the <a href="http://snowball.tartarus.org">Snowball stemmer</a>. It does the trick nicely.</li>
<li>"grouping" adjectives with their nouns is generally a task of <a href="http://en.wikipedia.org/wiki/Shallow_parsing">shallow parsing</a>. But if you are looking specifically for qualitative adjectives (good, bad, shitty, amazing...) you may be interested in <a href="https://secure.wikimedia.org/wikipedia/en/wiki/Sentiment_analysis">sentiment analysis</a>. <a href="http://alias-i.com/lingpipe">LingPipe</a> does this, and a lot more.</li>
</ul>
<p>I'm sorry, I know you said you wanted to KISS, but unfortunately, your demands aren't that easy to meet. Nevertheless, there exist tools for all of this, and you should be able to just tie them together and not have to perform any task yourself, if you don't want to. If you want to perform a task yourself, I suggest you look at stemming, it's the easiest of all.</p>
<p>If you go with Java, combine <a href="http://lucene.apache.org">Lucene</a> with the <a href="http://opennlp.sf.net">OpenNLP</a> toolkit. You will get very good results, as Lucene already has a stemmer built in and a lot of tutorial. The OpenNLP toolkit on the other hand is poorly documented, but you won't need too much out of it. You might also be interested in <a href="http://nltk.sf.net">NLTK</a>, written in Python.</p>
<p>I would say you drop your last requirement, as it involves shallow parsing and will definetly not impove your results.</p>
<p>Ah, btw. the exact term of that document-term-frequency-thing you were looking for is called <a href="http://en.wikipedia.org/wiki/Tf-idf">tf-idf</a>. It's pretty much the best way to look for document frequency for terms. In order to do it properly, you won't get around using multidimenional vector matrices.</p>
<p>... Yes, I know. After taking a seminar on IR, my respect for Google was even greater. After doing some stuff in IR, my respect for them fell just as quick, though.</p>
|
Benefits of SQL Server 2005 over 2000 <p>Could somebody please name a few. I could given time, but this is for somebody else, and I'd also like some community input.</p>
| <p>Some differences:</p>
<ul>
<li>CLR (.NET) stored procedures</li>
<li>SSIS instead of DTS</li>
<li>Management Studio instead of Enterprise Manager, with more functions (2008 version is even better)</li>
<li>VS integration</li>
<li>better replication</li>
<li>SMO and AMO (extensions to handle the server from applications)</li>
<li>table and index partitioning</li>
<li>XML as data type</li>
<li>XQuery to handle XML data type</li>
<li>Service Broker</li>
<li>Notification Services</li>
<li>Analysis Services</li>
<li>Reporting Service</li>
</ul>
<p>I have now these ones in mind. There are a lot of other small nice stuff, but I cannot name more.</p>
|
How can I report to users what is consuming the process address space of a windows application while they're running it? <p>I'm writing the memory manager for an application, as part of a team of twenty-odd coders. We're running out of memory quota and we need to be able to see what's going on, since we only appear to be using about 700Mb. I need to be able to report where it's all going - fragmentation etc. Any ideas?</p>
| <p>You can use existing memory debugging tools for this, I found Memory Validator <a href="http://www.vmvalidator.com/cpp/memory/index.html" rel="nofollow" title="Memory Validator">1</a> quite useful, it is able to track both API level (heap, new...) and OS level (Virtual Memory) allocations and show virtual memory maps.</p>
<p>The other option which I also found very usefull is to be able to dump a map of the whole virtual space based on VirtualQuery function. My code for this looks like this:</p>
<pre><code>void PrintVMMap()
{
size_t start = 0;
// TODO: make portable - not compatible with /3GB, 64b OS or 64b app
size_t end = 1U<<31; // map 32b user space only - kernel space not accessible
SYSTEM_INFO si;
GetSystemInfo(&si);
size_t pageSize = si.dwPageSize;
size_t longestFreeApp = 0;
int index=0;
for (size_t addr = start; addr<end; )
{
MEMORY_BASIC_INFORMATION buffer;
SIZE_T retSize = VirtualQuery((void *)addr,&buffer,sizeof(buffer));
if (retSize==sizeof(buffer) && buffer.RegionSize>0)
{
// dump information about this region
printf(.... some buffer information here ....);
// track longest feee region - usefull fragmentation indicator
if (buffer.State&MEM_FREE)
{
if (buffer.RegionSize>longestFreeApp) longestFreeApp = buffer.RegionSize;
}
addr += buffer.RegionSize;
index+= buffer.RegionSize/pageSize;
}
else
{
// always proceed
addr += pageSize;
index++;
}
}
printf("Longest free VM region: %d",longestFreeApp);
}
</code></pre>
|
How to match a single quote in sed <p>How to match a single quote in sed if the expression is enclosed in single quotes:</p>
<pre><code>sed -e '...'
</code></pre>
<p>For example need to match this text:</p>
<pre><code>'foo'
</code></pre>
| <p>You can either use:</p>
<pre><code>"texta'textb" (APOSTROPHE inside QUOTATION MARKs)
</code></pre>
<p>or</p>
<pre><code>'texta'\''textb' (APOSTROPHE text APOSTROPHE, then REVERSE SOLIDUS, APOSTROPHE, then APOSTROPHE more text APOSTROPHE)
</code></pre>
<p>I used unicode character names. REVERSE SOLIDUS is more commonly known as backslash.</p>
<p>In the latter case, you close your apostrophe, then shell-quote your apostrophe with a backslash, then open another apostrophe for the rest of the text.</p>
|
Optional Parameters in Mysql stored procedures <p>How do I create an optional parameter in a mysql stored procedure?</p>
| <p>According to <a href="http://bugs.mysql.com/bug.php?id=15975" rel="nofollow">this bug</a>, there is currently no way to create optional parameters.</p>
|
How do I best convert a DbType to System.Type? <p>How do I best convert a System.Data.DbType enumeration value to the corresponding (or at least one of the possible corresponding) System.Type values?</p>
<p>For example:</p>
<pre><code>DbType.StringFixedLength -> System.String
DbType.String -> System.String
DbType.Int32 -> System.Int32
</code></pre>
<p>I've only seen very "dirty" solutions but nothing really clean.</p>
<p>(yes, it's a follow up to a different question of mine, but it made more sense as two seperate questions)</p>
| <p>AFAIK there is no built-in converter in .NET for converting a SqlDbType to a System.Type. But knowing the mapping you can easily roll your own converter ranging from a simple dictionary to more advanced (XML based for extensability) solutions.</p>
<p>The mapping can be found here:
<a href="http://www.carlprothman.net/Default.aspx?tabid=97" rel="nofollow">http://www.carlprothman.net/Default.aspx?tabid=97</a></p>
|
Make Web Application Accessible <p>What things have to be done before I can honestly tell myself my web application is accessible by anyone? Or even better, convince Joe Clark. I don't have any video or audio to worry about, so I know I won't need transcripts. What else do I have to check?</p>
| <p>You should also check out the WAI-ARIA stuff: </p>
<ul>
<li><a href="http://www.w3.org/WAI/intro/aria" rel="nofollow">http://www.w3.org/WAI/intro/aria</a></li>
<li><a href="http://alistapart.com/articles/waiaria" rel="nofollow">http://alistapart.com/articles/waiaria</a></li>
<li><a href="http://juicystudio.com/article/wai-aria-live-regions.php" rel="nofollow">http://juicystudio.com/article/wai-aria-live-regions.php</a></li>
</ul>
<p>And, for a perspective on the challenges actually faced by users with various disabilities when they try to use the web, have a look at some of the presentations and videos from the Scripting Enabled conference in London on Friday: <a href="http://scriptingenabled.org/" rel="nofollow">http://scriptingenabled.org/</a> (I don't think all of them are uploaded yet)</p>
|
Statistically removing erroneous values <p>We have a application where users enter prices all day. These prices are recorded in a table with a timestamp and then used for producing charts of how the price has moved... Every now and then the user enters a price wrongly (eg. puts in a zero to many or to few) which somewhat ruins the chart (you get big spikes). We've even put in an extra confirmation dialogue if the price moves by more than 20% but this doesn't stop them entering wrong values...</p>
<p>What statistical method can I use to analyse the values before I chart them to exclude any values that are way different from the rest?</p>
<p><strong>EDIT:</strong> To add some meat to the bone. Say the prices are share prices (they are not but they behave in the same way). You could see prices moving significantly up or down during the day. On an average day we record about 150 prices and sometimes one or two are way wrong. Other times they are all good...</p>
| <p>Calculate and track the <a href="http://en.wikipedia.org/wiki/Standard_deviation" rel="nofollow">standard deviation</a> for a while. After you have a decent backlog, you can disregard the outliers by seeing how many standard deviations away they are from the mean. Even better, if you've got the time, you could use the info to do some <a href="http://en.wikipedia.org/wiki/Naive_Bayes_classifier" rel="nofollow">naive Bayesian classification</a>.</p>
|
Best solution for using EJBs from Excel <p>We would like to give access to some of our EJBs from Excel. The goal is to give an API usable from VBA.</p>
<p>Our EJBs are mostly Stateless Session Beans that do simple CRUD operations with POJOs.</p>
<p>Some possible solutions: </p>
<ul>
<li>Exposing the EJBs as WebServices and create a VB/C# dll wrapping them,</li>
<li>Using Corba to access the EJBs from C#,</li>
<li>Creating a COM Library that uses Java to access the EJBs,</li>
</ul>
<p>Pointers to frameworks for these solution or other ideas are welcome.</p>
| <p>You could take a look at <a href="http://www.codeproject.com/KB/cs/iiop_net_and_ejb.aspx" rel="nofollow">IIOP.NET</a>, which addresses this issue.</p>
|
Multiple forms on ASP.NET page <p>Coming from a Classic ASP background, I'm used to multiple forms on a page, but this clearly limited in a ASP.NET page.</p>
<p>However, I have a situation where I have a form that gathers input from the user, saves the data to a DB, and afterwards I want to render (and tweak the values of) a special form that posts to the PayPal website.</p>
<p>If the PayPal form's field values were static, there would be no problem, but since I want to manipulate the form server-side (to tweak the qty, desc, price fields etc) this <em>will</em> be a problem.</p>
<p>I was considering redirecting to a different page after writing to the DB, and I suspect this would work fairly well, but it's a bit of extra effort that may be unneccessary.</p>
<p>It has also been suggested to me that I could programmatically render a different form, depending on where in the cycle I am. That is, use a placeholder, and on Page_Load I would add a DB Form (complete with child controls) initially, and the PayPal form after a Postback.</p>
<p>This scenario has got to be a common one for you guys, so I'm looking for opinions advice and any relevant code samples if you have preferred approach.</p>
<p>I know I can get by, but this project is a learning vehicle so I want to adopt what passes for best practice.</p>
<p>Thanks in advance...</p>
<p>Chris</p>
| <p>You can have multiple forms, it's just only one form may have the runat="server" attribute.</p>
<p>There are a bunch of answers to getting paypal to work; but as it's a learning vehicle that may be cheating. In all honesty I'd look at the full blown paypal API rather than use the somewhat simplistic forms method (with the added advantage that it should stretch your learning more).</p>
<p>Otherwise yes, setup a HTML form outside of the server side form, and add a literal into it and write the bits and pieces in there. </p>
|
How to calculate the sum of values in a tree using SQL <p>I need to sum points on each level earned by a tree of users. Level 1 is the sum of users' points of the users 1 level below the user. Level 2 is the Level 1 points of the users 2 levels below the user, etc...</p>
<p>The calculation happens once a month on a non production server, no worries about performance.</p>
<p>What would the SQL look like to do it?</p>
<p>If you're confused, don't worry, I am as well!</p>
<p>User table:</p>
<pre><code>ID ParentID Points
1 0 230
2 1 150
3 0 80
4 1 110
5 4 54
6 4 342
Tree:
0
|---\
1 3
| \
2 4---
\ \
5 6
</code></pre>
<p>Output should be:</p>
<pre><code>ID Points Level1 Level2
1 230 150+110 150+110+54+342
2 150
3 80
4 110 54+342
5 54
6 342
</code></pre>
<p>SQL Server Syntax and functions preferably...</p>
| <p>If you were using Oracle DBMS that would be pretty straightforward since Oracle supports tree queries with the <strong>CONNECT BY/STARTS WITH</strong> syntax. For SQL Server I think you might find <a href="http://searchwindevelopment.techtarget.com/tip/0,289483,sid8_gci1277481,00.html" rel="nofollow">Common Table Expressions</a> useful</p>
|
Export variable from C++ static library <p>I have a static library written in C++ and I have a structure describing data format, i.e.<br></p>
<pre><code>struct Format{
long fmtId;
long dataChunkSize;
long headerSize;
Format(long, long, long);
bool operator==(Format const & other) const;
};
</code></pre>
<p>Some of data formats are widely used, like <code>{fmtId=0, dataChunkSize=128, headerSize=0}</code> and <code>{fmtId=0, dataChunkSize=256, headerSize=0}</code><br><br>
Some data structure classes receive format in constructor. I'd like to have some sort of shortcuts for those widely used formats, like a couple of global <code>Format</code> members <code>gFmt128, gFmt256</code> that I can pass by reference. I instantiate them in a .cpp file like </p>
<p><code>Format gFmt128(0, 128, 0);</code></p>
<p>and in .h there is</p>
<p><code>extern Format gFmt128;</code></p>
<p>also, I declare <code>Format const & Format::Fmt128(){return gFmt128;}</code> and try to use it in the main module.</p>
<p>But if I try and do it in the main module that uses the lib, the linker complains about unresolved external <code>gFmt128</code>.</p>
<p>How can I make my library 'export' those global vars, so I can use them from other modules?</p>
| <p>Don't use the static keyword on global declarations. <a href="http://msdn.microsoft.com/en-us/library/s1sb61xd.aspx" rel="nofollow">Here is an article explain the visibility of variables with/without static</a>. The static gives globals internal linkage, that is, only visible in the translation unit they are declared in.</p>
|
source for eclipse plugin.xml page <p>I would like to know where can I find the code which eclipse uses to display the forms in the plugin.xml file. In particular I am looking for the form layout used in the extension tab in the plugin.xml</p>
| <p>Unfortunately, Eclipse's plugin search doesn't work for referenced plugins. To do these searches I created a workspace that contains all the plugins from my eclipse install as source folders. I just open the workspace and perform my plugin search there. Just open the search dialog and choose plugin.</p>
|
When people talk about scaling a website with 'shards', what do they mean? <p>I have heard the 'shard' technique mentioned several times with regard to solving scaling problems for large websites. What is this 'shard' technique and why is it so good?</p>
| <p>Karl Seguin has a <a href="http://codebetter.com/blogs/karlseguin/archive/2008/06/30/scale-cheaply-sharding.aspx" rel="nofollow">good blog</a> post about sharding.</p>
<p>From the post:</p>
<blockquote>
<p>Sharding is the separation of your
data across multiple servers. How you
separate your data is up to you, but
generally itâs done on some
fundamental identifier.</p>
</blockquote>
|
Order SharePoint search results by more columns <p>I'm using a FullTextSqlQuery in SharePoint 2007 (MOSS) and need to order the results by two columns:</p>
<pre><code>SELECT WorkId FROM SCOPE() ORDER BY Author ASC, Rank DESC
</code></pre>
<p>However it seems that only the first column from ORDER BY is taken into account when returning results. In this case the results are ordered correctly by Author, but not by Rank. If I change the order the results will be ordered by Rank, but not by Author.</p>
<p>I had to resort to my own sorting of the results, which I don't like very much. Has anybody a solution to this?</p>
<p><strong>Edit</strong>: Unfortunately it also doesn't accept expressions in the ORDER BY clause (SharePoint throws an exception). My guess is that even if the query looks like legitimate SQL it is parsed somehow before being served to the SQL server.</p>
<p>I tried to catch the query with SQL Profiler, but to no avail.</p>
<p><strong>Edit 2</strong>: In the end I used ordering by a single column (Author in my case, since it's the most important) and did the second ordering in code on the TOP N of the results. Works good enough for the project, but leaves a bad feeling of kludgy code.</p>
| <p>Microsoft <em>finally</em> posted a knowledge base article about this issue.</p>
<p>"When using RANK in the ORDER BY clause of a SharePoint Search query, no other properties should be used"</p>
<p><a href="http://support.microsoft.com/kb/970830" rel="nofollow">http://support.microsoft.com/kb/970830</a></p>
<p>Symptom: When using RANK in the ORDER BY clause of a SharePoint Search query only the first ORDER BY column is used in the results. </p>
<p>Cause: RANK is a special property that is ranked in the full text index and hence cannot be used with other managed properties. </p>
<p>Resolution: Do not use multiple properties in conjunction with the RANK property. </p>
|
Is there a pretty printer for python data? <p>Working with python interactively, it's sometimes necessary to display a result which is some arbitrarily complex data structure (like lists with embedded lists, etc.)
The default way to display them is just one massive linear dump which just wraps over and over and you have to parse carefully to read it.</p>
<p>Is there something that will take any python object and display it in a more rational manner. e.g.</p>
<pre><code>[0, 1,
[a, b, c],
2, 3, 4]
</code></pre>
<p>instead of:</p>
<pre><code>[0, 1, [a, b, c], 2, 3, 4]
</code></pre>
<p>I know that's not a very good example, but I think you get the idea.</p>
| <pre><code>from pprint import pprint
a = [0, 1, ['a', 'b', 'c'], 2, 3, 4]
pprint(a)
</code></pre>
<p>Note that for a short list like my example, pprint will in fact print it all on one line. However, for more complex structures it does a pretty good job of pretty printing data.</p>
|
Multi tenant architecture and NHibernate <p>Could anyone explain me finally what is the best strategy to implement transparent and fluent support of multi-tenant functionality in NHibernate powered domain model?</p>
<p>Im looking for the way, how to keep the domain logic as isolated as possible from the multi-tenant stuff like filtering by TenantID etc</p>
| <p>The simplest approach is to use different databases for each client.</p>
<p>Implementing multi-tenanting in this manner allows you to effectively write a single tenant application and only worry about the multi-tenanting at the point where you create / retrieve the session.</p>
<p>I haven't delved deep into the details as yet (I need to do something similar in a few months), but I think the easiest way to manage which database a session is connected to is via a custom ISessionFactory implementation that can determine which connection to use (based on an external aspect such as the host portion of the request url).</p>
<p>I have seen at least one post around the net somewhere discussing this, but I cannot find the link at this time.</p>
<p>If you are using Castle Windsor, have a look at the NHibernate integration facility. This supports the concept of multiple ( named ) session factories which would allow you to have a session factory per client. The integration facility provides an ISessionManager interface which allows you to open a session on a named session factory ( as well as providing per request session semantics for web applications ). Anything requiring access to the session could simply take an ISession constructor parameter and you could create a factory that takes an ISessionManager as a constructor parameter. You factory could then open a session on the appropriate named session factory by inspecting the request to determine which named session factory should be used.</p>
|
Reading quicken data files <p>Looking for an open source library, for C++, Java, C# or Python, for reading the data from Quicken <strong>.qdf</strong> files.</p>
<p>@<a href="#91941">Swati</a>: Quicken <strong>.qif</strong> format is for transfer only and is not kept up to date by the application like the .qdf file is.</p>
| <p>QDF is proprietary and not really meant for reading other than my Quicken, probably for a reason as it is messy. </p>
<p>I would recommend finding a way to export the qdf into an OFX (Open Financial Exchange) or qif file. I have done some financial and quickbooks automation and I did something similar. The problem is if you don't export to an exchange format, each version differs and strange things happen for many conditions that since they aren't documented (QDF) it becomes a bad situation for the programmer.</p>
<p>OFX is what allows online banking, brokerages and apps like mint.com securely get financial data. It is a standard and consistent. Finding a way to this is much better if at all possible. </p>
|
Is it possible to set code behind a resource dictionary in WPF for event handling? <p>Is it possible to set code behind a resource dictionary in WPF. For example in a usercontrol for a button you declare it in XAML. The event handling code for the button click is done in the code file behind the control. If I was to create a data template with a button how can I write the event handler code for it's button click within the resource dictionary.</p>
| <p>I think what you're asking is you want a code-behind file for a ResourceDictionary. You can totally do this! In fact, you do it the same way as for a Window:</p>
<p>Say you have a ResourceDictionary called MyResourceDictionary. In your MyResourceDictionary.xaml file, put the x:Class attribute in the root element, like so:</p>
<pre><code><ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="MyCompany.MyProject.MyResourceDictionary"
x:ClassModifier="public">
</code></pre>
<p>Then, create a code behind file called MyResourceDictionary.xaml.cs with the following declaration:</p>
<pre><code>namespace MyCompany.MyProject
{
partial class MyResourceDictionary : ResourceDictionary
{
public MyResourceDictionary()
{
InitializeComponent();
}
... // event handlers ahead..
}
}
</code></pre>
<p>And you're done. You can put whatever you wish in the code behind: methods, properties and event handlers.</p>
<p><strong>== Update for Windows 10 apps ==</strong></p>
<p>And just in case you are playing with <strong>UWP</strong> there is one more thing to be aware of:</p>
<pre><code><Application x:Class="SampleProject.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:rd="using:MyCompany.MyProject">
<!-- no need in x:ClassModifier="public" in the header above -->
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<!-- This will NOT work -->
<!-- <ResourceDictionary Source="/MyResourceDictionary.xaml" />-->
<!-- Create instance of your custom dictionary instead of the above source reference -->
<rd:MyResourceDictionary />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
</code></pre>
|
Python, beyond the basics <p>I've gotten to grips with the basics of Python and I've got a small holiday which I want to use some of to learn a little more Python. The problem is that I have no idea what to learn or where to start. I'm primarily web development but in this case I don't know how much difference it will make.</p>
| <p>Well, there are great ressources for advanced Python programming :</p>
<ul>
<li>Dive Into Python (<a href="http://www.diveintopython.net/">read it for free</a>)</li>
<li>Online python cookbooks (e.g. <a href="http://code.activestate.com/recipes/langs/python/">here</a> and <a href="http://the.taoofmac.com/space/Python/Grimoire">there</a>)</li>
<li>O'Reilly's Python Cookbook (see amazon)</li>
<li>A funny riddle game : <a href="http://www.pythonchallenge.com/">Python Challenge</a> </li>
</ul>
<p>Here is a list of subjects you must master if you want to write "Python" on your resume :</p>
<ul>
<li><a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions">list comprehensions</a></li>
<li><a href="http://stackoverflow.com/questions/231767/the-python-yield-keyword-explained/231855#231855">iterators and generators</a></li>
<li><a href="http://stackoverflow.com/questions/739654/understanding-python-decorators/1594484#1594484">decorators</a></li>
</ul>
<p>They are what make Python such a cool language (with the standard library of course, that I keep discovering everyday).</p>
|
How to make visualstudio .net work with VB6 and service pack 6 <p>I have VB application that requires visual service pack 6 to run , now when I install visualstudio.net (any version of .net) Its debugger doesn't work properly ,I am able to create windows/web application in visualstudio.net but not able to debug anything , so I have to keep 2 computers , one for VB and one for .net , does anybody have any idea what is the cause for this and is there any fix for this ?</p>
| <p>I've used visual studio 6 and visual studio 2005 on the same system, so I know you can set it up so that both debuggers work. However, when I did it the setup just worked, so I can't tell you what I did to make it work, except that VS2005 was on the machine first.</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.