input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Where should I store SSIS Data? <p>I have a slow custom data source in a SSIS Dataa Flow Task.I have to run the package with multiple parameters</p>
<p>If I want to upload data to a DB using SQL Data Destination(Bulk Insert) the connection times out</p>
<p>If I write the data to a flat file I cannot run multiple instances of the package, since they will write to the same file. Can I pass the file name as a parameter somewhere?</p>
<p>Do I need to write a custom Script Destination as the last resort?</p>
| <p>A Raw File Destination allows you to store the file name in a package variable. You can then use the /Set or /Conf command line switches of dtexec to either set the variable on the command line, or bring in a configuration file for that run of the package. The Raw Files aren't great for manual processing, but if your data flow ends in one, then the next data flow picks it up and runs with it, it's very easy to handle.</p>
|
static class instances unique to a request or a server in ASP.NET? <pre><code> public sealed class UserLoginSingleton
{
UserLoginCollection _userLoginCol = new UserLoginCollection();
UserLoginSingleton()
{
}
public static UserLoginSingleton Instance
{
get
{
IDictionary items = HttpContext.Current.Items;
if (!items.Contains("TheInstance"))
{
items["TheInstance"] = new UserLoginSingleton();
}
return items["TheInstance"] as UserLoginSingleton;
}
}
public void CreateUserObj(string xmlData)
{
_userLoginCol = (UserLoginCollection)_xmlUtil.Deserialize(xmlData, typeof(UserLoginCollection));
}
public UserLoginCollection getUserObj()
{
return _userLoginCol;
}
}
</code></pre>
<p>Usage:</p>
<p>Page 1.aspx</p>
<pre><code>UserLoginSingleton.Instance.CreateUserObj(xml);
</code></pre>
<p>Pase2.aspx:</p>
<blockquote>
<p>UserLoginCollection
userLoginCollection =
UserLoginSingleton.Instance.getUserObj();</p>
</blockquote>
<p>Followed the article here:
<a href="http://stackoverflow.com/questions/194999/are-static-class-instances-unique-to-a-request-or-a-server-in-aspnet">link text</a></p>
<p>I set my collection object in page 1 and then do a response.redirect or click on link to get me to page 2.aspx. However, my singleton instance has no collection object i set. How do i persist my collection object across diff pages per each session?</p>
<p>I know static's wont work as every instance will see the object and i want that to specific per each user.</p>
| <p>The <code>HttpContext.Items</code> collection is per-request. So in your case when the user gets redirected to page2.aspx, the instance you created on page 1 is gone. For the same instance to be available across requests, you need to be using <code>HttpContext.Session</code> to store your instance.</p>
|
Getting PartCover to work <p>I want to try PartCover for code coverage. I'm running Visual Studio 2008 Professional with MSTest. The Professional Edition does not include the Team Testing tools, like Code Coverage.</p>
<p>So, I'm trying PartCover, but I can't get it to work. In the PartCover.Browser I've selected the MSTest executable, I've pointed the working arguments to my tests.dll, and I've tried pointing my Working Directory to the TestResults folder, but I get an error:</p>
<p>"Report is empty. Check settings and run target again."</p>
<p>I don't know what to try next.</p>
<p><strong>Edit</strong></p>
<p>It turns out I had two problems. First, I wasn't putting my Rules right. Second, I had spaces in my working arguments. The spaces were giving an error, but not showing up anywhere.</p>
| <p>Yep, I had this problem too.
Check out the format for the Rules field.</p>
<p>In the browser add something like:</p>
<p><code>+[MyNamespace.MyAssemblyName]*</code></p>
<p>Where the assembly name you specify is the name of the assembly containing the types you want coverage for. Start off with:</p>
<p><code>+[*]*</code></p>
<p>and partcover will happily give you coverage metrics for the unit test project, any libraries you reference and on and on.</p>
<p>From the command line you specify the same pattern in the --include argument:
<code>--include=[MyNamespace.MyAssembly]*</code></p>
<p>You can also exclude contained namespaces or types or restrict which types from within the namespace you get coverage data for in the report. The format for the rules is a subset of regular expression syntax according to the manual (consisting of asterix as a wildcard and characters that make up assembly and class names, so pretty limited but enough to get the data you want). Check out the section on rules in the manual. If you don't have the manual, <a href="http://sourceforge.net/forum/forum.php?forum_id=611572">download it from sourceforge</a>.</p>
|
Windows Explorer directory as bundle <p>I have been investigating for some time now a way to prevent my user from accidently entering a data directory of my application.</p>
<p>My application uses a folder to store a structured project. The folder internal structure is critic and should not be messed up. I would like my user to see this folder as a whole and not be able to open it (like a Mac bundle).</p>
<p>Is there a way to do that on Windows?</p>
<p><strong>Edit from current answers</strong></p>
<p>Of course I am not trying to prevent my users from accessing their data, just protecting them from accidentally destroying the data integrity. So encryption or password protection are not needed. </p>
<p>Thank you all for your .Net answers but unfortunately, this is mainly a C++ project without any dependency to the .Net framework.</p>
<p>The data I am mentioning are not light, they are acquired images from an electronic microscope. These data can be huge (~100 MiB to ~1 GiB) so loading everything in memory is not an option. These are huge images so the storage must provide a way to read the data incrementally by accessing one file at a time without loading the whole archive in memory.</p>
<p>Besides, the application is mainly legacy with some components we are not even responsible of. A solution that allows me to keep the current IO code is preferable.</p>
<p>Shell Extension looks interesting, I will investigate the solution further.</p>
<p>LarryF, can you elaborate on Filter Driver or DefineDOSDevice ? I am not familiar with these concepts.</p>
| <p>Inside, or outside of your program?</p>
<p>There are ways, but none of them easy. You are probably going to be looking at a Filter Driver on the file system.</p>
|
How to get the name of the component that's extending mine in ColdFusion? <p>Let's say I have the following component called <strong><em>Base</em></strong>:</p>
<pre><code><cfcomponent output="false">
<cffunction name="init" access="public" returntype="Any" output="false">
<cfset variables.metadata = getmetadata(this)>
<cfreturn this>
</cffunction>
<cffunction name="getmeta" access="public" returntype="Any" output="false">
<cfreturn variables.metadata>
</cffunction>
</cfcomponent>
</code></pre>
<p>and I want to extend base in another component called <strong><em>Admin</em></strong>:</p>
<pre><code><cfcomponent output="false" extends="Base">
</cfcomponent>
</code></pre>
<p>Now within my application if I do the following when creating the object:</p>
<pre><code><cfset obj = createobject("component", "Admin").init()>
<cfdump var="#obj.getmeta()#">
</code></pre>
<p>The metadata I get back tells me that the name of the component is <strong><em>Admin</em></strong> and it's extending my <strong><em>Base</em></strong> component. That's all good, but I don't want to have to call the <strong><em>init()</em></strong> method explicitly when creating the object.</p>
<p>I would be nice if I could do something like this in my <strong><em>Base</em></strong> component:</p>
<pre><code><cfcomponent output="false">
<cfset init()>
<cffunction name="init" access="public" returntype="Any" output="false">
<cfset variables.metadata = getmetadata(this)>
<cfreturn this>
</cffunction>
<cffunction name="getmeta" access="public" returntype="Any" output="false">
<cfreturn variables.metadata>
</cffunction>
</cfcomponent>
</code></pre>
<p>However then the metadata returned by the getmeta() method telling me that the component name is <strong><em>Base</em></strong> even though it's still being extended. Any thoughts on how to accomplish this?</p>
| <p>Is there a reason you don't want to call init in each extending cfc?</p>
<pre><code><cfcomponent output="false" extends="Base">
<cfset super.init()>
</cfcomponent>
</code></pre>
<p>That seems to populate the metadata like you want.</p>
|
ASP.net: Weird web user control problem <p>This is weird. I declare a web user control on a asp.net web page like so</p>
<pre><code>print("<%@ Register Src="~/Controls/blah.ascx" TagName="blahCtrl" TagPrefix="cc" %>");
</code></pre>
<p>I don't have problem with it until today in the code behind where it give me name blah is not declared error. does anyone know what cause this?</p>
| <p>Try registering it on the .aspx source page not the .aspx.cs page.</p>
|
Approach to convert from org.joda.time.DateTime to java.util.Calendar <p>Anyone done this and can share? I see an option or two but want to know what others have accomplished.</p>
| <p>According to joda-time documentation the preferred method to use is to call this:
<a href="http://joda-time.sourceforge.net/api-release/org/joda/time/base/AbstractDateTime.html#toCalendar(java.util.Locale)">AbstractDateTime#toCalendar</a>.</p>
|
Basic: How is the session id created? <p>Does IIS create the session id when a request is received and where is that saved (client or server)?</p>
<p>How does server recognize that the request is coming from the same user/session?</p>
| <p>The answer to your first question is Yes -- if sessions are used, and Both.</p>
<p>A cookie is a short bit of text passed back and forth between client and server with every request/response.</p>
<p>IIS generates a session id, saves it, and any associated data, and passes the in a cookie to the client (browser).</p>
<p>When the client makes another request, it sends the cookie, containing the sessionID back to the server. The server can then look at the cookie and find the session (and the associated data) which is saved on the server.</p>
|
Running multiple virtual directories on IIS - any performance issues? <p>I need to run 8-10 instances of my application on IIS 6.0 that are all identical but point to different backends (handled via config files, which would be different for each virtual directory). I want to create multiple virtual directories that point to different versions of the app and I want to know if there is any significant performance penalty for this. The server (Windows Server 2003) is a quad-core with 4 GB of ram and the single install of the app barely touches the CPU or memory, so it doesn't seem to be a concern. This doesn't seem to justify another server, especially since some of the instances will be very lightly used. Obviously, performance depends on the server and the application, but are there any concerns with this situation?</p>
| <p>No concerns. If you run into any performance issues, it won't be with IIS for 10 apps that size.</p>
|
Problem with table JOIN in MySQL and aggregation <p>I have three tables. This query will write down the right answer (x-lines for btv.id_user with appropriate btv.cas and race.id_zavod</p>
<pre><code>SELECT `btv.id_user`, `btv.id_zavod`,`btv.cas`
FROM `btv`
JOIN `btu` ON `btv.id_user` = `btu.id_user`
JOIN `race` ON 'btv.id_zavod' = `race.id_zavod`
WHERE `race.type` = '8' AND `btv.id_user` = '607'
</code></pre>
<p>Result:</p>
<pre><code>| 607 | 512 | 03:15:58 |
| 607 | 730 | 03:01:18 |
| 607 | 164 | 03:07:26 |
| 607 | 767 | 02:58:31 |
| 607 | 1147 | 03:06:47 |
| 607 | 1149 | 03:09:41 |
| 607 | 1178 | 03:24:20 |
</code></pre>
<p>But when I try to aggregate it to one row by the id_user it return correct min btv.cas but wrong join wrong race.id_zavod</p>
<pre><code>SELECT `btv.id_user`, `btv.id_zavod`, MIN( `btv.cas` )
FROM `btv`
JOIN `btu` ON `btv.id_user` = `btu.id_user`
JOIN `race` ON 'btv.id_zavod' = `race.id_zavod`
WHERE `race.type` = '8' AND `btv.id_user` = '607'
GROUP BY `btv.id_user`
</code></pre>
<p>Result:</p>
<pre><code>| 607 | 512 | 02:58:31 |
</code></pre>
| <p>The query you have written:</p>
<pre><code>SELECT `btv.id_user`, `btv.id_zavod`, MIN( `btv.cas` )
FROM `btv`
JOIN `btu` ON `btv.id_user` = `btu.id_user`
JOIN `race` ON 'btv.id_zavod' = `race.id_zavod`
WHERE `race.type` = '8' AND `btv.id_user` = '607'
GROUP BY `btv.id_user`</code></pre>
<p>won't run. You need a group by id_zavod or something. Can you tell us what query you are really running? And what result set you expect?</p>
|
How do YOU reduce compile time, and linking time for Visual C++ projects (native C++)? <p>How do YOU reduce compile time, and linking time for VC++ projects (native C++)?</p>
<p>Please specify if each suggestion applies to debug, release, or both.</p>
| <p>It may sound obvious to you, but we try to use forward declarations as much as possible, even if it requires to write out long namespace names the type(s) is/are in:</p>
<pre><code>// Forward declaration stuff
namespace plotter { namespace logic { class Plotter; } }
// Real stuff
namespace plotter {
namespace samples {
class Window {
logic::Plotter * mPlotter;
// ...
};
}
}
</code></pre>
<p>It greatly reduces the time for compiling also on others compilers. Indeed it applies to all configurations :)</p>
|
Javascript XML parser problem <p>test[_nObjectives].pool[j].feedbackCorrect = oQuestions[j].getElementsByTagName("feedbackCorrect")[0].firstChild.data;</p>
<p>and the XML in this case contains this: </p>
<pre><code> <feedbackCorrect>
</feedbackCorrect>
</code></pre>
<p>When executing that line of code the following error occurs: Message: Object required</p>
<p>I don't get it. The tag is there, if it is empty the error occurs and even has spaces chars it doesn't work.</p>
| <p>you are getting the error because</p>
<pre><code>oQuestions[j].getElementsByTagName("feedbackCorrect")[0]
</code></pre>
<p>is returning that tag, and the .firstChild is returning null, because it has no children...</p>
<p>Are you sure you dont want</p>
<pre><code>oQuestions[j].getElementsByTagName("feedbackCorrect")[0].data
</code></pre>
<p>?</p>
|
How to create a form object from 2 different model objects in Django? <p>I have 2 objects, both from different Model classes, and want to show a form containing some fields from each one. How can I do this?</p>
| <p>The way I do it is by creating two <code>ModelForm</code> classes that use the <code>fields</code> Meta attribute to specify which <a href="http://docs.djangoproject.com/en/dev/topics/forms/modelforms/?from=olddocs#using-a-subset-of-fields-on-the-form">subset of fields</a> to use to display in the form. I display both forms in the template, and handle them in the view. </p>
|
NHibernate session management in ASP.NET MVC <p>I am currently playing around with the HybridSessionBuilder class found on Jeffrey Palermo's blog post:</p>
<p><a href="http://jeffreypalermo.com/blog/use-this-nhibernate-wrapper-to-keep-your-repository-classes-simple/">http://jeffreypalermo.com/blog/use-this-nhibernate-wrapper-to-keep-your-repository-classes-simple/</a></p>
<p>Using this class, my repository looks like this:</p>
<pre><code>public class UserRepository : IUserRepository
{
private readonly ISessionBuilder _sessionBuilder;
public UserRepository(ISessionBuilder sessionBuilder)
{
_sessionBuilder = sessionBuilder;
}
public User GetByID(string userID)
{
using (ISession session = _sessionBuilder.GetSession())
{
return session.Get<User>(userID);
}
}
}
</code></pre>
<p>Is this the best way to go about managing the NHibernate session / factory? I've heard things about Unit of Work and creating a session per web request and flushing it at the end. From what I can tell, my current implementation isn't doing any of this. It is basically relying on the Repository to grab the session from the session factory and use it to run the queries.</p>
<p>Are there any pitfalls to doing database access this way?</p>
| <p>You should not wrap your ISession in a using statement -- the point of passing the ISessionBuilder into the repository constructor (dependency injection) is that the calling code is responsible for controlling the life cycle of the ISession. By wrapping it in a using, Dispose() is called on the ISession and you won't be able to lazy load object members or persist it.</p>
<p>We do something similar by just passing in an ISession to the repository constructor. Mr. Palermo's code, as I understand it, simply adds lazy initialization of the ISession. I don't think that's needed because why would you new up a repository if you're not going to use it?</p>
|
QueryInterface for interface VBA._Collection failed <p>We are randomly seeing this error during long executions of our system. The error is caught by our alarm system, and we successfully retry, and continue running the system. The only hits we found on Google seem to mention corrupt installations. We do not think this is the case here, since our systems are running, get the error, and can continue running.</p>
| <p>Register the .dll file again from a command window by using the below command:</p>
<pre><code>regsvr32 C:\WINDOWS\system32\msvbvm60.dll
</code></pre>
|
best practices to import text into html <p>What is the best practice for importing text into html from a multipage InDesign document, from designer to non-designer. Document designed on a mac going to CMS on PC - hand off the InDesign File or strip text into word file? Supplying all images and pdf as go-by?</p>
| <p>More people are likely to be able to open a PDF than InDesign, especially with font considerations. I prefer to get work in PDF format. I can easily extract the text and I can pull the document into PhotoShop to slice it up. You just have to make sure the quality/compression settings are right so it doesn't muck up the JPEGs too much.</p>
|
positioning logo and navigation links not aligning <p>Screenshot of the problem:</p>
<p><img src="http://i.stack.imgur.com/qutvW.jpg" alt="http://i36.tinypic.com/dfxdmd.jpg"></p>
<p>The yellow block is the logo and the blue box is the nav links (I have blanked them out). I would like to align the links at the bottom so they are stuck to the top of the body content (white box). How would I do this?
Here is the relevant CSS and HTML.</p>
<pre><code>#header {
height: 42px;
}
#logo {
width: 253px;
height: 42px;
background-image:url(logo.png);
float: left;
}
#nav {
width: 100%;
border-bottom: 2px solid #3edff2;
vertical-align: bottom;
}
#nav ul {
list-style-type: none;
margin: 0;
padding: 0;
margin-bottom: 4px;
text-align: right;
font-size: 1.25em;
}
#nav ul li {
display: inline;
background-color: #3edff2;
padding: 5px;
}
<div id="header">
<div id="logo"><a href="/"></a></div>
<div id="nav">
<ul>
<li><a href="#">*****</a></li>
[...]
</ul>
</div>
</div>
</code></pre>
<p>Thanks in advance.</p>
| <p>Try this. Seems to work in Firefox/Mac</p>
<pre><code>#header {
height: 42px;
}
#logo {
width: 253px;
height: 42px;
background: #00ffff;
float: left;
}
#nav {
width: 100%;
border-bottom: 2px solid #3edff2;
height: 42px;
}
#nav ul {
list-style-type: none;
margin: 0;
padding-top: 18px;
margin-bottom: 4px;
text-align: right;
font-size: 1.25em;
}
#nav ul li {
display: inline;
background-color: #3edff2;
padding: 5px;
}
</code></pre>
|
Linq 2 SQL or Linq Entities <p>I am starting to design a new application and what I am wondering is peoples opinions on Linq2SQL or Linq2Entities and what they feel is the better technology for rapid development.</p>
<p>I am also doing some research into ADO.net data services.</p>
| <p>Yes, agreed with Slace.</p>
<p>Just be careful on the framework you do choose, to ensure it meets all your needs.</p>
<p>For instance, I recently gutted out Entity Framework from a work project after working with it pretty solidly over the last couple of weeks, as it did not facilitate my needs, mainly due to:-</p>
<ol>
<li>The <a href="http://mosesofegypt.net/post/LINQ-to-Entities-what-is-not-supported.aspx" rel="nofollow">things you can't do in Linq to Entities</a> (such as mapping to .net enum types (grr) and the aggravation of receiving 'NotSupportedException' at nearly every turn if you try to get fancy in your linq query statement by calling on function or method calls (see link)).</li>
<li>Lack of native Lazy Loading (I understand there is tools such as EF Lazy LoadGen to facilitate this, but it was not something I wanted to encorporate).</li>
</ol>
<p>Other than that, commands and the framework seemed straight forward and neat, and the reason I went with EF was:</p>
<ol>
<li>I believed EF was targeted more for enterprise development and thought L2S was more for hobbyists and was a limited framework. However with further understanding and personally, not needing anything in EF I couldn't do with L2S, I am happy with L2S. Especially if it suits stackoverflow, scalability and efficiency is covered for me.</li>
<li>Option for multiple DBMS' (I'm yet to see this in action however)</li>
<li>It was rumored Microsoft was <a href="http://oakleafblog.blogspot.com/2008/05/is-adonet-team-abandoning-linq-to-sql.html" rel="nofollow">dropping support and investment on Linq to SQL</a>.</li>
<li>I love the fact you can update tables and DB changes within the EF .edmx without having to delete the existing schema model (which you are forced to do in Linq to SQL). Albeit, not super annoying unless you've customised any properties in your L2S schema (.dbml).</li>
</ol>
<p>Further reading (another SO post):<br>
<a href="http://stackoverflow.com/questions/252683/is-linq-to-sql-doa">http://stackoverflow.com/questions/252683/is-linq-to-sql-doa</a></p>
<p>I would love to choose EF, I really do not know what to make of the L2S vs. EF debarcle, and if L2S really is a dead duck, shrug. my main gripe admittedly with EF is the NotSupportedException's - I could get around lazy loading if I could perform method calls in linq without getting this...</p>
|
ROR: To scaffold or not? <p>I love scaffolding and it extremely helpful for prototyping. But Should we use scaffolding for developing application as such?</p>
| <p>The name "scaffolding" is sort of a misnomer in Rails now (post 2.0). The structure generated through scaffolding generator is more of a base application to build on, rather than a "prototype" that you throw away later.</p>
<p>At least, if you are designing your application to be RESTful, you will find yourself keeping most of the scaffold generator produced controller and model code, while adding more logic to them. You will perhaps replace the views eventually while keeping bits and pieces of Ruby code in them.</p>
|
How to save history within UpdatePanel? <p>I created an admin page for a web application, and it's mostly ajax. Almost all the events in the page update one of the UpdatePanels on the page.
How can I save each UpdatePanel state in the user's history so when the user pushes the browser "back" button they wont get redirected to the login screen ?</p>
| <p>The ability to manage history was added in .NET 3.5 SP 1. Here are some resources that will help get you up to speed.</p>
<p><a href="http://www.asp.net/learn/3.5-SP1/video-242.aspx">Introduction to ASP.NET Ajax History</a></p>
<p><a href="http://aspnetpodcast.com/CS11/blogs/asp.net_podcast/archive/2008/06/15/asp-net-podcast-show-116-using-the-history-functionality-with-the-asp-net-ajax-updatepanel-in-net-3-5-service-pack-1-beta-1.aspx">ASP.NET Podcast Show #117 - Using the History Functionality with the ASP.NET AJAX UpdatePanel in .NET 3.5 Service Pack 1 Beta 1</a></p>
<p><a href="http://aspnetpodcast.com/CS11/blogs/asp.net_podcast/archive/2008/07/01/asp-net-podcast-show-119-using-the-history-back-functionality-with-the-asp-net-ajax-web-services-in-net-3-5-service-pack-1-beta-1.aspx">ASP.NET Podcast Show #119 - Using the History (Back) Functionality with the ASP.NET AJAX Web Services in .NET 3.5 Service Pack 1 Beta 1</a></p>
|
Difference between a Postback and a Callback <p>I keep on hearing this words '<strong>callback</strong>' and '<strong>postback</strong>' tossed around.<br />
What is the difference between two ? </p>
<p>Is postback very specific to the ASP.NET pages ?</p>
| <p>A Postback occurs when the data (the whole page) on the page is posted from the client to the server..ie the <strong>data is posted-back to the server</strong>, and thus the page is refreshed (redrawn)...think of it as '<strong>sending the server the whole page (asp.net) full of data</strong>'.</p>
<p>On the other hand, <strong>a callback is also a special kind of postback</strong>, but it is just a quick round-trip to the server to get a small set of data (normally), and thus the page is not refreshed, unlike with the postback...think of it as '<strong>calling the server, and receiving <em>some</em> data back</strong>'.</p>
<p>With Asp.Net, <strong>the ViewState is not refreshed when a callback is invoked</strong>, unlike with a postback.</p>
<p>The reason that the whole page is posted with ASP.Net is because ASP.Net encloses the whole page in a <code><form></code> with a <strong>post method</strong>, and so when a submit button is clicked in the page, the form is sent to the server with all of the fields that are in the form... basically the whole page itself.</p>
<p>If you are using <em>FireBug</em> (for Firefox), you can actually see callbacks being invoked to the server in the <code>Console</code>. That way, you will see what <em>specific data</em> is being sent to the server (<code>Request</code>) and also the data the server sent you back (<code>Response</code>).</p>
<hr>
<p>The below image illustrates the Page Life Cycles of both a postback and a callback in a ASP.NET based Website:</p>
<p><img src="http://edndoc.esri.com/arcobjects/9.2/NET_Server_Doc/developer/ADF/graphics%5Cpage_lifecycle.png" alt="ASP.NET Page Life Cycles"></p>
|
Cross platform keylogger <p>I'm looking for ways to watch mouse and keyboard events on Windows, Linux and Mac from Python.</p>
<p>My application is a time tracker. I'm not looking into the event, I just record the time when it happens. If there are no events for a certain time, say 10 minutes, I assume that the user has left and stop the current project.</p>
<p>When the user returns (events come in again), I wait a moment (so this doesn't get triggered by the cleaning crew or your pets or an earthquake). If the events persist over a longer period of time, I assume that the user has returned and I pop up a small, inactive window where she can choose to add the time interval to "break", the current project (meeting, etc) or a different project.</p>
<p>I've solved the keylogger for Windows using the <a href="http://sourceforge.net/projects/pyhook/">pyHook</a>.</p>
<p>On Linux, I have found a solution but I don't like it: I can watch all device nodes in /etc/input and update a timestamp somewhere in /var or /tmp every time I see an event. There are two drawbacks: 1. I can't tell whether the event if from the user who is running the time tracker and 2. this little program needs to be run as root (not good).</p>
<p>On Mac, I have no idea, yet.</p>
<p>Questions:</p>
<ol>
<li><p>Is there a better way to know whether the user is creating events than watching the event devices on Linux?</p></li>
<li><p>Any pointers how to do that on a Mac?</p></li>
</ol>
| <p>There are couple of open source apps that might give you some pointers:</p>
<ul>
<li><a href="http://sourceforge.net/p/pykeylogger/wiki/Main_Page/" rel="nofollow">PyKeylogger</a> is python keylogger for windows and linux</li>
<li><a href="http://code.google.com/p/logkext/" rel="nofollow">logKext</a> is a c++ keylogger for mac</li>
</ul>
|
Proper way to stop TcpListener <p>I am currently using TcpListener to address incoming connections, each of which are given a thread for handling the communication and then shutdown that single connection. Code looks as follows:</p>
<pre><code>TcpListener listener = new TcpListener(IPAddress.Any, Port);
System.Console.WriteLine("Server Initialized, listening for incoming connections");
listener.Start();
while (listen)
{
// Step 0: Client connection
TcpClient client = listener.AcceptTcpClient();
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleConnection));
clientThread.Start(client.GetStream());
client.Close();
}
</code></pre>
<p>The <code>listen</code> variable is a boolean that is a field on the class. Now, when the program shuts down I want it to stop listening for clients. Setting listen to <code>false</code> will prevent it from taking on more connections, but since <code>AcceptTcpClient</code> is a blocking call, it will at minimum take the next client and THEN exit. Is there any way to force it to simply break out and stop, right then and there? What effect does calling listener.Stop() have while the other blocking call is running?</p>
| <p>There are 2 suggestions I'd make given the code and what I presume is your design. However I'd like to point out first that you should really use non-blocking I/O callbacks when working with I/O like network or filesystems. It's far <em>FAR</em> more efficient and your application will work a lot better though they are harder to program. I'll briefly cover a suggested design modification at the end.</p>
<ol>
<li>Use Using(){} for TcpClient</li>
<li>Thread.Abort()</li>
<li>TcpListener.Pending()</li>
<li>Asynchronous rewrite</li>
</ol>
<p>Use Using(){} for TcpClient</p>
<p><em>*</em> Note that you should really enclose your TcpClient call in a using(){} block to ensure that TcpClient.Dispose() or TcpClient.Close() methods are called even in the event of an exception. Alternately you can put this in the finally block of a try {} finally {} block.</p>
<p>Thread.Abort()</p>
<p>There are 2 things I see you could do. 1 is that if you have started this TcpListener thread from another you can simply call Thread.Abort instance method on the thread which will cause a threadabortexception to be thrown within the blocking call and walk up the stack.</p>
<p>TcpListener.Pending()</p>
<p>The second low cost fix would be to use the listener.Pending() method to implement a polling model. You would then use a Thread.Sleep to "wait" before seeing if a new connection is pending. Once you have a pending connection you'd call AcceptTcpClient and that would release the pending connection. The code would look something like this.</p>
<pre><code>while (listen){
// Step 0: Client connection
if (!listener.Pending())
{
Thread.Sleep(500); // choose a number (in milliseconds) that makes sense
continue; // skip to next iteration of loop
}
TcpClient client = listener.AcceptTcpClient();
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleConnection));
clientThread.Start(client.GetStream());
client.Close();
}
</code></pre>
<p>Asynchronous Rewrite</p>
<p>Finally I would recommend that you really move to a non-blocking methodology for your application. Under the covers the framework will use Overlapped I/O and I/O completion ports to implement non-blocking I/O from your asynchronous calls. It's not terribly difficult either, it just requires thinking about your code a little differently. </p>
<p>Basically you would start your code with the BeginAcceptTcpClient method and keep track of the IAsyncResult that you are returned. You point that at a method whose responsible for getting the TcpClient and passing it off <em>NOT</em> to a new thread but to a thread off of the ThreadPool.QueueUserWorkerItem so you're not spinning up and closing a new thread for each client request (Note you may need to use your own thread pool if you have particularly long lived requests because the thread pool is shared and if you monopolize all the threads other parts of your application implemented by the system may be starved). Once the listener method has kicked off your new TcpClient to it's own ThreadPool request it calls BeginAcceptTcpClient again and points the delegate back at itself.</p>
<p>Effectively you're just breaking up your current method into 3 different methods that will then get called by the various parts. 1. to bootstrap everything, 2. to be the target to call EndAcceptTcpClient, kick off the TcpClient to it's own thread and then call itself again, 3. to process the client request and close it when finished.</p>
|
Large primary key: 1+ billion rows MySQL + InnoDB? <p>I was wondering if InnoDB would be the best way to format the table? The table contains one field, primary key, and the table will get 816k rows a day (est.). This will get very large very quick! I'm working on a file storage way (would this be faster)? The table is going to store ID numbers of Twitter Ids that have already been processed?</p>
<p>Also, any estimated memory usage on a <code>SELECT min('id')</code> statement? Any other ideas are greatly appreciated!</p>
| <p>I'd recommend you start <a href="http://dev.mysql.com/doc/refman/5.1/en/partitioning.html" rel="nofollow">partioning</a> your table by ID or date. Partioning splits a large table into several smaller table according to some defined logic (like splitting it by date ranges), which makes them much more managable performance and memory wise. MySQL 5.1 has this feature built-in, or you can implement it using custom solutions. </p>
<p>In implement storage in a flat-file, you lose all the advantages of a database - you can no longer perform queries involving the data. </p>
|
select the <select> tag options using value <p>I want to select an option in select tag through the value. - javascript</p>
<pre><code>var selectbox=document.getElementById("Lstrtemplate");
var TemplateName=selectbox.options[selectbox.selectedIndex].text;
</code></pre>
<p>Now i am having the option text in TemplateName, using this i want to update an another select tag, which is having the same text.. </p>
<p>But dont want to use index or id.. </p>
<p>Want to achieve only by the value</p>
<p>Please help me</p>
| <p>Try it like this : </p>
<pre><code>var TemplateName = selectbox.options[selectbox.selectedIndex].value;
</code></pre>
|
Is it possible to do streaming WiFi Communications on the iPhone? <p>I am looking to develop an iPhone application that will require point-to-point WiFi communications on an iPhone. I would like to use the WiFi interface and have the application stream between the phone and a WiFi device. Does anyone have some experience with this? Is it even possible? I know there is a discovery application but I am looking for something a little more robust.</p>
| <p>As far as I know (as the SDK stands now), the only thing available is communication over the existing network connection. The SDK doesn't allow for setting up wireless network connections, or creating ad-hoc networks. I believe the only way to join or create wifi networks is through the settings app.</p>
|
Smart navigation <p>What is smart navigation in .NET? </p>
| <p>SmartNavigation is a property of the Page class in System.Web.UI. When a request comes in to Internet Explorer 5.5 or higher and SmartNavigation is turned on (set to true), the following actions are performed:</p>
<ul>
<li>The flash caused by navigation is eliminated</li>
<li>The scroll position is persisted when moving from page to page</li>
<li>Element focus is persisted between navigations</li>
<li>Only the last page state in the browser's history is retained</li>
</ul>
<p>Here is a <a href="http://msdn.microsoft.com/en-us/magazine/cc163735.aspx" rel="nofollow">good article</a> about it.</p>
<p><em>Warning</em> It doesn't work on other browser than IE. Should not be used for public website.</p>
|
Visual Studio skips build <p>When I try to build my project I get the following message in the build window :</p>
<p><strong>========== Build: 0 succeeded or up-to-date, 0 failed, 1 skipped ==========</strong></p>
<p>I tried rebuilding , then building again , but it doesn't help . Is there a way to view more detailed messages ? The "skipped" part doesn't give me any info on what's wrong . I am using Visual Studio 2005 Professional Edition .</p>
| <p>Check with the configuration manager like CMS said and make sure that you have the right platform set. A lot of the time when you use something like the MS Application Blocks the default platform is set to Itanium.</p>
|
Xpath sibling conditional testing? <p>I'm using VB.net (2003), and calling the SelectNodes method on an xml document.<br>
If I have a document:</p>
<pre><code><InqRs>
<DetRs>
<RefInfo>
<RefType>StopNum</RefType>
<RefId>0</RefId>
</RefInfo>
<RefInfo>
<RefType>Id</RefType>
<RefId>0</RefId>
</RefInfo>
</DetRs>
<DetRs>
<RefInfo>
<RefType>StopNum</RefType>
<RefId>0</RefId>
</RefInfo>
<RefInfo>
<RefType>Id</RefType>
<RefId>1</RefId>
</RefInfo>
</DetRs>
</InqRs>
</code></pre>
<p>How can I select just for the <code>DetRs</code> that has <code>RefType=Id</code> and <code>RefId=0</code>, ie, the 'first' one above?</p>
<p>I've tried several different attempts, among others: </p>
<pre><code>InqRs/DetRs[RefInfo/RefType='Id' and RefInfo/RefId='0']
InqRs/DetRs[RefInfo/RefType='Id'][RefInfo/RefId='0']
</code></pre>
<p>But these select both of the DetRs sections (because of the StopNum
RefId of 0, I presume). </p>
| <p>You want all <strong><code>DetRs</code></strong> children of the top element:</p>
<p> <code>/*/DetRs</code></p>
<p>That have a <strong><code>RefInfo</code></strong> child:</p>
<p> <code>/*/DetRs</code><br />
<code>[RefInfo]</code></p>
<p>That has <strong><code>RefType</code></strong> with value "<strong><code>Id</code></strong>": </p>
<p> <code>/*/DetRs</code><br />
<code>[RefInfo</code><br/>
[<code>RefType</code>='<code>Id</code>']<br/>
]</p>
<p>and that has a <strong><code>RefId</code></strong> with value <strong>0</strong>:</p>
<p> <code>/*/DetRs</code><br />
<code>[RefInfo</code><br/>
[<code>RefType</code>='<code>Id</code>'
<br /> <code>and</code><br /> <code>RefId</code>=0<br /> ]<br/>
]</p>
<p><strong>And this XPath expression correctly selects just the wanted first <code>DetRs</code> element in the provided XML document</strong>.</p>
<p>Certainly, if someone has other stylistic preferences, the above expression could be written also as:</p>
<p> <strong><code>/*/DetRs[RefInfo[RefType='Id' and RefId=0]]</code></strong></p>
|
How could I implement this strange WPF TreeListDataGridView? <p>As you can see in the image below I have a tree datamodel consisting of groups that can contain other groups plus an arbitary number of items wich again can hold Parameters. The Parameters itself are defined globally and just reoccur in the items. Only the parameter's actual value may differ from parameter usage to parameter usage in the different items.</p>
<p>The image below is an ordinary WPF treeview control with a custom control template and datatemplates for the items.</p>
<p>Now my goal is to remove the parameter names above the textboxes and stack them vertically in a separate column at the very left of the treeview and just leave the textboxes there but also stacked vertically so they the correspond with their parameter names in the first column.</p>
<p>Is there a way I can solve this with control templates and data templates and databinding to the view model ? (Yes I use MVVM)</p>
<p><img src="http://img242.imageshack.us/img242/5377/treebh8.th.png" alt="treeview image" />
<a href="http://img242.imageshack.us/img242/5377/treebh8.png" rel="nofollow">image link</a></p>
<p>The problem is a general layout problem that must work well with databinding. generally I want to bind the object graph to a view that somewhat looks like this (cutout mockup):</p>
<p><img src="http://img75.imageshack.us/img75/5763/treelayoutjh5.jpg" alt="treelayout" /></p>
<p>Note that the ParamX headers are not really part of the treelayout anymore. But the values still are. Now the values must keep a connection (i.e. the are on the same row) with them. Also if none of the items in the tree contain for example Param1 the Param1 header and the corresponding row must completely dissappear.</p>
| <p>I'm not a tree view expert, but it's easy to build something like that without a tree view.</p>
<p>Start with an empty VS2008 Wpf Application named WpfTreeGridWhatever</p>
<p>First, let's define our model:</p>
<pre><code>using System;
using System.Collections.Generic;
namespace WpfTreeGridWhatever
{
public class ItemBase
{
}
public class Group : ItemBase
{
public string Name { get; set; }
public IList<ItemBase> Items { get; set; }
}
public class Item : ItemBase
{
public string Name { get; set; }
public IList<Parameter> Parameters { get; set; }
}
public class Parameter
{
public string Name { get; set; }
public string Value { get; set; }
}
}
</code></pre>
<p>now, in the Window1 constructor create our objects (just so we have some data to bind to):</p>
<pre><code> public Window1()
{
DataContext = new Group[]
{
new Group()
{
Name="Group A",
Items = new List<ItemBase>()
{
new Item()
{
Name="Item",
Parameters=new List<Parameter>()
{
new Parameter(){Name="Param 1",Value="12"},
new Parameter(){Name="Param 2",Value="true"},
new Parameter(){Name="Param 3",Value="0.0"},
new Parameter(){Name="Param 4",Value="off"},
}
},
new Item()
{
Name="Item",
Parameters=new List<Parameter>()
{
new Parameter(){Name="Param 1",Value="12"},
new Parameter(){Name="Param 2",Value="true"}
}
},
new Group()
{
Name="Group B",
Items = new List<ItemBase>()
{
new Item()
{
Name="Item",
Parameters=new List<Parameter>()
{
new Parameter(){Name="Param 1",Value="12"},
new Parameter(){Name="Param 2",Value="true"},
new Parameter(){Name="Param 3",Value="0.0"},
new Parameter(){Name="Param 4",Value="off"},
}
},
new Item()
{
Name="Item",
Parameters=new List<Parameter>()
{
new Parameter(){Name="Param 1",Value="12"},
new Parameter(){Name="Param 2",Value="true"},
new Parameter(){Name="Param 3",Value="0.0"},
new Parameter(){Name="Param 4",Value="off"},
new Parameter(){Name="Param 5",Value="2000"},
}
},
new Item()
{
Name="Item",
Parameters=new List<Parameter>()
{
new Parameter(){Name="Param 1",Value="12"},
new Parameter(){Name="Param 2",Value="true"},
}
},
new Group()
{
Name="Group C",
Items = new List<ItemBase>()
{
new Item()
{
Name="Item",
Parameters=new List<Parameter>()
{
new Parameter(){Name="Param 1",Value="12"},
new Parameter(){Name="Param 2",Value="true"},
new Parameter(){Name="Param 3",Value="0.0"},
new Parameter(){Name="Param 4",Value="off"},
}
},
new Item()
{
Name="Item",
Parameters=new List<Parameter>()
{
new Parameter(){Name="Param 1",Value="12"},
new Parameter(){Name="Param 2",Value="true"},
new Parameter(){Name="Param 3",Value="0.0"},
new Parameter(){Name="Param 4",Value="off"},
new Parameter(){Name="Param 5",Value="2000"},
}
},
new Item()
{
Name="Item",
Parameters=new List<Parameter>()
{
new Parameter(){Name="Param 1",Value="12"},
new Parameter(){Name="Param 2",Value="true"},
}
},
}
}
}
}
}
}
};
InitializeComponent();
}
</code></pre>
<p>And now, the magic - use this code in Window1.xaml</p>
<pre><code><Window x:Class="WpfTreeGridWhatever.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:l="clr-namespace:WpfTreeGridWhatever"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<LinearGradientBrush x:Key="Bk" StartPoint="0,0" EndPoint="0,1" >
<GradientStop Offset="0" Color="DarkGray"/>
<GradientStop Offset="1" Color="White"/>
</LinearGradientBrush>
<DataTemplate DataType="{x:Type l:Parameter}">
<Border CornerRadius="5" Background="{StaticResource Bk}"
BorderThickness="1" BorderBrush="Gray" Margin="2" >
<StackPanel Margin="5">
<TextBlock Height="12" Text="{Binding Name}"/>
<TextBox Height="22" Text="{Binding Value}"/>
</StackPanel>
</Border>
</DataTemplate>
<DataTemplate DataType="{x:Type l:Item}" >
<StackPanel>
<Border CornerRadius="5" Background="{StaticResource Bk}"
BorderThickness="1" BorderBrush="Gray" Height="25" Margin="3">
<TextBlock Height="12" Text="{Binding Name}" VerticalAlignment="Center" Margin="3,0"/>
</Border>
<ItemsControl ItemsSource="{Binding Parameters}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</StackPanel>
</DataTemplate>
<DataTemplate DataType="{x:Type l:Group}">
<StackPanel>
<Border CornerRadius="5" Background="{StaticResource Bk}"
BorderThickness="1" BorderBrush="Gray" Height="25" Margin="3">
<TextBlock Height="12" Text="{Binding Name}" VerticalAlignment="Center" Margin="3,0"/>
</Border>
<ItemsControl ItemsSource="{Binding Items}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</StackPanel>
</DataTemplate>
</Window.Resources>
<Grid>
<ItemsControl ItemsSource="{Binding}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</Grid>
</Window>
</code></pre>
<p>This should get you started</p>
|
Howto rotate image using jquery rotate plugin? <p>How do you rotate an image using <a href="http://code.google.com/p/jquery-rotate/" rel="nofollow">jQuery-rotate</a> plugin?</p>
<p>I have tried the following and it doesn't seem to work:</p>
<pre><code><html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>View Photo</title>
<script type="text/javascript" src="scripts/jquery.js"></script>
<script type="text/javascript" src="scripts/jquery.rotate.1-1.js"></script>
<script type="text/javascript">
var angle = 0;
setInterval ( function (e) {
rotate();
}, 100 );
function rotate() {
angle = angle + 1;
$('#pic').rotate(angle);
}
</script>
</head>
<body>
<img border="0" src="player.gif" name="pic" id="pic">
</body>
</html>
</code></pre>
<p>Other methods that are supported by most browsers are wanted too, thanks!</p>
| <p>You've got a 404 on jQuery and the jQuery plugin. Because of that, your page is throwing a JavaScript error, that $ is not defined.</p>
<p>You need to learn basic JavaScript debugging techniques. A quick search found this article that looks like a good place for you to start:</p>
<ul>
<li><a href="http://www.developertutorials.com/tutorials/javascript/javascript-debugging-techniques-with-firebug-8-04-20/page1.html" rel="nofollow">JavaScript Debugging Techniques with Firebug</a></li>
</ul>
|
Android development with Netbeans IDE <p>Has anybody had any success with developing for Android platform using Netbeans (5.5+ ) IDE? I know of atleast netbeans one plugin that is supposed to support it but wanted to hear if anyone is using netbeans for Android development and how easy it is to set it up.</p>
| <p>There is a project called nbandroid (formerly called undroid) which is a Netbeans version of ADT and it works quite fine with SDK 1.0</p>
<p><a href="http://nbandroid.org/" rel="nofollow">http://nbandroid.org/</a></p>
<p>In the past it was hosted at undroid.nolimit.cz and nbandroid.kenai.com, both these sites are obsolete now.</p>
|
Should I have one class for every database I use? <p>First, let me explain what I am doing. I need to take an order, which is split up into different databases, and print out this very large order. What I need from the orders is about 100 or so columns from different databases. The way I was doing in was querying with a join and assigning all of the column values to a variable in my one large Order class. This has started to become troublesome. I am wondering of instead of having one class that is comprised of 100 or so members that make up the order. Should I have just one class for every database I use, and then work with that?</p>
<p>Let me add to this. Basically, is it better to map you objects to the original database tables, or the result set. Because I have my object mapped to the result set and not the individual tables.</p>
| <p>I would recommend an object-oriented solution to this. Presumably your database is designed with tables that represent logical groupings of data. Each of these tables can likely be mapped onto a class in your system, although in some cases, it may be more than one table that makes up an object or there might be multiple classes that a table maps onto using subclassing. If you need to display data from multiple tables -- say a list of orders with some data from the customer associated with the order -- then you can either use views, joins, or stored procedures to construct an object of a view class that represents the selected data in the view/join/sp.</p>
<p>Essentially what I am describing is an N-tier data architecture where you have a low-level data access layer that deals with data from a SQL orientation -- tables, views, stored procedures. Above this may be a generic object layer that deals with generic data objects and interfaces with the data access layer to store/retrieve objects from the database. Finally, above this you have a strongly-typed business object layer where your application works with classes that semantically linked to your application -- orders, customers, invoices, etc. There are many different patterns for implementing this type of general architecture and you should investigate several to see which fits your application needs the best. You might want to directly use an object-relational mapping like LINQ or nHibernate or you might want to layer a repository on top of an ORM.</p>
<p>Personally, I think that structuring your application to deal with objects within the context of your domain, rather than simply as table data, will improve your code. It should improve understandability and maintainability. You will be able to encapsulate behavior within your domain classes rather than have it spread throughout your application. Of course, this assumes that you follow good design practices, but using OO design will encourage this. Separating out the business and data logic from your display logic will also make your application much more testable, as will breaking down monolithic classes into smaller, more focused classes that are interrelated.</p>
|
How can I make Eclipse CDT auto-indent properly when using BOOST_FOREACH? <p>I write this tiny C++ example in Eclipse 3.4.1 (CDT 5.0.1):</p>
<pre><code>#include <iostream>
#include <vector>
#include <boost/foreach.hpp>
int foo()
{
std::vector<int> numbers;
BOOST_FOREACH(int n, numbers)
{
std::cout << n << std::endl;
}
std::cout << numbers.size << std::endl;
}
</code></pre>
<p>Then I hit Shift+Ctrl+F to format my code, and it becomes:</p>
<pre><code>#include <iostream>
#include <vector>
#include <boost/foreach.hpp>
int foo()
{
std::vector<int> numbers;
BOOST_FOREACH(int n, numbers)
{ std::cout << n << std::endl;
}
std::cout << numbers.size << std::endl;
}
</code></pre>
<p>This is with the BSD/Allman Code Style. Other styles obviously vary the look of the formatted code, but none give correct indentation.</p>
<p>When I use the format feature on a larger piece of code, subsequent functions or methods are also affected by too little indentation, making the formatting help pretty unhelpful.</p>
<p>Is there something I can do to make the indentation work properly with BOOST_FOREACH?</p>
| <p>Add this to some header used by your code:</p>
<pre><code>#ifdef __CDT_PARSER__
#undef BOOST_FOREACH
#define BOOST_FOREACH(a, b) for(a; ; )
#endif
</code></pre>
|
How do I get CakePHP bake to find mysql.sock and recognize MySQL while using MAMP on Mac OSX? <p>I am currently reading "Beginning CakePHP:From Novice to Professional" by David Golding. At one point I have to use the CLI-command "cake bake", I get the welcome-screen but when I try to bake e.g. a Controller I get the following error messages:</p>
<pre><code>Warning: mysql_connect(): Can't connect to local MySQL server through socket '/var/mysql/mysql.sock' (2) in /Applications/MAMP/htdocs/blog/cake/libs/model/datasources/dbo/dbo_mysql.php on line 117
Warning: mysql_select_db(): supplied argument is not a valid MySQL-Link resource in /Applications/MAMP/htdocs/blog/cake/libs/model/datasources/dbo/dbo_mysql.php on line 122
Warning: mysql_get_server_info(): supplied argument is not a valid MySQL-Link resource in /Applications/MAMP/htdocs/blog/cake/libs/model/datasources/dbo/dbo_mysql.php on line 130
Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in /Applications/MAMP/htdocs/blog/cake/libs/model/datasources/dbo/dbo_mysql.php on line 154
Error: Your database does not have any tables.
</code></pre>
<p>I suspect that the error-messages has to do with php trying to access the wrong mysql-socket, namely the default osx mysql-socket - instead of the one that MAMP uses. Hence I change my database configurations to connect to the UNIX mysql-socket (:/Applications/MAMP/tmp/mysql/mysql.sock):</p>
<pre><code>class DATABASE_CONFIG {
var $default = array(
'driver' => 'mysql',
'connect' => 'mysql_connect',
'persistent' => false,
'host' =>':/Applications/MAMP/tmp/mysql/mysql.sock', // UNIX MySQL-socket
'login' => 'my_user',
'password' => 'my_pass',
'database' => 'blog',
'prefix' => '',
);
}
</code></pre>
<p>But I get the same error-messages with the new socket:</p>
<pre><code>Warning: mysql_connect(): Can't connect to local MySQL server through socket '/Applications/MAMP/tmp/mysql/mysql.sock:3306' (2) in /Applications/MAMP/htdocs/blog/cake/libs/model/datasources/dbo/dbo_mysql.php on line 117
Warning: mysql_select_db(): supplied argument is not a valid MySQL-Link resource in /Applications/MAMP/htdocs/blog/cake/libs/model/datasources/dbo/dbo_mysql.php on line 122
Warning: mysql_get_server_info(): supplied argument is not a valid MySQL-Link resource in /Applications/MAMP/htdocs/blog/cake/libs/model/datasources/dbo/dbo_mysql.php on line 130
Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in /Applications/MAMP/htdocs/blog/cake/libs/model/datasources/dbo/dbo_mysql.php on line 154
Error: Your database does not have any tables.
</code></pre>
<p>Also, even though I use the UNIX-socket that MAMP show on it's welcome-screen, CakePHP loses the database-connection, when using this socket instead of localhost.</p>
<p>Any ideas on how I can get bake to work?</p>
<p><strong>-- Edit 1 --</strong></p>
<p>Thank you guys for helping me out! :)</p>
<p>I have a problem figuring out where in my.cnf to edit to get MySQL to listen to TCP/IP request. The only paragraph I can find where TCP/IP is mentioned is the following: </p>
<pre><code># Don't listen on a TCP/IP port at all. This can be a security enhancement,
# if all processes that need to connect to mysqld run on the same host.
# All interaction with mysqld must be made via Unix sockets or named pipes.
# Note that using this option without enabling named pipes on Windows
# (via the "enable-named-pipe" option) will render mysqld useless!
#
#skip-networking
</code></pre>
<p>That allows me to turn off TCP/IP completely, which is the opposite of my intention. I don't know how to go about what you suggest, if you could be more elaborate it would be great. I am a total n00b on these matters :S</p>
<p>Reg. connecting to a local socket: I removed the leading colon in the host-parameter, same result.</p>
| <p>I find the solution to this problem :
Add a socket config in the cakephp app/config/database.php file</p>
<pre><code>class DATABASE_CONFIG {
var $default = array(
'driver' => 'mysql',
'persistent' => false,
'host' => 'localhost',
'port' => '/Applications/MAMP/tmp/mysql/mysql.sock', // here is the key !
'login' => 'you',
'password' => 'yourpass',
'database' => 'yourdb',
'prefix' => '',
);
</code></pre>
|
How to organize python test in a way that I can run all tests in a single command? <p>Currently my code is organized in the following tree structure:</p>
<pre><code>src/
module1.py
module2.py
test_module1.py
test_module2.py
subpackage1/
__init__.py
moduleA.py
moduleB.py
test_moduleA.py
test_moduleB.py
</code></pre>
<p>Where the <code>module*.py</code> files contains the source code and the <code>test_module*.py</code> contains the <code>TestCase</code>s for the relevant module.</p>
<p>With the following comands I can run the tests contained in a single file, for example:</p>
<pre><code>$ cd src
$ nosetests test_filesystem.py
..................
----------------------------------------------------------------------
Ran 18 tests in 0.390s
OK
</code></pre>
<p>How can I run all tests? I tried with <code>nosetests -m 'test_.*'</code> but it doesn't work.</p>
<pre><code>$cd src
$ nosetests -m 'test_.*'
----------------------------------------------------------------------
Ran 0 tests in 0.000s
OK
</code></pre>
<p>Thanks</p>
| <p>Whether you seperate or mix tests and modules is probably a matter of taste, although I would strongly advocate for keeping them apart (setup reasons, code stats etc).</p>
<p>When you're using nosetests, make sure that all directories with tests are real packages:</p>
<pre><code>src/
module1.py
module2.py
subpackage1/
__init__.py
moduleA.py
moduleB.py
tests/
__init__.py
test_module1.py
test_module2.py
subpackage1/
__init__.py
test_moduleA.py
test_moduleB.py
</code></pre>
<p>This way, you can just run <code>nosetests</code> in the toplevel directory and all tests will be found. You need to make sure that <code>src/</code> is on the <code>PYTHONPATH</code>, however, otherwise all the tests will fail due to missing imports.</p>
|
When would you use the different git merge strategies? <p>From the man page on git-merge, there are a number of merge strategies you can use. </p>
<ul>
<li><p><em>resolve</em> -
This can only resolve two heads (i.e. the current branch and another branch you pulled from) using 3-way merge algorithm. It tries to carefully detect criss-cross merge ambiguities and is considered generally safe and fast.</p></li>
<li><p><em>recursive</em> -
This can only resolve two heads using 3-way merge algorithm. When there are more than one common ancestors that can be used for 3-way merge, it creates a merged tree of the common ancestors and uses that as the reference tree for the 3-way merge. This has been reported to result in fewer merge conflicts without causing mis-merges by tests done on actual merge commits taken from Linux 2.6 kernel development history. Additionally this can detect and handle merges involving renames. This is the default merge strategy when pulling or merging one branch.</p></li>
<li><p><em>octopus</em> -
This resolves more than two-head case, but refuses to do complex merge that needs manual resolution. It is primarily meant to be used for bundling topic branch heads together. This is the default merge strategy when pulling or merging more than one branches.</p></li>
<li><p><em>ours</em> -
This resolves any number of heads, but the result of the merge is always the current branch head. It is meant to be used to supersede old development history of side branches.</p></li>
<li><p><em>subtree</em> -
This is a modified recursive strategy. When merging trees A and B, if B corresponds to a subtree of A, B is first adjusted to match the tree structure of A, instead of reading the trees at the same level. This adjustment is also done to the common ancestor tree.</p></li>
</ul>
<p>When should I specify something different than the default? What scenarios are each best for?</p>
| <p>I'm not familiar with resolve, but I've used the others:</p>
<h2>Recursive</h2>
<p>Recursive is the default for non-fast-forward merges. We're all familiar with that one.</p>
<h2>Octopus</h2>
<p>I've used octopus when I've had several trees that needed to be merged. You see this in larger projects where many branches have had independent development and it's all ready to come together into a single head.</p>
<p>An octopus branch merges multiple heads in one commit as long as it can do it cleanly.</p>
<p>For illustration, imagine you have a project that has a master, and then three branches to merge in (call them a, b, and c).</p>
<p>A series of recursive merges would look like this (note that the first merge was a fast-forward, as I didn't force recursion):</p>
<p><a href="http://i.stack.imgur.com/y9LeY.png"><img src="http://i.stack.imgur.com/y9LeY.png" alt="series of recursive merges"></a></p>
<p>However, a single octopus merge would look like this:</p>
<pre><code>commit ae632e99ba0ccd0e9e06d09e8647659220d043b9
Merge: f51262e... c9ce629... aa0f25d...
</code></pre>
<p><a href="http://i.stack.imgur.com/jctXz.png"><img src="http://i.stack.imgur.com/jctXz.png" alt="octopus merge"></a></p>
<h2>Ours</h2>
<p>Ours == I want to pull in another head, but throw away all of the changes that head introduces.</p>
<p>This keeps the history of a branch without any of the effects of the branch.</p>
<p>(Read: It is not even looked at the changes between those branches. The branches are just merged and nothing is done to the files. If you want to merge in the other branch and every time there is the question "our file version or their version" you can use <code>git merge -X ours</code>)</p>
<h2>Subtree</h2>
<p>Subtree is useful when you want to merge in another project into a subdirectory of your current project. Useful when you have a library you don't want to include as a submodule.</p>
|
What are the differences between Perl, Python, AWK and sed? <p>just want to know what are the main differences among them? and the power of each language (where it's better to use it).</p>
<p><strong>Edit:</strong> it's not "vs." like topic, just information.</p>
| <p>In order of appearance, the languages are <code>sed</code>, <code>awk</code>, <code>perl</code>, <code>python</code>.</p>
<p>The <code>sed</code> program is a stream editor, and is designed to apply the actions from a script to each line (or, more generally, to specified ranges of lines) of the input file or files. Its language is based on <code>ed</code>, the Unix editor, and although it has conditionals and so on, it is hard to work with for complex tasks. You can work minor miracles with it - but at a cost to the hair on your head. However, it is probably the fastest of the programs when attempting tasks within its remit. (It has the least powerful regular expressions of the programs discussed - adequate for many purposes, but certainly not PCRE - Perl-Compatible Regular Expressions)</p>
<p>The <code>awk</code> program (name from the initials of its authors - Aho, Weinberger and Kernighan) is a tool originally for formatting reports. It can be used as a souped up <code>sed</code>; in its more recent versions, it is computationally complete. It uses an interesting idea - the program is based on 'patterns matched' and 'actions taken when the pattern matches'. The patterns are fairly powerful (Extended Regular Expressions). The language for the actions is similar to C. One of the key features of <code>awk</code> is that it splits the input lines into fields automatically.</p>
<p>Perl was written in part as an awk-killer and sed-killer. Two of the programs provided with it are <code>a2p</code> and <code>s2p</code> for converting <code>awk</code> scripts and <code>sed</code> scripts into Perl. Perl is one of the earliest of the next generation of scripting languages (Tcl/Tk can probably claim primacy). It has powerful integrated regular expression handling with a vastly more powerful language. It provides access to almost all system calls, and has the extensibility of the CPAN modules. (Neither <code>awk</code> nor <code>sed</code> is extensible.) One of Perl's mottos is "TMTOWTDI - There's more than one way to do it" (pronounced "tim-toady"). Perl has 'objects', but it is more of an add-on than a fundamental part of the language.</p>
<p>Python was written last, and probably in part as a reaction to Perl. It has some interesting syntactic ideas (indenting to indicate levels - no braces or equivalents). It is more fundamentally object-oriented than Perl; it is just as extensible as Perl.</p>
<p>OK - when to use each?</p>
<ul>
<li>sed - when you need to do simple text transforms on files.</li>
<li>awk - when you only need simple formatting and summarization or transformation of data.</li>
<li>perl - for almost any task, but especially when the task needs complex regular expressions.</li>
<li>python - for the same tasks that you could use Perl for.</li>
</ul>
<p>I'm not aware of anything that Perl can do that Python can't, nor vice versa. The choice between the two would depend on other factors. I learned Perl before there was a Python, so I tend to use it. Python has less accreted syntax and is generally somewhat simpler to learn. Perl 6, when it becomes available, will be a fascinating development.</p>
<p>(Note that the 'overviews' of Perl and Python, in particular, are woefully incomplete; whole books could be written on the topic.)</p>
|
Easiest way to animate background image sliding left? <p>What's the best way to animate a background image sliding to the left, and looping it? Say I've got a progress bar with a background I want to animate when it's active (like in Gnome or OS X).</p>
<p>I've been playing with the $(...).animate() function and trying to to modify the relevant CSS property, but I keep hitting a brick wall when trying to figure out how to modify the background-position property. I can't just increment its value, and I'm not sure if this is even the best approach.</p>
<p>Any help appreciated!</p>
| <p>As soon as I posted this I figured it out. In case it helps anyone else, here's the function I came up with:</p>
<pre><code>function animateBar(self) {
// Setup
var bar = self.element.find('.ui-progress-bar');
bar.css('background-position', '0px 0px');
bar.animate({
backgroundPosition: '-20px 0px'
}, 1000, 'linear', function() {
animateBar(self);
});
}
</code></pre>
|
Descendant Enumeration in Objective-C <p>Is it possible to get a list of all descendant classes of a particular class in objective-c?</p>
<p>Something like:</p>
<pre><code> @interface A : NSObject
@end
@interface B : A
@end
@interface C : A
@end
NSArray *descendants = [A allDescendants]; // descendants = [B, C]
</code></pre>
| <p>The only way I can think is to enumerate the entire list of classes in the runtime (obtained with <code>objc_getClassList</code>) and test each one for <code>isKindOfClass:A</code>.</p>
<p>This is likely the only solution because classes do not maintain links to their descendants (only to their superclass).</p>
|
Using Matlab, how can I find the value K in the following root locus? <p>In Matlab, how can I find value of K, in a system that has oscillation?</p>
<blockquote>
<p>(system's tf, if needed: (K * (s +
25))/(s^3 + 24 s^2 + 100 s) )</p>
</blockquote>
<p>PS. I'm using root locus.</p>
| <p>I assume this is the plant for a closed-loop system with gain compensation only (that would be K). In that case I would express it as a transfer function and then use the root-locus command to see where it hits on the x-axis:</p>
<pre><code>num = [1 25];
den = [1 24 100 0];
sys=tf(num,den)
rlocus(sys)
</code></pre>
<p>Unfortunately your system appears to be stable for all values of K! Doh!</p>
|
Title (in ASP.NET @ Page directive) not rendering in web page <p>I was intending on use the Title attribute in the @Page directive to customise each pages title, but it simply doesn't appear to do anything.</p>
<p>The site uses master pages - I don't know if that is a consideration.</p>
<p>Master Page snippet:</p>
<pre><code><%@ Master Language="VB" CodeFile="brightnorth.master.vb" Inherits="brightnorth" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" type="text/css" href="/css/style.css" />
</head>
<body>
etc....
</code></pre>
<p>Page snippet (from <a href="http://www.brightnorth.com/about/aboutus.aspx" rel="nofollow">http://www.brightnorth.com/about/aboutus.aspx</a>):</p>
<pre><code><%@ Page Language="VB" MasterPageFile="~/brightnorth.master" AutoEventWireup="false" CodeFile="aboutus.aspx.vb" Inherits="about_aboutus" Title="Brightnorth.com: About Us" %>
</code></pre>
<p>What is more, if I run the page through the <a href="http://validator.w3.org/check?verbose=1&uri=http%3A%2F%2Fwww.brightnorth.com%2Fabout%2Faboutus.aspx" rel="nofollow">validator</a>, it complains about... </p>
<blockquote>
<p>end tag for "head" which is not finished</p>
</blockquote>
<p>..whereas the the tag <em>is</em> present in the source code.</p>
<p>I've already got a workaround in place, but it's annoying the hell out of me, so I'm determined to find a resolution!</p>
| <p>Oops... A basic error! [aren't they always?]</p>
<p>Anyone spot a missing <code>runat="server"</code> in the element?</p>
<p>Oops.</p>
|
I want to assign a record to TStringList.Objects <p>I want create a Playlist control. I have a lot of information to display into a TStringList. I want to assign a record to TStringGrid.Objects instead of an object because so many objects may take a while to create/destroy. It also take a lot of RAM.</p>
<p>A record will be much faster and slim.
How can I do that?</p>
<pre><code>TYPE
AMyRec= packed record
FullName : string[255];
RelativePath : boolean;
IsInvalid : boolean;
InCache : boolean;
etc
end;
</code></pre>
| <p>You can use a TList to a Pointer of your record.</p>
<p>Eg:</p>
<pre><code>Type
PMyrec = ^AMyRec;
</code></pre>
<p>usage</p>
<pre><code>var
MyRec : PMyRec;
new(MyRec);
MyRec^.Fullname := 'test';
MyRec^.RelativePath := false;
</code></pre>
<p>etc</p>
<p>{ MyList is a List you have create elsewhere }</p>
<pre><code>MyList.Add(MyRec);
</code></pre>
<p>You'll have to handle disposing of items from the list eg</p>
<p><code>Dispose(PMyRec(MyList[Index]));</code></p>
<p>To use an item from the list:</p>
<pre><code>var
MyRec : PMyRec;
PMyRec := MyList.Items[i];
txtBox.Text = PMyRec^.Fullname;
</code></pre>
<p>etc</p>
|
Is it safe to run a pool under NT AUTHORITY\NETWORK SERVICE? <p>I normally would create a limited rights user and run the process under that but the fact that pools automatically created under IIS7 in 2008 use this account makes me think that this is perfectly safe, and possibly more so than something I create? The whole Secure By Default push from Redmond would lead me to believe this is the case.</p>
| <p>Yes it is safe. <a href="http://technet.microsoft.com/en-us/library/cc170953.aspx">Services and Service Accounts Security Planning Guide</a></p>
<p>One more thing. It is even better to use the local service account ( not to confuse with local System account! ). It has the same permission on the local server as network service. But does not have network permissions. The network service can access network resources with the permissions of the computer account ( like authenticated user ).</p>
<p><strong>Update 1</strong> ( reply to comment):</p>
<p>As far as I understand. both option will work. Your application code is not running ( by default) under the application pool identity. But under the identity of the user that authenticate to your site. Or, if anonymous user are allowed, the iuser_computername account. The reason that the application pool identity is important, is that you can by code, so attacker that inject his code can too, to change the identity of your application to the application pool identity.</p>
<p>That said, There are further complication that are too numerous to post.</p>
|
How do I kill an unruly spid in Sybase? <p>I've got a couple of rogue spid's in my database that I can see are sleeping when I log in as <code>sa</code> and use <code>sp_who</code>, but attempts to use <code>kill <spid></code> to eliminate them have failed and I don't actually have access to the server itself to bounce it. Is there any other way of killing these things off?</p>
| <p>System processes cannot be killed. For example in the output of sp_who where cmd is NETWORK HANDLER, MIRROR HANDLER and CHECKPOINT SLEEP (or rarely, CHECKPOINT) and AUDIT PROCESS cannot be killed. If they have status as "recv sleep", "send sleep", "alarm sleep" and "lock sleep" , they can be killed.</p>
<p>In sp_who output, you cannot tell whether a process whose status is "recv sleep" belongs to a user who is using SQL Server, but may be pausing to examine the results of a command, or whether the process indicates that a user has rebooted a PC or other terminal, and left a stranded process.You can learn more about a questionable process by querying the sysprocesses table for information. For ex : </p>
<p>select hostprocess, program_name from sysprocesses where spid = 8</p>
<p>If program_name is isql you know that this spid can be killed.(and so forth ... )</p>
|
Dynamic Memory Allocation Failure Recovery <p>I'm working on an embedded processor (400 MHz Intel PXA255 XScale), and I thought I saw one case where there wasn't enough memory to satisfy a 'new' operation. The program didn't crash, so I assumed other threads had freed their memory and it was just a transient thing. This is some pretty critical code, so exiting is not an option, and some sort of error needs to be returned to the remote user.</p>
<p>Would the following small fix be enough to solve the problem, or is there a better way? Before replacing every 'new' with the following code, I thought I'd ask.</p>
<pre><code>char someArr[];
do{
someArr = new char[10];
Sleep(100); // no justification for choosing 100 ms
} while ( someArr == NULL );
</code></pre>
<p>Does the Sleep help? Should I set some max number of retries? Is it possible to use static initialization everywhere?</p>
<p><strong>FINAL UPDATE:</strong> Thank you very much for the helpful responses, but it turns out there was an error in the code checking for failed memory allocation. I will keep all of these answers in mind, and replace as many malloc's and new's as I can, though (especially in error-handling code).</p>
| <p>You are trying to solve a global problem through local reasoning. The global problem is that the entire device has a limited amount of RAM (and possibly backing store) for the operating system and all of the applications. To make sure this amount of RAM is not exceeded, you have a few options:</p>
<ul>
<li><p>Each process operates in a fixed amount of RAM to be determined per process at startup time; the programmer does the reasoning to make sure everything fits. So, <strong>yes, it is possible to allocate everything statically</strong>. It's just a lot of work, and <strong>every time you change your system's configuration, you have to reconsider the allocations</strong>.</p></li>
<li><p>Processes are aware of their own memory usage and needs and continually advise each other about how much memory they need. They <strong>cooperate so they don't run out of memory</strong>. This assumes that at least some processes in the system can adjust their own memory requirements (e.g., by changing the size of an internal cache). Alonso and Appel wrote a <a href="http://portal.acm.org/citation.cfm?id=98753">paper about this approach</a>.</p></li>
<li><p>Each process is aware that memory can become exhausted and can <strong>fail over to a state in which it consumes a minimum amount of memory</strong>. Often this strategy is implemented by having an out-of-memory exception. The exception is handled in or near main() and the out-of-memory event essentially restarts the program from scratch. This failover mode can work if memory grows in response to user requests; if the program's memory requirements grow independent of what the user does, <strong>it can lead to thrashing.</strong></p></li>
</ul>
<p><strong>Your proposal above matches none of the scenarios.</strong> Instead, you are hoping <strong>some other process will solve the problem</strong> and the memory you need will eventually appear. You might get lucky. You might not.</p>
<p>If you want your system to work reliably, you would do well to <strong>reconsider the design of every process running on the system</strong> in light of the need to share limited memory. It might be a bigger job than you expected, but if you understand the problem, you can do this. Good luck!</p>
|
late static binding: which languages commonly used for web development support it? <p>Lately I've been seeing a lot of talk regarding PHP's lack of late static binding until 5.3. </p>
<p>From what I've read proper implementations of stuff like ActiveRecord are not possible until the language has this feature.</p>
<p>So, I'm curious about:</p>
<ul>
<li>Which languages do support it,
specifically those commonly
associated with web development such
as Python, Ruby, Perl, Java, C#,
(JavaScript?).</li>
<li>Which actually make use of it on a
regular basis?</li>
</ul>
| <p>If you want a work around, that admittedly is a little time consuming, yet will be easily removed when php 5.3 becomes available and mainstreamed, you can try the following code.</p>
<pre><code>class Specific_Model extends Model{
public static function GetAll($options = null){
parent::GetAll($options, get_class());
}
}
class Model{
public static function GetAll($options = null, $class = null){
if(is_null($class)) $class = get_class();
/* Do stuff here */
}
}
</code></pre>
<p>Then you can use the following code...</p>
<pre><code>Specific_Model::GetAll($options);
</code></pre>
<p>And easily strip out the excess code when moving to php 5.3.</p>
|
Associative array without toString, etc <p>I want to create an associative array:</p>
<pre><code>var aa = {} //equivalent to Object(), new Object(), etc...
</code></pre>
<p>and I want to be sure that any key I access is going to be a number:</p>
<pre><code>aa['hey'] = 4.3;
aa['btar'] = 43.1;
</code></pre>
<p>I know JS doesn't have typing, so I can't automatically check this, but I can ensure in my own code that I only assign strings to this aa. </p>
<p>Now I'm taking keys from the user. I want to display the value for that key. However, if the user gives me something like "toString", he'll get back a function, not an int! Is there any way to make sure any string he gives me is only something I define? Is the only solution something like:</p>
<pre><code>delete aa['toString'];
delete aa['hasOwnProperty'];
</code></pre>
<p>etc...</p>
| <p>One possibility would be to use hasOwnProperty to check that the key is something you explicitly added to the array. So instead of:</p>
<pre><code>function findNumber(userEnteredKey) {
return aa[userEnteredKey];
}
</code></pre>
<p>you'd say:</p>
<pre><code>function findNumber(userEnteredKey) {
if (Object.prototype.hasOwnProperty.call(aa,userEnteredKey))
return aa[userEnteredKey];
}
</code></pre>
<p>Alternately, you could use typeof to check that anything is a number before returning it. But I like the hasOwnProperty approach, because it'll keep you from returning anything that you didn't intentionally put in the array.</p>
|
In Java: How to handshake a secured connection using Keystore and Truststore certificate? <p>If I have 2 terminals A and B. T-A is connect T-B over secured socket connection. I need to write code to implement a connection between the 2 terminals.</p>
<p>How do I do handshake such connection using Keystore and Truststore. Another word, where do I place keystore/truststore certificate file? (T-A or T-B)</p>
<p>Any good advice or good example is greatly appreciated.</p>
<p>Thanks</p>
| <p>Here's a PDF whitepaper entitled <a href="https://www6.software.ibm.com/developerworks/education/j-jsse/j-jsse-ltr.pdf" rel="nofollow">Using JSSE for secure socket communication</a> which may help answer your question, including configuration of your keystore files.</p>
|
How much input validation should I be doing on my python functions/methods? <p>I'm interested in how much up front validation people do in the Python they write.</p>
<p>Here are a few examples of simple functions:</p>
<pre><code>def factorial(num):
"""Computes the factorial of num."""
def isPalindrome(inputStr):
"""Tests to see if inputStr is the same backwards and forwards."""
def sum(nums):
"""Same as the built-in sum()... computes the sum of all the numbers passed in."""
</code></pre>
<p>How thoroughly do you check the input values before beginning computation, and how do you do your checking? Do you throw some kind of proprietary exception if input is faulty (BadInputException defined in the same module, for example)? Do you just start your calculation and figure it will throw an exception at some point if bad data was passed in ("asd" to factorial, for example)?</p>
<p>When the passed in value is supposed to be a container do you check not only the container but all the values inside it?</p>
<p>What about situations like factorial, where what's passed in might be convertible to an int (e.g. a float) but you might lose precision when doing so?</p>
| <p>I <code>assert</code> what's absolutely essential.</p>
<p>Important: What's <em>absolutely</em> essential. Some people over-test things.</p>
<pre><code>def factorial(num):
assert int(num)
assert num > 0
</code></pre>
<p>Isn't completely correct. long is also a legal possibility.</p>
<pre><code>def factorial(num):
assert type(num) in ( int, long )
assert num > 0
</code></pre>
<p>Is better, but still not perfect. Many Python types (like rational numbers, or number-like objects) can also work in a good factorial function. It's hard to assert that an object has basic integer-like properties without being too specific and eliminating future unthought-of classes from consideration.</p>
<p>I never define unique exceptions for individual functions. I define a unique exception for a significant module or package. Usually, however, just an <code>Error</code> class or something similar. That way the application says <code>except somelibrary.Error,e:</code> which is about all you need to know. Fine-grained exceptions get fussy and silly.</p>
<p>I've never done this, but I can see places where it might be necessary. </p>
<pre><code>assert all( type(i) in (int,long) for i in someList )
</code></pre>
<p>Generally, however, the ordinary Python built-in type checks work fine. They find almost all of the exceptional situations that matter almost all the time. When something isn't the right type, Python raises a TypeError that always points at the right line of code.</p>
<p>BTW. I only add asserts at design time if I'm absolutely certain the function will be abused. I sometimes add assertions later when I have a unit test that fails in an obscure way.</p>
|
Gantt Chart Controls on Windows Forms <p>We are evaluating options for a Gantt chart control (on Windows Forms) as opposed developing one on our own. What are the various Gantt Chart controls you have had experience with? Pros and cons?</p>
<p>Is it a viable idea to develop such a control from scratch (given that the control is not the primary product in this case)?</p>
<p><strong>Update:</strong> Just bringing this up again since I've got only one answer. I'd be very grateful for more inputs. (Hope this is legal.)</p>
| <p>I have not worked with the Gantt charts from Telerik, but many people are very happy with Telerik.
I would never consider creating my own Gantt chart except if i was in the business of selling user controls</p>
|
Difference between User Control and Custom Control? <p>What are the differences between User Control and Custom Control in ASP.NET</p>
| <p>AFAIK, user controls are controls that you can create out of existing controls and can be part of the project and have a designer surface for you to drag/drop.</p>
<p>Custom controls are generally external to the project & would require to be hand-coded (using various asp.net control events & html building in the code).</p>
|
How to change XML Attribute <p>How can I change an attribute of an element in an XML file, using C#?</p>
| <p>Mike;
Everytime I need to modify an XML document I work it this way:</p>
<pre><code>//Here is the variable with which you assign a new value to the attribute
string newValue = string.Empty;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlFile);
XmlNode node = xmlDoc.SelectSingleNode("Root/Node/Element");
node.Attributes[0].Value = newValue;
xmlDoc.Save(xmlFile);
//xmlFile is the path of your file to be modified
</code></pre>
<p>I hope you find it useful</p>
|
Securing certain parts of an application <p>If someone logs on to my application this user contains a dictionary with certain permissions.</p>
<pre><code>ex: module.view.workspace = true
module.view.reporting = false
...
</code></pre>
<p>Then we know to what parts of the application the user has access.
What I want to know is how we can apply these permissions on the view.
We are working in an AS 3 (FLEX) environment.</p>
<p>This is what we came up with so far (but I wanna have an idea of other possibilities).
We have a modelLocator storing the loggedOnUser (which contains it's permissions).
these permissions are added to a permissionObject in the modellocator.
We Create a SecurityManager class that has a function called hasAccess("permission").
This object will check the PermissionObject in the modellocator and return true/false.
In the view we just check if the user has access and then show the control.</p>
<pre><code>If (SecurityManager.hasAccess("module.view.workspace") {
// code that generates the workspace;
}
</code></pre>
<p>I just don't know if this is the best practice.
Please help me out here.</p>
| <p>Sem, </p>
<p>I have a similar method and it worked fine so far. My application is written in C#.NET but the method is still valid. Since mine is a WinForms application I have to do other stuff but basically there is at some point an If statement asking that very same "question".</p>
<p>Martin.</p>
|
Java GUI Creating Components <p>I hope it is correct term-wise to say that components in a GUI is like JButton, JPanel, JTextField, all that good stuff.</p>
<p>I want to create a text field that takes in an integer. Then a submit button can be pressed and based on the integer that was inputted, create that many textfields in a popup window or whatever.</p>
<p>I have no clue, could someone get me started in the right direction?</p>
<p>The trouble I'm having is that I have no clue how to create a for loop to create the GUI components. I mean if I have a for loop and do something like:</p>
<pre><code>print("JTextField num1 = new JTextField()");
</code></pre>
<p>then in a for loop it will only create 1 text field when I want many. How do I generically create variables of JTextFields?</p>
<p>Thanks for your help...</p>
| <p>Use an appropriate LayoutManager (e.g. GridLayout) to create and add your textfields.</p>
<pre><code>for (i = 0; i < numberOfTextFields; i++) {
JTextField textField = new JTextField();
container.add(textField);
/* also store textField somewhere else. */
}
</code></pre>
|
MSSQLServer 2008 in virtual pc <p>What are your experiences with running SQL server in a virtual pc?
Currently we have an sql2008 instance running in a virtual machine.
Both CPU's hit the roof the moment a query is executed.</p>
<p>what are your experiences and what do you suggest in this matter?</p>
| <p>I've had some serious performance issues using virtualised SQL servers for database heavy applications (ETL development). See <a href="http://stackoverflow.com/questions/149318/virtualized-sql-server-why-not#149381">this Stackoverflow post</a> for a run-down on my experiences and the outcomes of digging into the underlying issues.</p>
<p>Essentially a DB heavy process like ETL will thrash the I/O (more sequential operations, so it isn't waiting for disk seeks as much as an OLTP app) and Translation Lookaside Buffer (large data sets), both of which are very slow on a naively virtualised image. The posting links out to <a href="http://developer.amd.com/assets/NPT-WP-1%201-final-TM.pdf" rel="nofollow">this whitepaper on AMD's site</a> (written by a vendor so take with a grain of salt) which (in between extolling the virtues of AMD's new Opteron chips) talks a bit about the underlying issues.</p>
|
WPF - How do i insert my proxy credentials in WebBrowser Control <p>I'm using a <code>webbrowser</code> <code>control</code> in WPF to show a virtual earth map, but because I'm developing behind a <code>proxy</code> of my company, every time I try to see the map, I have to insert my credentials. </p>
<p>I would like to insert them automatically in the c# code, how can I achieve that?</p>
<p>I already try in the navigating event of the web browser using:</p>
<pre><code>void webBrowser_Navigating(object sender, NavigatingCancelEventArgs e)
{
//NetworkCredential credential = new NetworkCredential("u007239", "****", "****");
//e.WebRequest.Proxy.Credentials = credential;
}
</code></pre>
<p>But this doesn't work because I'm getting that <code>e.webrequest</code> is a <code>null object</code>.</p>
<p>all the help is welcome. </p>
| <p>Can you not just put the following in your app.config?</p>
<pre><code><configuration>
<system.net>
<defaultProxy useDefaultCredentials="true" enabled="true"></defaultProxy>
</system.net>
</configuration>
</code></pre>
|
mysql range index <p>I have very simple select like this:</p>
<pre><code>SELECT * FROM table
WHERE column1 IN (5, 20, 30);
</code></pre>
<p>on column1 is seted index, after explaining query is index used, all looks to be ok. </p>
<p>but if there are more than three values in range, like this:</p>
<pre><code> SELECT * FROM table
WHERE column1 IN (5, 20, 30, 40);
</code></pre>
<p>index is not used and select runs thru all records. Am I doing something wrong? thanks</p>
| <p>How many rows does MySql think there are in the table?</p>
<p>Mysql often (usually correctly!) assumes it will be quicker to do a sequential scan of the rows, rather than mess around with the more complex access via an index.</p>
<p>It varies from DBMS to DBMS but the tradeoff point is somewhere about 30% of the rows.</p>
<p>IE. If the optimiser expects more than 30% of the rows to be selected it will sequentially scan the whole table as this is usually faster than doing lots of direct access via indexes. </p>
|
Can I embed a win32 DLL in a .NET assembly, and make calls into it using P/Invoke? <p>I'm writing a C# wrapper for a third-party native library, which we have as a DLL. I would like to be able to distribute a single DLL for the new assembly. Is it possible for me to embed the win32 DLL in my .NET DLL, and still make calls into it using P/Invoke? If so, how?</p>
| <p>Should work, if the native dll does not have any dependencies.</p>
<p>You can compile the dll in as embedded resource, than access the stream from inside your code, serialize it to the temporary folder and use it from there.</p>
<p>Too much to post example code here, but the way is not to complicated.</p>
|
Loop through PivotItems: runtime error 91 <p>I have a dataset in a worksheet that can be different every time. I am creating a pivottable from that data, but it is possible that one of the PivotItems is not there. For example:</p>
<pre><code>.PivotItems("Administratie").Visible = False
</code></pre>
<p>If that specific value is not in my dataset, the VBA script fails, saying that it can't define the item in the specified Field. (error 1004)</p>
<p>So I thought a loop might work.
I have the following: </p>
<pre><code>Dim pvtField As PivotField
Dim pvtItem As PivotItem
Dim pvtItems As PivotItems
For Each pvtItem In pvtField.pvtItems
pvtItem.Visible = False
Next
</code></pre>
<p>But that gives me an 91 error at the For Each pvtItem line:</p>
<pre><code>Object variable or With block variable not set
</code></pre>
<p>I thought I declared the variables well enough, but I am most likely missing something obvious... </p>
| <p>I've got it! :D</p>
<pre><code>Dim Table As PivotTable
Dim FoundCell As Object
Dim All As Range
Dim PvI As PivotItem
Set All = Worksheets("Analyse").Range("A7:AZ10000")
Set Table = Worksheets("Analyse").PivotTables("tablename")
For Each PvI In Table.PivotFields("fieldname").PivotItems
Set FoundCell = All.Find(PvI.Name)
If FoundCell <> "itemname" Then
PvI.Visible = False
End If
Next
</code></pre>
<p>woohoo</p>
<p>Thanks to MrExcel, the answer <em>was</em> there after all, though deeply buried.</p>
|
Finding an XmlNode by attribute in ASP.net <p>I'm trying to write some code to find a specific XmlNode object based on the URL in the XML sitemap but can't get it to find anything.</p>
<p>The sitemap is the standard ASP.net sitemap and contains:</p>
<pre><code><siteMapNode url="~/lev/index.aspx" title="Live-Eye-Views">
--- Child Items ---
</siteMapNode>
</code></pre>
<p>The code I'm using to search for the element is:</p>
<pre><code>XmlDocument siteMapXml = new XmlDocument();
siteMapXml.Load(AppDomain.CurrentDomain.BaseDirectory + _siteMapFileName)
XmlNode levRoot = siteMapXml.SelectSingleNode("siteMapNode[@url=\"~/lev/index.aspx\"]");
</code></pre>
<p>The levRoot object is always null. When I break after the Load method, I can see all the elements in the XML file so it's loading as expected.</p>
<p>I've tried using single quotes in the XPath query but that didn't make any difference.</p>
<p>_siteMapFileName is set in the Initialize method and is pointing at the correct file. </p>
<p>Does anyone have any ideas what could be up with this or suggest another way to find a specific element by attribute?</p>
| <p>The site map has a default name space, but you do not refer to it.</p>
<pre><code><siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
<siteMapNode url="~/lev/index.aspx" title="Live-Eye-Views">
<!-- Child Items -->
</siteMapNode>
</siteMap>
</code></pre>
<p>So, you should use this:</p>
<pre><code>XmlNamespaceManager nsmgr = new XmlNamespaceManager(siteMapXml.NameTable);
nsmgr.AddNamespace("smap", "http://schemas.microsoft.com/AspNet/SiteMap-File-1.0");
string xpath = "//smap:siteMapNode[@url=\"{1}\"]";
string url = "~/lev/index.aspx";
XmlNode levRoot = siteMapXml.SelectSingleNode(String.Format(xpath, url), nsmgr);
</code></pre>
|
Is there a way to prevent Reflector from being able to reflect my source code? <p>Is there a way (reliable and preferably not commercial) to prevent from Reflector to reflect my source code???</p>
<p>Thanks,
Adi</p>
| <p>No. Reflector looks at your assembly just like the .NET runtime would in order to generate native code to execute. The best you could hope for would be to <a href="http://stackoverflow.com/questions/2525/best-net-obfuscation-toolsstrategy">obfuscate</a> your code and make it (somewhat) harder for the reader to understand.</p>
<p>Some pros and cons of performing the obfuscation can be found at <a href="http://stackoverflow.com/questions/71195/should-you-obfuscate-a-commercial-net-application">Should you obfuscate a commercial .Net application?</a></p>
|
Disabling text selection in DocumentViewer <p>Simple question. How do you disable the text selection of DocumentViewer in WPF? This is the feature where an XPS document is displayed by the viewer and then text can be highlighted via mouse. The highlighted text can also be copied but I have already disabled this. I just don't know how to disable the highlighting.</p>
<p>Thanks!</p>
| <p>We have solved this by overriding the ControlTemplate of the ScrollViewer embedded in the DocumentViewer control. Insert the Style below in "Window.Resources":</p>
<pre><code><Style TargetType="{x:Type ScrollViewer}" x:Key="CustomScrollPresenter">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ScrollViewer}">
<Grid Background="{TemplateBinding Panel.Background}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Rectangle Grid.Column="1" Grid.Row="1" Fill="{DynamicResource {x:Static SystemColors.ControlBrushKey}}" />
<ScrollContentPresenter
PreviewMouseLeftButtonDown="ScrollContentPresenter_PreviewMouseLeftButtonDown"
Grid.Column="0"
Grid.Row="0"
Margin="{TemplateBinding Control.Padding}"
Content="{TemplateBinding ContentControl.Content}"
ContentTemplate="{TemplateBinding ContentControl.ContentTemplate}"
CanContentScroll="{TemplateBinding ScrollViewer.CanContentScroll}" />
<ScrollBar
x:Name="PART_VerticalScrollBar"
Grid.Column="1"
Grid.Row="0"
Minimum="0"
Maximum="{TemplateBinding ScrollViewer.ScrollableHeight}"
ViewportSize="{TemplateBinding ScrollViewer.ViewportHeight}"
Value="{Binding Path=VerticalOffset, Mode=OneWay, RelativeSource={RelativeSource Mode=TemplatedParent}}"
Visibility="{TemplateBinding ScrollViewer.ComputedVerticalScrollBarVisibility}"
Cursor="Arrow" AutomationProperties.AutomationId="VerticalScrollBar" />
<ScrollBar
x:Name="PART_HorizontalScrollBar"
Orientation="Horizontal" Grid.Column="0" Grid.Row="1" Minimum="0"
Maximum="{TemplateBinding ScrollViewer.ScrollableWidth}" ViewportSize="{TemplateBinding ScrollViewer.ViewportWidth}" Value="{Binding Path=HorizontalOffset, Mode=OneWay, RelativeSource={RelativeSource Mode=TemplatedParent}}" Visibility="{TemplateBinding ScrollViewer.ComputedHorizontalScrollBarVisibility}" Cursor="Arrow" AutomationProperties.AutomationId="HorizontalScrollBar" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</code></pre>
<p>Then override the Style of ScrollViewer with it in the ControlTemplate for DocumentViewer:</p>
<pre><code> <Style
x:Key="MyDVStyleExtend"
BasedOn="{StaticResource {x:Type DocumentViewer}}"
TargetType="{x:Type DocumentViewer}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="DocumentViewer">
<Border BorderThickness="2,2,2,2"
BorderBrush="SlateBlue" Focusable="False">
<Grid Background="{StaticResource GridBackground}"
KeyboardNavigation.TabNavigation="Local">
<Grid.ColumnDefinitions>
<ColumnDefinition Width ="*"/>
</Grid.ColumnDefinitions>
<ScrollViewer Style="{StaticResource CustomScrollPresenter}" Grid.Column ="0"
CanContentScroll="True"
HorizontalScrollBarVisibility="Auto"
x:Name="PART_ContentHost"
IsTabStop="True"/>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</code></pre>
<p>Then create a function for the "PreviewMouseLeftButtonDown="ScrollContentPresenter_PreviewMouseLeftButtonDown"" attribute stated in the CustomScrollPresenter style.</p>
<pre><code> private void ScrollContentPresenter_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
e.Handled = true;
}
</code></pre>
|
what does it mean when a bug doesn't crash the program <p>Sometimes Eclipse comes up saying "hey you should debug this line!!!" but doesn't actually close the program. I can then continue to play big two, and even go through the same events that caused the error the first time and get another error box to pop up!</p>
<p>The bug is simple, I'll fix it, I just want to know why some bugs are terminal and some are not? What's the difference?</p>
| <p>Programming mistakes can be categorized in these categories:</p>
<ol>
<li>Compile-time errors, which are caught by the compiler at the time of compilation and without correcting them, it's not possible to run the program at all.</li>
<li>Run-time errors, which are not caught by the compiler but put the computer in a situation which it cannot figure out what to do by itself, such as unhandled exceptions. Most of the times, this will cause the program to fail at run time and crash.</li>
<li>Logical errors, which are perfectly acceptable by the computer, as it is a valid computer program, but does not produce the result you expect. There is no way a computer can catch them since computer doesn't know your intention.</li>
</ol>
<p>In practice, it's a good thing to make errors be as deadly as possible as soon as they occur. It makes us find them sooner and correct them easier. This is why in "safer" languages such as Java, we have checked exceptions, and unhandled exceptions will cause the application to crash immediately instead of going on and probably producing incorrect results.</p>
|
JavaScript Hashmap Equivalent <p>As made clear in update 3 on <a href="http://stackoverflow.com/questions/367440/javascript-associative-array-without-tostring-etc#367454">this answer</a>, this notation:</p>
<pre><code>var hash = {};
hash[X]
</code></pre>
<p>does not actually hash the object <code>X</code>; it actually just converts <code>X</code> to a string (via <code>.toString()</code> if it's an object, or some other built-in conversions for various primitive types) and then looks that string up, without hashing it, in "<code>hash</code>". Object equality is also not checked - if two different objects have the same string conversion, they will just overwrite each other.</p>
<p>Given this - are there any efficient implementations of hashmaps in javascript? (For example, the 2nd Google result of <a href="http://www.google.com/search?rlz=1C1GGLS_en-USUS299US303&sourceid=chrome&ie=UTF-8&q=javascript+hashmap"><code>javascript hashmap</code></a> yields an implementation which is O(n) for any operation. Various other results ignore the fact that different objects with equivalent string representations overwrite each other.</p>
| <p>Why not hash your objects yourself manually, and use the resulting strings as keys for a regular JavaScript dictionary? After all you are in the best position to know what makes your objects unique. That's what I do.</p>
<p>Example:</p>
<pre><code>var key = function(obj){
// some unique object-dependent key
return obj.totallyUniqueEmployeeIdKey; // just an example
};
var dict = {};
dict[key(obj1)] = obj1;
dict[key(obj2)] = obj2;
</code></pre>
<p>This way you can control indexing done by JavaScript without heavy lifting of memory allocation, and overflow handling.</p>
<p>Of course, if you truly want the "industrial-grade solution", you can build a class parameterized by the key function, and with all necessary API of the container, but … we use JavaScript, and trying to be simple and lightweight, so this functional solution is simple and fast.</p>
<p>The key function can be as simple as selecting right attributes of the object, e.g., a key, or a set of keys, which are already unique, a combination of keys, which are unique together, or as complex as using some cryptographic hashes like in <a href="http://archive.dojotoolkit.org/nightly/dojotoolkit/dojox/encoding/">DojoX Encoding</a>, or <a href="http://archive.dojotoolkit.org/nightly/dojotoolkit/dojox/uuid/">DojoX UUID</a>. While the latter solutions may produce unique keys, personally I try to avoid them at all costs, especially, if I know what makes my objects unique.</p>
<p><strong>Update in 2014:</strong> Answered back in 2008 this simple solution still requires more explanations. Let me clarify the idea in a Q&A form.</p>
<p><em>Your solution doesn't have a real hash. Where is it???</em></p>
<p>JavaScript is a high-level language. Its basic primitive
(<a href="http://en.wikipedia.org/wiki/JavaScript_syntax#Objects">Object</a>)
includes a hash table to keep properties. This hash table is usually written
in a low-level language for efficiency. Using a simple object with string keys we use an efficiently implemented hash table with no efforts on our part.</p>
<p><em>How do you know they use hash?</em></p>
<p>There are three major ways to keep a collection of objects addressable by a key:</p>
<ul>
<li>Unordered. In this case to retrieve an object by its key we have to go over all keys stopping when we find it. On average it will take n/2 comparisons.</li>
<li>Ordered.
<ul>
<li>Example #1: a sorted array — doing a binary search we will find our key after ~log2(n) comparisons on average. Much better.</li>
<li>Example #2: a tree. Again it'll be ~log(n) attempts.</li>
</ul></li>
<li>Hash table. On average it requires a constant time. Compare: O(n) vs. O(log n) vs. O(1). Boom.</li>
</ul>
<p>Obviously JavaScript objects use hash tables in some form to handle general cases.</p>
<p><em>Do browser vendors really use hash tables???</em></p>
<p>Really.</p>
<ul>
<li>Chrome/node.js/<a href="https://github.com/v8/v8/">V8</a>:
<a href="https://github.com/v8/v8/blob/master/src/objects.h#L1680">JSObject</a>. Look for
<a href="https://github.com/v8/v8/blob/master/src/objects.h#L3618">NameDictionary</a> and
<a href="https://github.com/v8/v8/blob/master/src/objects.h#L3606">NameDictionaryShape</a> with
pertinent details in <a href="https://github.com/v8/v8/blob/master/src/objects.cc">objects.cc</a>
and <a href="https://github.com/v8/v8/blob/master/src/objects-inl.h">objects-inl.h</a>.</li>
<li>Firefox/<a href="https://github.com/mozilla/gecko-dev">Gecko</a>:
<a href="https://github.com/mozilla/gecko-dev/blob/master/js/src/jsobj.h#L99">JSObject</a>,
<a href="https://github.com/mozilla/gecko-dev/blob/master/js/src/vm/NativeObject.h#L349">NativeObject</a>, and
<a href="https://github.com/mozilla/gecko-dev/blob/master/js/src/vm/NativeObject.h#L1238">PlainObject</a> with pertinent details in
<a href="https://github.com/mozilla/gecko-dev/blob/master/js/src/jsobj.cpp">jsobj.cpp</a> and
<a href="https://github.com/mozilla/gecko-dev/blob/master/js/src/vm/NativeObject.cpp">vm/NativeObject.cpp</a>.</li>
</ul>
<p><em>Do they handle collisions?</em></p>
<p>Yes. See above. If you found a collision on unequal strings, please do not hesitate to file a bug with a vendor.</p>
<p><em>So what is your idea?</em></p>
<p>If you want to hash an object, find what makes it unique and use it as a key. Do not try to calculate real hash or emulate hash tables — it is already efficiently handled by the underlying JavaScript object.</p>
<p>Use this key with JavaScript <code>Object</code> to leverage its built-in hash table while steering clear of possible clashes with default properties.</p>
<p>Examples to get you started:</p>
<ul>
<li>If your objects include a unique user name — use it as a key.</li>
<li>If it includes a unique customer number — use it as a key.
<ul>
<li>If it includes unique government-issued numbers like an SSN, or a passport number, and your system doesn't allow duplicates — use it as a key.</li>
</ul></li>
<li>If a combination of fields is unique — use it as a key.
<ul>
<li>State abbreviation + driver license number makes an excellent key.</li>
<li>Country abbreviation + passport number is an excellent key too.</li>
</ul></li>
<li>Some function on fields, or a whole object, can return a unique value — use it as a key.</li>
</ul>
<p><em>I used your suggestion and cached all objects using a user name. But some wise guy is named "toString", which is a built-in property! What should I do now?</em></p>
<p>Obviously, if it is even remotely possible that the resulting key will exclusively consists of Latin characters, you should do something about it. For example, add any non-Latin Unicode character you like at the beginning or at the end to un-clash with default properties: "#toString", "#MarySmith". If a composite key is used, separate key components using some kind of non-Latin delimiter: "name,city,state".</p>
<p>In general this is the place, where we have to be creative, and select the easiest keys with given limitations (uniqueness, potential clashes with default properties).</p>
<p>Note: unique keys do not clash by definition, while potential hash clashes will be handled by the underlying <code>Object</code>.</p>
<p><em>Why don't you like industrial solutions?</em></p>
<p>IMHO, the best code is no code at all: it has no errors, requires no maintenance, easy to understand, and executes instantaneously. All "hash tables in JavaScript" I saw were >100 lines of code, and involved multiple objects. Compare it with: <code>dict[key] = value</code>.</p>
<p>Another point: is it even possible to beat a performance of a primordial object written in a low-level language, using JavaScript and the very same primordial objects to implement what is already implemented?</p>
<p><em>I still want to hash my objects without any keys!</em></p>
<p>We are in luck: ECMAScript 6 (scheduled for mid 2015 release, give or take 1-2 years after that to become widespread) defines
<a href="https://people.mozilla.org/~jorendorff/es6-draft.html#sec-map-objects">map</a> and
<a href="https://people.mozilla.org/~jorendorff/es6-draft.html#sec-set-objects">set</a>.</p>
<p>Judging by the definition they can use object's address as a key, which makes objects instantly distinct without artificial keys. OTOH, two different, yet identical objects, will be mapped as distinct.</p>
|
Why does com.mysql.jdbc.Driver take forever to open in MATLAB? <p>I'm having an issue with com.mysql.jdbc.Driver in MATLAB and I'm hoping someone else has run into it and can help me out. Basically, my problem is that on one machine, every time I call <code>database('mysql.jdbc.Driver', ...)</code>, that call takes approximately 30 seconds. I would just chalk this up as normal except that when I run the same script on a different machine, it the call to <code>database</code> takes about 15 seconds the first time, and less than 1 second every time after. Once I have the database connection, running queries takes the same amount of time no matter what machine I'm working on.</p>
<p>Has anyone else run into (and solved) this issue? My best guess is that there's some sort of environment issue causing the problem, but I have no idea even where to begin looking.</p>
| <p>It turns out this was some sort of networking / service issue. When I turned off some of the unneeded services (Wireless Zero Configuration among others), I went from a consistent 20 seconds to create the connection to a few milliseconds. I wish I had paid better attention to the services I changed, but hopefully this helps someone else.</p>
<p>Thanks to Mr. Fooz for suggesting using something else, that allowed me to confirm that it was a system issue, and not MATLAB specific.</p>
|
Associate arbitrary data with ejb call context <p>I've got a bunch of stateless ejb 3.0 beans calling each other in chain.
Consider, BeanA.do(message) -> BeanB.do() -> BeanC.do() -> BeanD.do().
Now i'd like to access message data from BeanD.do(). Obvious solution is to pass message as a parameter to all that do() calls (actually that's how it works now), but i want some nicer solution.</p>
<p>Is there some kind of call context? And can i associate arbitrary data with it?</p>
<p>What i'd like to do, is simply put message in BeanA.do(message) to some local storage associated with bean function call and retrieve it in BeanD.do().</p>
<p>Any ideas?</p>
| <p>i don't believe there is anything in the EJB spec that provides that functionality. If you are on a specific app server, you may be able to use app server specific stuff (i think JBoss allows you to add stuff to a call context). you also may be able to fake something up using JNDI.</p>
<p>personally, this seems (to me) like a poor design. i could see doing this if you had some code in the middle you could not control, but why do it otherwise? you are making your code logic very hard to follow because you have a bunch of "magic" data which just appears in your function.</p>
|
How can I get this request structure via .asmx web service? <p>I am working on creating a .asmx webservice to meet the specific needs of an integration environment and for the life of me I cannot figure out how to get one section of it to work. The key is that the request WSDL needs to be something like the following. (Note I removed the soap envelope and namespace information)</p>
<pre><code><methodOne>
<myValue>string</myValue>
<myDemoGroup>
<myDemoGroupItem>string</myDemoGroupItem>
<myDemoGroupItem2>string</myDemoGroupItem2>
</myDemoGroup>
<myComplexGroup>
<mySubStructure>
<subItem1>string</subItem1>
<subItem2>string</subItem2>
</mySubStructure>
</myComplexGroup
</methodOne>
</code></pre>
<p>Now, I know how to take care of most of this, the method one tag is handled by the name of my parameter, and then the items inside are simply elements in the class. SO something like this gets everything except for "MyComplexGroup"</p>
<pre><code>[Web Method]
public void MyWebMethod(MyWebMethodRequest methodOne)
{
//Do my stuff
}
public class MyWebMethodRequest
{
public string myValue {get; set;}
public MyDemoGroupInfo myDemoGroup {get; set;}
}
public class MyDemoGroupInfo
{
public string myDemoGroupItem {get; set;}
public string myDemoGroupItem2 {get; set;}
}
</code></pre>
<p>The question is how to I define the "myComplexGroup" to allow the creation of multiple mySubStructure elements, while still outputting all items to the WSDL.</p>
<p>If I continue on and do something like this</p>
<pre><code>public class MyComplexGroupInfo
{
public List<MySubStructureInfo> mySubStructure {get; set;}
}
public class MySubStructureInfo
{
public string subItem1 {get; set;}
public string subItem2 {get; set;}
}
</code></pre>
<p>I can then add <code>public MyComplexGroupInfo myComplexGroup {get; set;}</code> to the object and I will get part of it, but instead of listing subItem1 and subItem2 it simply says MySubStructureInfo with nil set to one.</p>
<p>How can I get around this?</p>
| <p>If you have WSDL contract that needs to be implemented, you may try <code>wsdl.exe /serverInterface</code> to get service stub generated.</p>
|
Tool to show processes writing to the hard drive? <p>Is there a tool that will show me what applications are writing to the hard drive in real time? I'm thinking something like Task Manager but for I/O. I've got a number of background processes running, and can never tell when Visual Studio is holding everything up, or some other process is hogging the disk (especially when the processor is running at less than 20%).</p>
| <p><a href="http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx">ProcMon</a> from Sysinternals/Microsoft.</p>
|
Removing scrollbars from Content Editor/Page Viewer Webpart <p>I am trying to display an HTML page inside another SharePoint webpart page.</p>
<p>I used the Out-of-the-box page viewer webpart, but the page viewer webpart displays a disabled scrollbar inside it.</p>
<p>I also tried using a content editor webpart with an IFRAME tag in it, but still it didnt't work.</p>
<p>This is the code i used in the content editor webpart. </p>
<pre><code><iframe name="Iframe" src="URL1" scrolling="no"
FRAMEBORDER="0" style="width:100%; border:0; height:100%; overflow:hidden;">
</iframe>
</code></pre>
| <p>Use this on your stylesheet:</p>
<pre><code>#s4-workspace {
overflow-y: hidden !important;
overflow-x: hidden !important;
}
</code></pre>
|
How can I log *all* ColdFusion scripts and CFCs used? <p>I am looking to determine from a large code base, what files are actually being used over a period of time. I need to know about CFM pages and CFCs as well as any included CFM files etc. </p>
<p>I know I can get <em>some</em> of this info using logging in application.cfm, or by using IIS, but I will still be missing any include files and any CFCs used. </p>
<p>Is there any way to get CF to log every file it executes? Ideally I would like to keep any new coding to a minimum or just in one place. </p>
<p>Thanks,
Ciarán </p>
| <p>Hmmm, I think you'll need to turn on debugging and create a custom debug template.</p>
<p>The debug templates are in: [coldfusiondir]/wwwroot/WEB-INF/debug</p>
<p>Have a look at the code which <code>classic.cfm</code> uses to display Templates to screen, and then create some similar code which logs each template run to a suitable data store.</p>
<p>Note: there is a performance issue (in CFMX6/7) with Report Execution Times and CFCs, so make sure you have that setting disabled, and any related code removed.</p>
<p>Infact, if this is to be running in a Live environment (not ideal), then make sure you strip down your custom template to the minimum necessary code to perform just this logging.</p>
|
What .NET functions should be better supported in Mono? <p>I'm trying to implement a Visual Studio Addin to support cross-platform development. The addon currently only warns developer when using unsupported functions but I also want to implement a feature that informs him about functions that are implemented but produce sideffects / are unstable etc. </p>
<p>Can anyone help me? I would really appreciate this!</p>
| <p>Mono provides a utility to analyze application binary and check for mono support called Mono Migration Analyzer. You can probably read the source code to understand more about less supported features. You can even directly use run this tool with your add in and process the results.</p>
|
Search engines and browser accept-language <p>I'm building a web portal where language content will generally depend on the "accept-language" sent by the browser. The same content-URI will thus serve different content to different users depending on their browser setting.</p>
<p>I'm very curious to know how this will affect search indexing. Does Google index using all languages, and is it handled well?</p>
| <p>They don't send accept-language, so the site will be indexed in the default language that you select.</p>
<p>I recommend you to have different URL for each language, not only for the search engines, but for letting the user change the site language without changing the "accept-language" and letting the user to send a URL to a friend with the language selected.</p>
<p>In this <a href="http://stackoverflow.com/questions/82380/best-way-to-handle-urls-in-a-multilingual-site-in-aspnet">answer</a> you have how I managed it in .net, but you will get the idea: Using the "accept-language" the make the first redirect, and them play only with the url.</p>
|
Some (anti-)patterns on using assert (Java, and others) <p>Finally, I have a question to ask on Stack Overflow! :-)</p>
<p>The main target is for Java but I believe it is mostly language agnostic: if you don't have native assert, you can always simulate it.</p>
<p>I work for a company selling a suite of softwares written in Java. The code is old, dating back to Java 1.3 at least, and at some places, it shows... That's a large code base, some 2 millions of lines, so we can't refactor it all at once.<br />
Recently, we switched the latest versions from Java 1.4 syntax and JVM to Java 1.6, making conservative use of some new features like <code>assert</code> (we used to use a DEBUG.ASSERT macro -- I know <code>assert</code> has been introduced in 1.4 but we didn't used it before), generics (only typed collections), foreach loop, enums, etc.</p>
<p>I am still a bit green about the use of assert, although I have read a couple of articles on the topic. Yet, some usages I see leave me perplex, hurting my common sense... ^_^ So I thought I should ask some questions, to see if I am right to want to correct stuff, or if it goes against common practices. I am wordy, so I <strong>bolded</strong> the questions, for those liking to skim stuff.</p>
<p>For reference, I have searched <em>assert java</em> in SO and found some interesting threads, but apparently no exact duplicate.</p>
<ul>
<li><a href="http://stackoverflow.com/questions/271526/how-to-avoid-null-statements-in-java" rel="nofollow" title=" How to avoid â!= nullâ statements in java? "> How to avoid â!= nullâ statements in java? </a> and <a href="http://stackoverflow.com/questions/302736/how-much-null-checking-is-enough" rel="nofollow" title="How much null checking is enough?">How much null checking is enough?</a> are quite relevant, because lot of asserts we have just check if variable is null. At some places in our code, there are usages of the null object (eg. returning <code>new String[0]</code>) but not always. We have to live with that, at least for maintenance of legacy code.</li>
<li>Some good answers also in <a href="http://stackoverflow.com/questions/298909/java-assertions-underused" rel="nofollow" title="Java assertions underused">Java assertions underused</a>.</li>
<li>Oh, and SO indicates with reason that <a href="http://stackoverflow.com/questions/129120/when-should-i-use-debugassert" rel="nofollow" title="When should I use Debug.Assert()?">When should I use Debug.Assert()?</a> question is related too (nice feature to reduce duplicates!).</li>
</ul>
<p>First, main issue, which triggered my question today:</p>
<pre><code>SubDocument aSubDoc = documents.GetAt( i );
assert( aSubDoc != null );
if ( aSubDoc.GetType() == GIS_DOC )
{
continue;
}
assert( aSubDoc.GetDoc() != null );
ContentsInfo ci = (ContentsInfo) aSubDoc.GetDoc();
</code></pre>
<p>(<em>Yes, we use MS' C/C++ style/code conventions. And I even like it (coming from same background)! So sue us.</em>)<br />
First, the <code>assert()</code> form comes from conversion of <code>DEBUG.ASSERT()</code> calls. I dislike the extra parentheses, since assert is a language construct, not (no longer, here) a function call. I dislike also <code>return (foo);</code> :-)<br />
Next, the asserts don't test here for invariants, they are rather used as guards against bad values. But as I understand it, they are useless here: the assert will throw an exception, not even documented with a companion string, and only if assertions are enabled. So if we have <code>-ea</code> option, we just have an assertion thrown instead of the regular NullPointerException one. That doesn't look like a paramount advantage, since we catch unchecked exceptions at highest level anyway.<br />
<strong>Am I right supposing we can get rid of them and live with that (ie. let Java raise such unckecked exception)?</strong> (or, of course, test against null value if likely, which is done in other places).</p>
<p>Side note: should I have to assert in the above snippet, I would do that against ci value, not against the getter: even if most getters are optimized/inlined, we cannot be sure, so we should avoid calling it twice.</p>
<p>Somebody told, in the last referenced thread, that public methods should use tests against values of parameters (usage of the public API) and private methods should rely on asserts instead. Good advice.<br />
Now, both kinds of methods must check another source of data: external input. Ie. data coming from user, from a database, from some file or from the network, for example.<br />
In our code, I see asserts against these values. I always change these to real test, so they act even with assertions disabled: these are not invariants and must be properly handled.<br />
I see only one possible exception, where input is supposed constant, for example a database table filled with constants used in relations: program would break if this table is changed but corresponding code wasn't updated.<br />
<strong>Do you see other exceptions?</strong></p>
<p>Another relatively frequent use I see, which seems OK: in the default of a switch, or at the end of a series of <code>else if</code> testing all possible values (these cases date back before our use of enums!), there is often an <code>assert false : "Unexpected value for stuff: " + stuff;</code><br />
<strong>Looks legitimate for me (these cases shouldn't happen in production), what do you think?</strong> (beyond the "no switch, use OO" advices which are irrelevant here).</p>
<p>And finally, <strong>are there any other useful use cases or annoying gotchas</strong> I missed here? (probably!)</p>
| <p>The number one rule is to avoid side-effects in assertions. In other words, the code should behave identically with assertions turned off as it does when assertions are turned on and not failing (obviously assertions that fail are going to alter the behaviour because they will raise an error).</p>
<p>The number two rule is not to use assertions for essential checks. They can be turned off (or, more correctly, not turned on). For parameter-checking of non-private methods use IllegalArgumentException.</p>
<p>Assertions are executable assumptions. I use assertions to state my beliefs about the current state of the program. For example, things like <em>"I assume that n is positive here"</em>, or <em>"I assume that the list has precisely one element here"</em>.</p>
|
Dynamic Graph Filtering <p>I am working on a graph in WPF, in each section there are thousands of points to draw. The performance for rendering this graph is horrible. </p>
<p>Does anyone have any experience with a filter that will represent the graph with much fewer points - similar to the way a stock graph draws itself when its zoomed out. </p>
<p>Thank you.</p>
| <p>When you talk about a graph, I'm assuming you mean as in a chart rather than lots of nodes and edges (hence the stock example).</p>
<p>So, assuming that's the case, here are a couple of webpages covering algorithms for simplifying polylines:</p>
<p><a href="http://www.kevlindev.com/tutorials/geometry/simplify_polyline/page2.htm" rel="nofollow">http://www.kevlindev.com/tutorials/geometry/simplify_polyline/page2.htm</a></p>
<p><a href="http://softsurfer.com/Archive/algorithm_0205/algorithm_0205.htm" rel="nofollow">http://softsurfer.com/Archive/algorithm_0205/algorithm_0205.htm</a></p>
<p>You could generate simplified polyline versions of the graph lines for various scales (on demand).</p>
|
Best way to quickly determine whether a user account is a member of an AD group? <p>I currently have some code that pulls down a list of users in a group and then iterates through that group to determine if a given account exists, but it seems like there ought to be a more concise (and perhaps faster) way to accomplish this.</p>
<p>This code (VB.NET) attempts to use the member property of the group object, but it is returning false even when the user is a member of that group. Can anyone see what I am doing wrong here?</p>
<pre><code>Dim group As DirectoryEntry = GetNetworkObject(GroupDomanName, NetworkObjectType.NetworkGroup, GroupName)
Dim user As DirectoryEntry =GetNetworkObject(UserDomainName, NetworkObjectType.NetworkUser, Login)
Return group.Properties("member").Contains(user.Path)
</code></pre>
<p>FYI: The GetNetworkObject calls just return a directoryEntry object, I have confirmed that the correct object is being returned for both the group and user object.</p>
| <p>If you are on .NET 3.5 stack, <a href="http://msdn.microsoft.com/en-us/library/system.directoryservices.accountmanagement.aspx">System.DirectoryServices.AccountManagement.dll assembly</a> has a nice API on top of AD. The following method can be implemented to solve your issue:</p>
<pre><code>static bool IsUserMemberOf(string userName, string groupName)
{
using (var ctx = new PrincipalContext(ContextType.Domain))
using (var groupPrincipal = GroupPrincipal.FindByIdentity(ctx, groupName))
using (var userPrincipal = UserPrincipal.FindByIdentity(ctx, userName))
{
return userPrincipal.IsMemberOf(groupPrincipal);
}
}
// Usage:
bool result = IsUserMemberOf("CONTOSO\\john.doe", "CONTOSO\\Administrators");
</code></pre>
<p>I don't know how this method performs but it is a clean solution.</p>
|
When to separate certain entities into different repositories? <p>I generally try and keep all related entities in the same repository. The following are entities that have a relationship between the two (marked with indentation):</p>
<ul>
<li>User
<ul>
<li>UserPreference</li>
</ul></li>
</ul>
<p>So they make sense to go into a user repository. However users are often linked to many different entities, what would you do in the following example?</p>
<ul>
<li><p>User</p>
<ul>
<li>UserPrefence</li>
<li>Order</li>
</ul></li>
<li><p>Order</p>
<ul>
<li>Product</li>
</ul></li>
</ul>
<p>Order has a relationship with both product and user but you wouldn't put functionality for all 4 entities in the same repository. What do you do when you are dealing with the user entities and gathering order information? You may need extra information about the product and often ORMs will offer the ability of lazy loading. However if your product entity is in a separate repository to the user entity then surely this would cause a conflict between repositories?</p>
| <p>In the Eric Evan's Domain Driven Design ( <a href="http://domaindrivendesign.org/index.htm" rel="nofollow">http://domaindrivendesign.org/index.htm</a> ) sense of things you should first think about what about your Aggregates. You then build you repositories around those.</p>
<p>There are many techniques for handling Aggregates that relate to each other. The one that I use most often is to only allow Aggregates to relate to each other through a read only interface. One of the key thoughts behind Aggregates is that you can't change state of underlying objects without going through the root. So if Product and User are root Aggregates in your model than I can't update a Product if I got to it by going through User->Order->Product. I have to get the Product from the Product repository to edit it. (From a UI point of view you can make it look like you go User->Order->Product, but when you hit the Product edit screen you grab the entity from the Product Repository).</p>
<p>When you are looking at a Product (in code) by going from User->Order->Product you should be looking at a Product interface that does not have any way to change the underlying state of the Product (only gets no sets etc.)</p>
<p>Organize your Aggregates and therefor Repositories by how you use them. I can see User and Prodcut being their own Aggregates and having their own Repositories. I'm not sure from your description if Order should belong to User or also be stand alone.</p>
<p>Either way use a readonly interface when Aggregates relate. When you have to cross over from one Aggregate to the other go fetch it from its own Repository.</p>
<p>If your Repositories are caching then when you load an Order (through a User) only load the Product Id's from the database. Then load the details from the Product Repository using the Product Id. You can optimize a bit by loading any other invariants on the Product as you load the Order.</p>
|
Passing a Python array to a C++ vector using Swig <p>I have an array of objects in Python </p>
<pre><code>[obj1, obj2, obj3]
</code></pre>
<p>and I want to pass them to off to a C++ function to perform some computation. I'm using SWIG to write my interface. The class type of the passed object is already defined in C++. </p>
<p>What's the best way to do this?</p>
| <p>It depends on if your function is already written and cannot be changed, in which case you may need to check Swig docs to see if there is already a typemap from PyList to std::vector (I think there is). If not, taking PyObject* as the argument to the function and using the Python C API for manipulating lists should work fine. I haven't had any problems with it so far. For self-documentation, I recommend typedef'ing PyObject* to some kind of expected type, like "PythonList" so that the parameters have some meaning.</p>
<p>This may also be useful:</p>
<p><a href="http://stackoverflow.com/questions/276769/how-to-expose-stdvectorint-as-a-python-list-using-swig">http://stackoverflow.com/questions/276769/how-to-expose-stdvectorint-as-a-python-list-using-swig</a></p>
|
Reading an Oracle Lite ODB file without Oracle Lite <p>Is there a way to extract the data from an Oracle Lite ODB file without installing Oracle Lite? Is there a reader out there which will let me browse and copy the data?</p>
| <p>You should be able to export the data using the OLLOAD utility, which is part of, but should not require the installation of, Oracle Lite.</p>
<p><a href="http://download.oracle.com/docs/cd/E12095_01/doc.10302/e12548/cdbtools.htm#BABIIJGF" rel="nofollow">OLLOAD Documentation</a></p>
|
Monitoring load on ASP.NET Application <p>I am looking for ways to keep track of simultaneous users within an application. I cannot use IIS logs due to a load balancer that abstracts the users IP address. I am looking for a .NET code based solution or a configuration item, possibly with health monitoring to be able to track the "true" simultaneous user count.</p>
<p>I know that I can monitor the number of sessions, but that isn't really an ideal method to show, as it can be bloated based on the number of sessions with users abandoning their session.</p>
| <p>There is a similiar question here: <a href="http://stackoverflow.com/questions/259105/tools-and-methods-for-live-monitoring-aspnet-web-applications">Tools and methods for live-monitoring ASP.NET web applications?</a></p>
<p>I found an advanced logging tool for debugging and monitoring .NET applications: <a href="http://www.gurock.com/products/smartinspect/" rel="nofollow">SmartInspect</a>. But I don't know if it meets your requirements.</p>
|
iFrame causes scriptaculous dragging issues in IE7 (full code included)? <p>When I drag a link that is inside a draggable div over an iframe in IE7, I get very strange results. Try the code below and let me know if you have any suggestions about how to fix this.</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<!--<script type="text/javascript" src="/js/prototype.js"></script>-->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.3/prototype.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/scriptaculous/1.8.2/scriptaculous.js?load=effects,dragdrop,controls"></script>
<!--<script type="text/javascript" src="/js/scriptaculous.js?load=effects,dragdrop,controls"></script>-->
</head>
<body>
<div id="test" style="background-color: #aaaaaa; width: 200px; height: 50px;">
<a href="blah" onclick="blah(); return false;">blah</a>
</div>
<iframe>
</iframe>
</body>
<script>
function blah(){
//blackbird.debug("blah");
}
var dummy = new Draggable("test", {scroll:window,scrollSensitivity: 20,scrollSpeed: 25, revert: true, onStart: onDragStart, onEnd: onDragEnd });
var temp;
function onDragStart(drgObj,mouseEvent){
temp = mouseEvent.target.onclick;
mouseEvent.target.onclick = function(e){
mouseEvent.target.onclick = temp;
return false;
}
}
function onDragEnd(drgObj,mouseEvent){
}
</script>
</html>
</code></pre>
| <p>I found the only way to handle this gracefully was to place a full size div, with transparency = 1% over the iframe, then drag my content over top of it.</p>
<p>PS the dragging issue is in IE6 and IE8 too.</p>
|
Why does mx:states have trouble being resolved to a component implementation? <p>Every now and then I get an error when I set up states in an MXML file. The error I get says that mx:states could not be resolved to a component implementation.</p>
<p>I read, at the following url, that this issue is caused by extending components - that somehow throws off the compiler's ability to resolve mx:states. I don't see why this should be the case, but I don't have any answer of my own. I also can't necessarily make this approach work with all of my extended components.</p>
<p><a href="http://life.neophi.com/danielr/2007/01/could_not_resolve_to_a_compone.html" rel="nofollow">http://life.neophi.com/danielr/2007/01/could_not_resolve_to_a_compone.html</a></p>
<p>The workaround I've come up with is to not use any namespace.
So, my code then looks like this:</p>
<pre><code><states>...</states>
</code></pre>
<p>rather than:</p>
<pre><code><mx:states>...</mx:states>
</code></pre>
<p>Making this stranger (at least, to me) is the fact that the children of the tag - - does not have this issue. mx:states can not be resolved, but its child mx:State can. And mx:SetProperty - a child of mx:State - is also resolved.</p>
<p>Can anyone explain this, and/or offer a better solution to the problem than what I've come up with?</p>
<p>Incidentally, I see the same issue with mx:transitions.</p>
| <p>If you have a custom component, you'll probably have it in a namespace other than <em>mx</em>. You're on the right track by removing the namespace, but you don't have to do that. Consider the following example</p>
<pre><code><example:MyComponent xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:example="com.example.*">
</example:MyComponent>
</code></pre>
<p>In that code, we have a custom component named MyComponent in the com.example package. Now, how do we add custom states? It's easy!</p>
<pre><code><example:MyComponent xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:example="com.example.*">
<example:states>
<mx:State name="CustomState">
</mx:State>
</example:states>
</example:MyComponent>
</code></pre>
<p>Properties of a component, like <em>states</em>, <em>transitions</em>, or even <em>label</em> on a Button can be created as child elements. Those properties must use the same namespace as the component instance. It doesn't matter where the property comes from in the inheritance chain. Even if com.example.MyComponent extends mx.containers.Canvas, the states property will use the XML namespace in which MyComponent is defined.</p>
<p>In short, don't think of the <em>states</em> property as <em>mx:states</em> because the <em>mx:</em> prefix of a property is merely inherited from the component. However, we do have to use <em>mx:</em> when we define the actual state itself because that's a class (not a property) and that class is defined in the mx namespace.</p>
<p>To go a step further in the explanation, you can change the <em><a href="http://www.adobe.com/2006/mxml">http://www.adobe.com/2006/mxml</a></em> namespace to be something other than <em>mx</em>.</p>
<pre><code><zzz:VBox xmlns:zzz="http://www.adobe.com/2006/mxml">
<zzz:states>
</zzz:states>
</zzz:VBox>
</code></pre>
<p>In that example, we change <em>mx</em> to <em>zzz</em>. Now, the <em>states</em> property has to be prefixed with <em>zzz:</em> instead of <em>mx:</em>.</p>
|
How to make php5 on a machine running php4, without breaking anything <p>I know with python and a couple other languages there is a way to safely make install a newer generational version of a language onto a machine, but after digging through PHP5's configure & makefile the only thing I've seen is the prefix dir option and the ini scan path.</p>
<p>Ideally I'd like php5 to have its own lib/bin subdirectories in /usr/local and then I can just put php5 after php4 in the path or make a symbolic link from the php5 binaries to php5-cli, php5-cgi, etc. </p>
<p>Also, am I missing anything dramatically bad here, the server in question is a legacy application server that's still somewhat busy and is due to be deprecated by June of 2009 but in the meantime the plan is to start updating parts with php5 code.</p>
<p>Machine states:
CENTOS 5
PHP 4 was built from a source RPM outside of yum's control</p>
<p>Most of php4 is in ambiguous directories:
/usr/{include,lib}/php </p>
| <p>Here's a pretty detailed explanation on how to do this on Gentoo with some tips to watch out for.</p>
<p><a href="http://www.gentoo.org/proj/en/php/php4-php5-configuration.xml" rel="nofollow">link text</a></p>
<p>And here's another one for good measure</p>
<p><a href="http://www.howtoforge.com/apache2_with_php5_and_php4" rel="nofollow">link text</a></p>
|
If I wanted to work using dates and time going millions of years into the past/future how would I do it? <p>If I wanted to work using dates and time going millions of years into the past/future how would I do it in C/C++/C#? </p>
<p>For example say I was working on an algorithm to see if a comet was going to hit the earth? Are there commercial or open source libraries that do this?</p>
<p>Most DateTime values only work for a few years. Unixes will run out in only 2038!.</p>
<p>Tony</p>
| <p>Astronomers use their own calendar, different from the civil, Gregorian calendar.</p>
<p><a href="http://scienceworld.wolfram.com/astronomy/JulianDate.html" rel="nofollow">Astronomical Julian Dates</a> are what they use.</p>
<p>Look at <a href="http://en.wikipedia.org/wiki/Julian_day" rel="nofollow">http://en.wikipedia.org/wiki/Julian_day</a></p>
<p>Here's a typical package: <a href="http://sourceforge.net/projects/solarclock/" rel="nofollow">Solar Clock</a>.</p>
|
Why should you not use Number as a constructor? <p>I entered this statement in JSLint:</p>
<pre><code>var number = new Number(3);
</code></pre>
<p>And received the following message:</p>
<blockquote>
<p>Do not use Number as a constructor.</p>
</blockquote>
<p>Why is that? The statement is creating a number object, not a primitive value, so I don't see why using <code>new</code> is a problem.</p>
<p><strong>EDIT:</strong> Thanks for all the responses. They've got me thinking further, so I posted a follow-up question <a href="http://stackoverflow.com/questions/369424/question-about-objectmethod-in-javascript">here</a>.</p>
<p><strong>UPDATE:</strong> Thanks again for all the responses! They've been very helpful. I guess to sum up, in JavaScript, an Object type is not equal to another Object type, even when they have the exact same value, unless they are both the EXACT SAME object.</p>
<p>In other words, in Matthew's example below, n1 == n2 is false because you are comparing two REFERENCES to two SEPARATE objects, but n1 == n1 is true because you are comparing references to the EXACT SAME object.</p>
<p>So, while I now understand why using Number as a constructor can cause problems, I found you can use the valueOf property when comparing Number objects. </p>
<p>In other words, n1.valueOf == n2.valueOf is true! (This is because you're comparing the return values of the valueOf FUNCTION, not the REFERENCES to the objects themselves.)</p>
| <p>In addition to breaking === and typeof returning "object", using the Number constructor also changes the way the value is used in boolean contexts. Since "new Number(0)" is an object, not a literal value, it evaluates as "true" because it is not null. So for example:</p>
<pre><code>var n1 = 0;
var n2 = new Number(0);
n1 == n2 // true
n1 === n2 // false
if (n1) {
// Doesn't execute
}
if (n2) {
// Does execute, because n2 is an object that is not null
}
</code></pre>
<p><strong>Edit:</strong> Even worse than breaking === between number literals and Number objects, == doesn't even work between two Number objects (at least not in the intuitive way -- they test for identity, not equality).</p>
<pre><code>var n1 = new Number(3);
var n2 = new Number(3);
alert(n1 == n2); // false
alert(n1 === n2); // false
</code></pre>
|
What is the best way to serialize a ModelForm object in Django? <p>I am using Django and the Google Web Toolkit (GWT) for my current project. I would like to pass a ModelForm instance to GWT via an Http response so that I can "chop" it up and render it as I please. My goal is to keep the form in sync with changes to my models.py file, yet increase control I have over the look of the form. However, the django classes for serialization, serializers and simplejson, cannot serialize a ModelForm. Neither can cPickle. What are my alternatives? </p>
| <p>If you were using pure Django, you'd pass the form to your template, and could then call individual fields on the form for more precise rendering, rather than using ModelForm.to_table. You can use the following to iterate over each field and render it exactly how you want:</p>
<pre><code>{% for field in form.fields %}
<div class="form-field">{{ field }}</div>
{% endfor %}
</code></pre>
<p>This also affords you the ability to do conditional checks using {% if %} blocks inside the loop should you want to exclude certain fields.</p>
|
Flex: invalidateData <p>I've trouble getting my components to update when the params has changed:</p>
<pre><code>package mycompany
{
import flash.events.Event;
import mx.events.SliderEvent;
import mx.controls.HSlider;
import mx.controls.sliderClasses.Slider;
public class FromToSlider extends HSlider
{
/* from: */
private var _from:int;
[Bindable]
public function get from():int
{
return _from;
}
public function set from(value:int):void
{
this._from = value;
this.values[0] = value;
invalidateProperties();
}
/* //from */
/* to: */
private var _to:int;
[Bindable]
public function get to():int
{
return _to;
}
public function set to(value:int):void
{
this._to = value;
this.values[1] = value;
}
/* //to */
override public function initialize():void
{
super.initialize();
addEventListener(SliderEvent.CHANGE, handleChange, false, 0, true);
}
protected function handleChange(event:SliderEvent):void
{
var ct:Slider=Slider(event.currentTarget);
this.from = ct.values[0];
this.to = ct.values[1];
}
}
}
</code></pre>
<p>When I set "from" and "to" the thumbs aren't updating. I've tried invalidateProperties but that didn't work. </p>
| <p>Add a call to invalidateDisplayList() after invalidateProperties(). That will ensure that Flex redraws the component on the next keyframe.</p>
<p>You should also add the same to the 'set to()' function.</p>
|
How do I map a hibernate Timestamp to a MySQL BIGINT? <p>I am using Hibernate 3.x, MySQL 4.1.20 with Java 1.6. I am mapping a Hibernate Timestamp to a MySQL TIMESTAMP. So far so good. The problem is that MySQL stores the TIMESTAMP in seconds and discards the milliseconds and I now need millisecond precision. I figure I can use a BIGINT instead of TIMESTAMP in my table and convert the types in my Java code. I'm trying to figure out if there is a better way of doing this using hibernate, mysql, JDBC or some combination so I can still use date functions in my HSQL and/or SQL queries?</p>
| <p>Also, look at creating a custom Hibernate Type implementation. Something along the lines of (psuedocode as I don't have a handy environment to make it bulletproof):</p>
<pre><code>public class CalendarBigIntType extends org.hibernate.type.CalendarType {
public Object get(ResultSet rs, String name) {
return cal = new GregorianCalendar(rs.getLong(name));
}
public void set(PreparedStatement stmt, Object value, int index) {
stmt.setParameter(index, ((Calendar) value).getTime());
}
}
</code></pre>
<p>Then, you'll need to map your new object using a hibernate TypeDef and Type mappings. If you are using Hibernate annotations, it be along the lines of:</p>
<pre><code>@TypeDef (name="bigIntCalendar", typeClass=CalendarBigIntType.class)
@Entity
public class MyEntity {
@Type(type="bigIntCalendar")
private Calendar myDate;
}
</code></pre>
|
Manipulate a file in code (VB.NET) without executing the file's macros <p>I have an Excel file that has a bunch of VBA and macro code in it. When I open the file in Excel I can choose not to 'enable' them - so the values in the fields all stay as they were during the last save. I need to manipulate the values as they were last saved - so I don't want the macros (which look at the current date and update values accordingly) to run.</p>
<p>When I open it via our dot net code: </p>
<pre><code>Dim oxlRep As Excel.Application
Dim oWBRep As Excel.Workbook
Dim oSheetRep As Excel.Worksheet
Dim oRngRep As Excel.Range
oxlRep.Open(path)
</code></pre>
<p>the vb code runs - throwing off the values. I've been looking for a way to open it without macros, or in 'secure' mode where the macros aren't run. If I simply double click the file and don't choose to enable macros the values are all there as I want them. </p>
<p>Usually we run this code within the month that the files are created, so we haven't seen this problem in the 3 or 4 years that it has been working. Now I need to go back to some of the old files and run some archival code... </p>
<p>Anyone have a suggestion?</p>
| <pre><code>Application.AutomationSecurity = msoAutomationSecurity.msoAutomationSecurityForceDisable
</code></pre>
<p>Try opening the workbook after this statement.
I think, this will disable macros at Application Level (not at workbook level)</p>
<p>Hope that helps.</p>
|
VS2005: How to not have VS try to parse text file resources as html? <p>I have included a resource in my Visual Studio 2005 solution that was a file on the hard drive. It is a text file, that contains text, and has a <strong>.htm</strong> extension.</p>
<p>For months it worked fine, until I wanted to edit the contents of the text file. Suddenly Visual Studio insists on syntax checking the file as though it were an HTML file - when it is not.</p>
<p>i would really rather not workaround this bug in Visual Studio by forcing the file to be named:</p>
<pre><code>SomeFilename.htm.VSbug.doNotRemove
</code></pre>
<p>rather than</p>
<pre><code>SomeFilename.htm
</code></pre>
<p>Not everything that uses the file is Visual Studio, and it would be a shame to force everyone to change because of issues with Visual Studio.</p>
<p>Even more to the point - what did i originally do so that VS would (correctly) ignore randomly added text files - and how do i do that again?</p>
<p><hr /></p>
<h2>Update One</h2>
<p>Since some people are, of course, curious - here is the contents of the file:</p>
<p>SomeFilename.htm</p>
<pre><code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<HTML>
<HEAD>
<TITLE>New Document</TITLE>
<META http-equiv="X-UA-Compatible" content="IE=edge">
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
</HEAD>
<BODY style="margin: 0 auto">
<DIV style="text-align:center;">
<A href="%PANELLINK%" target="_blank"><IMG border="0" src="%PANELIMAGE%" style="%IMAGESTYLE%"></A><BR>
%CAPTIONTEXT%
</DIV>
</BODY>
</HTML>
</code></pre>
<p>As you can see, the file does not contain html. Don't forget - the file's contents are beside the point.</p>
<p><hr /></p>
<h1>Answer</h1>
<p>Editing the file through Visual Studio is what triggers Visual Studio to think it has some jurisdiction over the contents of the resource file. </p>
<p>Deleting the file and re-adding it, as well as only editing the resource text file outside of VS, ensures that VS will not try to parse the file's contents.</p>
| <p>This obviously begs the question â why do you use a wrong file extension on a system, where file type is determined by these extensions?</p>
<p>Sorry, the answer is of course wrong. I was pretty sure I had done it that way already. Still, I think the above comment is still valid, even if not applicable universally. Marking the answer âoffensiveâ is just rude and doesnât change that.</p>
<p><del>However, your problem can be solved relatively easily. Instead of opening the file through double-click, you can right-click it and choose âOpen with ...â in its context menu. There you can select the text editor.</del></p>
|
Example of setting up a name entry box for high score submission on iPhone? <p>Does anyone have an example of setting up a text field where users can enter their name and/or email address to submit it online to a high score database? I would like to have
it be similar to the form that pops up when you attempt to download something from the AppStore, where you put in your email and password then can hit OK or Cancel. I can handle all the submission code and the server side processing at the website, but I just have had a hell of a time getting the text field and buttons setup properly.</p>
<p>Thanks in advance!</p>
| <p>This will show the dialog, but I am unsure how to make it responsive:</p>
<pre><code>[dialog setDelegate:self];
[dialog setTitle:@"Enter Name"];
[dialog addButtonWithTitle:@"Cancel"];
[dialog addButtonWithTitle:@"OK"];
UITextField * nameField = [[UITextField alloc] initWithFrame:CGRectMake(20.0, 45.0, 245.0, 25.0)];
[nameField setBackgroundColor:[UIColor whiteColor]];
[dialog addSubview:nameField];
CGAffineTransform moveUp = CGAffineTransformMakeTranslation(0.0, 100.0);
[dialog setTransform: moveUp];
[dialog show];
</code></pre>
|
java append to file <p>I googled for this for a while but can't seem to find it and it should be easy. I want to append a CR to then end of an XML file that I am creating with a Transformer. Is there a way to do this></p>
<p>I tried the following but this resulted in a blank file?</p>
<pre><code>
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "file:///ReportWiz.dtd");
xformer.transform(source, result);
OutputStream writer = new FileOutputStream(file);
Byte b = '\n';
writer.write(b);
writer.close();</code></pre>
| <p>Simple... just add the <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/io/FileOutputStream.html#FileOutputStream(java.io.File,%20boolean)">append</a> option:</p>
<pre><code> new FileOutputStream(f, true /* append */);
</code></pre>
|
How to create a form on its own thread and keep it open throughout application lifetime <p>I am creating a little testing component and am running into a problem</p>
<p>Basically the component is a decorator on a class that controls all access to the database, it creates a form with a two buttons on it: "Simulate Lost Connection" and "Reconnect". Press the button, and instead of letting function calls pass through the wrapper starts throwing NoConnectionException()s nice and simple, and real helpful for testing.</p>
<p>The problem is that this particular application when it detects a lost connection raises a modal dialog box "connection lost!" that sits there until the connection is regained. Because it is modal I cannot press my nifty button to simulate regained connectivity.</p>
<p>What I need to do therefore is to run my little testing form in a different thread. I'm not absolutely sure how to do that. I tried</p>
<pre><code>new Thread(
new ThreadStart(
(Action)delegate {_form.Start();}
)
).Start();
</code></pre>
<p>But the thread closes as soon as the method returns so the form never shows up except for an instant.</p>
<p>Any idea how I go about achieving what I want?</p>
| <p>You will need to start a message loop on the newly created thread. You can do that by calling Application.Run(form).</p>
|
How can I run Perl scripts using FastCGI on Nginx? <p>So I am following this guide: <a href="http://technotes.1000lines.net/?p=23">http://technotes.1000lines.net/?p=23</a> and I am going through the steps. I have a VPN (slicehost.com) with Debian Etch, serving a website (static so far) with nginx. I used wget to download FastCGI and I did the usual make make install routine. </p>
<p>So I guess since FastCGI can't normally run CGI scripts you have to use some type of perl wrapper to interpret the perl.</p>
<p>Now I run this script</p>
<p><a href="http://technotes.1000lines.net/fastcgi-wrapper.pl">http://technotes.1000lines.net/fastcgi-wrapper.pl</a></p>
<p>and I run into the exact same problem that a person ran into on the page that the script was submitted: </p>
<p><a href="http://www.ruby-forum.com/topic/145858">http://www.ruby-forum.com/topic/145858</a></p>
<p>(I'm not a ruby person and there is nothing ruby oriented in there)</p>
<p>I keep getting a </p>
<pre><code># bind/listen: No such file or directory
</code></pre>
<p>And I have no idea how to proceed. I would appreciate any help and I can give any more details that anyone would need.</p>
| <p>The webserver needs a Unix domain socket to connect to the FastCGI application, but the socket can't be created. Most likely the directory you want it to be in doesn't exist (because they are automatically created when you do a <code>bind</code>).</p>
|
How do I programmatically open a MS Word document without invoking the Document_Open macro <p>I am trying to use Office Automation to open a word document. The problem is that I would like to open it without invoking the Document_Open macro. Is there a way to do this?</p>
<p>The relevant line below is wordApp.Documents.Open()</p>
<pre><code>Imports Microsoft.Office.Interop
Public Class WordFunctions
Public Shared Function ConvertToDoc(ByVal file As String) As Boolean
Dim wordDoc As Word.Document
Dim wordApp As Word.Application
Try
wordApp = CreateObject("Word.Application", "")
Catch ex As Exception
Return False
End Try
Try
wordApp.Caption = "Automated Word Instance"
wordApp.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone
wordDoc = wordApp.Documents.Open(FileName:=file, Visible:=False, ConfirmConversions:=False)
wordDoc.SaveAs(FileName:=file + ".doc", FileFormat:=Word.WdSaveFormat.wdFormatDocument)
wordDoc.Activate()
wordDoc.Close()
Return True
Catch ex As Exception
Return False
Finally
wordApp.Quit(SaveChanges:=False)
End Try
End Function
End Class
</code></pre>
| <p>The accepted answer here may be of use:</p>
<p><a href="http://stackoverflow.com/questions/369510/manipulate-a-file-in-code-vbnet-without-executing-the-files-macros#369583">http://stackoverflow.com/questions/369510/manipulate-a-file-in-code-vbnet-without-executing-the-files-macros#369583</a></p>
|
Simple Interpreted Language Design & Implementation <p>I need some resources for implementing a simple virtual machine and interpreted language. Something that is pratical is most useful. I have read the Virtual Machine Implementation book and found that it is quite old and doesn't represent the vms I see today. Also if someone know of a fairly simplistic language that would be great as well.</p>
| <p>check <a href="http://www.tecgraf.puc-rio.br/~lhf/ftp/doc/jucs05.pdf" rel="nofollow">The implementation of Lua 5.0</a></p>
|
Is it possible to customize error display in powershell? <p>I find the standard Powershell display of errors (red text, multi-line display) a bit distracting. Is it possible to customize this?</p>
| <p>Yes and yes.</p>
<p>You can use the built-in <code>$host</code> object if all you want to do is change the text color. However, you can't change the error message itself - that's hardcoded.</p>
<p>What you could do is (a) suppress the error messages, and instead (b) trap the errors and display your own.</p>
<p>Accomplish (a) by setting <code>$ErrorActionPreference = "SilentlyContinue"</code> - this won't STOP the error, but it suppresses the messages.</p>
<p>Accomplishing (b) requires a bit more work. By default, most PowerShell commands don't produce a trappable exception. So you'll have to learn to run commands and add the -EA "Stop" parameter to generate a trappable exception if something goes wrong. Once you've done that, you can create a trap in the shell by typing:</p>
<pre><code>trap {
# handle the error here
}
</code></pre>
<p>You could put this in your profile script rather than typing it every time. Inside the trap, you can output whatever error text you like by using the Write-Error cmdlet.</p>
<p>Probably more work than you were wanting to do, but that's basically how you'd do what you asked.</p>
|
Measuring Response Times In Combination With WatiN <p>I'm looking for a tool that I could potentially use in combination with <a href="http://watin.sourceforge.net/" rel="nofollow">WatiN</a> that would allow me to more or less measure both the response time of an interaction and also the filesize of the same interaction in combination with WatiN. Let's say, I make a google request. That's great, we've all seen that example, but what if I want to see how long that request took and also what was downloaded and how long it took. Does anyone know any tools that can be used programmatically to do this? Sure, there are many tools such as <a href="http://www.charlesproxy.com/" rel="nofollow">Charles</a>, <a href="http://www.fiddlertool.com/fiddler/" rel="nofollow">Fiddler 2</a> and <a href="https://addons.mozilla.org/en-US/firefox/addon/1843" rel="nofollow">Firebug</a> that allow you to do this via an interface, but I'd like to be able to automatically generate reports and the like based on this tool.</p>
| <p>Check out <a href="http://www.httpwatch.com/" rel="nofollow">HttpWatch</a>: <br>
"HttpWatch is an HTTP viewer and debugger that integrates with IE and Firefox to provide seamless HTTP and HTTPS monitoring without leaving the browser window." <br>
There is an article on the website called <a href="http://blog.httpwatch.com/2008/10/30/using-httpwatch-with-watin/" rel="nofollow">Using HttpWatch with WatiN</a> with sample code for using it with WatiN.</p>
|
Why git can't remember my passphrase under Windows <p>I have just start using git and i can't get it to remember my passphrase I'm using cmd.exe elevated and my git host is github and i have create a ssh key like that guide on github</p>
<p>but i still get </p>
<pre><code>*\subnus.mvc>git push origin master
Enter passphrase for key '/c/Users/Subnus/.ssh/id_rsa':
</code></pre>
| <p>I realize that this question is coming up on two years old, but I had the same issue and several answers here did not completely answer the question for me. Here is two step-by-step solutions, depending on whether you use TortoiseGit in addition to msysgit or not.</p>
<p><strong>First solution</strong> Assumes Windows, msysgit, and PuTTY.</p>
<ol>
<li>Install msysgit and PuTTY as instructed.</li>
<li>(Optional) Add PuTTY to your path. <em>(If you do not do this, then any references to PuTTY commands below must be prefixed with the full path to the appropriate executable.)</em></li>
<li>If you have not done so already, then generate a key hash as instructed at GitHub or as instructed by your Git host.</li>
<li>Again, if you have not already done so, convert your key for use with PuTTY's pageant.exe using <strong>puttygen.exe</strong>. Instructions are in PuTTY's documentation, in <a href="http://www.electrictoolbox.com/putty-rsa-dsa-keys/">this helpful guide</a>, and several other places in cyberspace.</li>
<li>Run PuTTY's <strong>pageant.exe</strong>, open your .ppk file ("Add Key"), and provide your passphrase for your key.</li>
<li><p>Access Windows' environment variables dialog (Right-click on "Computer", Click on "Properties", Click on "Advanced system settings" or the "Advanced" tab, click on "Environment Variables"). Add the following environment variable:</p>
<p>GIT_SSH=C:\full\path\to\plink.exe</p>
<p>Replace "C:\full\path\to" with the full installation path to PuTTY, where plink.exe is found. It is probably best to add it to the "User variables" section. Also, make sure that the path you use to plink.exe matches the path you use for Pageant (pageant.exe). In some cases you may have several installations of PuTTY because it might be installed along with other applications. Using plink.exe from one installation and pageant.exe from another will likely cause you trouble.</p></li>
<li><p>Open a command prompt.</p></li>
<li><p>If you are trying to connect to a git repository hosted at Github.com then run the following command:</p>
<p>plink.exe git@github.com</p>
<p>If the git repository you are trying to connect to is hosted somewhere else, then replace <em>git@github.com</em> with an appropriate user name and URL. (Assuming Github) You should be informed that the server's host key is not cached, and asked if you trust it. Answer with a <strong>y</strong>. This will add the server's host key to PuTTY's list of known hosts. Without this step git commands will not work properly. After hitting enter, Github informs you that Github does not provide shell access. That's fine...we don't need it. (If you are connecting to some other host, and it gives you shell access, it is probably best to terminate the link without doing anything else.)</p></li>
<li>All done! Git commands should now work from the command line. You may want to have pageant.exe <a href="http://blog.shvetsov.com/2010/03/making-pageant-automatically-load-keys.html">load your .ppk file automatically at boot time</a>, depending on how often you'll be needing it.</li>
</ol>
<p><strong>Second solution</strong> Assumes Windows, msysgit, and TortoiseGit.</p>
<p>TortoiseGit comes with PuTTY executables, and a specially modified version of plink (called TortoisePlink.exe) that will make things easier.</p>
<ol>
<li>Install msysgit and TortoiseGit as instructed.</li>
<li>If you have not done so already, then generate a key hash as instructed at GitHub or as instructed by your Git host.</li>
<li>Again, if you have not already done so, convert your key for use with TortoiseGit's pageant.exe using TortoiseGit's <strong>puttygen.exe</strong>. Instructions are in PuTTY's documentation, in the helpful guide linked to in the first solution, and several other places in cyberspace.</li>
<li>Run TortoiseGit's <strong>pageant.exe</strong>, open your .ppk file ("Add Key"), and provide your passphrase for your key.</li>
<li><p>Access Windows' environment variables dialog (Right-click on "Computer", Click on "Properties", Click on "Advanced system settings" or the "Advanced" tab, click on "Environment Variables"). Add the following environment variable:</p>
<p>GIT_SSH=C:\full\path\to\TortoisePlink.exe</p>
<p>Replace "C:\full\path\to" with the full installation path to TortoiseGit, where TortoisePlink.exe is found. It is probably best to add it to the "User variables" section. Also, make sure that the path you use to TortoisePlink.exe matches the path you use for Pageant (pageant.exe). In some cases you may have several installations of PuTTY because it might be installed along with other applications. Using TortoisePlink.exe from the TortoiseGit installation and pageant.exe from another installation of a different application (or from a standalone PuTTY installation) will likely cause you trouble.</p></li>
<li><p>All done! Git commands should now work from the command line. The first time you try to connect to your git repository you will probably be informed that the server's host key is not cached, and asks if you trust the server. Click on "Yes". (This is TortoisePlink.exe in action.)</p>
<p>You may want to have pageant.exe <a href="http://blog.shvetsov.com/2010/03/making-pageant-automatically-load-keys.html">load your .ppk file automatically at boot time</a>, depending on how often you'll be needing it.</p></li>
</ol>
<p><strong>Third solution</strong> Assumes Window, msysgit, and native command prompt.</p>
<ol>
<li>Install msysgit</li>
<li>Make sure to allow git to be used on the MS-DOS command prompt</li>
<li>Run <code>start-ssh-agent</code></li>
<li>Enter SSH passphrases</li>
<li>All done! Git commands should now work in the native command prompt.</li>
</ol>
|
How can I include css files from an MVC partial control? <p>I'm using ASP.NET MVC and I have a partial control that needs a particular CSS & JS file included. Is there a way to make the parent page render the <code>script</code> and <code>link</code> tags in the 'head' section of the page, rather than just rendering them inline in the partial contol?</p>
<p>To clarify the control that I want to include the files from is being rendered from a View with <code>Html.RenderPartial</code> and so cannot have server-side content controls on it. I want to be able to include the files in the html <code>head</code> section so as to avoid validation issues.</p>
| <p>If I have requirements for CSS/Javascript in a partial view, I simply make sure that any page that may include the partial view, either directly or as content retrieved from AJAX, has the CSS/Javascript included in it's headers. If the page has a master page, I add a content placeholder in the master page header and populate it in the child page. To get intellisense in the partial view, I add the CSS/Javascript includes in the partial view but wrapped with an <code>if (false)</code> code block so they are not included at runtime.</p>
<pre><code><% if (false) { %>
<link href=...
<script type=...
<% } %>
</code></pre>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.