input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
What sets Page.User.Identity.Name <p>I keep track of the current logged in userID and base the behavior of my site on this value. My code sets the logged in user ID with this statement:</p>
<pre><code>FormsAuthentication.SetAuthCookie(UserID.ToString(), true);
</code></pre>
<p>Subsequently, I read this value <code>from Page.User.Identity.Name</code>.</p>
<p>This works fine on my desktop, but on my server, I set it to 8 and it comes back 20. I am trying to figure out what can set Page.User.Identity.Name to a value and when this happens.</p>
<p>Thanks...</p>
| <p><code>FormsAuthenticationModule</code> handles <code>Application_OnAuthenticate</code> and assigns the <code>HttpContext.User</code> to a prinicipal object which is in turn used by <code>Page.User.Identity.Name</code>.</p>
<p>Isn't there a time difference issue on the server and your desktop?</p>
|
java.util.ConcurrentModificationException in JasperReports <p>We have a web application deployed to Websphere 6.1.0.19 on Windows. We occasionally see this ConcurrentModificationException on a few of our reports. We are using JasperReports 2.0.5 in production. The full stacktrace is following:</p>
<pre>
java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:464)
at java.util.AbstractList$Itr.next(AbstractList.java:435)
at net.sf.jasperreports.engine.data.JRBeanCollectionDataSource.next(JRBeanCollectionDataSource.java:91)
at com.advtechgrp.bop.medical.reports.core.implementation.MedicalReportDataSourceImpl.next(MedicalReportDataSourceImpl.java:61)
at net.sf.jasperreports.engine.fill.JRFillDataset.advanceDataSource(JRFillDataset.java:830)
at net.sf.jasperreports.engine.fill.JRFillDataset.next(JRFillDataset.java:748)
at net.sf.jasperreports.engine.fill.JRBaseFiller.next(JRBaseFiller.java:1438)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReport(JRVerticalFiller.java:111)
at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:895) at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:817)
at net.sf.jasperreports.engine.fill.JRFiller.fillReport(JRFiller.java:89)
at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:601)
at com.advtechgrp.bop.medical.reports.core.MedicalReportBase.getReportList(MedicalReportBase.java:160)
at com.advtechgrp.bop.medical.reports.core.implementation.MedicalReportCreator.createJasperExporter(MedicalReportCreator.java:275)
at com.advtechgrp.bop.medical.reports.core.implementation.MedicalReportCreator.createExporter(MedicalReportCreator.java:228)
at com.advtechgrp.bop.medical.reports.core.implementation.MedicalReportCreator.createReportUnsafe(MedicalReportCreator.java:196)
at com.advtechgrp.bop.medical.reports.core.implementation.MedicalReportCreator.createReport(MedicalReportCreator.java:80)
at com.advtechgrp.bop.medical.reports.core.web.MedicalReportServlet.doPost(MedicalReportServlet.java:132)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:763)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
at com.ibm.ws.cache.servlet.ServletWrapper.serviceProxied(ServletWrapper.java:282)
at com.ibm.ws.cache.servlet.CacheHook.handleFragment(CacheHook.java:459)
at com.ibm.ws.cache.servlet.CacheHook.handleServlet(CacheHook.java:265)
at com.ibm.ws.cache.servlet.ServletWrapper.service(ServletWrapper.java:262)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1075)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1016)
at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:118)
at com.ibm.ws.webcontainer.filter.WebAppFilterChain._doFilter(WebAppFilterChain.java:87)
at com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:771)
at com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:679)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:546)
at com.ibm.ws.wswebcontainerservlet.ServletWrapper.handleRequest(ServletWrapper.java:478)
at com.ibmws.webcontainer.webapp.WebAppRequestDispatcher.forward(WebAppRequestDispatcher.java:321)
at com.advtechgrp.bop.medical.web.filter.UrlRewritingFilter.doFilter(UrlRewritingFilter.java:132)
at com.ibm.ws.webcontainer.filterFilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:190)
at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:130)
at com.advtechgrp.bop.medical.web.filter.GZIPFilter.doFilter(GZIPFilter.java:36)
at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:190)
at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:130)
at com.advtechgrp.bop.medical.web.filter.WebLogFilter.doFilter(WebLogFilter.java:69)
at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:190)
at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:130)
at com.advtechgrp.bop.medical.web.filter.SecurityFilter.doFilter(SecurityFilter.java:174)
at com.ibm.ws.webcontainerfilter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:190)
at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:130)
at com.ibm.ws.webcontainer.filter.WebAppFilterChain._doFilter(WebAppFilterChain.java:87)
at com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:771)
at com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:679)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:546)
at com.ibm.ws.wswebcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:478)
at com.ibm.ws.webcontainer.servlet.CacheServletWrapper.handleRequest(CacheServletWrapper.java:90)
at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:744)
at com.ibm.ws.wswebcontainer.WebContainer.handleRequest(WebContainer.java:1455)
at com.ibmws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:115)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:458)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewInformation(HttpInboundLink.java:387)
at com.ibm.ws.http.channel.inbound.impl.HttpICLReadCallback.complete(HttpICLReadCallback.java:102)
at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:165)
at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:136)
at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:195)
at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:743)
at com.ibmio.async.ResultHandler$2.run(ResultHandler.java:873)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1473)
</pre>
<p>Thanks,<br />
Tom</p>
| <p>This is caused by the backing store of the iterator being altered while the iterator is in use. This is not a concurrency problem related to threading, as it is easy enough to do on a single thread as well.</p>
<p>More detailed description on this <a href="http://stackoverflow.com/questions/602636/concurrentmodificationexception-and-a-hashmap/602660#602660">question</a></p>
<p>Your biggest problem now will be if it is fixable by you or a bug in the Jasper code.</p>
|
Why does this WSDL file generate an empty service proxy in VS2008? <p>Why does <a href="http://services.fliqz.com/searchservice/20071001/service.svc?wsdl" rel="nofollow">this WSDL file</a> generate an empty service proxy in VS2008?</p>
<p>If you look at the Reference.cs file generated, it's empty. Any ideas?</p>
| <p>right click on service reference , cofigure , un-check âReuse types in referenced assemblesâ and click OK. Try to Update Service Reference. This worked for me!</p>
|
How can I have an abstract and introduction on the same page of a Latex document? <p>I need to change the layout of my document to send my paper to a conference. My abstract is currenly on a separate page. The introduction should be straight after the abstract, not on the separate pages. </p>
<blockquote>
<p>How can I have an abstract and an introduction on the same page? </p>
</blockquote>
| <p>The conference should provide with at least information on how to format your paper, and often they have LaTeX styles ready, for instance <a href="http://www.ieee.org/web/publications/authors/index.html" rel="nofollow">at IEEE</a>, or <a href="http://www.acm.org/publications/latex%5Fstyle/" rel="nofollow">at ACM</a> (btw, the IEEEtran class is bundled in TeXlive).</p>
<p>They are pretty standard customizations of the basic article class from LaTeX and actually I never saw one format the abstract on a separate page.</p>
|
Automatic Hibernate Transaction Management with Spring? <p>How far does the spring framework go with transaction handling? My reading of the book "Spring In Action" suggestions with its examples that you create DAO methods that don't worry about Session and Transaction management fairly simply by setting up a session factory and transaction template in XML and then wiring them into your DAO. SpringSource.org's documentation, on the other hand, suggests that need tons of XML and/or annotation to make this happen.</p>
<p>What is the truth here, what is the simplest way I can take code along the lines of</p>
<pre><code>get session from sessionfactory
open transaction
preform database actions
commit transaction with error handling
</code></pre>
<p>and make it just</p>
<pre><code>preform database actions
</code></pre>
<p>reducing the amount of boiler plate transactional code that I have across my methods to a minimum?</p>
| <p>There is some work you are supposed to do to be able to do just that but it's not much at all. Supposedly, you will use JPA with pick your own provider, e.g. Hibernate. Then you need to place persistence.xml that defines the persistence unit in the META-INF folder:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
<persistence-unit name="YourDatabasePersistenceUnitName" transaction-type="RESOURCE_LOCAL"/>
</persistence>
</code></pre>
<p>Next, define everything necessary for database connection in the Spring application context you use, at minimum it should contain these:</p>
<pre><code><bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>/WEB-INF/jdbc.properties</value>
</property>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" scope="singleton">
<property name="driverClassName" value="org.postgresql.Driver"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="YourDatabasePersistenceUnitName"/>
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="POSTGRESQL" />
<property name="databasePlatform" value="org.hibernate.dialect.PostgreSQLDialect"/>
<property name="showSql" value="true"/>
<property name="generateDdl" value="false"/>
</bean>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
</code></pre>
<p>Some properties above may be changed or added depending on your needs. The example is for JPA with Hibernate and PostgreSQL database as you may have guessed. </p>
<p>Now you can simply define your data access methods like this:</p>
<pre><code>@Repository
@Transactional
public class UserJpaDAO {
protected EntityManager entityManager;
@PersistenceContext
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
public void save(User theUser) {
entityManager.persist(theUser);
}
public User update(User theUser) {
return entityManager.merge(theUser);
}
}
</code></pre>
<p>where User is a JPA entity defined by your application. You may manager transactions at manager/controller layer that calls your DAOs - in fact I do it that way - but I placed it together here not to clutter example too much. </p>
<p>Nice references that you may want to go straight to instead of my examples is
<a href="http://icoloma.blogspot.com/2006/11/jpa-and-spring-fucking-cooltm_26.html">http://icoloma.blogspot.com/2006/11/jpa-and-spring-fucking-cooltm_26.html</a>
The top 3 links it references are worth going to as well.</p>
|
How do I dynamically create multiple controls in Silverlight? <p>I know how to create a list of Controls and add new instances of them to it:</p>
<pre><code>private List<FirstCircleControl> Circles = new List<FirstCircleControl>();
FirstCircleControl mc = new FirstCircleControl();
Circles.Add(mc);
</code></pre>
<p>I want to add a whole bunch of "FirstCircleControls". How would I add 10 controls to my list? I want to be able to "create" and then "add" them to the list using a loop.</p>
| <p>I wonder why you might need to create them all at once and then add them to the list, but here's a solution:</p>
<pre><code>Enumerable.Range(0, 10)
.Select(x => new FirstCircleControl())
.ToList() // Forces creation of controls.
.ForEach(x => Circles.Add(x)); // Adds them to the list.
</code></pre>
|
Dummy Item in ComboBox <p>I've reached the time for a design decision on how to indicate 'none selected' in a data bound ComboBox. I wish to apply this to all future occurrences where a ComboBox needs this. One cannot set SelectedIndex to -1 on data bound combos, nor can one set SelectedValue to null.</p>
<p>Commonly suggested solutions are to add a dummy row to the combo, but without knowledge of the objects bound to rows, a combo cannot reliably create a dummy object in such a way as to display the 'none selected' message. I don't want to add another item on the data source, as this will compromise the list for other clients that don't use a dummy object.</p>
<p>What other options are there? BTW, I'm using a Telerik RadComboBox, but this scenario is not specific to the Telerik control.</p>
| <p>You can define the "empty item" in the markup, and append any data-bound items:</p>
<pre><code><asp:DropDownList DataSourceID="..." AppendDataBoundItems="true" ...>
<asp:ListItem Value="-1" Text="None"></asp:ListItem>
</asp:DropDownList>
</code></pre>
<p>The key is to specify <strong>AppendDataBoundItems="true"</strong> to append the data-bound items to any items that were specified directly in the markup.</p>
<p>This works for the standard ASP.NET DropDownList but also for the Telerik RadComboBox.</p>
|
Finding when an Iframe's content changes when in designMode <p>I have an Iframe which I have enabled <a href="http://www.mozilla.org/editor/midas-spec.html" rel="nofollow">designMode</a> on. Quite simply I would like to have a callback function called if the cursor in the Iframe moves or content changes. It seemed quite simple at first but I can't use onchange/ onkeyup on the Iframe.</p>
<p>I assume I need to add an event to a member of the Iframe. I've tried</p>
<pre><code>frames['writer'].document.body.onkeyup = eventHandler
</code></pre>
<p>to no success.</p>
<p><hr /></p>
<p><strong>Update</strong></p>
<p>I've found that setting <code>designMode = 'on'</code> is causing the problems. If I comment out the line that sets designMode to <code>'on'</code> then handling events works fine.</p>
| <p>OK, I have a solution:</p>
<pre><code>if(document.addEventListener)
{
frames['writer'].document.addEventListener('keyup', updateStatus, false);
frames['writer'].document.addEventListener('mouseup', updateStatus, false);
}
</code></pre>
<p>It works a charm!</p>
|
How do I link a dynamic library with qmake into my app? <p>In my qmake .pro file I add my desired dynamic library to LIB which allows for compilation but doesn't link to the library in the compiled application (i.e. I get a library not found error at run time).</p>
<p>The problem is that I have the library in my build directory, not in the system directory (i.e. /usr/lib). But, I want to generate a OSX app that doesn't touch the system outside of the .app folder.</p>
<p>Also, I'd link to know how to do this on a linux system - is it possible?</p>
<p>My question is related to the <a href="http://stackoverflow.com/questions/26904/getting-qmake-to-generate-a-proper-app">Qmake generating a proper .app question</a> but differs in that the link that answers that question doesn't answer my question.</p>
| <p>Put a wrapper script round your program so the current working directory is in the dynamic library search path:</p>
<pre><code>#!/bin/bash
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:.
./program
</code></pre>
|
Definitive dot.net Single Sign-On Solution - Develop, Steal, or Buy? <p>The problem: We have several dozen one off applications in our environment scattered across a dozen servers. Some apps are secured with one-off form/db based logins. Some apps have permissions defined in web.config. Some apps have folder level NTFS permissions set (some with domain user accounts, some with local user accounts for external users). Needless to say, this is an absolute mess. </p>
<p>An SSO solution is definitely in order, but should I build one, leverage an existing FOSS one, or buy one (and if so, which ones?)</p>
<p>I need to be able to</p>
<ul>
<li>authenticate once via form login and naturally the login token would carry from server to server</li>
<li>mix-and-match domain accounts (preferred) and create db table accounts for external users</li>
<li>have centralized role/permission management</li>
<li>in situations where users authenticate with an AD/domain account, use this same account to allow whatever application they're using to connect to a database via integrated authentication</li>
<li>a portal would be nice</li>
</ul>
<p>If someone would provide some direction I'd be much obliged.</p>
| <p>ISA Server 2006 might be what you're looking for. (roughly.).<br />
See: <a href="http://www.microsoft.com/forefront/edgesecurity/isaserver/en/us/default.aspx" rel="nofollow">http://www.microsoft.com/forefront/edgesecurity/isaserver/en/us/default.aspx</a></p>
<p>This can support forms based authentication, as well as SSO against active directory.</p>
<p>It will require some standardization to your existing systems, however I would prefer this route, to writing your own.</p>
<p>Relating to the critieria:</p>
<ul>
<li>ISA Server 2006 can do this.</li>
<li>I'm not entirely sure what you mean by the first part of this, however you mentioned AD use later, I would suggest you consolidate all security into Active directory, including external users, and permissions, and use that as your primary tool for managing them.</li>
<li>See point above.</li>
<li>This is fine, you just need to configure your IIS/web.config's accordingly.</li>
<li>Not sure if you want to create a portal, or if you want the tool to use a portal as it's UI?</li>
</ul>
|
How do I design a sub class with features not available in the base class? <p>For example suppose I have a class Vehicle and I wish for a subclass ConvertibleVehicle which has extra methods such as foldRoof(), turboMode(), foldFrontSeats() etc. I wish to instantiate as follows</p>
<pre><code>Vehicle convertible = new ConvertibleVehicle()
</code></pre>
<p>so I still have access to common method such as openDoor(), startEngine() etc. How do I designed such a solution?</p>
<p>To clarify my two initial solutions, neither of which I am happy with are:</p>
<ol>
<li>Have dummy methods foldRoof(), turboMode(), foldFrontSeats() which I override in ConvertibleVehicle only, leaving them to do nothing in other subclasses</li>
<li>Have abstract methods foldRoof(), turboMode(), foldFrontSeats() and force each subclass to provide an implementation even if it will be blank in all instances other than ConvertibleVehicle</li>
</ol>
<p>The above seem slightly convoluted since they both pollute the base class as I add an increasing number of subclasses each with their own unique functions</p>
<p>After reading some of the responses perhaps there is some type of fundamental flaw in my design. Suppose I have a class VehicleFleet which takes vehicles and instructs them to drive as follows:</p>
<pre><code>public VehicleFleet(Vehicle[] myVehicles) {
for (int i=0; i < myVehicles.length; i++) {
myVehicles[i].drive();
}
}
</code></pre>
<p>Suppose this works for dozens of subclasses of Vehicle but for ConvertibleVehicle I also want to fold the roof before driving. To do so I subclass VehicleFleet as follows:</p>
<pre><code>public ConvertibleVehicleFleet(Vehicle[] myVehicles) {
for (int i=0; i < myVehicles.length; i++) {
myVehicles[i].foldRoof();
myVehicles[i].drive();
}
}
</code></pre>
<p>This leaves me with a messy function foldRoof() stuck in the base class where it doesn't really belong which is overridden only in the case of ConvertibleVehicle and does nothing in all the other cases. The solution works but seems very inelegant. Does this problem lend itself to a better architecture?</p>
<p>I'm using Java although I would hope that a general solution could be found that will work in any object oriented language and that I will not need to rely upon language specific quirks</p>
| <p>Any objects that use Vehicle shouldn't know about ConvertibleVehicle and its specialized methods. In proper loosely coupled object-oriented design Driver would only know about the Vehicle interface. Driver might call startEngine() on a Vehicle, but it's up to subclasses of Vehicle to override startEngine() to handle varying implementations such as turning a key versus pushing a button.</p>
<p>Consider reviewing the following two links which should help to explain this concept:
<a href="http://en.wikipedia.org/wiki/Liskov_substitution_principle" rel="nofollow">http://en.wikipedia.org/wiki/Liskov_substitution_principle</a>
<a href="http://en.wikipedia.org/wiki/Open/closed_principle" rel="nofollow">http://en.wikipedia.org/wiki/Open/closed_principle</a></p>
<p>Consider posting a real world problem that you feel leads to the dilemma you describe here and someone will be more than happy to demonstrate a better approach.</p>
|
Creating a Custom DTD for Visual Studio <p>I've got some custom templated controls which take JavaScript as template content, like so:</p>
<pre><code><ns:Custom runat="server">
<contentTemplate>
var a = new Array();
for (var i=0; i<a.length; i++) {
// do something
}
</contentTemplate>
</ns:Custom>
</code></pre>
<p>I want VisualStudio to treat the content of exactly the same as it does elements so that code coloring take effect and the validator doesn't puke on the "<" in the for-loop definition.</p>
<p>My understanding is that a custom DTD needs to be created to solve this. Does anybody know how to do this, have have links to resources for it?</p>
<p>Thanks!</p>
| <p>I admit I'm not familiar with VS templated controls, but this looks like XML (given the "ns:" namespace), and the standard way to embed left angle brackets inside XML, without them being treated as tags, is with CDATA:</p>
<pre><code><ns:Custom runat="server">
<contentTemplate>
<![CDATA[
var a = new Array();
for (var i=0; i<a.length; i++) {
// do something
}
]]>
</contentTemplate>
</ns:Custom>
</code></pre>
|
What is the best Java-based Mailing List application allowing opt-in/opt-out <p>I'm looking for a java-based (preferable) mailing list application that allows users to opt-in/opt-out of mailing lists. Open-source is preferable but not mandatory.</p>
<p>This product would be used to send email notifications to subscribed people when certain events happen in another application - i.e. when a new record is saved and approved with certain attributes, a message is sent to one or more mailing lists. </p>
<p>It should be able to handle multiple mailing lists and must have an interface for sending new messages programatically without the need to use it's web/gui interface.</p>
<p>A last resort would be to develop our own application to perform this functionality.</p>
| <p>I would recommend using a hosted service for email marketing. Sure, you may find just the right software for the job. The main issue is deliverability. A mailing service increases the chances of your mail reaching the destination. It also provides very useful reports of how many opened and who clicked what. IMHO, the price of those services is very much justified.</p>
<p>I'm using <a href="http://www.mailchimp.com/" rel="nofollow">MailChimp</a> and I'm happy with their service. They have an easy to use API, so you can control your campaigns programatically. I'm invoking it from Java and I'm in the process of packing my code to post it online. </p>
|
Mailing Address Verification, Etc. Get County from Zip <p>It seems fairly common today for websites to perform some address verification behind the scenes. For example, the 4 digit extension on zip codes is commonly filled in. In addition to filling in the 4 digit zip code extension, I would like to know what county the address belongs to.</p>
<p>This will be utilized in an ASP.NET 3.5 application that already has all the hooks in place for ASP.NET AJAX along with jQuery.</p>
<p>What services out there would allow for this to be done? Web services, 3rd party includes, etc.</p>
<p><strong>UI Structure</strong></p>
<pre><code>ADDRESS_LINE1
ADDRESS_LINE2
CITY
STATE
ZIP
</code></pre>
| <p>If you've got cash, <a href="http://www.softwarecompany.com/dotnet/netaddress.htm" rel="nofollow">NetAddress</a> is built for .NET.</p>
<p>It's also been asked on SO before: <a href="http://stackoverflow.com/questions/682093/address-validation-api">here</a>.</p>
|
Is it possible to make anonymous inner classes in Java static? <p>In Java, nested classes can be either <code>static</code> or not. If they are <code>static</code>, they do not contain a reference to the pointer of the containing instance (they are also not called inner classes anymore, they are called nested classes).</p>
<p>Forgetting to make an nested class <code>static</code> when it does not need that reference can lead to problems with garbage collection or escape analysis.</p>
<p>Is is possible to make an anonymous inner class <code>static</code> as well? Or does the compiler figure this out automatically (which it could, because there cannot be any subclasses)?</p>
<p>For example, if I make an anonymous comparator, I almost never need the reference to the outside:</p>
<pre><code> Collections.sort(list, new Comparator<String>(){
int compare(String a, String b){
return a.toUpperCase().compareTo(b.toUpperCase());
}
}
</code></pre>
| <p>No, you can't, and no, the compiler can't figure it out. This is why FindBugs always suggests changing anonymous inner classes to named <code>static</code> nested classes if they don't use their implicit <code>this</code> reference.</p>
<p><strong>Edit:</strong> Tom Hawtin - tackline says that if the anonymous class is created in a static context (e.g. in the <code>main</code> method), the anonymous class is in fact <code>static</code>. But the JLS <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.9.5">disagrees</a>:</p>
<blockquote>
<p>An anonymous class is never <code>abstract</code> (§8.1.1.1). An anonymous class is always an inner class (§8.1.3); it is never <code>static</code> (§8.1.1, §8.5.1). An anonymous class is always implicitly <code>final</code> (§8.1.1.2).</p>
</blockquote>
<p>Roedy Green's Java Glossary <a href="http://mindprod.com/jgloss/anonymousclasses.html">says that</a> the fact that anonymous classes are allowed in a static context is implementation-dependent:</p>
<blockquote>
<p>If you want to baffle those maintaining your code, wags have discovered <code>javac.exe</code> will permit anonymous classes inside <code>static</code> init code and <code>static</code> methods, even though the language spec says than anonymous classes are never <code>static</code>. These anonymous classes, of course, have no access to the instance fields of the object. I donât recommend doing this. The <em>feature</em> could be pulled at any time. </p>
</blockquote>
<p><strong>Edit 2:</strong> The JLS actually covers static contexts more explicitly in <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.9.2">§15.9.2</a>:</p>
<blockquote>
<p>Let <em>C</em> be the class being instantiated, and let <em>i</em> be the instance being created. If <em>C</em> is an inner class then <em>i</em> may have an immediately enclosing instance. The immediately enclosing instance of <em>i</em> (§8.1.3) is determined as follows.</p>
<ul>
<li>If <em>C</em> is an anonymous class, then:
<ul>
<li>If the class instance creation expression occurs in a static context (§8.1.3), then <em>i</em> has no immediately enclosing instance. </li>
<li>Otherwise, the immediately enclosing instance of <em>i</em> is <code>this</code>.</li>
</ul></li>
</ul>
</blockquote>
<p>So an anonymous class in a static context is roughly equivalent to a <code>static</code> nested class in that it does not keep a reference to the enclosing class, even though it's technically not a <code>static</code> class.</p>
|
Extract embedded resource without WebResource.axd <p>Are there any ways to programmatically extract an embedded resource instead of going through the WebResource.axd handler? I have the two parameters (d & t) that are passed to the WebResource.axd handler. I'm hoping there's a way I can use those parameters to extract the resource myself. Any tips are appreciated, thanks.</p>
| <p>You can use the Assembly class. The code below returns an embedded resource as a stream from the current assembly:</p>
<pre><code>using System.Reflection;
Assembly assembly = Assembly.GetExecutingAssembly();
Stream stream = assembly.GetManifestResourceStream("YourEmbeddedResource");
</code></pre>
|
Application Screen capture and rendering <p>I'm trying to write a simple app that will do a screen capture of an application and then rendering that capture in the 'main' application (ie, the application that took the screen capture). </p>
<p>I've figured out how to get the window handle and get the application's screen capture, but I'm having trouble rendering the captured screen in the 'main' application. </p>
<p>Using GDI, I have the following code to render: </p>
<pre><code>Bitmap bit(hSrcbmp,hpal);
graphics.DrawImage(&bit,Gdiplus::PointF(0,0));
</code></pre>
<p>where hSrcbmp is a bitmap of the captured screen and graphics is a GDI+ 'Graphics' object. </p>
<p>I get the following error after the constructor call to Bitmap:
Gdiplus::Image = {nativeImage=0x00000000 lastResult=Win32Error loadStatus=-858993460 }</p>
<p>*Using Visual Studio 2005 </p>
<p>*Windows XP</p>
<p>*Visual C++ (non-managed)</p>
<p>Any ideas? </p>
<p>Another question: Any better approach? C# or DirectX or openGL?
Thanks</p>
| <p>Screen capture is a Win32 FAQ for 18 years.<br />
See on <a href="http://news://nntp.aioe.org/comp.os.ms-windows.programmer.win32" rel="nofollow">win32 group</a> for standard code (MS and other), C and C++</p>
|
Best groovy closure idiom replacing java inner classes? <p>As new to groovy...</p>
<p>I'm trying to replace the java idiom for event listeners, filters, etc.</p>
<p>My working code in groovy is the following:</p>
<pre><code>def find() {
ODB odb = ODBFactory.open(files.nodupes); // data nucleus object database
Objects<Prospect> src = odb.getObjects(new QProspect());
src.each { println it };
odb.close();
}
class QProspect extends SimpleNativeQuery {
public boolean match(Prospect p) {
if (p.url) {
return p.url.endsWith(".biz");
}
return false;
}
}
</code></pre>
<p>Now, this is far from what I'm used to in java, where the implementation of the Query interface is done right inside the odb.getObjects() method. If I where to code "java" I'd probably do something like the following, yet it's not working:</p>
<pre><code>Objects<Prospect> src = odb.getObjects( {
boolean match(p) {
if (p.url) {
return p.url.endsWith(".biz");
}
return false;
}
} as SimpleNativeQuery);
</code></pre>
<p>Or better, I'd like it to be like this:</p>
<pre><code> Objects<Prospect> src = odb.getObjects(
{ it.url.endsWith(".biz") } as SimpleNativeQuery
);
</code></pre>
<p>However, what groovy does it to associate the "match" method with the outer script context and fail me. </p>
<p>I find groovy... groovy anyways so I'll stick to learning more about it. Thanks.</p>
<hr>
<p>What I should've asked was how do we do the "anonymous" class in groovy. Here's the java idiom:</p>
<pre><code>void defReadAFile() {
File[] files = new File(".").listFiles(new FileFilter() {
public boolean accept(File file) {
return file.getPath().endsWith(".biz");
}
});
}
</code></pre>
<p>Can groovy be as concise with no additional class declaration?</p>
| <p>I think it would have helped you to get answers if you'd abstracted the problem so that it didn't rely on the Neodatis DB interface -- that threw me for a loop, as I've never used it. What I've written below about it is based on a very cursory analysis.</p>
<p>For that matter, I've never used Groovy either, though I like what I've seen of it. But seeing as no one else has answered yet, you're stuck with me :-)</p>
<p>I think the problem (or at least part of it) may be that you're expecting too much of the SimpleNativeQuery class from Neodatis. It doesn't look like it even tries to filter the objects before it adds them to the returned collection. I think instead you want to use <code>org.neodatis.odb.impl.core.query.criteria.CriteriaQuery</code>. (<strong>Note the "impl" in the package path.</strong> This has me a bit nervous, as I don't know for sure if this class is meant to be used by callers. But I don't see any other classes in Neodatis that allow for query criteria to be specified.)</p>
<p>But instead of using CriteriaQuery directly, I think you'd rather wrap it inside of a Groovy class so that you can use it with closures. So, I think a Groovy version of your code with closures might look something like this:</p>
<pre><code>// Create a class that wraps CriteriaQuery and allows you
// to pass closures. This is wordy too, but at least it's
// reusable.
import org.neodatis.odb.impl.core.query.criteria;
class GroovyCriteriaQuery extends CriteriaQuery {
private final c;
QProspect(theClosure) {
// I prefer to check for null here, instead of in match()
if (theClosure == null) {
throw new InvalidArgumentException("theClosure can't be null!");
}
c = theClosure;
}
public boolean match(AbstractObjectInfo aoi){
//!! I'm assuming here that 'aoi' can be used as the actual
//!! object instance (or at least as proxy for it.)
//!! (You may have to extract the actual object from aoi before calling c.)
return c(aoi);
}
}
// Now use the query class in some random code.
Objects<Prospect> src = odb.getObjects(
new GroovyCriteriaQuery(
{ it.url.endsWith(".biz") }
)
)
</code></pre>
<p>I hope this helps!</p>
|
IPhone OpenGL ES single or multiple views? <p>I'm confused on what the best approach is when writing a game for the iphone. The game will be rendered with OpenGL , but im curious when creating the Start Screen, Menu's, High Score page, etc. Do you do all of that with OpenGL or do you create additional UIViews and use the UIKit?</p>
| <p>I don't think there is a best approach. If you have the time to code up menus and high score tables in OpenGL the you have a lot more flexibility - you could for example have a 3d animation going on in the background. </p>
<p>If you code menus, high score tables, etc. using standard UIKit views and switch out the OpenGL view while they are shown then this has the advantage that it's very quick to code (esp. if you took the time to learn to use Interface Builder), but it is inherently 2d. Even though you can still use custom button graphics and fonts to make it look less like a business app, it's still going to look less polished compared to other games in the app store.</p>
<p>What you don't want to do is to layer a transparent UIView over the top of you OpenGL view - this will be very slow. </p>
<p>I personally use Interface Builder generated views to get stuff like menus in while I'm building the rest of the program. The intention is to replace that with OpenGL animated code later. In the end though, it's really down to how much time you have available.</p>
|
The HTTP verb POST used to access path '/Membership/user/' is not allowed <p>This code: </p>
<pre><code>private void Submit_Click(object sender, RoutedEventArgs e)
{
user temp = new user();
temp.Username = UserName.Text;
temp.Password = Password.Text;
dataBase.AddTouser(temp);
IAsyncResult result = dataBase.BeginSaveChanges(new AsyncCallback (OnSaveChangesCompleted), temp);
}
void OnSaveChangesCompleted(IAsyncResult result)
{
try
{
string name = ((user) result.AsyncState).Username.ToString();
dataBase.EndSaveChanges(result);
}
catch (DataServiceRequestException ex)
{
MessageBox.Show("OnSaveChangesCompleted Error: " + ex.ToString());
}
}
</code></pre>
<p>produces this error: </p>
<p>The HTTP verb POST used to access path '/Membership/user/' is not allowed</p>
<p>I think it may have something to do with this being incorrect:</p>
<pre><code>public static void InitializeService(IDataServiceConfiguration config)
{
config.SetEntitySetAccessRule("*", EntitySetRights.All);
config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
}
</code></pre>
<p>Or it may have something to do with the ASP.NET configuration, but I am not sure what to do in there.</p>
<p>I am trying to use Silverlight, DataEntityFramework, and a WCF Service all together (for the first time) and have no idea where exactly the solution to this problem lies.</p>
| <p>I got a similar problem, it seems that there are problems with the url rewriting.</p>
<p><a href="http://www.lukemelia.com/blog/archives/2007/01/05/aspnet-the-http-verb-post-used-to-access-path-is-not-allowed/" rel="nofollow">http://www.lukemelia.com/blog/archives/2007/01/05/aspnet-the-http-verb-post-used-to-access-path-is-not-allowed/</a></p>
<p>You have to remove the mapping of â*â to aspnet_isapi.dll in yourIIS settings.</p>
|
How to delete a PHP session? <p>It's possible I'm not properly deleting PHP sessions when the user signs out. I've noticed that if I sign out and sign back in without closing the browser, the session ID doesn't change but if I sign out, close the browser window, open a new one and sign in, the session ID will be different. Do I need to be doing something different or is this normal behavior? I've been using the same process for three years but something happened recently that made me think that <em>maybe</em> I need to do something different. </p>
<p>Here's what I basically do when someone clicks Sign Out. </p>
<pre><code><?php
session_start();
if( isSet($_SESSION['FacID']) )
$facID = $_SESSION['FacID']; //Want to re-instate this after we destroy the session.
unset($_SESSION);
session_destroy();
if( isSet($_SESSION['FacID']) )
$_SESSION['FacID'] = $facID;
?>
</code></pre>
| <p>If you feel the need to force a new id
<a href="http://pl.php.net/manual/en/function.session-regenerate-id.php" rel="nofollow">http://pl.php.net/manual/en/function.session-regenerate-id.php</a></p>
<p>And to your question, from the manual:</p>
<blockquote>
<p>session_destroy() destroys all of the
data associated with the current
session. It does not unset any of the
global variables associated with the
session, or unset the session cookie.
To use the session variables again,
session_start() has to be called.</p>
<p>In order to kill the session
altogether, like to log the user out,
the session id must also be unset. If
a cookie is used to propagate the
session id (default behavior), then
the session cookie must be deleted.
setcookie() may be used for that.</p>
</blockquote>
|
Easiest way to programatically add aliases to Exchange 03/07 mailboxes? <p>We currently have a specific format for how our email addresses are defined, based upon name. This system originated some time ago and is beginning to become a bit of a hindrance. </p>
<p>We would like to move to a new format, based along the line of </p>
<pre><code><first name initial><second name initial><last name>@organisation.com
</code></pre>
<p>However, we dont just want to rename the mailboxes etc, instead we're opting to keep the existing email addresses for all current users, but using the new form for new users. In addition, we want to add a mail alias to all of the mailboxes using the legacy format.</p>
<p>Can anyone suggest a relatively straight-forward way to add these aliases via code? Pulling the user's name details is not an issue, moreso just adding the alias to the mailbox. We're currently running exchange 2003 for most users, but are on the verge of a 2007 migration, and so have the odd user on 2007 also (the two servers are running side by side at present).</p>
<p>I've read that all exchange 2007 management should be done using the 2007 tools and not active directory as was previously the case, so can all of this be performed via the exchange 2007 APIs, even for 2003 "legacy mailboxes" (as termed in exchange)?</p>
<p>Basically I'm just looking for a good direction to go here; I've never really done any coding for exchange. Thanks!</p>
| <p>Here's a MS KB that describes modifying the alias through extended MAPI. It looks like you'll need the Exchange Developers Kit to do this.</p>
<p><a href="http://support.microsoft.com/kb/183249" rel="nofollow">http://support.microsoft.com/kb/183249</a></p>
|
How do you generate a AntiForgeryToken in a code behind file? <p>I have an action that resets a user's password. In that same action after the password is reset I want to login the user. I wanted to just use a "RedirectToAction" and send the username and password to my SignIn action. Since I have logic in that action that handles errors and what not. </p>
<p>So I need to send the AntiForgeryToken value to the SignIn action also.</p>
| <p>The AntiForgeryToken is only valid for POST requests (GET requests are supposed to be idempotent... that is, not change state on the server). RedirectToAction does an HTTP/302 redirect, which is results in a GET request. Therefor, an AntiForgeryToken would make no sense for RedirectToAction.</p>
<p>I would reconsider what it is you are trying to do.</p>
<p>Remember, actions are just public methods on the controller, so you should be able to call one (and return its result) from any other action.</p>
|
What programming tools haven't been written yet? <p>What tools would you like to have to make development easier, which either don't exist yet or are too niche/un-featured to be useful. This question was prompted by <a href="http://www.red-gate.com/" rel="nofollow">Redgate</a> (no connection) who are looking to build a proper version control tool for Sql - that's been an obvious gap for years and will hopefully now be filled.</p>
<p>Joel has been after a <a href="http://www.joelonsoftware.com/articles/PleaseLinker.html" rel="nofollow">.Net static linker</a> since Jan 2004.</p>
<p>I'd personally like an <a href="http://stackoverflow.com/questions/749792/ratio-of-real-code-to-supporting-code">IDE that understood the difference between business logic and other code</a></p>
<p>What (feasible) tools would you like to see?</p>
| <p>This may sound stupid to some people, but when I was learning COBOL back in school, you could tell the IDE to step over your code line by line for you, and if you touched the mouse, the debugger would pause as if you hit a break point. There are times when I would much rather watch the debugger than press F10 repeatedly. One of my favorite features of this was you could change the stepping speed. Basically number of lines per second, or the delay in seconds between steps.</p>
<p>Or if you have a long running or complex process and you want to say test step 5, without having to rerun steps 1-4 (because they take 20 minutes to complete), being able to save the program execution at a certain point, and resume it to a particular line of code. I'm working on a tool for work right now where this would be a god send.</p>
<p>I know that VS2010 has a historical debugging feature, but I'm not sure if that only works for exceptions and not for program state.</p>
<p>I was just listening to RunAs radio Episode #<a href="http://www.runasradio.com/default.aspx?showNum=93" rel="nofollow">92</a> on Applications Compatibility and about 27 minutes into it they are talking about hard coding folder paths in applications. I really blame the tool for not providing enough guidance around that. If we can have intellisense for complex technologies like LINQ, why can't it also produce some type of warning when you do something that will hurt you down the road. There is fxcop, but you have to know to run it. It should be part of the process.</p>
<p>Maybe I'm asking too much and we need to rely on a third party for this.</p>
|
Matplotlib suddenly crashes after reinstalling Xcode? <p>I was happy in my world of python and matplotlib with a good level of familiarity. I notied Xcode on my Mac wasn't working so I installed the latest version from Apple and it somehow broke my install of matplotlib (or numpy?)! I'm now getting </p>
<pre><code>...
/sw/lib/python2.5/site-packages/matplotlib-0.91.1-py2.5-macosx-
10.5-i386.egg/matplotlib/numerix/ma/__init__.py in <module>()
14 print "using maskedarray"
15 else:
---> 16 from numpy.core.ma import *
17 #print "using ma"
18 def getmaskorNone(obj):
ImportError: No module named ma
</code></pre>
<p>I've tried reinstalling numpy (Ver 1.3.0) and matplotlib (Ver 0.91.1) to no avail. Any ideas?</p>
| <p>You're using Python from Fink, so Xcode doesn't have anything to do with it. <code>from numpy.core.ma import *</code> works fine with Apple's bundled Python and NumPy too.</p>
|
SML function call doesn't parse arguments as arguments <p>I'm getting what seems to be a precedence issue in calling an SML function, substitute:</p>
<pre><code>fun substitute v new (typevar q) = ...
</code></pre>
<p>And I am calling this from another function:</p>
<pre><code>fun new_type_vars (typevar v) non_gens =
substitute v new_var() (typevar v)
</code></pre>
<p>But I get an error:</p>
<pre>
C:/sml/type_checker.sml:22.48-23.44 Error: operator and operand don't agree [tycon mismatch]
operator domain: type_exp
operand: unit -> string
in expression:
(substitute v) new_var
</pre>
<p>Which seems to suggest that it's trying to call (substitute v), and then call the result of that call with argument new_var. </p>
<p>I've tried adding parentheses around the whole thing, but that doesn't help, and when I add parenthesis around the arguments like <code>(v new_var...)</code> it thinks that v is a function application on new_var. What's going on with this function call?</p>
| <p>I don't understand everything, since you don't give all the types of the different operations and variables.</p>
<p>But the general problem you've got is as you already guessed, SML executes the function calls (and binds the variables) from the left side. Here an example:</p>
<pre><code>fun f a:int b:int c:string = ...
</code></pre>
<p>f is thus a function of the type int -> int -> string -> ... and implicitly adds the parentheses fun (((f a:int) b:int) c:int) = ...</p>
<p>This means you can use it for example like this:</p>
<pre><code>var f2 = f 3;
</code></pre>
<p>And f2 has now the type int -> string -> ...</p>
|
How can I deduce a day for a date object in javascript? <p>How can I deduce a day for a date object in javascript?</p>
<p>Example:</p>
<p>If I assig a date into an object as below:
var date_value = this.cfg.getProperty(cfgPageDate);</p>
<p>and the date format in date_value as below:
Fri May 29 2009 00:00:00 GMT+1000 (AUS Eastern Standard Time)</p>
<p>how can I deduce a day from this object so that the object date will become as below:<br />
Thu May 28 2009 00:00:00 GMT+1000 (AUS Eastern Standard Time)</p>
| <pre><code>var dat = new Date('2009/05/29');
alert (dat.setDate(dat.getDate()-1));
</code></pre>
|
How to move a Grid Panel in WPF Window <p>HI,</p>
<p>How do I move (drag) a Grid Panel inside a WPF Window? The Grid Panel does not have a Position or Location or X and Y coordinate porperty. All I am looking at is to move the Grid Panel from its current location to a new location using Mouse so that the controls that are "burried" underneath it will show up.</p>
<p>Any pointers?</p>
<p>Many Thanks.</p>
| <p>Here's some code examples to get you started:</p>
<p>In XAML:</p>
<p>Create a grid and define a render transform on it:</p>
<pre><code><Grid x:Name="grid" Background="Blue"
Width="100" Height="100"
MouseDown="Grid_MouseDown" MouseMove="Grid_MouseMove" MouseUp="Grid_MouseUp">
<Grid.RenderTransform>
<TranslateTransform x:Name="tt"/>
</Grid.RenderTransform>
</Grid>
</code></pre>
<p>Name the control that you want the grid to move within:</p>
<pre><code><Window x:Name="window" ...>
<Grid x:Name="grid"...
</Window>
</code></pre>
<p>In code behind:</p>
<pre><code>Point m_start;
Vector m_startOffset;
private void Grid_MouseDown(object sender, MouseButtonEventArgs e)
{
m_start = e.GetPosition(window);
m_startOffset = new Vector(tt.X, tt.Y);
grid.CaptureMouse();
}
private void Grid_MouseMove(object sender, MouseEventArgs e)
{
if (grid.IsMouseCaptured)
{
Vector offset = Point.Subtract(e.GetPosition(window), m_start);
tt.X = m_startOffset.X + offset.X;
tt.Y = m_startOffset.Y + offset.Y;
}
}
private void Grid_MouseUp(object sender, MouseButtonEventArgs e)
{
grid.ReleaseMouseCapture();
}
</code></pre>
|
asp.net gridview control does not show paging numbers <p>My asp.net site has master page. On one of the pages that use master page, I have 2 grid view controls. Both are tied to their own datasourcecontrols. I tried to enable paging on the grid but paging does not show up. </p>
<p>please help. </p>
| <p>Try setting the PageSize property to something small, like 5, and see if it comes or not.</p>
<p>Also try setting the <code>AllowCustomPaging="true"</code> property.</p>
|
Problems building VS database project on TFS build server <p>I have two Visual Studio database projects. Both build fine on my local dev environment.
On the TFS build server, with a TFS build solution containing both projcets, one builds fine and the other fails with this error:</p>
<pre><code>Task "SqlBuildTask"
Creating a model to represent the project...
C:\Program Files\MSBuild\Microsoft\VisualStudio\v9.0\TeamData\Microsoft.Data.Schema.SqlTasks.targets(58,5): error MSB4018: The "SqlBuildTask" task failed unexpectedly.
C:\Program Files\MSBuild\Microsoft\VisualStudio\v9.0\TeamData\Microsoft.Data.Schema.SqlTasks.targets(58,5): error MSB4018: System.NullReferenceException: Object reference not set to an instance of an object.
C:\Program Files\MSBuild\Microsoft\VisualStudio\v9.0\TeamData\Microsoft.Data.Schema.SqlTasks.targets(58,5): error MSB4018: at Microsoft.Data.Schema.Tasks.TaskHostLoader.Load(ITaskHost providedHost, TaskLoggingHelper providedLogger)
C:\Program Files\MSBuild\Microsoft\VisualStudio\v9.0\TeamData\Microsoft.Data.Schema.SqlTasks.targets(58,5): error MSB4018: at Microsoft.Data.Schema.Tasks.DBBuildTask.Execute()
C:\Program Files\MSBuild\Microsoft\VisualStudio\v9.0\TeamData\Microsoft.Data.Schema.SqlTasks.targets(58,5): error MSB4018: at Microsoft.Build.BuildEngine.TaskEngine.ExecuteInstantiatedTask(EngineProxy engineProxy, ItemBucket bucket, TaskExecutionMode howToExecuteTask, ITask task, Boolean& taskResult)
</code></pre>
<p>I've noticed the following difference in the build log, which I think is relevant, but I don't know what is causing it.</p>
<p>Good project:</p>
<pre><code>Overriding target "Build" in project "C:\Windows\Microsoft.NET\Framework\v3.5\Microsoft.Common.targets" with target "Build" from project "C:\Program Files\MSBuild\Microsoft\VisualStudio\v9.0\TeamData\Microsoft.VisualStudio.TeamSystem.Data.Tasks.targets".
</code></pre>
<p>Failing project:</p>
<pre><code>Overriding target "Build" in project "C:\Windows\Microsoft.NET\Framework\v3.5\Microsoft.Common.targets" with target "Build" from project "C:\Program Files\MSBuild\Microsoft\VisualStudio\v9.0\TeamData\Microsoft.Data.Schema.Common.targets".
</code></pre>
<p>Both DB projects include the following import (only):</p>
<pre><code><Import Project="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v9.0\TeamData\Microsoft.Data.Schema.SqlTasks.targets" />
</code></pre>
<p>Clues welcome!</p>
| <p>Ahh, the problem was that I didn't have the GDR release installed on the build server.
One project was created with VSDB RTM, the other with VSDB GDR.</p>
<p>If only there were better error messages to help diagnose this!</p>
|
Best way of dynamically setting color of control at runtime <p>I currently load controls at run time, and want to set the color, but not a named color.
I was thinking I need to create a color object , set the color of this then assign it, any direction?
Thanks</p>
| <p>You can use Color.FromName() method to set colors : </p>
<pre><code>txt.ForeColor = System.Drawing.Color.FromName("#00B300");
txt.ForeColor = System.Drawing.Color.FromName("red");
</code></pre>
|
Notification message using php <p>I am developing an application in php. I need to display a notification message on windows taskbar. So please help me...How to do it using php.</p>
| <p>With PHP, your domain is the web browser. You can display a message in the browser or in a pop up window. You can't connect to the operating system.</p>
|
Silverlight child windows in MVVM pattern <p>I am trying to find the right way to get the data from a ChildWindow/popup using a MVVM pattern in Silverlight (3). For example: I have a main page with a data entry form and I want to open a popup with a list of customers. When user selects a customer I want to transfer selected customer into the main page. This is what the (example) code which I am using at the moment:</p>
<p><strong>Main page</strong></p>
<pre><code>public partial class MainPage : UserControl
{
public MainPageViewModel ViewModel { get; private set; }
public MainPage()
{
InitializeComponent();
ViewModel = new MainPageViewModel();
DataContext = ViewModel;
}
private void SearchCustomer_Click(object sender, RoutedEventArgs e)
{
ViewModel.SearchCustomer();
}
}
public class MainPageViewModel: ViewModel
{
private string customer;
public string Customer
{
get { return customer; }
set { customer = value; RaisePropertyChanged("Customer"); }
}
public void SearchCustomer()
{
// Called from a view
SearchWindow searchWindow = new SearchWindow();
searchWindow.Closed += (sender, e) =>
{
if ((bool)searchWindow.DialogResult)
{
Customer = searchWindow.ViewModel.SelectedCustomer.ToString();
}
};
searchWindow.Show();
}
}
</code></pre>
<p><strong>Child window</strong></p>
<pre><code>public partial class SearchWindow : ChildWindow
{
public SearchWindowViewModel ViewModel { get; private set; }
public SearchWindow()
{
InitializeComponent();
ViewModel = new SearchWindowViewModel();
DataContext = ViewModel;
}
private void OKButton_Click(object sender, RoutedEventArgs e)
{
DialogResult = ViewModel.OkButtonClick();
}
private void CancelButton_Click(object sender, RoutedEventArgs e)
{
DialogResult = ViewModel.CancelButtonClick();
}
}
public class SearchWindowViewModel: ViewModel
{
private Customer selectedCustomer;
private ObservableCollection<Customer> customers;
public ObservableCollection<Customer> Customers
{
get { return customers; }
set {customers = value; RaisePropertyChanged("Customers"); }
}
public Customer SelectedCustomer
{
get { return selectedCustomer; }
set { selectedCustomer = value; RaisePropertyChanged("SelectedCustomer"); }
}
public SearchWindowViewModel()
{
Customers = new ObservableCollection<Customer>();
ISearchService searchService = new FakeSearchService();
foreach (Customer customer in searchService.FindCustomers("dummy"))
Customers.Add(customer);
}
public bool? OkButtonClick()
{
if (SelectedCustomer != null)
return true;
else
return null; // show some error message before that
}
public bool? CancelButtonClick()
{
return false;
}
}
</code></pre>
<p>Is this the right way or is there anything more "simple"?</p>
<p>Cheers,
Rok</p>
| <p>More problematic here is the use of View specific terms and types in your VMs. Click events, DialogResults should not be anywhere near your ViewModels. </p>
<p>With regards to the question, I had a similiar question about this here:
<a href="http://stackoverflow.com/questions/454868/handling-dialogs-in-wpf-with-mvvm">http://stackoverflow.com/questions/454868/handling-dialogs-in-wpf-with-mvvm</a></p>
<p>The answer I accepted was the use of the Mediator pattern to get around this. Have a look. :)</p>
|
How do I connect to a CRM IFD web service? <p>I have taken the code from the SDK and made just one modification to set the authentication type but when I try to connect I get an "Unauthorized" error.</p>
<p>My code is:</p>
<pre><code>// Set up the CRM Service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
token.AuthenticationType = 2;
token.OrganizationName = "TESTCRM";
CrmService service = new CrmService();
service.Url = "https://testcrm.ifdtestsystem.com/MSCrmServices/2007/CrmService.asmx";
service.CrmAuthenticationTokenValue = token;
//service.Credentials = System.Net.CredentialCache.DefaultCredentials;
service.Credentials = new NetworkCredential("Bill", "Password");
// Create an account entity and assign data to some attributes.
account newAccount = new account();
newAccount.name = "Greg Bike Store";
newAccount.accountnumber = "123456";
newAccount.address1_postalcode = "98052";
newAccount.address1_city = "Redmond";
// Call the Create method to create an account.
Guid accountId = service.Create(newAccount);
</code></pre>
| <p>When using SPLA (IFD) you need to also populate the token with a crmticket.The ticket can be retrieved by quering the CrmDiscoveryService. </p>
|
How to implement a Keyword Search in MySQL? <p>HI all,
I am really a new sq l programmer, can some one help me in solving this.
I have a table job where the fields are id,position,category,location,salary range, description, refno.
I want to implement a <strong>keyword search</strong> from the front end. The keyword can be reside in any of the field of the said table.</p>
| <p>For a single keyword on VARCHAR fields you can use <a href="http://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html"><code>LIKE</code></a>:</p>
<pre><code>SELECT id, category, location
FROM table
WHERE
(
category LIKE '%keyword%'
OR location LIKE '%keyword%'
)
</code></pre>
<p>For a description you're usually better adding a full text index and doing a <a href="http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html">Full-Text Search</a> (MyISAM only):</p>
<pre><code>SELECT id, description
FROM table
WHERE MATCH (description) AGAINST('keyword1 keyword2')
</code></pre>
|
Where do you put your SQL Queries? <p>We are using a mix of EJB 2.1 and JDBC to access our Database. </p>
<p>I just had a co-worker mention the idea to put his SQL Queries into a .properties file. </p>
<p>How and Where do you put your SQL Queries?</p>
<p>EDIT: </p>
<p>Do you inline it with the code, put into the class instantiation?</p>
| <p>In <a href="http://en.wikipedia.org/wiki/Data_Access_Object" rel="nofollow">DAOs</a> since I consider them part of my application and not a configurable (changeable by a sysadmin) element of the application.</p>
|
Using Codedom to write VB.Net Properties <p>Looking at the example code on <a href="http://msdn.microsoft.com/en-us/library/system.codedom.codepropertysetvaluereferenceexpression%28loband%29.aspx" rel="nofollow">MSDN</a>:</p>
<p>This </p>
<pre><code> ' Declares a type.
Dim type1 As New CodeTypeDeclaration("Type1")
' Declares a constructor.
Dim constructor1 As New CodeConstructor
constructor1.Attributes = MemberAttributes.Public
type1.Members.Add(constructor1)
' Declares an integer field.
Dim field1 As New CodeMemberField("System.Int32", "integerField")
type1.Members.Add(field1)
' Declares a property.
Dim property1 As New CodeMemberProperty
property1.Name = "integerProperty"
property1.Type = New CodeTypeReference(GetType(Integer))
' Declares a property get statement to return the value of the integer field.
property1.GetStatements.Add(New CodeMethodReturnStatement(New CodeFieldReferenceExpression(New CodeThisReferenceExpression, "integerField")))
' Declares a property set statement to set the value to the integer field.
' The CodePropertySetValueReferenceExpression represents the value argument passed to the property set statement.
property1.SetStatements.Add(New CodeAssignStatement(New CodeFieldReferenceExpression(New CodeThisReferenceExpression, "integerField"), New CodePropertySetValueReferenceExpression))
type1.Members.Add(property1)
Dim dump As New VBCodeProvider
Dim gen As Compiler.ICodeGenerator = dump.CreateGenerator
Dim opt As New Compiler.CodeGeneratorOptions
gen.GenerateCodeFromType(type1, Console.Out, opt)
</code></pre>
<p>should generate</p>
<pre><code>Public Class Type1
Private integerField As Integer
Public Sub New()
MyBase.New()
End Sub
Private Property integerProperty() As Integer
Get
Return Me.integerField
End Get
Set(ByVal Value As Integer)
Me.integerField = value
End Set
End Property
End Class
</code></pre>
<p>But I'm not seeing it generate the parameter to the Set method, I.e. I get:</p>
<pre><code> Set
Me.integerField = value
End Set
</code></pre>
<p>Given that I already had to add in bits to the example code to actually name the property to match their example output, I suspect that there is a detail missing that is causing this, but I can't seem to track it down? Whilst the code compiles, I'm unable to use the properties without manually adding in the parameters, which defeats the purpose somewhat. Any idea what is missing?</p>
| <p>Comment #3 on <a href="http://www.devcity.net/Articles/71/codedom%5F1.aspx" rel="nofollow">this DevCity article</a> suggests it shouldn't matter, but I do know that <a href="http://www.red-gate.com/products/reflector/" rel="nofollow">Reflector</a> does behave as you're expecting, although it <em>may</em> have it's own implementation for code generation...</p>
|
Unexpected result from sys.getrefcount <p>When I typed:</p>
<pre><code>>>> astrd = 123
>>> import sys
>>> sys.getrefcount(astrd)
3
>>>
</code></pre>
<p>I am not getting where is <code>astrd</code> used 3 times ?</p>
| <p>It's not <code>astrd</code> that is referenced three times, but the value <code>123</code>. <code>astrd</code> is simply a name for the (immutable) number 123, which can be referenced however many times. Additionally to that, small integers are usually shared:</p>
<pre><code>>>> astrd = 123
>>> sys.getrefcount(astrd)
4
>>> j = 123
>>> sys.getrefcount(astrd)
5
</code></pre>
<p>In the second assignment, no new integer is created, instead <code>j</code> is just a new name for the integer <code>123</code>.</p>
<p>However, given very large integers, this does not hold:</p>
<pre><code>>>> i = 823423442583
>>> sys.getrefcount(i)
2
>>> j = 823423442583
>>> sys.getrefcount(i)
2
</code></pre>
<p>Shared integers are an implementation detail of CPython (among others). Since small integers are instantiated very often, sharing them saves a lot of memory. This is made possible by the fact that integers are immutable in the first place.</p>
<p>For the additional reference in the second example, cf. <a href="http://stackoverflow.com/questions/759740/sys-getrefcount/759763#759763">codeape's answer</a>.</p>
|
Is Apache XML security library compatibile with IBM's JDK <p>I developed an application that uses Apache XML security library for xml encryption and signing. It runs on SUN's JDK without any problems, however, IBM JDK gives me tons of problems. </p>
<p>It doesn't sign right (validation fails), pkcs11 provider fails to encrypt.</p>
<p>It seems that problem is because IBM provides their own security providers.
I tried to comment out those providers (namely fips), and I almost managed to get same behaviour as on sun's jdk, except pkcs11 provider, which alwasy fails.</p>
<p>Any suggestions?</p>
| <p>Does this thread help - <a href="http://www.ibm.com/developerworks/forums/message.jspa?messageID=1315965" rel="nofollow">http://www.ibm.com/developerworks/forums/message.jspa?messageID=1315965</a>?</p>
<p>I had trouble in the past with an SSL enabled web application in Apache Tomcat because Tomcat defaults to using algorithm=SunX509 when you define a secure Connector. When using the IBM JDK, you must override by explicitly using algorithm=Ibmx509.</p>
<p>I'm guessing there's a similar issue at the root of your problem.</p>
|
Storing arbitrary meta-data in Microsoft Word document <p>I need to store custom meta-data in a Word document. The 'document properties' are limited to 255 bytes but I have data which is >> 10k</p>
<p>We are using VBA to write a word extension to interact with our application and want to have our application data stored in the word document. The idea is that that the user can share just the word document without sharing any other data files of our application.</p>
<p>Has anyone ideas how to store arbitrary meta-data efficently in Office 2003+ documents?</p>
| <p>Just tried this in the VBA editor immediate window:</p>
<pre><code>ActiveDocument.Variables.Add "foo", String(10000, ".")
? Len(ActiveDocument.Variables("foo"))
10000
</code></pre>
<p>Document variables are stored with the document. They seem to go up to 65280 Unicode characters, as I just found out (tested in Word 2003; <strong>Update:</strong> This limit is the same in Word 2007 and 2010).</p>
<p>If you fear to get near the 60k for your data, I'd recommend either splitting it over several variables, or compressing it before you store it. <a href="http://stackoverflow.com/questions/167888/how-can-i-gzip-compress-a-file-from-excel-vba-using-code-in-an-xla-file-only/168539#168539">This post</a> shows some options to do that in VBA.</p>
|
add request to django model method? <p>I'm keeping track of a user status on a model. For the model 'Lesson' I have the status 'Finished', 'Learning', 'Viewed'. In a view for a list of models I want to add the user status. What is the best way to do this?</p>
<p>One idea: Adding the request to a models method would do the trick. Is that possible?</p>
<p>Edit: I meant in templatecode: {{ lesson.get_status }}, with get_status(self, request). Is it possible? It does not work (yet).</p>
| <p>If your status is a value that changes, you have to break this into two separate parts.</p>
<ol>
<li><p>Updating the status. This must be called in a view function. The real work, however, belongs in the model. The view function calls the model method and does the save.</p></li>
<li><p>Displaying the status. This is just some string representation of the status.</p></li>
</ol>
<p>Model</p>
<pre><code>class MyStatefulModel( models.Model ):
theState = models.CharField( max_length=64 )
def changeState( self ):
if theState is None:
theState= "viewed"
elif theState is "viewed":
theState= "learning"
etc.
</code></pre>
<p>View Function</p>
<pre><code> def show( request, object_id ):
object= MyStatefulModel.objects.get( id=object_id )
object.changeState()
object.save()
render_to_response( ... )
</code></pre>
<p>Template</p>
<pre><code> <p>Your status is {{object.theState}}.</p>
</code></pre>
|
Need user to input string /check string length (C++) <p>I'll need to accept a string of 5 numbers from the user (only 5).
Should I use </p>
<pre><code>istringstream
</code></pre>
<p>for the same ?</p>
<p>Can't I get away with something like this ?</p>
<pre><code>int main()
{
char *InputMain;
InputMain=(char *)malloc(5+1);
cout << "Enter the number : " <<endl;
cin.getline ( InputMain, 5, '\n' ); // Input goes into InputMain
cout << "The number entered is : " << InputMain <<endl;
cin.get();
}
</code></pre>
<p>Then comes the next part..</p>
<p>How'd I make sure the user inputs only 5 chars? And maybe if the user enters more than 5 chars, I should display a warning saying only 5 chars allowed..</p>
<p>One more question, since this essentially is a string, I'll need to validate the input to be only numbers by parsing through each char in the string and checking against respective ASCII values (for numerals).. Is that approach the right thing?</p>
| <p>Unfortunately there is no portable way to restrict the number of characters input in C++. But whatever platform you are using will provide some mechanism: for example on Windows, look up <a href="http://msdn.microsoft.com/en-us/library/ms682073(VS.85).aspx" rel="nofollow">Console functions</a>.</p>
<p>If you do go with plain old C++ iostreams input from <code>cin</code>, it's a good idea to read the initial text into a <code>std::string</code> using <code>istream& getline(istream&, string&)</code> -- this will prevent buffer overflows, because <code>string</code>s resize as necessary. (Your code involving <code>getline(InputMain, 5, '\n')</code> is technically safe in that it won't read more than 5 characters into <code>InputMain</code>, but this code is fragile -- if you later decide you want 6 characters, you could easily forget to update your call to <code>malloc()</code>, leading to crashes. Also, you need to remember to <code>free(InputMain)</code>. But as I said, use <code>string</code> instead.)</p>
<p><strong>Regarding parsing:</strong></p>
<p>Whether you read the input into a <code>string</code> using <code>getline(cin, str)</code> or some platform-specific code, once it's in there you need to get it out in the form of a number. This is where the <code>istringstream</code> class is useful -- it lets you treat an existing <code>string</code> as a stream to read from, so you can use the formatted input <code>>></code> operator:</p>
<pre><code>string str;
if (!getline(cin, str)) {
cerr << "Something went seriously wrong...\n";
}
istringstream iss(str);
int i;
iss >> i; // Extract an integer value from the stream that wraps str
if (!iss) {
// Extraction failed (or a more serious problem like EOF reached)
cerr << "Enter a number dammit!\n";
} else if (i < 1000 || i > 9999) {
cerr << "Out of range!\n";
} else {
// Process i
}
</code></pre>
<p>If you're using C++ iostreams, you can actually just extract directly from <code>cin</code> instead of going via a <code>string</code> and an <code>istringstream</code>:</p>
<pre><code>int i;
cin >> i; // Extract an integer value from cin
</code></pre>
<p>However this can have subtle undesirable effects; notably, any additional characters on the line typed by the user (in particular the <code>'\n'</code> typed when they press Enter) will remain in the input buffer to be read by the next <code><<</code> operation. Often this doesn't matter, but sometimes it does: e.g. if you follow up with <code>cin.get();</code>, expecting that this will wait for a keypress, it won't -- it will just read the <code>'\n'</code> (or the first non-digit character the user typed).</p>
|
Clear fields on CreateUserWizard, Login control <p>I have a createuserwizard and a login control on a page. both of them are customized (standard textboxes are replaced by RadTextBoxes)</p>
<p>When i enter a value in the form and refresh the browser without submitting, the forms retain their values. Is there any way i can clear these fields on refresh. </p>
<p>I have tried settinf EnableViewState false on the controls (as seen somewhere on the web) but it doesnt work</p>
<p>I have added code in page load to clear the fields if the page !IsPostBack. it looks something like this</p>
<pre><code> if (!IsPostBack)
{
((RadTextBox)Login1.FindControl("Username")).Text="";
((RadTextBox)Login1.FindControl("Password")).Text = "";
((RadTextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Username")).Text = "";
((RadTextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Password")).Text = "";
((RadTextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("confirmPassword")).Text = "";
((RadTextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Email")).Text = "";
}
</code></pre>
<p>Still of no avail
Any suggestions</p>
| <p>Turned out to be the Behavior of RadTextBox in Mozilla firefox</p>
|
VB.NET How do I reduce int to 1 decimal place? <p>I'm using the code below to convert the file size in bytes (test file is 31718 bytes) to KB (30.974609375 KB) but I want to display this to one decimal place (i.e. 30.9 KB). How would I do this in VB.NET?</p>
<pre><code>New FileInfo(FileName).Length / 1024
</code></pre>
<p>Thanks</p>
| <pre><code>Math.Round(New FileInfo(FileName).Length / 1024,1)
</code></pre>
|
What does the suffix #DEN mean on the value of a variable <p>When debugging in VS2005 I have a float in the Locals window whose values is:
<code>1.744e-039#DEN</code></p>
<p>What does the <code>#DEN</code> signify/stand for?</p>
| <p>This is for "<a href="http://en.wikipedia.org/wiki/Denormal_number">denormalized number</a>". See <a href="http://www.masonzhang.com/2008/09/floating-point-bit-value-of-inf-nan-den.html">this</a> for more info.</p>
|
How to store "wishlist" in database? <p>I am thinking of creating a "wishlist". Each user will be able to purchase wishes in a shop. How do I store the wishlist? I am thinking of creating an user table and a wishlist table. </p>
<p>The structure of user table:
Columns: id, username, password etc</p>
<p>Columns: id, wish, price, quantity etc</p>
<p>user id is the primary key for user table and its a foreign key in wishlist table. However, when I come to think of it, my wishlist table will have duplicate items for each user, won't it?</p>
<p>Is there a better way to store the wishlist things?</p>
<p>I am using mysql. Thanks</p>
| <p>You should also have another table to store the purchases:</p>
<p>Purchases</p>
<ul>
<li>Id</li>
<li>UserId</li>
<li>WishId</li>
<li>PurchaseDate</li>
</ul>
<p>Users</p>
<ul>
<li>Id</li>
<li>Name</li>
<li>Password</li>
</ul>
<p>Wishes</p>
<ul>
<li>Id</li>
<li>Wish</li>
<li>Price</li>
<li>Quantity</li>
</ul>
<p>Every time a user purchases a wish, you create a record in the Purchases table, and decrement the Quantity count for that wish.</p>
|
Bitmap and geographic coordinates <p>I have an array of geographic coordinates. I must draw a circle on each geographic coordinate. And I must get a bitmap on which these circles located.</p>
<p>Bitmap size is also in geographic coordinate.</p>
| <p>Sounds like you need to read up on <a href="http://en.wikipedia.org/wiki/Map%5Fprojection" rel="nofollow">map projections</a>, and pick a suitable one to either look for implementations of, or implement yourself.</p>
|
Can I get the absolute path to the current script in KornShell? <p>Is it possible to find out the full path to the script that is currently executing in KornShell (ksh)?</p>
<p>i.e. if my script is in <code>/opt/scripts/myscript.ksh</code>, can I programmatically inside that script discover <code>/opt/scripts/myscript.ksh</code> ?</p>
<p>Thanks,</p>
| <p>You could use:</p>
<pre><code>## __SCRIPTNAME - name of the script without the path
##
typeset -r __SCRIPTNAME="${0##*/}"
## __SCRIPTDIR - path of the script (as entered by the user!)
##
__SCRIPTDIR="${0%/*}"
## __REAL_SCRIPTDIR - path of the script (real path, maybe a link)
##
__REAL_SCRIPTDIR=$( cd -P -- "$(dirname -- "$(command -v -- "$0")")" && pwd -P )
</code></pre>
|
Can an email address contain international (non-english) characters? <p>If it's possible, should I accept such emails from users and what problems to expect when I will be sending mails to such addresses?</p>
| <p>Officially, per <a href="http://tools.ietf.org/html/rfc6532" rel="nofollow">RFC 6532</a> - <strong>Yes</strong>.</p>
<p>For a quick explanation, check out <a href="http://en.wikipedia.org/wiki/E-mail_address#Internationalization" rel="nofollow">wikipedia</a> on the subject.</p>
|
Mapping a ternary association with FluentNHibernate, using IDictionary<TKey,TValue> <p>I'm trying to map a ternary association using FluentNhibernate.</p>
<p>I have 3 tables:</p>
<ul>
<li><code>TUser(PK int id, string name, ...)</code></li>
<li><code>TGroup(PK int id, string name, ...)</code></li>
<li><code>TRole(PK int id, string name, ...)</code></li>
</ul>
<p>And a 4th one that associates them, representing the ternary association:</p>
<ul>
<li><code>TUserGroupRole(FK int userid, FK int groupid, FK int roleid)</code></li>
</ul>
<p>Basically, a user has a particular role for a group. I'm using 3 types in my model :</p>
<ul>
<li><code>User</code></li>
<li><code>UserGroup</code></li>
<li><code>UserRole</code></li>
</ul>
<p>In the <code>User</code> class, I want to use an <code>IDictionary<UserGroup,UserRole></code> to index user roles by groups:</p>
<pre><code>public class User
{
public virtual int Id { get; set; }
public virtual IDictionary<UserGroup, UserRole> Roles { get; set; }
// ...
}
</code></pre>
<p>Using regular hbm fashioned XML mapping file, I achieved that with a <code><map></code> element, like so (pseudo mapping):</p>
<pre><code><map name="Roles" table="TUserGroupRole">
<key column="userid"/>
<index-many-to-many column="groupid" class="UserGroup"/>
<many-to-many column="roleid" class="UserRole"/>
</map>
</code></pre>
<p><strong>I wasn't able to figure out how to generate the same mapping using FluentNhibernate</strong>, so any help on this point would be very appreciated.</p>
| <p>In response to the reply you got on the FNH group, make sure you are exporting your mapping files like:</p>
<pre><code>.Mappings(m => m.FluentMappings.AddFromAssemblyOf<MyObject>()
.ExportTo("path")
</code></pre>
<p>I tend to agree with that response because I have only ever seen that type of exception when elements are out of order; that is when the key/index or id element is not the first child.</p>
|
How do you create a read-only user in PostgreSQL <p>I'd like to create a user in PostgreSQL that can only do SELECTs from a particular database. In MySQL the command would be...</p>
<pre><code>GRANT SELECT ON mydb.* TO 'xxx'@'%' IDENTIFIED BY 'yyy';
</code></pre>
<p>What is the equivalent command or series of commands in PostgreSQL?</p>
<p>I tried...</p>
<pre><code>postgres=# CREATE ROLE xxx LOGIN PASSWORD 'yyy';
postgres=# GRANT SELECT ON DATABASE mydb TO xxx;
</code></pre>
<p>But it appears that the only things you can grant on a DB are CREATE, CONNECT, TEMPORARY, and TEMP.</p>
| <h2>Grant usage/select to a single table</h2>
<p>If you only grant CONNECT to a database, the user can connect but has no other privileges. You have to grant USAGE on namespaces (schemas) and SELECT on tables and views individually like so:</p>
<pre><code>GRANT CONNECT ON DATABASE mydb TO xxx;
-- This assumes you're actually connected to mydb..
GRANT USAGE ON SCHEMA public TO xxx;
GRANT SELECT ON mytable TO xxx;
</code></pre>
<h2>Multiple tables/views (PostgreSQL 9.0+)</h2>
<p>In the latest versions of PostgreSQL, you can grant permissions on all tables/views/etc in the schema using a single command rather than having to either type them one by one:</p>
<pre><code>GRANT SELECT ON ALL TABLES IN SCHEMA public TO xxx;
</code></pre>
<p>This only affects tables that have already been created. More powerfully, you can automatically have <a href="http://www.postgresql.org/docs/9.0/static/sql-alterdefaultprivileges.html">default roles assigned to new objects</a> in future:</p>
<pre><code>ALTER DEFAULT PRIVILEGES IN SCHEMA public
GRANT SELECT ON TABLES TO xxx;
</code></pre>
<p>Note that by default this will only affect objects (tables) created by the user that issued this command: although it can also be set on any role that the issuing user is a member of. However, you don't pick up default privileges for all roles you're a member of when creating new objects... so there's still some faffing around. If you adopt the approach that a database has an owning role, and schema changes are performed as that owning role, then you should assign default privileges to that owning role. IMHO this is all a bit confusing and you may need to experiment to come up with a functional workflow.</p>
<h2>Multiple tables/views (PostgreSQL versions before 9.0)</h2>
<p>To avoid errors in lengthy, multi-table changes, it is recommended to use the following 'automatic' process to generate the required <code>GRANT SELECT</code> to each table/view:</p>
<pre><code>SELECT 'GRANT SELECT ON ' || relname || ' TO xxx;'
FROM pg_class JOIN pg_namespace ON pg_namespace.oid = pg_class.relnamespace
WHERE nspname = 'public' AND relkind IN ('r', 'v', 'S');
</code></pre>
<p>This should output the relevant GRANT commands to GRANT SELECT on all tables, views, and sequences in public, for copy-n-paste love. Naturally, this will only be applied to tables that have already been created.</p>
|
Is Serialization reliable for object size estimation? <p>I use serialization, in order to estimate the amount of memory used for an object.
I already read <a href="http://stackoverflow.com/questions/426396/how-much-memory-does-a-c-net-object-use">this</a>, and <a href="http://stackoverflow.com/questions/26570/sizeof-equivalent-for-reference-types">this</a>.
So I know that it may be better to use a profiler or sizeof (for value types).</p>
<p>I would like to know, what is the exact difference between the serialized object and the object in memory ? In what measure is serialization reliable for object size estimation ?</p>
<p>I am especially interested in C# serialization mechanisms.</p>
| <p>The serialized form of data is not the same as in-memory; for example, a collection/dictionary will involve multiple objects for the items, the arrays, hash-buckets/indexes, etc - but the raw data (when serialized) will <em>typically</em> be just the data - so you might see less volume when serialized.</p>
<p>Equally, things like <code>BinaryFormatter</code> have to include a lot of (verbose) type metadata - but in the objects it just has a (terse) type handle in the object handle - so you might see <em>more</em> data in the serialized data. Likewise, the serializer (unless it is manually optimized) needs to tokenize the individual fields - but in memory this is implicit in the offset from the objects address.</p>
<p>So you might get <em>a</em> number from serialization, but it is not the <strong>same</strong> number.</p>
<p>To get an accurate idea of the size of an object graph is tricky. SOS might help; otherwise, create a whole shed-load of them and divide. Crude, but it might just work.</p>
|
Problem exposing custom complex interface types in WCF services <p>I'm trying to get hold of an object from another application using WCF. With built in classes it works fine but I run into probems when trying to return a custom interface type from the WCF operation. </p>
<p>Whether I include the interface in both applications separately, or specif it as a shared assembly, I get the same result: a CommunicationException with the message "There was an error reading from the pipe: Unrecognized error 109". </p>
<p>The interface looks like this:</p>
<pre><code>[ServiceContract]
public interface IBase {
int IntTest {
[OperationContract]
get;
}
String StringTest {
[OperationContract]
get;
}
IOther OtherTest {
[OperationContract]
get;
}
}
[ServiceContract]
public interface IOther {
String StringTest {
[OperationContract]
get;
}
}
</code></pre>
<p>My server looks like this:</p>
<pre><code>public partial class MainWindow : Window {
private Base fb;
private ServiceHost host;
public MainWindow() {
InitializeComponent();
fb = new Base();
host = new ServiceHost(fb, new Uri[] { new Uri("net.pipe://localhost") });
host.AddServiceEndpoint(typeof(IBase), new NetNamedPipeBinding(),
"PipeReverse");
host.Open();
}
private void Window_Closing(object sender, CancelEventArgs e) {
host.Close();
}
}
</code></pre>
<p>And here is my implementation of the interface:</p>
<pre><code>[Serializable]
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
public class Base : MarshalByRefObject, IBase {
public int IntTest {
get { return 4; }
}
public string StringTest {
get { return "A string from Base"; }
}
public IOther OtherTest {
get { return new Other(); }
}
}
[Serializable]
[DataContract]
public class Other : MarshalByRefObject, IOther {
[DataMember]
public string StringTest {
get { return "A string from Other"; }
}
}
</code></pre>
<p>The client looks like this:</p>
<pre><code>public partial class Form1 : Form {
IBase obj;
public Form1() {
InitializeComponent();
ChannelFactory<IBase> pipeFactory = new ChannelFactory<IBase>(
new NetNamedPipeBinding(), new EndpointAddress(
"net.pipe://localhost/PipeReverse"));
obj = pipeFactory.CreateChannel();
}
private void button2_Click(object sender, EventArgs e) {
Console.WriteLine("Returns: " + obj.StringTest + " " +
obj.StringTest.Length);
Console.WriteLine("Returns: " + obj.IntTest);
Console.WriteLine(obj.OtherTest);
}
}
</code></pre>
<p>Everything works like a charm except this line:</p>
<pre><code>Console.WriteLine(obj.OtherTest);
</code></pre>
<p>It give me a CommunicationException with the message "There was an error reading from the pipe: Unrecognized error 109". As far as I can tell that is a broken pipe due to a faulted state but I can't figure out why, or more importantly how to fix it. Any ideas?</p>
<p>I have no config file as everthing is done in the code above so I don't know how to turn on tracing, otherwise I would have included that too.</p>
| <p>The returned property <strong>OtherTest</strong> needs to be a concrete type and not an interface, otherwise the serialization will not work.</p>
|
jQuery fading/dimming other list elements when one is hovered over, I'm 90% there..? <p>I have an unordered list, which has maybe 30 items. When one of these items are hovered over, the rest of the list items fade to 30% and the hovered item stays at 100%; when you move away from the list, they all fade back up to 100% and I have managed this.</p>
<p>My problems arises when you move from item to item, the other list items fade back up to 100% and then back down to 30%. I want them to stay at 30% unless the user moves away from the whole list.</p>
<p>I use the hoverIntent plugin on each list item. I also used jQuery to add a class to the current list item, so I could then fade the rest and remove it once you move away. I have used a wait function found on the jQuery Cookbook site (<a href="http://docs.jquery.com/Cookbook/wait" rel="nofollow">http://docs.jquery.com/Cookbook/wait</a>)</p>
<p>Do you get me?</p>
<p>Here's my code so far:</p>
<pre><code>$.fn.wait = function(time, type) {
time = time || 300;
type = type || "fx";
return this.queue(type, function() {
var self = this;
setTimeout(function() {
$(self).dequeue();
}, time);
});
};
$("#sites li:not(#sites li li)").hoverIntent(function(){
$(this).attr('class', 'current'); // Add class .current
$("#sites li:not(#sites li.current,#sites li li)").fadeTo("slow", 0.3); // Fade other items to 30%
},function(){
$("#sites li:not(#sites li.current,#sites li li)").wait().fadeTo(600, 1.0); // This should set the other's opacity back to 100% on mouseout
$(this).removeClass("current"); // Remove class .current
});
</code></pre>
<p>*Obviously this is within a $(document).ready(function()</p>
<p>Can anyone help me please? </p>
<p>Many thanks</p>
| <p>This sounded like fun, so I implemented it. From the looks of things, your css selector can be simplified. I think you only want the topmost list item to fade in and out, but it's not clear from the example. This example highlights the topmost node and does the fading correctly. I think this is the effect you were going for, but I'm not 100% sure. I didn't use the wait() functionality, as I'm not sure what it does do you.</p>
<p>Essentially, it sounds like the problem you are running into is that you are fading items in on hover out when you haven't left the list yet. You only want to fade in the list or other list items when you've entirely left the list. Don't use hoverIntent for that part, and handle the fading on the entire unordered list and it should be good to go.</p>
<p>The example: <a href="http://jsbin.com/usobe">http://jsbin.com/usobe</a></p>
<p>Tinker with the example: <a href="http://jsbin.com/usobe/edit">http://jsbin.com/usobe/edit</a></p>
<pre><code><ul id="sites">
<li> site 1
<ul><li>sub item 1</li><li>sub item 2</li><li>sub item 3</li></ul>
<li> site 2
<ul><li>sub item 1</li><li>sub item 2</li><li>sub item 3</li></ul>
<li> site 3
<ul><li>sub item 1</li><li>sub item 2</li><li>sub item 3</li></ul>
<li> site 4
<ul><li>sub item 1</li><li>sub item 2</li><li>sub item 3</li></ul>
<li> site 5
</ul>
<script>
$(function() {
$("#sites").hover(
function() {},
function() {
$('#sites>li').fadeTo("fast", 1.0);
}
);
$("#sites>li").hoverIntent(
function(){
$(this).attr('class', 'current'); // Add class .current
$(this).siblings().fadeTo("fast", 0.3); // Fade other items to 30%
$(this).fadeTo("slow", 1.0); // Fade current to 100%
},
function(){
$(this).removeClass("current"); // Remove class .current
$(this).fadeTo("fast", 1.0); // This should set the other's opacity back to 100% on mouseout
});
});
</script>
</code></pre>
|
How can I prevent line breaks in PHP variable used as HTML email body <p>I've created a PHP script that takes the contents of an array and stuffs them into a variable called $body:</p>
<pre><code>foreach($_POST as $var => $value)
{
if (($var != "Submit") && ($value != "")) {
$body .= $var .': '.filter_var($value, FILTER_SANITIZE_STRING) . '<br>';}
}
</code></pre>
<p>This $body then forms the body of an HTML email. All is fine until those contents get too long, and then I end up with an emails that sometimes lose a <code><br /></code> (because it becomes <code><b</code> on one line and <code>r /></code> on the next. This causes my fields to run together in the email client.</p>
<p>Ideas?</p>
<p>EDIT: I tried adding <code>\n</code> before the break, but my email client displays them
But with double quotes it worked. Thanks!</p>
| <p>Print your <code>"\n<br/>"</code>. That way you'll always get your <code><BR></code> in new lines.</p>
|
How to mark a device in a way that can be retrived by HAL but does not require mounting or changing the label <p>I'm trying to find a way to mark a USB flash device in a way that I can programmaticly test for without mounting it or changing the label. </p>
<p>Are there any properties I can modify about a device that will not cause it to behave/look differently to the user?</p>
<p>Running Ubuntu Jaunty.</p>
| <p>You cannot modify this property, but the tuple (vendor_id, product_id, serial_number) is unique to each device, so you can use this as mark that is already there.
You can enumerate the devices on the USB bus using lsusb or usblib.</p>
|
Modeling Tools that understand both Relational and LDAP <p>I am looking to do some modeling and would like to have a tool that can capture not only a relational model like ERWIN but also allow us to easily port to LDAP as an option.</p>
<p>NOTE: Visio can connect to an existing LDAP server and draw, but does not allow for you to model first and then deploy, unlike its relational capabilities.</p>
| <p>I haven't used it in a few years, but Microsoft has an Enterprise Architect version of Visio which allows for data modeling. I would be surprised if Visio didn't also handle LDAP.</p>
<p>The data modeling part probably isn't as extensive as something like ErStudio, but it allows reverse engineering of ODBC data sources and most of the other basic data modeling capabilities (at least it did). They had just started with moving towards data modeling when I used it, so hopefully it's improved since then.</p>
|
Monitor the console output from within the actionscript - flash application <p>I am loading an as2 swf into an as3 swf. When I am debugging the as3 application (I am using flex builder as my ide) I can see the debug output from the as2 app. You can't call functions or properties of an as2 swf from within an as3 swf so I have no way of knowing what is going on within the as2 swf programmatically.</p>
<p>Is there a clever workaround whereby I can consume the debug output from the as2 swf from within my as3 swf? What api is flexbuilder plugging into to display the debug output? Can I use that in my as3 app?</p>
<p>I tried the swfBridge but ran into limitations after a week of trying. This would be a great workaround.</p>
| <p>How about LocalConnection? Here's an <a href="http://www.learningactionscript3.com/2007/12/14/sending-data-from-avm2-to-avm1/#more-29" rel="nofollow">example</a> that may or may not suit your needs.</p>
|
Textbox on ReportViewer (RDLC) not wrapping but forcing a page break <p>Situation: My report uses several ReportViewer Textbox controls which grow and shrink, depending on the size of the bound text. When the text in the ReportViewer textbox control is too long to fit on the current page, a page break occurs <strong><em>before</em></strong> the textbox and it is then wholly rendered in the next page. This often results in a large empty gap at the bottom of the first page where the page break occurred.</p>
<p>I would prefer the textbox to wrap the text across both pages, rendering as much of the text as will fit on the current page and then wrapping the remainder to the next page. Anyone know if this is possible? </p>
| <p>This is quite possible. The <strong>KeepTogether</strong> property of the textbox defaults to true, and is what keeps the textbox from splitting into more than one section. To get your textbox to wrap to the next page, just set <strong>KeepTogether</strong> to false. (Note that you have to use the <em>Property Window</em> (F4), not the <em>TextBox Properties...</em> dialog box.)</p>
|
100% to 100% Flex application preloader positioning <p>I've got a problem trying to apply a loading animation to my Flex application - a whole browser window occupant.
I'm subclassing DownloadProgressBar class as described on Adobe's <a href="http://livedocs.adobe.com/flex/3/html/help.html?content=app_container_4.html" rel="nofollow">article</a> about this. <code>stageHeight</code> and <code>stageWidth</code>, reported by base class are incorrect. It says 500x375 pixels in constructor and 0x0 elsewhere. Why?</p>
| <p>i have code to center my custom progress loader and is working very much fine from this article
<a href="http://askmeflash.com/article_m.php?p=article&id=7" rel="nofollow">http://askmeflash.com/article_m.php?p=article&id=7</a> </p>
|
Class Zend_Test_PHPUnit_ControllerTestCase could not be found <p>When I run phpunit to test my controller there always comes the message: <code>Class Zend_Test_PHPUnit_Controller_TestCase could not be found ...</code></p>
<p>All require_once are executed and run without errors.</p>
<p>My files:</p>
<p><strong>Test.php:</strong></p>
<pre><code><?php
require_once 'bootstrap.php';
class indexTest extends Zend_Test_PHPUnit_ControllerTestCase
{
protected function setUp ()
{
$this->bootstrap = array($this, 'appBootstrap');
parent::setUp();
}
public function appBootstrap ()
{
$this->frontController->registerPlugin(new DemoApp_Controller_Plugin_Initialize('test', PROJECT_ROOT));
}
public function testIndex()
{
$this->dispatch('/');
$this->assertController('login');
}
}
</code></pre>
<p><strong>bootstrap.php:</strong></p>
<pre><code><?php
define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../src/application/'));
set_include_path( APPLICATION_PATH . '/../library' . PATH_SEPARATOR .
APPLICATION_PATH . '/modules' . PATH_SEPARATOR .
APPLICATION_PATH . '/layouts' . PATH_SEPARATOR .
get_include_path() );
require_once 'PHPUnit/Framework.php';
require_once 'PHPUnit/Framework/TestSuite.php';
require_once 'PHPUnit/TextUI/TestRunner.php';
error_reporting(E_ALL);
require_once APPLICATION_PATH . "/../library/Zend/Loader.php";
Zend_Loader::registerAutoload();
// Set up the config in the registry path relative to public/index.php
$config = new Zend_Config_Ini(APPLICATION_PATH . '/config.ini'); //, 'test'
Zend_Registry::set('config', $config);
/*// Set up the database in the Registry
$db = Zend_Db::factory($config->db);
Zend_Db_Table_Abstract::setDefaultAdapter($db);
*/
// Set timezone
date_default_timezone_set("Europe/Berlin");
</code></pre>
| <p>The class is not in your include path, Or, you don't have the class at all.<br />
Steps to take: </p>
<ol>
<li>Find the class file</li>
<li>Make sure the class is in your
include path, including the
auto_loader name parsing:
Z_Y_YourClass will be looked at the
include_path/Z/Y/YourClass.php</li>
</ol>
<p>Good Luck</p>
|
Why does this code compile and run successfully it seems it should get an index out of bounds <p>I was reading through some java code in a project I was working on and came along a method with something to this effect in it.</p>
<pre><code>Object[] objs = null;
objs[0] = str1;
objs[1] = obj1;
for(String str: strArray)
{
objs[objs.length+1] = str;
}
</code></pre>
<p>I can't figure out what is going on here. I was hoping someone could explain how this code is working to me, preferably on both a high level and the behind the scenes low level.</p>
| <p>That should not run. objs[0] will give an error.</p>
<p>Are you sure you are running the correct version of the file?</p>
|
Is it legal to write to std::string? <p>In std::string there are only const members to fetch the data like c_str(). However I can get a reference to the first element of the string via <code>operator[]</code> and I can write to it.</p>
<p>For example, if I have function:</p>
<pre><code>void toupper(char *first,char *last_plus_one);
</code></pre>
<p>I can write directly to vector getting a pointer to the first element:</p>
<pre><code>vector<char> message // has "Some Message";
toupper(&message[0],&message[0]+message.size());
</code></pre>
<p>Can I do same thing with std::string?</p>
<pre><code>string message="Some Message";
toupper(&message[0],&message[0]+message.size());
</code></pre>
<p>Does the standard guarantee that the location of the memory is actually linear? ie:</p>
<pre><code>&(*(message.begin()+n)) == &message[n]
</code></pre>
<p>Thanks.</p>
| <p>Herb Sutter has this to say (<a href="http://herbsutter.wordpress.com/2008/04/07/cringe-not-vectors-are-guaranteed-to-be-contiguous/#comment-483">http://herbsutter.wordpress.com/2008/04/07/cringe-not-vectors-are-guaranteed-to-be-contiguous/#comment-483</a>):</p>
<blockquote>
<p>current ISO C++ does require &str[0] to cough up a pointer to contiguous string data (but not necessarily null-terminated!), so there wasnât much leeway for implementers to have non-contiguous strings, anyway. For C++0x we have already adopted the guarantee that std::string contents must indeed be stored contiguously. For details, see <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-defects.html#530">http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-defects.html#530</a> </p>
</blockquote>
<p>And Matt Austern says similar in the referenced document (<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-defects.html#530">http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-defects.html#530</a>).</p>
<p>So, it seems that you can assume that once you call str[0] you do get a modifyable array of characters (but note that it is not required to be null terminated).</p>
|
WCF: How to get Host IP or Server Name <p>I have a WCF service that is hosted via IIS on multiple web servers. I have a logging method that logs the calls to the database and I'd like to log which server the call is executing on.</p>
<p>Does anyone know how to get the host server name or IP address that the WCF call is executing on?</p>
| <p>Use Dns.GetHostName(), because it's much better to get the name of the computer than the host IP. Consider the case when your host computer have more than one IP address, has virtual network cards (VMWare).</p>
|
Data import wizard library for .Net? <p>Does anyone know of a 3rd party data import wizard that can be embedded into applications? It should import from Excel, Access, SQLServer, csv, tab-separated flat file, XML, Oracle etc. We have a fixed data structure within our application and the user should be able to configure the wizard to match his/her import fields to our own data structure.</p>
<p>The wizard should be a library of sorts â preferably a .Net type library. We may want to have it both web-based and desktop based (hence we may need an ASP.Net controls version and a Winforms version). We may also want integration with WPF and Silverlight.</p>
<p>If thereâs no UI wizard available, does anyone know of a non-UI library that supports easily configurable import from many, many different datasources?</p>
| <p>If you can assume that your application has SQL Server available, it is fairly straightforward to programmatically set up a SSIS package to do this type of transformation. Your application would provide a UI where you could set up the metadata for the data source and map it to the destination. You could possibly even just use SSIS package editor in BIDS itself for the job and incorporate a facility in your application to execute the package.</p>
<p>If SSIS is not available to you then you would have to purchase something commercial - I am not aware of any mature open-source .Net based ETL tooling of this sort. </p>
<p>If you don't strictly need a .Net based toolchain (for example, your application could possibly just shell out to an external executable) there are open source tools of this type, mostly written in Java. Take a look at the offerings from various open-source B.I. vendors such as <a href="http://www.jaspersoft.com" rel="nofollow">Jasper</a> or <a href="http://www.pentaho.com" rel="nofollow">Pentaho.</a> </p>
<p>Another alternative might be to embed a scripting language interpreter such as Python into your system (Check out <a href="http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython" rel="nofollow">IronPython</a> - a .net based python system). These languages have quite a variety of library tooling for reading various types of files. The language can be used as a macro facility for the application and data imports can be implemented through this mechanism. This comes at the expense of being a somewhat technical, so it's something that would be done by support staff rather than directly by end users. Depending on the customer base and other implementation costs of your application this may or may not be acceptable.</p>
|
ClickOnce deployment error on upgraded .NET application <p>I have a Windows forms application that was developed in Visual Studio 2005 and deployed to an IIS server via ClickOnce. I've upgraded to VS2008 so I decided to upgrade and redeploy the application (in test). I ran the upgrade wizard, manually changed the project's target runtime to 3.5, removed all of the old publish files from the deployment server, and published the application. </p>
<p>I can launch it with no problem (i.e., "works on my machine"), but when others launch it they get an error.</p>
<blockquote>
<p>Cannot continue. The application is improperly formatted. Contact the application vendor for assistance.</p>
</blockquote>
<p>There's a Details... button on the error dialog. Here are some of the contents.</p>
<pre><code>PLATFORM VERSION INFO
Windows : 5.1.2600.131072 (Win32NT)
Common Language Runtime : 2.0.50727.1433
System.Deployment.dll : 2.0.50727.1433 (REDBITS.050727-1400)
mscorwks.dll : 2.0.50727.1433 (REDBITS.050727-1400)
dfdll.dll : 2.0.50727.1433 (REDBITS.050727-1400)
dfshim.dll : 2.0.50727.1433 (REDBITS.050727-1400)
</code></pre>
<p>Note that the CLR is 2.0.</p>
<pre><code>ERROR SUMMARY
Below is a summary of the errors, details of these errors are listed later in the log.
* Activation of http://{deployment host name}/ resulted in exception. Following failure messages were detected:
+ Exception reading manifest from http://{deployment host name}/{application name}.application: the manifest may not be valid or the file could not be opened.
+ Manifest XML signature is not valid.
+ No signature was present in the subject.
</code></pre>
<p>I didn't sign the application. It's a completely internal departmental application. I suspect that the problem isn't the lack of a signature, it's that .NET is using the wrong runtime, and that the 2.0 runtime can't handle the 3.5 manifest. But if that's the case, I can't figure out how to get it to use the 3.5 runtime.</p>
<p>I thought maybe the older version was cached, so I had the user run <code>rundll32 %windir%\system32\dfshim.dll CleanOnlineAppCache</code>. That cleared the cache (the application did a full reload the next time), but it didn't solve the problem.</p>
<p>Has anybody had a problem like this upgrading a ClickOnce app from 2.0 to 3.5? Any idea what my problem could be?</p>
| <p>Please verify that you have .NET Framework 3.5 set as a prerequisite.</p>
<p>Project Settings -> Publish -> Prerequisites</p>
|
How to do a Select in a Select <p>I have a table containing a unique ID field. Another field (REF) contains a reference to another dataset's ID field.
Now I have to select all datasets where REF points to a dataset that doesn't exist.</p>
<pre><code>SELECT * FROM table WHERE ("no dataset with ID=REF exists")
</code></pre>
<p>How can I do this?</p>
| <p>3 ways</p>
<pre><code>SELECT * FROM YourTable y WHERE NOT EXISTS
(SELECT * FROM OtherTable o WHERE y.Ref = o.Ref)
SELECT * FROM YourTable WHERE Ref NOT IN
(SELECT Ref FROM OtherTable WHERE Ref IS NOT NULL)
SELECT y.* FROM YourTable y
LEFT OUTER JOIN OtherTable o ON y.Ref = o.Ref
WHERE o.Ref IS NULL
</code></pre>
<p>See also <a href="http://wiki.lessthandot.com/index.php/5%5Fways%5Fto%5Freturn%5Frows%5Ffrom%5Fone%5Ftable%5Fnot%5Fin%5Fanother%5Ftable" rel="nofollow">Five ways to return all rows from one table which are not in another table</a> </p>
|
best way of converting letters to base-10 <p>So far I have something such as: </p>
<pre><code>if( Char.IsDigit( c ) )
return Int32.Parse( "" + c );
if( Char.IsLetter( c ) )
return Char.ToUpper( c ) - 'A' + 1;
</code></pre>
| <p>For the first one:</p>
<pre><code>if (Char.IsDigit(c))
return c - '0';
</code></pre>
|
How to debug a windows service using breakpoints? <p>I have a windows service with a timer. Its very hard to debug it. Because I start the service and put break points in different parts of the code. When I attach the process, I expect the service to start from the very beginning instead of some randome place in the middle code where I have break points. Its hard to debug like a normal application where you know the starting point. It appears that there are processes in the back ground that have not completed yet. So every single time, I start to debug, instead of starting from the very first break point, it starts from some random break point in the middle of application. </p>
<p>I want to know how windows service works in terms of processes, threads etc... and how can I start debugging from the beginning?</p>
| <p>I assume you're talking about .Net of course. I've always used the following code to debug my services. I place it where I want to the debugger to launch. Start the service and it automatically launches Visual Studio. Works well for me. </p>
<p><code>System.Diagnostics.Debugger.Launch();</code></p>
<p><code>System.Diagnostics.Debugger.Debug();</code></p>
|
Bind multiple TextBoxes to one struct in WPF <p>How do i bind two TextBox objects to a <a href="http://msdn.microsoft.com/en-us/library/system.windows.size.aspx" rel="nofollow">System.Windows.Size</a> <strong>struct</strong>?
The binding only has to work in this direction:</p>
<p>(textBox1.Text + textBox2.Text) => (Size)</p>
<p>After a user inserts the width and height in the TextBoxes on the UI the Size object should be created.</p>
<p>XAML:</p>
<pre><code><TextBox Name="textBox_Width" Text="{Binding ???}" />
<TextBox Name="textBox_Height" Text="{Binding ???}" />
</code></pre>
<p>C#:</p>
<pre><code>private Size size
{
get;
set;
}
</code></pre>
<p>Is there an easy way to do this?</p>
<p><strong>Edit:</strong> Size is a struct! Therefore "someObject.Size.Width = 123" does not work. I need to call the Size-Constructor and set someObject.Size = newSize</p>
| <p>Could you not just expose 2 properties - width and height from your model, along with a size property. The width and height would appear in your {Binding} expressions, and then when you want to get the size property, it initialises based on these two fields. </p>
<p>Eg, your model might be something like;</p>
<pre><code>public class MyModel
{
public int Width{ get; set; }
public int Height{ get; set; }
public Size Size{ get{ return new Size( Width, Height ); }}
};
</code></pre>
<p>Hope this helps.</p>
<p>Tony</p>
|
WiFi connection is dropped after user inactivity period <p>My iPhone application establishes a TCP connection through wifi to a remote server. However, if there is no user activity for a certain time, the device closes wifi and drops the connection. Is it possible to prevent it? I need the connection to be persistent while the application is running. Setting <em>setIdleTimerDisabled:YES</em> doesn't help - it prevents the screen to go off, but still the wifi is closed. </p>
<p>Do you know if this is possible and how to achieve it?</p>
| <p>Check out this URL:
<a href="http://developer.apple.com/iphone/library/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/ApplicationEnvironment/ApplicationEnvironment.html#//apple_ref/doc/uid/TP40007072-CH7-SW59" rel="nofollow">http://developer.apple.com/iphone/library/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/ApplicationEnvironment/ApplicationEnvironment.html#//apple_ref/doc/uid/TP40007072-CH7-SW59</a></p>
<blockquote>
<p>Table 1-3 Important keys in the Info.plist file</p>
<p>UIRequiresPersistentWiFi:</p>
<p>A Boolean value that notifies the system that the application uses the Wi-Fi network for communication. Applications that use Wi-Fi for any period of time must set this key to true; otherwise, after 30 minutes, the device shuts down Wi-Fi connections to save power. Setting this flag also lets the system know that it should display the network selection dialog when Wi-Fi is available but not currently being used. The default value is false.</p>
</blockquote>
|
How does the IN predicate work in SQL? <p>After prepairing an answer for <a href="http://stackoverflow.com/questions/761044/sql-query-help">this question</a> I found I couldn't verify my answer.</p>
<p>In my first programming job I was told that a query within the <code>IN ()</code> predicate gets executed for every row contained in the parent query, and therefore using <code>IN</code> should be avoided.</p>
<p>For example, given the query:</p>
<pre><code>SELECT count(*) FROM Table1 WHERE Table1Id NOT IN (
SELECT Table1Id FROM Table2 WHERE id_user = 1)
</code></pre>
<pre>
Table1 Rows | # of "IN" executions
----------------------------------
10 | 10
100 | 100
1000 | 1000
10000 | 10000
</pre>
<p>Is this correct? How does the <code>IN</code> predicate actually work?</p>
| <p>The warning you got about subqueries executing for each row is true -- for <strong>correlated subqueries.</strong></p>
<pre><code>SELECT COUNT(*) FROM Table1 a
WHERE a.Table1id NOT IN (
SELECT b.Table1Id FROM Table2 b WHERE b.id_user = a.id_user
);
</code></pre>
<p>Note that the subquery references the <code>id_user</code> column of the outer query. The value of <code>id_user</code> on each row of <code>Table1</code> may be different. So the subquery's result will likely be different, depending on the current row in the outer query. The RDBMS <em>must</em> execute the subquery many times, once for each row in the outer query. </p>
<p>The example you tested is a <strong>non-correlated subquery</strong>. Most modern RDBMS optimizers worth their salt should be able to tell when the subquery's result <em>doesn't</em> depend on the values in each row of the outer query. In that case, the RDBMS runs the subquery a single time, caches its result, and uses it repeatedly for the predicate in the outer query.</p>
<p>PS: In SQL, <code>IN()</code> is called a "predicate," not a statement. A predicate is a part of the language that evaluates to either true or false, but cannot necessarily be executed independently as a statement. That is, you can't just run this as an SQL query: "2 IN (1,2,3);" Although this is a valid predicate, it's not a valid statement.</p>
|
Optimal Way to Store/Retrieve Array in Table <p>I currently have a table in MySQL that stores values normally, but I want to add a field to that table that stores an array of values, such as cities. Should I simply store that array as a CSV? Each row will need it's own array, so I feel uneasy about making a new table and inserting 2-5 rows for each row inserted in the previous table.</p>
<p>I feel like this situation should have a name, I just can't think of it :)</p>
<p>Edit</p>
<p>number of elements - 2-5 (a selection from a dynamic list of cities, the array references the list, which is a table)</p>
<p>This field would not need to be searchable, simply retrieved alongside other data.</p>
| <p>The "right" way would be to have another table that holds each value but since you don't want to go that route a delimited list should work. Just make sure that you pick a delimiter that won't show up in the data. You can also store the data as XML depending on how you plan on interacting with the data this may be a better route. </p>
|
Why won't this PHP iteration work? <p>I want to make the results of a foreach loop into a string variable I can use later all over (so I don't need to paste the foreach loop everywhere). I have this:</p>
<pre><code>foreach($pairs as $d=>$m) {
$orderedpairs .= "[".$d."],[".$m."]"+"<br />";
}
echo $orderedpairs;
</code></pre>
<p>If I substitute the assignment operator with "echo", it works fine, so the loop is ok, I think it's just the variable assignment that's at issue. Thanks!</p>
| <p>You have a + in there for concatenation. You need .</p>
<p>Also, you should define $orderedpairs as an empty string before the loop.</p>
|
Strange Rails Routing behaviour: two ids swapped around in nested resources <p>I have the following routing set up in my app (forms belong to a site):</p>
<pre><code>map.resources :sites do |site|
site.resources :forms
end
</code></pre>
<p>However, when I try to go to a path for edit (or such) for a form using the helpers (e.g.</p>
<pre><code>edit_site_form_path(form)
</code></pre>
<p>or </p>
<pre><code><%= link_to 'Show', [:site, form] %>
</code></pre>
<p>my URLs are coming out with the ID's swapped over ( /sites/5/forms/1 ) where 5 is the form Id, and 1 is the site id. This is from the page /sites/1.</p>
<p>Help(?)</p>
| <p>The <code>edit_site_form_path</code> method has to have two parameters, the site_id and the form_id. So in your example you are only passing in the form_id. The first parameter is what ever model comes first in the method, in this case it is <code>site</code>. The second parameter is the form_id.</p>
<p>A revamped path method might look like this</p>
<pre><code> edit_site_form_path(form.site, form)
</code></pre>
<p>(assuming you have a model <code>Form</code> which <code>belongs_to :site</code>)</p>
|
Why csv.reader is not pythonic? <p>I started to use the <a href="https://docs.python.org/2/library/csv.html#csv.reader" rel="nofollow">csv.reader</a> in Python 2.6 but you can't use <code>len</code> on it, or slice it, etc. What's the reason behind this? It certainly feels very limiting.</p>
<p>Or is this just an abandoned module in later versions?</p>
| <p>I'm pretty sure you can't use len or slice because it is an iterator. Try this instead.</p>
<pre><code>import csv
r = csv.reader(...)
lines = [line for line in r]
print len(lines) #number of lines
for odd in lines[1::2]: print odd # print odd lines
</code></pre>
|
Hibernate: No CurrentSessionContext configured <p>I keep getting a :</p>
<blockquote>
<p>HibernateException: No
CurrentSessionContext configured!</p>
</blockquote>
<p>in my code. The only information other searches that returned is that the culprit is:</p>
<pre><code><property name="current_session_context_class">thread</property>
</code></pre>
<p>in my hibernate.cfg.xml. I do have that in my hibernate.cfg.xml file, and I am running this in Tomcat 6. Does anyone know other possible causes?</p>
| <p>I believe you need to set your current_session_context_class to an actual class...I have my hibernate.cfg.xml configured for that as follows:</p>
<pre><code><property name="hibernate.current_session_context_class">org.hibernate.context.ThreadLocalSessionContext</property>
</code></pre>
<p>The above code is used for a mySql database but i don't think it matters what type the database is for the above property</p>
<p>Hope this helps</p>
|
Fastest way to compare two data structures in java <p>I would like to know what is the fastest way in java 1.5 to compare two data structures.</p>
<p>My data structure represents a tree that can be pretty big. I can traverse the whole data structure and compare the 2 node by node (which I guess will be slow). Or I can compute a hash of the data structure to do it faster, right ?</p>
<p>What is the best (efficient and not too long) way to compute this hash ? </p>
<p>I wouldn't like to need too much time to compute hash...</p>
<p>Hope I'm clear.. :-)...</p>
| <p>Have you considered keeping a running hashCode which is continually updated as elements are inserted or removed from your trees? This way, comparing a tree at any given time by hashCode will be instantaneous.</p>
<p>Depending on how you implement your hash function, and how frequently you insert and remove nodes, this could be a horrible solution. If your hash function is fast, you aren't making many changes, and you need to do a lot of comparisons, this could work.</p>
|
DDD: Saving Changes to Model and accessing Repository <p>I have a Question object thats the root of the Question Aggregate. THe question has associated Answer Entities in its aggregate . When a new Answer object is created, the changes will be saved to DB via repository. Can I call a repository method SaveAnswer(Question ID) or must I call a SaveQuestion(QUestionID) and have the Repository determine what changes were made? If the latter, how is this implemented? </p>
<p>Conversely, If I want to load up all the Answers to a particular Question, must I call GetQuestion() and then pull the answers, or can I simply call GetAnswers(questionID).</p>
<p>tia</p>
| <p>Firstly, let me say there are no hard and fast rules here, this is my understanding of DDD and repository access, but it's a fairly subjective area...</p>
<p>So, from a DDD perspective what you might want to do when adding an Answer to an existing Question is something like the following C# style pseudocode:</p>
<pre class="lang-cs prettyprint-override"><code>using(unitOfWork = new UnitOfWork())
{
var question = _questionRepository.GetQuestion(questionId);
question.AddAnswer(new Answer("blah"));
unitOfWork.SaveChanges();
}
</code></pre>
<p>Assuming you are using an ORM that handles change tracking and that is configured to cascade child objects back to the database that is all you would need to do (I'm thinking of NHibernate here, but other ORMs can work in a similar way). By adding the Answer to the Question you have told the ORM that you want the Answer to be persisted in the database when the unit of work completes. You typically wouldn't call SaveAnswer(QuestionId) - that's not a very DDD-centric way of approaching things where Answer is in the same aggregate as Question and Question is the aggregate root.</p>
<p>For getting the objects out of the database, typically you would ask the repository for a question object (by id presumably), and then navigate to the Answer from there (via an Answers collection on the Question) - e.g.</p>
<pre class="lang-cs prettyprint-override"><code>var question = _questionRepository.GetQuestion(questionId);
foreach(var answer in question.Answers)
{
Console.WriteLine(answer.Description); // or do something useful instead!
}
</code></pre>
<p>If this seems like a strange way to save or retrieve the Answer object then you might want to re-assess whether Answer does actually belong in the same aggregate, or whether it would be better to break it out of the question aggregate altogether.</p>
|
.NET: Disposing a HashAlgorithm object <p>Objects that derive from HashAlgorithm such as MD5CryptoServiceProvider have a Dispose() method, but it's private. Instead it has a Clear() method which "Releases all resources" used by it.</p>
<p>WTF?</p>
<p>Is this how to correctly dispose of a HashAlgorithm then?</p>
<pre><code>var hasher = new MD5CryptoServiceProvider();
byte[] hashCode = hasher.ComputeHash(data);
hasher.Clear();
</code></pre>
<p>Someone wanna explain this one to me? :)</p>
| <p>While the <code>Dipose()</code> method is private, if you cast it to <code>IDisposable</code> you can gain access to it. As others have said, though, <code>Clear()</code> will call it for you.</p>
<p>A better approach, however, is to enclose the declaration and and assignment of the variable in a using() block:</p>
<pre><code>byte[] hashCode;
using(var hasher = new MD5CryptoServiceProvider())
{
hashCode = hasher.ComputeHash(data);
}
</code></pre>
|
How can I check for average concurrent events in a SQL table based on the date, time and duration of the events? <p>I have a set of call detail records, and from those records, I'm supposed to determine the average concurrent active calls per system, per hour (at a precision of one minute). If I query 7pm to 8pm, I should see the average concurrent calls for the hour (averaging the concurrent calls for each minute) within that hour (for each system). </p>
<p>So, I need a way to check for a count of active calls for 7:00-7:01, 7:01-7:02, etc then average those numbers. A call is considered active if the call's time and duration fall within the current minute being checked.</p>
<p>What makes this even more difficult is that it needs to span SQL 7.0 and SQL 2000 (some functions in 2000 aren't available in 7.0, such as GetUTCTime()), if I can just get 2000 working I'll be happy.</p>
<h2>What approaches to this problem can I take?</h2>
<p>I thought about looping through minutes (60) in the hour being checked and adding the count of calls that fall between that minute and then somehow cross referencing the duration to make sure that a call that starts at 7:00 pm and has a duration of 300 seconds shows active at 7:04, but I can't imagine how to approach the problem. I tried to figure out a way to weight each call against particular minute that would tell me if the call was active during that minute or not, but couldn't come up with an effective solution. </p>
<p>The data types here are the same as I have to query against. I don't have any control over the schema (other than possibly converting the data and inserting into another table with more appropriate data types). I've provided some example data that I know has concurrent active calls.</p>
<pre><code>CREATE TABLE Records(
seconds char(10),
time char(4),
date char(8),
dur int,
system int,
port int,
)
--seconds is an stime value. It's the difference of seconds from UTC 1/1/1970 00:00:00 to the current UTC time, we use it as an identifier (like epoch).
--time is the time the call was made.
--date is the day the call was made.
--dur is the duration of the call in seconds.
--system is the system number.
--port is the port on the system (not particularly relevant for this question).
INSERT INTO Records(seconds, time, date, dur, system, port) VALUES('1239924228','1923','20090416',105,2,2)
INSERT INTO Records(seconds, time, date, dur, system, port) VALUES('1239923455','1910','20090416',884,1,97)
INSERT INTO Records(seconds, time, date, dur, system, port) VALUES('1239924221','1923','20090416',116,2,15)
INSERT INTO Records(seconds, time, date, dur, system, port) VALUES('1239924259','1924','20090416',90,1,102)
INSERT INTO Records(seconds, time, date, dur, system, port) VALUES('1239923458','1910','20090416',891,2,1)
INSERT INTO Records(seconds, time, date, dur, system, port) VALUES('1239924255','1924','20090416',99,2,42)
INSERT INTO Records(seconds, time, date, dur, system, port) VALUES('1239924336','1925','20090416',20,2,58)
INSERT INTO Records(seconds, time, date, dur, system, port) VALUES('1239924293','1924','20090416',64,2,41)
INSERT INTO Records(seconds, time, date, dur, system, port) VALUES('1239923472','1911','20090416',888,2,27)
INSERT INTO Records(seconds, time, date, dur, system, port) VALUES('1239924347','1925','20090416',25,1,100)
INSERT INTO Records(seconds, time, date, dur, system, port) VALUES('1239924301','1925','20090416',77,2,55)
INSERT INTO Records(seconds, time, date, dur, system, port) VALUES('1239924332','1925','20090416',52,2,43)
INSERT INTO Records(seconds, time, date, dur, system, port) VALUES('1239924240','1924','20090416',151,1,17)
INSERT INTO Records(seconds, time, date, dur, system, port) VALUES('1239924313','1925','20090416',96,2,62)
INSERT INTO Records(seconds, time, date, dur, system, port) VALUES('1239924094','1921','20090416',315,2,16)
INSERT INTO Records(seconds, time, date, dur, system, port) VALUES('1239923643','1914','20090416',788,2,34)
INSERT INTO Records(seconds, time, date, dur, system, port) VALUES('1239924447','1927','20090416',6,2,27)
INSERT INTO Records(seconds, time, date, dur, system, port) VALUES('1239924342','1925','20090416',119,2,15)
INSERT INTO Records(seconds, time, date, dur, system, port) VALUES('1239924397','1926','20090416',76,2,41)
INSERT INTO Records(seconds, time, date, dur, system, port) VALUES('1239924457','1927','20090416',23,2,27)
</code></pre>
| <p>I think MarkusQ has the answer, but let me develop an alternative that you may find easier to use. I'll use my <a href="http://stackoverflow.com/questions/702500/sql-query-to-collapse-duplicate-values-by-date-range/712309#712309">customary method</a> of developing this as a series of simple transformations in views, an analogue of <a href="http://stackoverflow.com/questions/754527/best-way-to-test-sql-queries/754570#754570">functional decomposition</a> in a procedural language. </p>
<p>First, let's put everything in common units. Recall that <code>record</code>'s column <code>s</code> is seconds since the <em>epoch</em>, midnight 1 January 1970. We can find the number of seconds since midnight of the day of the call, that call occurred, by just taking s modulus the number of seconds in a day: <code>s % (60 * 60 * 24)</code>.</p>
<pre><code>select *,
s % (60 * 60 * 24) as start_secs_from_midnight,
s % (60 * 60 * 24) + dur - 1 as end_secs_from_midnight,
;
</code></pre>
<p>We subtract one from <code>s + dur</code> because a one second call that starts at 12:00:00 also ends on 12:00:00.</p>
<p>We can find minutes since midnight by dividing those results by 60, or just by <code>floor( s / 60 ) % (60 * 24)</code> : </p>
<pre><code>create view record_mins_from_midnight as
select *,
floor( s / 60 ) % (60 * 24) as start_mins_fm,
floor( ( s + dur - 1) / 60 ) % (60 * 24) as end_mins_fm
from record
;
</code></pre>
<p>Now we create a table of minutes. We need 1440 of them, numbered from 0 to 1439. In databases that don't support arbitrary sequences, I <em>create an artificial range or sequence</em> like this:</p>
<pre><code> create table artificial_range (
id int not null primary key auto_increment, idz int) ;
insert into artificial_range(idz) values (0);
-- repeat next line to double rows
insert into artificial_range(idz) select idz from artificial_range;
</code></pre>
<p>So to create a <code>minute</code> table:</p>
<pre><code> create view minute as
select id - 1 as active_minute
from artificial_range
where id <= 1440
;
</code></pre>
<p>Now we just join <code>minute</code> to our record view</p>
<pre><code>create view record_active_minutes as
select * from minutes a
join record_mins_from_midnight b
on (a.active_minute >= b.start_mins_fm
and a.active_minute <= b.end_mins_fm
;
</code></pre>
<p>This just cross products/multiplies record rows, so we have one record row for each whole minute over which the call was active.</p>
<p>Note that I'm doing this by defining active as "(part of) the call occurred during a minute". That is, a two second call that starts at 12:00:59 and ends at 12:01:01 by this definition occurs during two different minutes, but a two second call that starts at 12:00:58 and ends at 12:00:59 occurs during one minute.</p>
<p>I did that because you specified "So, I need a way to check for a count of active calls for 7:00-7:01, 7:01-7:02". If you prefer to consider only calls lasting more than sixty seconds to occur in more than one minute, you'll need to adjust the join.</p>
<p>Now if we want to find the number of active records for any granularity equal to or larger than minute granularity, we just group on that last view. To find average calls per hour we divide by 60 to turn minutes to hours:</p>
<pre><code> select floor( active_minute / 60 ) as hour,
count(*) / 60 as avg_concurent_calls_per_minute_for_hour
from record_active_minutes
group by floor( active_minute / 60 ) ;
</code></pre>
<p>Note that that is the average per hour for <em>all calls</em>, over all days; if we want to limit it to a particular day or range of days, we'd add a <code>where</code> clause.</p>
<hr>
<p><strong>But wait, there's more!</strong></p>
<p>If we create a version of <code>record_active_minutes</code> that does a left outer join, we can get a report that shows the average over all hours in the day:</p>
<pre><code> create view record_active_minutes_all as
select *
from
minutes a
left outer join record_mins_from_midnight b
on (a.active_minute >= b.start_mins_fm
and a.active_minute <= b.end_mins_fm)
;
</code></pre>
<p>Then we again do our select, but against the new view:</p>
<pre><code> select floor( active_minute / 60 ) as hour,
count(*) / 60 as avg_concurent_calls_per_min
from record_active_minutes_all
group by floor( active_minute / 60 ) ;
+------+------------------------------+
| hour | avg_concurrent_calls_per_min |
+------+------------------------------+
| 0 | 0.0000 |
| 1 | 0.0000 |
| 2 | 0.0000 |
| 3 | 0.0000 |
etc....
</code></pre>
<p>We can also index into this with a where. Unfortunately, the join means we'll have null values for the underlying <code>record</code> table where no calls exist for a particular hour, e.g., </p>
<pre><code> select floor( active_minute / 60 ) as hour,
count(*) / 60 as avg_concurent_calls_per_min
from record_active_minutes_all
where month(date) = 1 and year(date) = 2008
group by floor( active_minute / 60 ) ;
</code></pre>
<p>will bring back no rows for hours in which no calls occurred. If we still want our "report-like" view that shows all hours, we make sure we also include those hours with no records:</p>
<pre><code> select floor( active_minute / 60 ) as hour,
count(*) / 60 as avg_concurent_calls_per_minute_for_hour
from record_active_minutes_all
where (month(date) = 1 and year(date) = 2008)
or date is null
group by floor( active_minute / 60 ) ;
</code></pre>
<p>Note that in the last two examples, I'm using a SQL date (to which the functions <code>month</code> and <code>year</code> can be applied), not the char(4) date in your record table.</p>
<p>Which brings up another point: both the date and time in your record table are superfluous and denormalized, as each can be derived from your column s. Leaving them in the table allows the possibility of inconsistent rows, in which <code>date(s) <> date</code> or <code>time(s) <> time</code>. I'd prefer to do it like this:</p>
<pre><code> create table record ( id int not null primary key, s, duration) ;
create view record_date as
select *, dateadd( ss, s, '1970-01-01') as call_date
from record
;
</code></pre>
<p>In the <code>dateadd</code> function, the <code>ss</code> is an enumerated type that tells the function to add seconds; <code>s</code> is the column in record. </p>
|
VS2008 Immediate Window Lost <p>I work in Visual Studio 2008, and a moment ago, I lost access to the windows usually docked at the bottom of the IDE (Immediate, Error List, Search Results) and I can't find a way to get them back again.</p>
<p>I tried</p>
<ul>
<li>Using all the possible shortcuts (<kbd>CTRL</kbd>+<kbd>ALT</kbd>+<kbd>I</kbd>, <kbd>CTRL</kbd>+<kbd>ALT</kbd>+<kbd>O</kbd>)- none of them work</li>
<li>Using the menu: Debug > Windows > Immediate- did not work</li>
<li>Doing a search- no results appear</li>
<li>Rebooting- didn't work either</li>
</ul>
<p>I can however watch, dock, and generally work the breakpoints window.
When I am in Debug mode I can see them again, but if I try to de-dock the window, I get a VS Exception.</p>
<p>Has anyone experienced this issue before?</p>
| <p>The menu commands (which you've already tried)</p>
<ul>
<li>Debug > Windows > Immediate</li>
<li>View > Find Results > Find Results</li>
</ul>
<p>or the keyboard shortcuts</p>
<p><kbd>Ctrl</kbd> + <kbd>D</kbd>, <Kbd>I</kbd> or <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <Kbd>I</kbd> (For the Immediate window)</p>
<p>should work. </p>
<p>If they don't, (and it isn't because the windows are collapsed, undocked, etc) then something has gone wrong.</p>
<p>Try </p>
<pre>Window > Reset Window Layout</pre>
<p>(see Mladen's post) and if that fails, try restarting Visual Studio. </p>
<p>If all else fails, you can try</p>
<pre>Tools > Import and Export Settings... > Reset all settings</pre>
<p>(It gives you an option to backup your current settings)</p>
|
How to use custom serialization during .NET remoting? <p>I've written a custom serialization routine that does not use ISerializable or the SerialzableAttribute to save my objects to a file.</p>
<p>I also remote these same objects and would like to use the same serialization technique. However, I don't want to implement ISerializable because my serialization method is completely decoupled from my objects (and I'd like for it to stay that way).</p>
<p>Is there an easy way (possibly with remoting sinks) where I can take a stream and write bytes to it and on the other side read bytes from it, skipping the Serialization framework in .NET?</p>
| <p>If you want to use <em>remoting</em> then you are limited to <code>BinaryFormatter</code>. Normally, you can use a "serialization surrogate" to provide a serializer separate to the formatter, but AFAIK this deoesn't work with .NET remoting.</p>
<p>However; if you write your own RPC stack (over TCP/IP or HTTP, for example), you'll have a lot more control. Equally, with WCF you can replace the serializer via a behavior. I use both of these tricks in <a href="http://code.google.com/p/protobuf-net/" rel="nofollow">protobuf-net</a> (the WCF hooks <a href="http://code.google.com/p/protobuf-net/source/browse/#svn/trunk/protobuf-net/ServiceModel" rel="nofollow">are here</a>).</p>
<p>Not sure you can do this with <em>remoting</em> though - you'd probably have to use <code>ISerializable</code>.</p>
|
Active Directory - Django/Rails <p>I'm thinking about re-writing a web app in Django or Rails and wondering about authenticating against AD. Is one ecosystem better suited for this (libraries, etc) or is it a toss-up?</p>
<p>(The app will be hosted on Linux)</p>
<p>I have lots of reasons for the re-write, one them is to make myself more marketable. Anyone care to comment on the which of these frameworks has better long-term outlook for a new programmer? (I've read the StackOverflow threads already, but ask just in case something new has come up).</p>
<p>Thanks in advance.</p>
| <p>A quick google to give you some pointers on using Active Directory in these environments.</p>
<ul>
<li><a href="http://www.djangosnippets.org/snippets/501/" rel="nofollow">http://www.djangosnippets.org/snippets/501/</a></li>
<li><a href="http://www.zorched.net/2007/06/04/active-directory-authentication-for-ruby-on-rails/" rel="nofollow">http://www.zorched.net/2007/06/04/active-directory-authentication-for-ruby-on-rails/</a></li>
</ul>
|
Best Way to Handle SQL Parameters? <p>I essentially have a database layer that is totally isolated from any business logic. This means that whenever I get ready to commit some business data to a database, I have to pass all of the business properties into the data method's parameter. For example:</p>
<p><code>Public Function Commit(foo as object) as Boolean</code></p>
<p>This works fine, but when I get into commits and updates that take dozens of parameters, it can be a lot of typing. Not to mention that two of my methods--update and create--take the same parameters since they essentially do the same thing. What I'm wondering is, what would be an optimal solution for passing these parameters so that I don't have to change the parameters in both methods every time something changes as well as reduce my typing :) I've thought of a few possible solutions. One would be to move all the sql parameters to the class level of the data class and then store them in some sort of array that I set in the business layer. Any help would be useful! </p>
| <p>So essentially you want to pass in a <a href="http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx" rel="nofollow">List</a> of <a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparameter.aspx" rel="nofollow">Parameters</a>?</p>
<p>Why not redo your Commit function and have it accept a List of Parameter objects?</p>
|
NHibernate Conceptual Aggregate Roots <p>I have a couple of entities that I want to treat as an aggregate. The problem is their association is conceptual rather than via foreign keys in the DB.</p>
<p>The schema I was given:
<img src="http://files.robtennyson.us/2009/2009-04-17%5F1414.png" alt="alt text" /></p>
<p>My goal is to create an <code>InventoryWeek</code> class that I add inventory transactions to. So the inventory week obviously wraps <code>FACIL_INVENTORY_WEEK</code> and the transactions are added to <code>FACIL_INVENTORY</code>. So pulling this from the DB, I would get the week given the facility and date, and then I would want all of the transactions that have an <code>INVENTORY_DATE</code> within the week.</p>
<p><strong>Is there a way to map this relationship in nhibernate? Or is there a better way to model this altogether?</strong></p>
| <p>You can map relations between tables based on non-primary-keys, but in a limited way. </p>
<p>To give some specific advise, you have to ask a more specific question. Try to map it and if something does not work as you expect, ask.</p>
|
Getting Object Functionallity out of C++ code in C# <p>I have have a function in wrote in C++ that calls some functions in a old lib. This function creates some memory makes the calls and destroys the memory. To optimize this I would create an object that would keep the memory allocated until the object was destroyed. However I'm going to be calling this function from C# and don't believe I can export a Class, just functions or variables.</p>
<p>My idea is instead this; Think of the DLL as a class and the use local vars inside the scope of the dll to point to memory. Then have a function to create the memory, call the worker functions and another to destroy the memory when done with the DLL.</p>
<p>Is this a good approach? Is there a better way?</p>
| <p>I prefer to write a managed wrapper in C++/CLI (formerly Managed C++), as it makes it much easier to explicitly do what you want with managed/unmanaged interoperability on the C++ side, and your C# doesn't get polluted with P/Invoke style code.</p>
<p><strong>Edit</strong> Just noticed your comment "<em>However I'm going to be calling this function from C# and don't believe I can export a Class, just functions or variables.</em>"</p>
<p>That's not entirely true - C# <strong>can</strong> import full classes from an assembly generated from C++/CLI code.</p>
|
SSRS 2005: Change column display from item column value/one row to something else? <p>I have a table/dataset like:</p>
<pre><code>1/1/2009 | Training 1 | Mike
1/1/2009 | Training 1 | Bill
1/1/2009 | Training 1 | Steve
</code></pre>
<p>I would like to display as</p>
<pre><code>1/1/2009 | Training 1
Mike, Bill, Steve
</code></pre>
<p>The idea is that the resulting printed page space is not wasted by printing one column on most of the page down but shortening the space to either a horizontal list or a columned result inside that field. What is the best way?</p>
<p>I would like to handle this is report designer as opposed to mucking with SQL results. I see several ways that gets close but not exact. I'm on SSRS 2005. </p>
| <p>Without using SQL to generate the CSV, then try a matrix control to change the rows into columns and groups on the date/training... but you won't have commas in between.</p>
|
How do I keep my world data in synch in a multi-threaded game engine? <p>So I'm trying to create a simple multi-threaded game engine for the game I want to write. So far, everything has worked without any problems, I even know what steps I have to take to finish it.</p>
<p>There is only one thing I don't know (well, technically, I know a solution for it, but I'm hoping there is something more elegant and faster): Basically, I have a seperate thread for every part of my engine - Graphics, Input, Physics, Audio, etc.</p>
<p>The physics thread has a complete scene node structure of the world, where it simulates everything. However, I now have to get this structure over to my graphics thread, with the least overhead possible. Ideally, it should only transfer the parts which changed since the last update.</p>
<p>I have components in place for transfering this data, only problem is generating it.</p>
<p>So far, I have thought of two different approaches:</p>
<ul>
<li>copy the whole structure for every update - very simple, but possibly time and memory intensife (I don't have experience with large engines - would this be viable?)</li>
<li>Keep track of which parts of the scene changed by marking the scene nodes with some flags, and then only copying over the changed parts</li>
</ul>
<p>Approach one would copy a big amount of memory, but without much processing power, approach two would do the reverse: plenty of processing power, less memory copied.</p>
<p>Is there some general answer which approach would be faster in a typical gaming environment?</p>
| <p>No, there is not an accepted general answer, it is a current area of research in games development. </p>
<p>My 2 cents is the conventional wisdom - which one to use really depends on your specific use case - if your game has lots of data (ie it's very memory intensive, like most blockbuster titles), you'll probably want to just transmit changes. If your game isn't memory intensive (eg, arcade games), you can probably get away with copying the entire object.</p>
<p>I'd suggest implementing both and hooking up performance timers to see which works better for you; it is possible to implement an architecture which can handle both methods transparently.</p>
|
Filer DataTable to exclude DBNull.Value <p>I receive a DataTable from excel file and data in the first Column looks like this:</p>
<p>11129</p>
<p>DBNull.Value</p>
<p>29299</p>
<p>29020</p>
<p>DBNull.Value</p>
<p>29020</p>
<p>I'm using LINQ to select distict and it works if there are no DBNull.Value values as below.
albumIds = dt.AsEnumerable().Select(p => (int)p.Field("F1")).Distinct().ToArray();</p>
<p>But if DBNull.Value present which represent empty excel cells I get conversion errors. </p>
<p>How do I filter out those DBNull.Value from my result set? </p>
<p>Thank you</p>
| <p>As hinted at in Jeremy's answer, If you've a reference to <a href="http://msdn.microsoft.com/en-us/library/bb360891.aspx" rel="nofollow">System.Data.DataSetExtensions.dll</a>, you'll get some handy extension methods for working with DataSets and DataTables using LINQ. Specifically, you can use the Field<code><int?></code>() method to convert an integer column that might contain DBNull into a column of nullable ints...</p>
<pre><code>albumIds = dt.AsEnumerable().Select(row => row.Field<int?>("F1"))
.Where(val => val.HasValue)
.Select(val => val.Value)
.Distinct()
.ToArray();
</code></pre>
|
Axis 2 java2wsdl creates different wsdl than JBoss shows in the ?wsdl URL <p>I'm refactoring the way the client code for a bottom-up web service is built. The existing build creates the Java client code by using a deployment of the web service on JBoss 4.2 and executing the Axis 2 AntCodegenTask against <a href="http://devserver.url?wsdl" rel="nofollow">http://devserver.url?wsdl</a>. This method fails if the development server is down or has outdated wsdl. (Crusie Control fails whenever the wsdl changes.)</p>
<p>I need to build the client code against the web service class itself instead of having to point to a deployment of the web service. I use java2wsdl to generate wsdl from the web service class and then use the same AntCodegenTask to generate the client classes.</p>
<p>The problem is that wsdl created by java2wsdl is different than what JBoss displays in <a href="http://devserver.url?wsdl" rel="nofollow">http://devserver.url?wsdl</a>. Among other things, some of the namespaces are different and the AntCodegenTask step doesn't convert these namespaces into the correct package structure.</p>
<p>I've got to get the final package structure to be what the client code expects. The existing AntCodegenTask uses namespacetopackages="..." to accomplish that, but when I execute the same AntCodegenTask to the wsdl generated by java2wsdl it doesn't convert the namespaces to the package name.</p>
<p>Why would Axis show different wsdl when the web service is deployed in JBoss than it generates from java2wsdl?</p>
<p>Is there a way to use Axis to create the client code from the web service class without generating the intermediate wsdl?</p>
<p>The documentation for the java2wsdl and wsdl2java Ant tasks is a little bit spotty. Axis 2 v 1.4.1 gives Ant tasks for AntCodegenTask and 2 Java2WSDLTasks in different packages. The Axis 2 installation includes binaries for wsdl2java and java2wsdl, but no codegen binary. Maybe AntCodegenTask is the same as wsdl2java.</p>
<p>Has anyone got something like this to work with Axis 2?</p>
| <p>Deploy webservice on JBoss server. Save locally WSDL file and pass it as a parameter to Ant task. Hopefully generated classes would be correct, however it may happen that Axis 2 would not like to work with JBoss generated WSDL.</p>
<p>In that case use wsconsume.bat provided with JBoss instead of AXIS ant task.</p>
<p>Always use that once generated WSDL file, package it with application, etc, since even different versions of JBoss produce different WSDL files.</p>
<p>Axis always sort of sucked, if you can (I now it is not so obvious...) use Apache CXF or native JBoss implementation.</p>
|
How to capture output of execvp <p>I'm developing a program which executes a program using execvp. It needs to capture the results of the child process and parse them in the main process. It seems there is a way, using named pipes, and duping. I'm trying to hunt down a good example of this, but so far no luck. If anyone has any pointers, links and/or suggestions about this, I'd greatly appreciate it. </p>
| <p>You don't need named pipes; unnamed pipes work just fine. Actually, often you can just use <code>popen</code> instead of doing the <code>pipe</code>/<code>fork</code>/<code>dup</code>/<code>exec</code> yourself. <code>popen</code> works like this (though your <code>libc</code>'s implementation likely has more error checking):</p>
<pre><code>FILE *popen(const char *command, const char *type) {
int fds[2];
const char *argv[4] = {"/bin/sh", "-c", command};
pipe(fds);
if (fork() == 0) {
close(fds[0]);
dup2(type[0] == 'r' ? 0 : 1, fds[1]);
close(fds[1]);
execvp(argv[0], argv);
exit(-1);
}
close(fds[1]);
return fdopen(fds[0], type);
}
</code></pre>
<p>This creates an unnamed pipe, and <code>fork</code>s. In the child, it reattaches stdout (or stdin) to one end of the pipe, then <code>exec</code>s the child. The parent can simply read (or write) from the other end of the pipe.</p>
|
ASP.NET Store uploaded file sql server table <p>How do you store a file that was uploaded by an ASP.net webform into a sql server 2005 varbinary(max) field?</p>
<p>Here is what I have so far:</p>
<pre><code>protected void btnUpload_Click(object sender, EventArgs e)
{
for (int i = 0; i < Request.Files.Count; i++)
{
StoreFile(Request.Files[i]);
}
}
private void StoreFile(HttpPostedFile file)
{
// what do i do now?
}
</code></pre>
<p>A plain old ado.net example would be good. So would a linq to sql example.</p>
<p>Thanks</p>
| <p>There's nice tutorial on how to upload a file directly into the database
at <a href="http://www.4guysfromrolla.com/articles/120606-1.aspx" rel="nofollow">4GuysFromRolla</a></p>
|
How can I automatically fold a long C code in Vim? <p>I regularly run into C-codes without folding. It is irritating to read them if there is no folding, particularly with long files. How can I fold them?</p>
| <p>To fold according to syntax</p>
<pre><code>:set foldmethod=syntax
</code></pre>
<p>If you want to do it manually on the bits you want to fold away</p>
<pre><code>:set foldmethod=manual
</code></pre>
<p>then create new folds by selecting / moving and pressing zf
e.g.</p>
<pre><code>shift-v j j zf
</code></pre>
<p>(ignoring the spaces)</p>
<p>Edit: Also see the comments of this answer for indent and marker foldmethods.</p>
|
Do singleton exceptions work? <p>A collegue of mine at work gave a presentation on static factory methods (right out of Effective Java), and then gave an example of its use for obtaining static / singleton exceptions. </p>
<p>This set off a red flag for me. Aren't exceptions stateful? Aren't they populated by the JVM for stack trace info? What savings do you really get with this, since exceptions should only occur for, well, exceptional situations?</p>
<p>My knowledge on Exceptions is rather limited, so I come to you with this: will singleton exceptions work, and is there any reason to use them?</p>
| <p>Singleton exceptions are supposed to be a performance optimization. The thinking is that you eliminate the cost of populating the stack trace when creating an exception which is usually the most expensive part of exceptions.</p>
<p>If the exception were sufficiently unique and descriptive and the stacktrace was not going to be used, then a singleton could potentially be effective. You could design the app such that a specific exception type with a specific message always means that an exception orgininated from a specific location. Then the stack trace would be irrelevant.</p>
<p>The <a href="http://java.sun.com/developer/JDCTechTips/2003/tt0422.html#2" rel="nofollow">April 22, 2003 Tech Tips article</a> describes a scenario where you reuse an exception. In this case, they are trying to game the garbage collector by reducing the number of objects created. If you skipped the <code>populateStackTrace()</code> call, you would not have to worry about threading.</p>
<p>Generally, if the performance impact of an exception is causing problems, that is a sign that exceptions are being used for application logic and an error-code should be used instead.</p>
<p>In newer JVM's (1.4+, I believe), this "optimization" can be done automatically by the JVM when running in "-server" mode. This hotspot optimization can be controlled by the option <code>-XX:+OmitStackTraceInFastThrow</code>.</p>
<p><em>Personally, I would recommend against using the singleton exception [anti-]pattern.</em></p>
|
Does anybody have a code review checklist for annual reviews? <p>I have a software engineer that I supervise and management needs a "code review" as part of his annual review. I'm thinking that there might be something out there that could help with this. Something along the lines of a list of categories and maybe a rating (1-5?) in each category with a space for comments. Categories that I'm thinking of:</p>
<ul>
<li>Documents code properly</li>
<li>Clearly organizes source files (?!?)</li>
<li>Adheres to coding standards</li>
<li>etc.</li>
</ul>
<p>I haven't been asked to review any of the usual employee attributes like "ability to work well with others", etc. That will be handled by his non-engineer supervisor. I just need to review his abilities as a developer.</p>
<p>Any ideas on this?</p>
<p><strong>Edit:</strong> Norman Ramsey asked "why" management needs this. The answer is that I'm an outside consultant and do not directly supervise this developer. There's nobody else technical in the company. They are doing his annual review and want feedback on the product of his work for the last year. I know that they are frustrated with the fact that their (artifical) deadlines have been missed. But I think they guy does good work. So I want to present this information to management in a formalized way that they can understand. </p>
| <p>I've got just what you need. It's a comprehensive assortment of already created documents including but not limited to review forms, inspection data spreadsheets, process descriptions, etc. :
<p>
<a href="http://www.processimpact.com/pr%5Fgoodies.shtml" rel="nofollow">http://www.processimpact.com/pr_goodies.shtml</a></p>
|
Matlab subclassing question <p>Question about subclassing in matlab, under the new class system. I've got class A with some protected properties:</p>
<pre><code>classdef Table < Base
properties (SetAccess = protected, GetAccess = public)
PropA = [];
end %properties
</code></pre>
<p>I'd like to make a subclass with some specialized features, and further restrict access to PropA. (i.e. make get access private in the subclass). My first thought was:</p>
<pre><code>classdef subTable < Table
...
methods (Access = private)
out = get.PropA(obj, value);
end %private methods
</code></pre>
<p>However, in the help it says: "You must define property access methods in a methods block that specifies no attributes." So much for that idea.</p>
<p>Any ideas?</p>
| <p>I don't believe this is possible. From <a href="http://www.mathworks.com/access/helpdesk/help/techdoc/matlab%5Foop/brenyev-1.html#zmw57dd0e11935" rel="nofollow">MATLAB Documentation</a>:</p>
<p>There are only two conditions that allow you to redefine superclass properties:</p>
<ul>
<li>The superclass property Abstract attribute is set to true</li>
<li>The superclass property has both the SetAccess and GetAccess attributes set to private</li>
</ul>
<p>Nor do I think that doing this would be a good idea. It violates the <a href="http://en.wikipedia.org/wiki/Liskov%5Fsubstitution%5Fprinciple" rel="nofollow">Liskov Substitution Principle</a>. Functions written to accept a Table should also be able to accept a subTable and work properly. If such a function accessed PropA, it would fail when passed a subTable.</p>
|
How to display all elements in an arraylist? <p>Say I have a car class with attributes <code>make</code> and <code>registration</code>, and i create an ArrayList to store them. How do I display all the elements in the ArrayList?</p>
<p>I have this code right now:</p>
<pre><code>public Car getAll()
{
for(int i = 0; i < cars.size(); i++) //cars name of arraylist
{
Car car = cars.get(i);
{
return cars.get (i);
}
}
return null;
}
</code></pre>
<p>It compiles fine but when I try it out in my tester class using this code:</p>
<pre><code>private static void getAll(Car c1)
{
ArrayList <Car> cars = c1.getAll(); // error incompatible type
for(Car item : cars)
{
System.out.println(item.getMake()
+ " "
+ item.getReg()
);
}
}
</code></pre>
<p>I am getting a error of incompatible type. Is my coding correct? If not can someone please show me how it should be?</p>
<p>Thank You</p>
| <p>Are you trying to make something like this?</p>
<pre><code>public List<Car> getAll() {
return new ArrayList<Car>(cars);
}
</code></pre>
<p>And then calling it:</p>
<pre><code>List<Car> cars = c1.getAll();
for (Car item : cars) {
System.out.println(item.getMake() + " " + item.getReg());
}
</code></pre>
|
How do social networking websites compute friend updates? <p>Social networking website probably maintain tables for users, friends and events... </p>
<p>How do they use these tables to compute friends events in an efficient and scalable manner?</p>
| <p>Many of the social networking sites like Twitter don't use an RDBMS at all but a Message Queue application. A lot of them start out with a already present application like RabbitMQ. Some of them get big enough they have to heavily customize or build their own. Twitter is in the process of doing this for the second time.</p>
<p>A message queue application works by holding messages from one service for one or more other services. For instance say service Frank is publishing messages to a queue foo. Joe and Jill are subscribed to Franks foo queue. the application will keep track of whether or not Joe or Jill have recieved the messages and once every subscriber to the queue has recieved the message it discards it. Frank fires messages and forgets about it. Joe and Jill ask for messages from foo and get whatever messages they haven't gotten yet. Joe and Jill do whatever they need to do with the message. Perhaps keeping it around perhaps not. </p>
<p>The message queue application guarantees that everyone who is supposed to get the message can and will get the message when they request them. The publisher can send the messages confident that subscriber can get them eventually. This has the benefit of being completely asynchronous and not requiring costly joins.</p>
<p>EDIT: I should mention also that usually the storage for these kind of things at high scale are heavily denormalized. So Joe and Jill may be storing a copy of the exact same message. This is considered ok because it helps the application scale to billions of users.</p>
<p>Other reading:</p>
<ol>
<li><a href="http://www.rabbitmq.com/">http://www.rabbitmq.com/</a></li>
<li><a href="http://qpid.apache.org/">http://qpid.apache.org/</a></li>
</ol>
|
Using Javascript OpenID Selector with Rails <p>Based on <a href="http://stackoverflow.com/questions/702114/stackoverflow-like-login-system-in-rails">this article</a>, it seems like SO is using <a href="http://code.google.com/p/openid-selector/" rel="nofollow">Javascript OpenID Selector</a> (JOIS) to handle OpenID logins in its "view". </p>
<p>I love the simple interface and I would like to use it in a Rails project. </p>
<p>I know that <a href="https://rpxnow.com/" rel="nofollow">RPX</a> would probably be the easier choice, but I'd like to build this on my own.</p>
<p>Can you help me find answers to a few questions I have?</p>
<ol>
<li>Has anyone of you already done this
or does anyone know of a good
example? </li>
<li>What setup (combination of
plugins/gems) would you recommend if
I'm using JOIS in my
view?</li>
<li>Is there a JOIS
implementation (or anything similar besides RPX) based on <a href="http://www.prototypejs.org/" rel="nofollow">Prototype</a>
instead of <a href="http://jquery.com/" rel="nofollow">JQuery</a>?</li>
<li>Will I need another library besides the <a href="http://openidenabled.com/ruby-openid/" rel="nofollow">Ruby OpenID library</a>
to support all the account providers (OpenID, Google, Yahoo, etc.) supported
by JOIS?</li>
</ol>
<p>Thank you!</p>
| <p>In answer to #4, no. All the options provided by the OpenID Selector are standard OpenID Providers and the ruby OpenID library (I'm assuming you're talking about the Janrain one) supports all of them.</p>
<p>Sorry I can't help you with the rest. I haven't actually used the Ruby library myself for over 3 years.</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.