instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>I have written a custom control, that has several sub panels. I want these sub panels to accept any additional controls dropped on them at design time.</p>
<p>Unfortunately any control that gets dropped at design time ends up on my custom control, not on the panels. This shows in particular if I try to drop a label: The label's blue dots are shown, but it's caption isn't and if I deselect the label, it is no longer visible at all.</p>
<p>simplified code (only one sub panel):</p>
<pre><code>type
TMyContainer = class(TPanel)
p_SubPanel: TPanel;
public
constructor Create(_Owner: TComponent); override;
end;
constructor TMyContainer.Create(_Owner: TComponent);
begin
inherited;
p_SubPanel := TPanel.Create(Self);
p_SubPanel.Parent := Self;
p_SubPanel.Align := alClient;
end;
</code></pre>
<p>What am I doing wrong here?</p>
<p>(Just in case it matters: I am using Delphi 2007.)</p>
<p>[edit]</p>
<p>I have now solved it differently. The component no longer contains panels but refers to external panels. This makes it actually much more flexible, but on the downside it is no longer as intuitive to use.</p>
<p>I would still like to know how to accomplish what I described originally. Isn't there an open source component somewhere that does this, so I can study the source code?</p>
|
<p>This is a good question. You can allow your custom TWinControl to have other controls dropped on it at design-time by adding csAcceptControls to your controls ControlStyle property.</p>
<pre><code>constructor TMyContainer.Create(AOwner: TComponent);
begin
inherited;
ControlStyle := ControlStyle + [csAcceptControls];
end;
</code></pre>
<p>But in trying to work this out, I've had little success with being able to drop controls onto a sub panel within a custom control. Adding csAcceptControls to a sub panel's ControlStyle isn't enough. The cloest I've gotten is a hack to convince the sub panel it's being designed like so:</p>
<pre><code>type
TGiveMeProtected_Component = class(TComponent);
procedure TMyContainer.Create(AOwner: TComponent);
begin
FSubPanel := TPanel.Create(Self);
TGiveMeProtected_Component(FSubPanel).SetDesigning(True, True);
end;
</code></pre>
<p>Using that code, you can now drop controls onto the sub panel, but it means you can also select the sub panel, change it's properties and even delete it which you definately don't want. Sorry I couldn't come up with the answer, I'd still love to know if you work it out. :)</p>
|
<p>I did this, but ended up replacing the controls with regular panels which would be shown/hidden when required. </p>
<p>Instead of descending from TPanel my controls descend from TCustomControl. I don't think I could get it to work descending from TPanel but can't remember what the issue was. </p>
<p><strong>The container control:</strong></p>
<pre><code>TPageControl = class(TCustomControl)
private
PageList:TObjectList; // To hold references to all sub-pages for easy access.
end;
constructor TPageControl.Create(AOwner: TComponent);
begin
inherited;
ControlStyle := ControlStyle + [csAcceptsControls];
PageList := TObjectList.Create;
PageList.OwnsObjects := false;
end;
destructor TVstPageControl.Destroy;
begin
PageList.Free;
inherited;
end;
procedure TPageControl.NewPage;
var
Page:TPage;
begin
Page := TPage.Create(Self.Owner);
Page.Parent := Self;
Page.Align := alClient;
PageList.Add(Page);
end;
procedure TPageControl.DeletePage(Index:integer);
var
Page:TPage;
begin
Page := PageList[Index] as TPage;
Page.Free;
PageList.Delete(Index);
end;
</code></pre>
<p><strong>The page/sub-panel control:</strong></p>
<pre><code>TVstPage = class(TCustomControl)
public
constructor Create(AOwner: TComponent); override;
end;
constructor TPage.Create(AOwner: TComponent);
begin
inherited;
ControlStyle := ControlStyle + [csAcceptsControls];
end;
</code></pre>
| 48,973
|
<p>Which profiler is better for general purpose profiling and heap analysis? 90% of our apps are standalone command line programs with substantial database and numeric processing. The other 10% are webapps/servlet container apps (with very little JSP and NO SCRIPLETS!). Target user would be Sr Software Engineer with 5-10 years of industry experience. We need support only for Sun JDK 5 and.</p>
<p>As of writing this question (2008-10-02), JProfiler was at 5.1.4 and YourKit was 7.5. Looks like YourKit 8.0 will be released soon.</p>
|
<p>I've used both JProfiler 4 and YourKit 7.5, and YourKit wins hands down. It's so much less invasive than JProfile, in that I'll happy run production servers with the YourKit agent installed, which I would never do with JProfiler.</p>
<p>Also, the analysis tool that comes with YourKit is more intuitive (in my opinion), making it easier to get the root cause of problems.</p>
|
<p>I've only used JProfiler (and some JProbe). As far as I can tell, one limitation of YourKit is that they don't appear to support JDK 1.4.2. That's not an issue for many people, but it might be.</p>
| 19,792
|
<p>I am taking in a string from user input, and splitting it on whitespace (using \w) into an array of strings. I then loop through the array, and append a part of the where clause like this:</p>
<pre><code> query += " AND ( "
+ "field1 LIKE '%" + searchStrings[i] +"%' "
+ " OR field2 LIKE '%" + searchStrings[i] +"%' "
+ " OR field3 LIKE '%" + searchStrings[i] +"%' "
+ ") ";
</code></pre>
<p>I feel like this is dangerous, since I am appending user input to my query. However, I know that there isn't any whitespace in any of the search strings, since I split the initial input on whitespace.</p>
<p>Is it possible to attack this via a SQL injection? Giving <code>Robert');DROP TABLE students;--</code> wouldn't actually drop anything, since there needs to be whitespace in there. In that example, it would not behave properly, but no damage would be done.</p>
<p>Can anyone with more experience fighting SQL injections help me either fix this, or put my mind at ease?</p>
<p>Thanks!</p>
<p><strong>EDIT:</strong></p>
<p>Wow, that is a lot of great input. Thank you everyone who responded. I will investigate full-text search and, at a minimum, parameterize my query.</p>
<p>Just so I can better understand the problem, would it be possible to inject if all whitespace <strong>AND</strong> single quotes were escaped?</p>
|
<p>Any time you allow a user to enter data into a query string like this you are vulnerable to SQL injection and it should be avoided like the plague!</p>
<p>You should be very careful how you allow your searchStrings[] array to be populated. You should always append variable data to your query using parameter objects:</p>
<pre><code>+ field1 like @PropertyVal Or field2 like @PropertyVal Or field3 like @PropertyVal etc...
</code></pre>
<p>And if you're using SQL Server for example</p>
<pre><code>Query.Parameters.Add(new SqlParameter("PropertyVal", '%' + searchStrings[i] + '%'));
</code></pre>
<p>Be very wary how you build a query string that you're going to run against a production server, especially if it has any data of consequence in it!</p>
<p>In your example you mentioned Little Bobby Tables</p>
<p>Robert');DROP TABLE students;--</p>
<p>And cited that because it needs white space, you couldn't do it - but if the malicious user encoded it using something like this:</p>
<pre><code>Robert');Exec(Replace('Drop_Table_students','_',Char(32)));--
</code></pre>
<p>I would say - better to be safe and do it the right way. There's no simple way to make sure you catch every scenario otherwise...</p>
|
<p>Yes, they could still inject items, without spaces it might not do much, but it is still a vulnerability.</p>
<p>In general blindly adding user input to a query is not a good idea.</p>
| 48,758
|
<p>VB 6.0 does not have any global handler.To catch runtime errors,we need to add a handler in each method where we feel an error can occur.But, still some places might be left out.So,we end up getting runtime errors.Adding error handler in all the methods of an application,the only way?</p>
|
<p>No there is no way to add a global error handler in VB6. However, you do not need to add an error handler in every method. You only really need to add an error handler in every event handler. E.g. Every click event,load event, etc</p>
|
<p>on error resume next - is kinda close but its been a while.
you might want to look up any caveats</p>
| 9,072
|
<p>I'd like to use gSOAP in a product which will be distributed commercially. The use I have in mind is what I suspect is a pretty typical workflow—generating a header using wsdl2h, consuming the header with soapcpp2, and then calling the functions generated in the stub in my code.</p>
<p>I'm not 100 percent sure which <a href="http://www.cs.fsu.edu/~engelen/soap.html" rel="noreferrer">license(s)</a> I need to use to be able to do this. Has anybody here already gone through this and figured out the solution?</p>
|
<p>I hope the following clarification helps. Please contact us at contact@genivia.com for questions.</p>
<p>The gSOAP software requires a commercial license for commercial product development if any one of the following conditions hold:</p>
<ol>
<li><p>If you use wsdl2h to generate code. Because the generated code is GPL by default, you should obtain a commercial license from Genivia (<a href="http://www.genivia.com/Products/gsoap/contract.html" rel="nofollow noreferrer">www.genivia.com/Products/gsoap/contract.html</a>). The wsdl2h tool itself is GPL, and we hold the copyright rights to it.</p></li>
<li><p>Or you use the web server code in gsoap/samples/webserver. This component is GPL by default.</p></li>
<li><p>Or you use the UDDI components in gsoap/uddi2, which are also GPL by default.</p></li>
</ol>
<p>The commercial license is a development site license. There is a one-time fee for perpetual use of gSOAP to develop a product (a "target application"). No royalties.</p>
<p>The other good news is that all other parts of the software are released under the gSOAP public license, which allows commercial use without fees.</p>
<p>So the answer is that as long as you do NOT use wsdl2h, do NOT use the web server code, and do NOT use the UDDI code then you can use the gSOAP public license for free (which is based on the MPL1.1 open source license and a copy of the gSOAP public license is included in the package).</p>
<p>Hope this clarifies our licensing model.</p>
<ul>
<li>Robert van Engelen, Genivia Inc.</li>
</ul>
|
<p>As I understand the GPL, as long as you release all derived products under the GPL, the code is free for even commercial use. Of course most companies don't want to release their source code for anyone to copy freely, hence the commercial license. I think Genivia's summary is not as clear as it could be on this one point.</p>
| 42,773
|
<p>I was wondering if someone would be able to help me write a CQL query for NDepend that will show me all the methods in my form class that handle the form events. So I would like to be able to find all the methods that look like this:</p>
<pre><code>Private Sub AddFolderButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddFolderButton.Click
</code></pre>
<p>I have had a look through some of the options but I can't really find anything that does what I need.</p>
<p>I have only just started using NDepend, so I haven't really got used to it yet, but I do know one thing how the hell did I live without it all this time.</p>
|
<p>I am Patrick from the NDepend team and I confirm, so far using a condition 'Namelike + regular expression' on the 'method name + signature' is the best way to achieve what you want with CQL.</p>
|
<p>I have sort of got something that works but its not really 100% correct, because all the form generated event handlers have an underscores in there name, I used the underscore as a filter, I also filter where the name has "EventArgs" in it. The query looks like this:</p>
<pre><code>SELECT METHODS WHERE NameLike "_" OR NameLike "EventArgs" AND !IsSpecialName AND IsPrivate
</code></pre>
<p>That query pretty much returns all the methods that handle events but I would still like to find a more correct way. </p>
| 35,815
|
<p>What issues or refactoring did you have to do when you upgraded from ASP.NET MVC Preview 5 to the newly released <a href="http://www.microsoft.com/downloads/details.aspx?familyid=a24d1e00-cd35-4f66-baa0-2362bdde0766&displaylang=en&tm" rel="nofollow noreferrer">Beta</a> version?</p>
|
<p>I'm about to do this myself. Here's the list of changes from the readme:</p>
<h2>Changes Made Between CodePlex Preview 5 and Beta</h2>
<ul>
<li>Changed the default validation messages to be more end-user friendly. </li>
<li>Renamed CompositeViewEngine to AutoViewEngine.</li>
<li>Added a Url property to Controller of type UrlHelper. This makes it convenient to generate routing-based URLs from within a controller.</li>
<li>Added the ActionNameSelectorAttribute abstract base class, which serves as the base type for ActionNameAttribute. By inheriting from this base attribute class, you can create custom attributes that participate in action selection by name.</li>
<li>Added a new ReleaseView method to IViewEngine that allows custom view engines to be notified when a view is done rendering. This is useful for cleanup or for view-pooling scenarios.</li>
<li>Renamed the ControllerBuilder method DisposeController to ReleaseController to fit with the pattern that is established for view engines.</li>
<li>Removed most of the methods on the HtmlHelper class, converting them to extension methods of the HtmlHelper class instead. These methods exist in a new namespace (System.Web.Mvc.Html). If you are migrating from Preview 5, you must add the following element to the namespaces section of the Web.config file:
<code><add namespace="System.Web.Mvc.Html"/></code>
This makes it possible for you to completely replace our helper methods with your own. </li>
<li>Changed the default model binder (DefaultModelBinder) to handle complex types. The IModelBinder interface has also been changed to accept a single parameter of type ModelBindingContext.</li>
<li><p>Added a new HttpVerbs enumeration that contains the most commonly used HTTP verbs (GET, POST, PUT, DELETE, HEAD). Also added a constructor overload to AcceptVerbsAttribute that accepts the enumeration. The enumerated values can be combined. Because it is possible to respond to HTTP verbs that are not included in the enumeration, the AcceptVerbsAttribute retains the constructor that accepts an array of strings as a parameter. For example, the following snippet shows an action method that can respond to both POST and PUT requests. </p>
<pre><code>[AcceptVerbs(HttpVerbs.Post | HttpVerbs.Put)]
public ActionResult Update() {...
}
</code></pre></li>
<li><p>Modified the RadioButton helper method to ensure that every overload accepts a value. Because radio buttons are used to specify a choice from a set of possible values, specifying a value for a radio button is necessary.</p></li>
<li>Made modifications and fixes to the default project template. This includes moving script files to a new Scripts folder. The default template uses the ModelState class to report validation errors.</li>
<li><p>Changed action-method selection. If two action methods match a request, but only one of those has an attribute that derives from ActionMethodSelectorAttribute that matches the request, that action is invoked. In earlier releases, this scenario resulted in an exception.
For example, the following two action methods are in the same controller:</p>
<pre><code>public ActionResult Edit() {
//...
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(FormCollection form) {
//...
}
</code></pre></li>
</ul>
<p>In Preview 5, a POST request for the Edit action would cause an exception, because two methods match the request. In the Beta, precedence is given to the method that matches the current request via the AcceptVerb attribute. In this example, the first method will handle any non-POST requests for the Edit action. </p>
<ul>
<li>Added an overload for the ViewDataDictionary.Eval method that accepts a format string.</li>
<li>Removed the ViewName property from the ViewContext class.</li>
<li>Added an IValueProvider interface for value providers, along with a default implementation, DefaultValueProvider. Value providers supply values that are used by the model binders when binding to a model object. The UpdateModel method of the Controller class has been updated to allow you to specify a custom value provider.</li>
</ul>
|
<p>If you are using Html.Form from the futures assembly (Microsoft.Web.Mvc) you might get a name collision on the FormMethod enum. For example:</p>
<pre><code>Html.Form<FooController>(c => c.Bar(), FormMethod.Post, new Hash(@class => "foobar"))
</code></pre>
<p>This will complain that FormMethod is an ambiguous reference between Microsoft.Web.Mvc and System.Web.Mvc. This is quite sad because IMHO BeginForm does not provide a viable option due to its lack of an override that uses a lambda expression. Your only option is to use magic strings, which resist refactoring.</p>
<p>The best solution, it seems, is to put the following into every view that uses FormMethod:</p>
<pre><code><%@ Import Namespace="FormMethod=Microsoft.Web.Mvc.FormMethod"%>
</code></pre>
<p>Ugh. Hopefully this is temporary. I expect that the futures assembly can be changed to use the enum from System.Web.Mvc. Or much better yet, hopefully they overload BeginForm to use expressions.</p>
| 25,575
|
<p>I have a Tronxy P802M (very similar to the Anet A8, but using a Melzi2.0V5 board) that seems to work fine (I just finished building, and axes movement and the integrated display work) but when I try to connect to the printer from my Simplify3D on Windows 10, I get the following:</p>
<pre><code>[...]
Connected to machine!
SENT: T0
READ: ok 0
READ: wait
SENT: M105
READ: ok 0
READ: T:24.44 /0 B:23.33 /0 B@:0 @:0
Connection failed.
</code></pre>
<p>My other printers all connect fine.</p>
|
<p>The <a href="https://www.simplify3d.com/support/faq/#faq-4630" rel="nofollow noreferrer">Simplify3D support site</a> mentions to disable the "wait for startup command" option in the firmware configuration for S3D.</p>
<p>This allows me to make a rudimentary connection to control the printer, however e.g. during the bed levelling wizard of S3D, the connection still breaks off.</p>
<p>It works reliably with Octoprint. I'll consider that good enough.</p>
|
<p>Try changing your port in the control menu. By default, mine is set to <code>COM 1</code> and I have to change it to <code>COM 3</code>.</p>
| 498
|
<p>Where I work, we have small teams of 2 - 5 people. As a dev lead, what are some things that you've implemented which makes your team stand out from the others? Meaning, it makes the others teams say, "that's cool" or "why didn't we think of that". Just some thinking out of the box that made your team extremely efficient.</p>
|
<p>Automated unit testing and an automated build system (like CruiseControl)</p>
|
<p>First and foremost -- we get things done on time that meet the done criteria. That's the best thing to do, in my opinion :)</p>
| 41,012
|
<p>I have a c# class which uses the WindowsIdentity namespace to return details of the current Active Directory user. This is accessible through a web part on SPS and sure enough returns the desired record values specific to that user. </p>
<p>I have a classic ASP application which I would like to have inherit this functionality. After wrapping it up as a COM and registering it to the server, I created a Classic ASP page from which to call and display the details to the browser window.</p>
<p>My problem is that when this page is accessed from an authenticated user on a client machine the only user details it displays is that of the local machine.</p>
<p>How do I therefore alter my code so I can display the details of the user accessing the page from a client machine?</p>
|
<p><a href="http://weblogs.asp.net/scottgu/about.aspx" rel="noreferrer">Scott Guthrie</a> (the guy who runs the .Net dev teams at MS) covered how to do this on his blog some months ago much better than I ever could, <strong><a href="http://weblogs.asp.net/scottgu/archive/2007/08/16/linq-to-sql-part-6-retrieving-data-using-stored-procedures.aspx" rel="noreferrer">link here</a></strong>. On that page there is a section titled "Handling Multiple Result Shapes from SPROCs". That explains how to handle multiple results from stored procs of different shapes (or the same shape).</p>
<p>I highly recommend subscribing to his RSS feed. He is pretty much <strong>THE</strong> authoritative source on all things .Net.</p>
|
<p>Just curious, if a Post have have one or many Categories, is it possible to instead of using the for loop, to load the Post.PostCategories with the list of Categories (one to many), all in one shot, using a JOIN?</p>
<pre><code>var rslt = from p in results.GetResult<Post>()
join c in results.GetResult<Category>() on p.PostId = c.PostID
...
p.Categories.Add(c)
</code></pre>
| 48,543
|
<p>Usually pagination queries look like this. Is there a better way instead of making two almost equal methods, one of which executing "select *..." and the other one "count *..."?</p>
<pre><code>public List<Cat> findCats(String name, int offset, int limit) {
Query q = session.createQuery("from Cat where name=:name");
q.setString("name", name);
if (offset > 0) {
q.setFirstResult(offset);
}
if (limit > 0) {
q.setMaxResults(limit);
}
return q.list();
}
public Long countCats(String name) {
Query q = session.createQuery("select count(*) from Cat where name=:name");
q.setString("name", name);
return (Long) q.uniqueResult();
}
</code></pre>
|
<p>If you don't need to display the total number of pages then I'm not sure you need the count query. Lots of sites including google don't show the total on the paged results. Instead they just say "next>".</p>
|
<p>here's the way pagination is done in hibernate</p>
<pre><code>Query q = sess.createQuery("from DomesticCat cat");
q.setFirstResult(20);
q.setMaxResults(10);
List cats = q.list();
</code></pre>
<p>you can get more info from hibernate docs at : <a href="http://www.hibernate.org/hib_docs/v3/reference/en-US/html_single/#objectstate-querying-executing-pagination" rel="nofollow noreferrer">http://www.hibernate.org/hib_docs/v3/reference/en-US/html_single/#objectstate-querying-executing-pagination</a>
10.4.1.5 and 10.4.1.6 section give you more flexbile options.</p>
<p>BR,<BR>
~A</p>
| 20,298
|
<p>I've got this problem with dynamically created TextBox.</p>
<p>When the TextBox is created in PageLoad, it's TextChanged event was fired.<br>
But when I dynamically delete and recreated the TextBox, the TextChanged was not fired.</p>
<p>This is the code:</p>
<p><strong>.aspx file</strong></p>
<pre><code><body>
<form id="form1" runat="server">
<div>
<asp:Table ID="Table1" runat="server">
<asp:TableRow>
<asp:TableCell ColumnSpan="2">Fixed content</asp:TableCell>
</asp:TableRow>
</asp:Table>
</form>
</body>
</code></pre>
<p><strong>.cs file</strong></p>
<pre><code>public partial class test : System.Web.UI.Page
{
string myText = "a";
protected void Page_Load(object sender, EventArgs e)
{
WriteRows();
}
private void WriteRows()
{
TableRow tr = new TableRow();
TableCell tc = new TableCell();
TextBox txt = new TextBox();
txt.Text = myText;
txt.TextChanged += new EventHandler(txt_TextChanged); // Assign event handler
tc.Controls.Add(txt);
tr.Controls.Add(tc);
tc = new TableCell();
tc.Text = txt.Text;
tr.Controls.Add(tc);
Table1.Controls.AddAt(1, tr);
}
private void txt_TextChanged(object sender, EventArgs e)
{
myText = ((TextBox)sender).Text;
RedrawTable(); // Delete the row (incl. the TextBox) and rewrite it
}
private void RedrawTable()
{
Table1.Controls.RemoveAt(1);
WriteRows();
}
}
</code></pre>
<p>Does anyone have a solution so that the event is always fired?</p>
|
<p>Event handling is done by ASP.NET by matching up control's ID & the request parameters. In your case, the TextBox created during txtTextChanged() will have an auto ID because you don't specify any explicit ID. That ID will be posted back during the text changed event. </p>
<p>After page load event, ASP.NET will try to find a control with such ID to fire the event for it. Obviously ASP.NET won't be able to find the match because the TextBox created during Page_Load() is different and would have different ID.</p>
<p>To solve this: specify an explicit ID for your textbox:</p>
<pre><code>TextBox txt = new TextBox();
txt.Text = myText;
txt.ID = "txtBox";
</code></pre>
|
<p>When I was researching this issue, it was in the context of Dynamic Menus, and there are a bunch of Google responses that, together, got me through it (because it's a common enough requirement, I guess.) I don't have a summary of the answer, but it might be a helpful place to start (i.e. google for Dynamic Menus .NET). There are several questions here on this site too.</p>
| 39,619
|
<p>I haven't a clue about encryption at all. But I need it. How?</p>
<p>Say you have a system of nodes communicating with each other on a network via asynchronous messages. The nodes do not maintain session information about other nodes (this is a design restriction).</p>
<p>Say you want to make sure only your nodes can read the messages being sent. I believe encryption is the sollution to that.</p>
<p>Since the nodes are not maintaining a session and communication must work in a stateless, connectionless fashion, I am guessing that asymmetric encryption is ruled out.</p>
<p>So here is what I would like to do:</p>
<ul>
<li>messages are sent as UDP datagrams</li>
<li>each message contains a timestamp to make messages differ (counter replay attacks)</li>
<li>each message is encrypted with a shared secret symmetric key and sent over the network</li>
<li>other end can decrypt with shared secret symmetric key</li>
</ul>
<p>Keys can obviously be compromised by compromising any single node. At the same time, in this scenario, access to any single compromised node reveals all interesting information anyway, so the key is not the weakest link.</p>
<p>What cypher should I use for this encryption? What key length?</p>
<p>I would prefer to use something supported by <a href="http://www.freenet.org.nz/ezPyCrypto/" rel="nofollow noreferrer">ezPyCrypto</a>.</p>
<p>Assuming, as most point out, I go with AES. What modes should I be using?</p>
<p>I couldn't figure out how to do it with ezPyCrypto, <a href="http://www.dlitz.net/software/pycrypto/" rel="nofollow noreferrer">PyCrypto</a> seems to be hung on a moderator swap and googles <a href="http://www.keyczar.org/" rel="nofollow noreferrer">keyczar</a> does not explain how to set this up - I fear if I don't just <em>get</em> it, then I run a risk of introducing insecurity. So barebones would be better. <a href="http://www.josh-davis.org/pythonAES" rel="nofollow noreferrer">This guy</a> claims to have a nice module for AES in python, but he also asserts that this is his first python project - Allthough he is probably loads smarter than I, maybe he got tripped up?</p>
<p><strong>EDIT:</strong> I moved the search for the python implementation to <a href="https://stackoverflow.com/questions/172486/what-pure-python-library-to-use-for-aes-256-encryption">another question</a> to stop clobber...</p>
|
<p>Your first thought should be channel security - either SSL/TLS, or IPSec.<br>
Admittedly, these both have a certain amount of setup overhead, IPSec more than SSL/TLS, especially when it comes to PKI etc. - but it more than pays for itself in simplicity of development, reliability, security, and more. Just make sure you're using strong cipher suites, as appropriate to the protocol.</p>
<p>If neither SSL/TLS or IPSec fits your scenario/environment, your next choice should be <a href="http://en.wikipedia.org/wiki/Advanced_Encryption_Standard" rel="noreferrer">AES</a> (aka Rijndael).<br>
Use keys at least 256 bits long, if you want you can go longer.<br>
Keys should be randomly generated, by a cryptographically secure random number generator (and not a simple rnd() call).<br>
Set the cipher mode to <a href="http://en.wikipedia.org/wiki/Cipher_block_chaining" rel="noreferrer">CBC</a>.<br>
Use PKCS7 padding.<br>
Generate a unique, crypto-random Initialization Vector (IV).
Don't forget to properly protect and manage your keys, and maybe consider periodic key rotations.</p>
<p>Depending on your data, you may want to also implement a keyed hash, to provide for message integrity - use <a href="http://en.wikipedia.org/wiki/SHA-256" rel="noreferrer">SHA-256</a> for hashing.</p>
<p>There are also rare situations where you may want to go with a stream cipher, but thats usually more complicated and I would recommend you avoid it your first time out.</p>
<p>Now, I'm not familiar ezpycrypto (or really python in general), and cant really state that it supports all this; but everything here is pretty standard and recommended best practice, if your crypto library doesnt support it, I would suggest finding one that does ;-).</p>
|
<p>I'd probably go for <a href="http://en.wikipedia.org/wiki/Advanced_Encryption_Standard#Implementations" rel="nofollow noreferrer">AES</a>.</p>
| 20,775
|
<p>Should be available to non-U.S. companies, easy to setup, reliable, cheap, customizable, etc. What are your experiences?</p>
|
<p>You can't really answer this kind of question with a "I like 'insert provide name here'" type answer because like so many things it is a balance and the reasons for choosing a payment processing solution tend to be complex.</p>
<h2>Volume / Value</h2>
<p>The most important factor in choosing a secure payment clearance service (the people who will connect to the banking networks and clear the money for you - will refer to them as SPCS) is how many widgets will you be selling at what cost. The pricing models of all the SCPS providers is based around this equation. This dictates the economics of using the service, which is nearly always the most important factor.</p>
<p>For example, in the UK <a href="http://securetrading.net" rel="noreferrer">securetrading.net</a> have a large annual fee and high minimum transaction values (been a while since I've seen the exact numbers and they don't make it immediately obvious on the site, but this is for illustration only anyway) making it one of the most expensive solutions to use <em>if</em> you are selling high value low volume. Most smaller clients will fall into this model. High value is really anything over a couple of dollars. Low volume is typically anything less than tens of thousands of units per month. <em>However</em>, if you are running a donations service in the aftermath of an international environmental disaster (relatively low value <em>very</em> high volume) then they become one of the cheapest.</p>
<p>Factor in to this the setup costs (relatively high), and the cost to tie the service into the site (in SecureTrading's case it's very easy to do, but still a lot harder than adding a PayPal button) and you start to build up a true picture.</p>
<p>On the flip side, a service such as <a href="http://www.paypal.com" rel="noreferrer">PayPal</a> has very low setup costs (no fee to pay, and trivially easy to integrate), but relatively high transaction costs. It is great for high value / low volume transactions.</p>
<h2>The Bank</h2>
<p>There are two main categories of payment clearance service - Bureau and Bank Acquired.</p>
<p>In the UK at least <a href="http://www.netbanx.com" rel="noreferrer">NetBanx</a>, <a href="http://www.securetrading.net" rel="noreferrer">SecureTrading</a> and <a href="http://www.worldpay.com" rel="noreferrer">WorldPay</a> offer both bank acquired and bureau services. <a href="http://www.protx.com" rel="noreferrer">ProtX</a> and <a href="http://www.secpay.com" rel="noreferrer">SecPay</a> offer only bank acquired services. PayPal and its ilk operates slightly outside both definitions (see Protection below).</p>
<p>A Bank Acquired service plumbs into your normal banking merchant account and clears the funds straight into it. As well as charging you for this service, your bank will also take a slice, typically this is more than the SPCS provider will charge and so it actually is the <em>bank</em> that becomes the deciding factor.</p>
<p>Some banks will only work with their preferred provider. In the UK, most banks want you to have a separate Internet Merchant Account <em>even</em> if you already have a Merchant Account with them.</p>
<p>I always tell clients to shop around, as this will make a huge difference to how much their e-commerce venture can bring in. All banks are not created equal.</p>
<p>Bureau services effectively act as your bank at the same time as providing the clearance service. They were popular in a time when banks hadn't grasped the concept of the Internet and would prefer transactions be chiseled into stone tablets if they got their way. Often the choice between a bureau service and a bank acquired service is made for you based on circumstances.</p>
<h3>Trading History</h3>
<p>In many countries (including the UK), most banks won't give you a merchant account until you have been trading for a particular period of time (2 years in the UK). Your only option is then a bureau service.</p>
<h3>Cash flow</h3>
<p>Most bureau services will hold onto your cash as security against "charge backs".</p>
<p>If you sell me a Ferrari and I am horrified to learn that you've sold me a small metal toy rather than the 1.5 tonnes of Italian automotive passion I was expecting, I will complain to my credit card company who will refund me and then chase your merchant services provider for a refund. They will have to give them the refund and then chase you for the money.</p>
<p>It's therefore in their interests to hold on to your money for a period of 4-6 weeks to protect against this. If you sell services or goods with no capital outlay (software for instance), then you can afford this. If on the other hand, you really are having to pay your luxury car importer to provide you with stock, then cash flow becomes very important and you're going to need a bank acquired service where you can be paid immediately.</p>
<h2>Protection</h2>
<p>One major downside to PayPal and similar services is that it is not covered under the same regulations that govern credit cards.</p>
<p>Simply put, if you buy something on a credit card your card provider is liable for ensure you get what you paid for (broadly speaking, in most countries, does not constitute legal advice etc.) and if you have a problem with your purchase they will refund you very quickly and then will go and chase the person that you paid.</p>
<p>This is the kind of protection you hear about when Leo Laporte advertises American Express on his podcasts. It is a "Good Thing"TM. You don't have that protection with PayPal because when you use your credit card on PayPal, you are actually buying PayPal's service. So, even if you are mis-sold a product, the person you paid for the service (PayPal) <em>didn't</em> mis-sell, they provided the service you paid for. This breaks the chain.</p>
<p>PayPal don't have a legal obligation to protect you in the same way, and their record on refunding ripped off customers is less than spangly. I'm guessing they have "Caveat Emptor" writ large on the walls of their head office. :)</p>
<p>I'm not dissing PayPal, they are way ahead of the curve on many other security features, but just another factor to bear in mind.</p>
<h2>End to end integration</h2>
<p>Different services differ in their ease of integration. Oh boy do they differ. I'm sitting on some work right now to do an HSBC integration. I'd rather have a root canal. Some of the systems make big assumptions about the way you have to work with them, and are poorly designed or inflexible. Retro-fitting them to an active site can be very painful. Some of them are beautiful and easy to work with (and not necessarily less secure). The biggest difference is how you choose to integrate though.</p>
<p>Most services integrate by allowing you to redirect to a secure site where your customer fills in his / her details. They are finally redirected back to a page on your own site with the results of the transaction. This works well in most cases and is easiest to integrate.</p>
<p>When you buy something on Amazon, you don't get redirected to WorldPay, or PayPal however. If you want end-to-end integration, most services now will let the communication happen behind the scenes. Your own site has to have a decent secure server certificate of course, and the integration is necessarily more complex.</p>
<h2>Reputation</h2>
<p>It used to be that PayPal was used on dinky sites. You wouldn't catch Amazon using it. That perception has changed a lot, and in fact in some senses PayPal does security better than most. If your audience expects to see PayPal and you give them some other service then you may lose custom, or vice versa. These days many merchants offer a choice to customers.</p>
<h2>UK Providers</h2>
<ul>
<li><a href="http://www.worldpay.com" rel="noreferrer">WorldPay</a>. Well established. Bureau and bank acquired. Relatively high transaction costs and annual costs. Fairly easy to integrate. Owned ultimately by Royal Bank of Scotland.</li>
<li><a href="http://www.secpay.com" rel="noreferrer">SecPay</a>. Bank Acquired. Low per transaction cost and low annual cost and flexible payment models.</li>
<li><a href="http://www.protx.com" rel="noreferrer">ProtX</a>. Bank Acquired. Low per transaction cost and low annual cost, flexible payment models. Can be quite demanding to integrate.</li>
<li><a href="http://www.hsbc.com" rel="noreferrer">HSBC</a>. Bank Acquired. Low per transaction cost. High set up and annual costs. Very inflexible to integrate.</li>
<li><a href="http://www.securetrading.net" rel="noreferrer">SecureTrading</a>. Bureau and Bank Acquired. Low per transaction cost but high setup and annual costs. Was a doddle to integrate last time I used it (9 years ago!)</li>
<li><a href="http://www.netbanx.com" rel="noreferrer">NetBanx</a>. Bureau and Bank Acquired. Haven't used since 1996 so can't comment!</li>
</ul>
<p>And of course <a href="http://www.paypal.com" rel="noreferrer">PayPal</a>, <a href="http://checkout.google.com" rel="noreferrer">Google Checkout</a> and <a href="http://aws.amazon.com/fps/" rel="noreferrer">Amazon FPS</a> are well worth looking at and worth a whole answer on their own!</p>
<h2>Summary</h2>
<p>Told you it wasn't that simple! Usually, as developers, we're not in the position to choose for ourselves, and these decisions should be driven by the business needs of our employer / client.</p>
<p>Most e-commerce projects would start with PayPal or similar. When the business gets enough orders that they could save money by switching to another service, then they've got enough money to pay for the switch.</p>
<p><em>Disclaimer: I am UK based, and have performed many integrations with a whole slew of these services over the years, however the market changes all the time and things may have changed and your mileage may vary! I am not a lawyer or accountant, and if you take my advice it's not my fault :)</em></p>
|
<p>Try AlertPay, they have very competetive fees.</p>
| 2,470
|
<p>Currently I am working very basic game using the C++ environment. The game used to be a school project but now that I am done with that programming class, I wanted to expand my skills and put some more flourish on this old assignment.</p>
<p>I have already made a lot of changes that I am pleased with. I have centralized all the data into folder hierarchies and I have gotten the code to read those locations.</p>
<p>However my problem stems from a very fundamental flaw that has been stumping me. </p>
<p>In order to access the image data that I am using I have used the code:</p>
<pre><code>string imageLocation = "..\\DATA\\Images\\";
string bowImage = imageLocation + "bow.png";
</code></pre>
<p>The problem is that when the player picks up an item on the gameboard my code is supposed to use the code:</p>
<pre><code>hud.addLine("You picked up a " + (*itt)->name() + "!");
</code></pre>
<p>to print to the command line, "You picked up a Bow!". But instead it shows "You picked up a ..\DATA\Images\!". </p>
<p>Before I centralized my data I used to use:</p>
<pre><code>name_(item_name.substr(0, item_name.find('.')))
</code></pre>
<p>in my Item class constructor to chop the item name to just something like bow or candle. After I changed how my data was structured I realized that I would have to change how I chop the name down to the same simple 'bow' or 'candle'. </p>
<p>I have changed the above code to reflect my changes in data structure to be:</p>
<pre><code>name_(item_name.substr(item_name.find("..\\DATA\\Images\\"), item_name.find(".png")))
</code></pre>
<p>but unfortunately as I alluded to earlier this change of code is not working as well as I planned it to be.</p>
<p>So now that I have given that real long winded introduction to what my problem is, here is my question.</p>
<p>How do you extract the middle of a string between two sections that you do not want? Also that middle part that is your target is of an unknown length. </p>
<p>Thank you so very much for any help you guys can give. If you need anymore information please ask; I will be more than happy to upload part or even my entire code for more help. Again thank you very much.</p>
|
<p>In all honeasty, you're probably approaching this from the wrong end.</p>
<p>Your item class should have a string "bow", in a private member. The function Item::GetFilePath would then (at runtime) do "..\DATA\Images\" + this->name + ".png".</p>
<p>The fundamental property of the "bow" item object isn't the filename bow.png, but the fact that it's a "bow". The filename is just a derived proerty.</p>
|
<p>One thing that looks wrong is that the second parameter to substr should be the number of chars to copy, not the position.</p>
| 47,985
|
<p>I am trying to come up with the best data structure for use in a high throughput C++ server. The data structure will be used to store anything from a few to several million objects, and no sorting is required (though a unique sort key can be provided very cheaply).</p>
<p>The requirements are that it can support efficient insert, ideally O(1), moderately efficient removal, and efficient traversal. It doesn't need to support a find operation (other than might be needed for removal).</p>
<p>The twist is that it must be thread safe with respect to modifications while other threads are enumerating the data structure. This means that a simple red-black tree doesn't work, since one thread can't insert an element (and perform the necessary tree rotations) without messing up any cursors held by other threads.</p>
<p>It is <strong>not</strong> acceptable to use a read/write lock and defer the write operations until all readers have finished, since read operations may be long lived. It doesn't matter if inserts that happen while there is a reader are visible to that reader or not.</p>
<p>Memory footprint is also very important, and small is obviously better!</p>
<p>What suggestions are there?</p>
<p><strong>Response to comments:</strong></p>
<p>Thanks for the answers.</p>
<p>No, inserts cannot invalidate existing iterators. Iterators may or may not see the new insert, but they must see everything that they would have seen if the insert hadn't occurred.</p>
<p>Deletion is required, however due to higher level rules I can guarantee that a iterator will never be stopped on an item that is available for deletion.</p>
<p>Locking per node for a cursor would have too great an impact on performance. There may be a number of threads reading at once, and any kind of memory hot spot that multiple threads are using in a lock kills memory bandwidth (as we discovered the hard way!). Even a simple count of readers with multiple threads calling InterlockedIncrement fails to scale cleanly. </p>
<p>I agree a linked list is likely the best approach. Deletes are rare, so paying the memory penalty for the back pointers to support O(1) delete is costly and we may compute those separately on demand and since deletes tend to be batch operations.</p>
<p>Fortunately insertion into a linked list doesn't require any locking for readers, as long as the pointers are updated in the inserted node before the head pointer is changed.</p>
<p>The lock-copy-unlock idea is interesting. The amount of data involved is too large for this to work as the default for readers, but it could be used for writers when they collide with readers. A read/write lock would protect the whole structure, and the write would clone the data structure if it collides with a reader. Writes are much rarer than reads.</p>
|
<p>Personally, I'm quite fond of persistent immutable data structures in highly-concurrent situations. I don't know of any specifically for C++, but Rich Hickey has created some excellent (and blisteringly fast) immutable data structures in Java for <a href="http://clojure.org" rel="noreferrer">Clojure</a>. Specifically: vector, hashtable and hashset. They aren't too hard to port, so you may want to consider one of those.</p>
<p>To elaborate a bit more, persistent immutable data structures really solve a lot of problems associated with concurrency. Because the data structure itself is immutable, there isn't a problem with multiple threads reading/iterating concurrently (so long as it is a const iterator). "Writing" can also be asynchronous because it's not really writing to the existing structure but rather creating a new version of that structure which includes the new element. This operation is made efficient (<em>O(1)</em> in all of Hickey's structures) by the fact that you aren't actually copying everything. Each new version shares most of its structure with the old version. This makes things more memory efficient, as well as dramatically improving performance over the simple copy-on-write technique.</p>
<p>With immutable data structures, the only time where you actually need to synchronize is in actually writing to a reference cell. Since memory access is atomic, even this can usually be lock-free. The only caveat here is you might lose data between threads (race conditions). The data structure will never be corrupted due to concurrency, but that doesn't mean that inconsistent results are impossible in situations where two threads create a new version of the structure based on a single old and attempt to write their results (one of them will "win" and the other's changes will be lost). To solve this problem, you either need to have a lock for "writing operations", or use some sort of <a href="http://en.wikipedia.org/wiki/Software_transactional_memory" rel="noreferrer">STM</a>. I like the second approach for ease-of-use and throughput in low-collision systems (writes are ideally non-blocking and reads <em>never</em> block), but either one will work.</p>
<p>You've asked a tough question, one for which there isn't really a good answer. Concurrency-safe data structures are hard to write, particularly when they need to be mutable. Completely lock-free architectures are provably impossible in the presence of shared state, so you may want to give up on that requirement. The best you can do is minimize the locking required, hence the immutable data structures.</p>
|
<p>I am a bit late to the party. But if someone is still looking for a practical solution to this problem and they have not yet decided on a server, let me suggest <a href="https://developers.google.com/appengine/" rel="nofollow">Google's App Engine</a>. Their Datastore is optimized for these type of requirements.</p>
| 32,810
|
<p>I have just got a Monoprice Maker Select 3d printer (which is really just a Wanhao Duplicator i3). </p>
<p>I want to print a model that came on the included SD card (<code>1.gcode</code>) with ABS filament. I first press "<code>Preheat ABS</code>" and wait for the display to show the correct temperatures, 245°C for the extruder and 90°C for the print bed. Then, I mount the SD card and select the file to print. </p>
<p>However, once I do that, the "goal" temperatures change to 195°C for the extruder and 50°C for the print bed, and the temperatures reported by the printer gradually go down as the printer waits for it to match the "goal" temperature. This results in a failed print, with the filament sticking to the extruder in a clump. </p>
<p>What is going on here? I am trying PLA with the same file, and it seems to work fine, although the temperature change still occurs. </p>
|
<p>The demo files are gcode files generated for use with the sample PLA that comes with the printer. If you want to print it with ABS select the file and set the temperature manually afterwards. </p>
|
<p>If you want to use the demo files, you can probably pause the print as soon as it starts, and manually set the extruder temperatures before resuming the print. Easier to generate new g-code though.</p>
| 465
|
<p>I have a dictionary where keys are strings, and values are integers.</p>
<pre><code>stats = {'a': 1, 'b': 3000, 'c': 0}
</code></pre>
<p>How do I get the key with the maximum value? In this case, it is <code>'b'</code>.</p>
<hr />
<p>Is there a nicer approach than using an intermediate list with reversed key-value tuples?</p>
<pre><code>inverse = [(value, key) for key, value in stats.items()]
print(max(inverse)[1])
</code></pre>
|
<p>You can use <code>operator.itemgetter</code> for that:</p>
<pre><code>import operator
stats = {'a': 1000, 'b': 3000, 'c': 100}
max(stats.iteritems(), key=operator.itemgetter(1))[0]
</code></pre>
<p>And instead of building a new list in memory use <code>stats.iteritems()</code>. The <code>key</code> parameter to the <code>max()</code> function is a function that computes a key that is used to determine how to rank items.</p>
<p>Please note that if you were to have another key-value pair 'd': 3000 that this method will only return <strong>one</strong> of the <strong>two</strong> even though they both have the maximum value.</p>
<pre><code>>>> import operator
>>> stats = {'a': 1000, 'b': 3000, 'c': 100, 'd': 3000}
>>> max(stats.iteritems(), key=operator.itemgetter(1))[0]
'b'
</code></pre>
<p>If using Python3:</p>
<pre><code>>>> max(stats.items(), key=operator.itemgetter(1))[0]
'b'
</code></pre>
|
<p>I tested the accepted answer AND @thewolf's fastest solution against a very basic loop and the loop was faster than both:</p>
<pre><code>import time
import operator
d = {"a"+str(i): i for i in range(1000000)}
def t1(dct):
mx = float("-inf")
key = None
for k,v in dct.items():
if v > mx:
mx = v
key = k
return key
def t2(dct):
v=list(dct.values())
k=list(dct.keys())
return k[v.index(max(v))]
def t3(dct):
return max(dct.items(),key=operator.itemgetter(1))[0]
start = time.time()
for i in range(25):
m = t1(d)
end = time.time()
print ("Iterating: "+str(end-start))
start = time.time()
for i in range(25):
m = t2(d)
end = time.time()
print ("List creating: "+str(end-start))
start = time.time()
for i in range(25):
m = t3(d)
end = time.time()
print ("Accepted answer: "+str(end-start))
</code></pre>
<p>results:</p>
<pre><code>Iterating: 3.8201940059661865
List creating: 6.928712844848633
Accepted answer: 5.464320182800293
</code></pre>
| 33,662
|
<p>Our application defines a URL scheme whose resolution is context-sensitive: The content of the URL depends on the state of an in-progress database transaction. As such, to retrieve the content I cannot, for example, open a new database connection. However, I can't see a way to get at external context from the <code>URLStreamHandler</code> instance.</p>
<p>The documentation is a bit misleading, too: I checked at <a href="http://java.sun.com/developer/onlineTraining/protocolhandlers/" rel="nofollow noreferrer">the java Protocol Handler</a> site and it indicated (in the <em>Implementing URLStreamHandlerFactory</em> section) that the URL class would accept a <code>URLStreamHandlerFactory</code> instance, but the 1.5 JDK indicates that URL accepts only a <code>URLStreamHandler</code> when building a URL.</p>
<p>So, my question is, what is the best way to have context-sensitive URL resolution? Is there any better way than to have a <code>ThreadLocal</code> class variable on my <code>URLStreamHandler</code> implementation, that is set before the calls?</p>
|
<p>See <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/net/URL.html#setURLStreamHandlerFactory(java.net.URLStreamHandlerFactory)" rel="nofollow noreferrer">URL.setURLStreamHandlerFactory</a></p>
<p>This is a static method and:</p>
<blockquote>
<p>Sets an application's
URLStreamHandlerFactory. This method
can be called at most once in a given
Java Virtual Machine.</p>
</blockquote>
|
<p>It turns out that for our purposes, at least, the thread-local context object works best.</p>
| 32,833
|
<pre><code>SELECT DISTINCT
'LRS-TECH 1' || rpad(code,7) || rpad('APPTYPE',30) ||
rpad(licensing_no,30) || rpad(' ',300) AS RECORD
FROM APPS
WHERE L_code = '1000' AND licensing_no IS NOT NULL
</code></pre>
<p>This seems to be the primary culprit in why I cannot export these records to a textfile in my development environment. Is there any way I can get this query to run quicker. It returns roughly 2000+ lines of text. </p>
|
<p>You cannot diagnose this problem unless you know how the query is being optimised.</p>
<p>Try this:</p>
<pre><code>explain plan for SELECT DISTINCT
'LRS-TECH 1' || rpad(code,7) || rpad('APPTYPE',30) ||
rpad(licensing_no,30) || rpad(' ',300) AS RECORD
FROM APPS
WHERE L_code = '1000' AND licensing_no IS NOT NULL
/
select * from table(dbms_xplan.display)
/
</code></pre>
<p>Now, try this also ... it will help you detect a statistics problem:</p>
<pre><code>explain plan for SELECT /*+ dynamic_sampling(4) */ DISTINCT
'LRS-TECH 1' || rpad(code,7) || rpad('APPTYPE',30) ||
rpad(licensing_no,30) || rpad(' ',300) AS RECORD
FROM APPS
WHERE L_code = '1000' AND licensing_no IS NOT NULL
/
select * from table(dbms_xplan.display)
/
</code></pre>
<p>Please update your original post with the results of those.</p>
|
<p>Get rid of the DISTINCT.</p>
| 36,646
|
<p>As you know, in ASP.NET, you can store session data in one of following three modes:</p>
<ul>
<li>InProc</li>
<li>Session State </li>
<li>SQL Server</li>
</ul>
<p>For InProc mode, you can store any kind of data objects even it's not serializable. However, in Session State and SQL Server modes, you can only store serialized data. </p>
<p>In my project, I have a ready made portal which use "InProc" mode to store its session. I need to use Session State instead due to some scalability and failure handling issues. </p>
<p>The problem that this portal is internally storing unserialized objects in the session context (i.e The stored objects doesn't implement ISerializable interface). I have no access to their code. Is there any work around so that I can be able to store the session objects in State Server without changing their code. I still have access to their web.config file if this would help in any kind.</p>
|
<p>Below is a quick (and simple) ISAPI Filter example. I found it very useful when trying to write my first ISAPI plugin.
<a href="http://blogs.msdn.com/rakkimk/archive/2007/03/01/writing-a-simple-isapi-filter.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/rakkimk/archive/2007/03/01/writing-a-simple-isapi-filter.aspx</a></p>
<p>Best of luck.</p>
|
<p>Visual Studio used to have an ISAPI wizard which was great for writing plugins. If you have 6.0, it might still be there. VS 2003 has one under MFC for ISAPI with MFC support (not hard to remove if you don't want it).</p>
<p>If you are doing an Extension (not a filter) -- here is the minimal code you need:</p>
<p><a href="http://groups.google.com/group/microsoft.public.platformsdk.internet.server.isapi-dev/browse_thread/thread/d29e1a767cbb4717" rel="nofollow noreferrer">http://groups.google.com/group/microsoft.public.platformsdk.internet.server.isapi-dev/browse_thread/thread/d29e1a767cbb4717</a></p>
| 30,112
|
<p>I have a custom user control with a textbox on it and I'd like to expose the baseline (of the text in the textbox) snapline outside of the custom control. I know that you create a designer (inherited from ControlDesigner) and override SnapLines to get access to the snaplines, but I'm wondering how to get the text baseline of a control that I have exposed by my custom user control.</p>
|
<p>I just had a similar need, and I solved it like this:</p>
<pre><code> public override IList SnapLines
{
get
{
IList snapLines = base.SnapLines;
MyControl control = Control as MyControl;
if (control == null) { return snapLines; }
IDesigner designer = TypeDescriptor.CreateDesigner(
control.textBoxValue, typeof(IDesigner));
if (designer == null) { return snapLines; }
designer.Initialize(control.textBoxValue);
using (designer)
{
ControlDesigner boxDesigner = designer as ControlDesigner;
if (boxDesigner == null) { return snapLines; }
foreach (SnapLine line in boxDesigner.SnapLines)
{
if (line.SnapLineType == SnapLineType.Baseline)
{
snapLines.Add(new SnapLine(SnapLineType.Baseline,
line.Offset + control.textBoxValue.Top,
line.Filter, line.Priority));
break;
}
}
}
return snapLines;
}
}
</code></pre>
<p>This way it's actually creating a temporary sub-designer for the subcontrol in order to find out where the "real" baseline snapline is.</p>
<p>This seemed reasonably performant in testing, but if perf becomes a concern (and if the internal textbox doesn't move) then most of this code can be extracted to the Initialize method.</p>
<p>This also assumes that the textbox is a direct child of the UserControl. If there are other layout-affecting controls in the way then the offset calculation becomes a bit more complicated.</p>
|
<p>You're on the right track. You will need to override the SnapLines property in your designr and do something like this:</p>
<pre><code>Public Overrides ReadOnly Property SnapLines() As System.Collections.IList
Get
Dim snapLinesList As ArrayList = TryCast(MyBase.SnapLines, ArrayList)
Dim offset As Integer
Dim ctrl As MyControl = TryCast(Me.Control, MyControl)
If ctrl IsNot Nothing AndAlso ctrl.TextBox1 IsNot Nothing Then
offset = ctrl.TextBox1.Bottom - 5
End If
snapLinesList.Add(New SnapLine(SnapLineType.Baseline, offset, SnapLinePriority.Medium))
Return snapLinesList
End Get
End Property
</code></pre>
<p>In this example the usercontrol contains a textbox. The code adds a new snapline that represents the baseline for the textbox. The important thing is to calculate the offset correctly.</p>
| 11,906
|
<p>I am looking for a simple system to manage inbound emails from a support mailbox for a group with about 3 support people. I've looked at <a href="http://otrs.org/" rel="nofollow noreferrer">OTRS</a> which seems to have the features that we need. Unfortunately, so far the UI still looks like a confusing mess.</p>
<p>Are there any good FOSS tools that would meet this need? I've heard murmurings that something called fooogzeeebugzo might have similar features, but it seems quite expensive for such simple needs.</p>
|
<p>I have to agree, Fogbugz is probably the best out there. I have used both the hosted version and the purchased version which I hosted. It is top-notch.</p>
|
<p>We use FogBugz...er, "fooogzeeebugzo"...and while it may be a bit expensive for your needs, it works very well.</p>
| 6,205
|
<p>What is the best way to initialize a private, static data member in C++? I tried this in my header file, but it gives me weird linker errors:</p>
<pre><code>class foo
{
private:
static int i;
};
int foo::i = 0;
</code></pre>
<p>I'm guessing this is because I can't initialize a private member from outside the class. So what's the best way to do this?</p>
|
<p>The class declaration should be in the header file (Or in the source file if not shared).<br>
File: foo.h</p>
<pre><code>class foo
{
private:
static int i;
};
</code></pre>
<p>But the initialization should be in source file.<br>
File: foo.cpp</p>
<pre><code>int foo::i = 0;
</code></pre>
<p>If the initialization is in the header file then each file that includes the header file will have a definition of the static member. Thus during the link phase you will get linker errors as the code to initialize the variable will be defined in multiple source files.
The initialisation of the <code>static int i</code> must be done outside of any function.</p>
<p><b>Note:</b> Matt Curtis: points out that C++ allows the simplification of the above if the static member variable is of <a href="https://en.cppreference.com/w/cpp/language/types" rel="noreferrer">const integer type</a> (<em><code>bool</code>, <code>char</code>, <code>char8_t</code> [since C++20], <code>char16_t</code>, <code>char32_t</code>, <code>wchar_t</code>, <code>short</code>, <code>int</code>, <code>long</code>, <code>long long</code>, or any implementation-defined extended integer types, including any signed, unsigned, and cv-qualified variants.</em>). You can then declare and initialize the member variable directly inside the class declaration in the header file:</p>
<pre><code>class foo
{
private:
static int const i = 42;
};
</code></pre>
|
<p>Does this serves your purpose?</p>
<pre><code>//header file
struct MyStruct {
public:
const std::unordered_map<std::string, uint32_t> str_to_int{
{ "a", 1 },
{ "b", 2 },
...
{ "z", 26 }
};
const std::unordered_map<int , std::string> int_to_str{
{ 1, "a" },
{ 2, "b" },
...
{ 26, "z" }
};
std::string some_string = "justanotherstring";
uint32_t some_int = 42;
static MyStruct & Singleton() {
static MyStruct instance;
return instance;
}
private:
MyStruct() {};
};
//Usage in cpp file
int main(){
std::cout<<MyStruct::Singleton().some_string<<std::endl;
std::cout<<MyStruct::Singleton().some_int<<std::endl;
return 0;
}
</code></pre>
| 22,481
|
<p>How do I put a gridview row in edit mode programmatically?</p>
|
<p>Set the EditIndex property to the appropriate row and then ReBind the GridVIew again to it's DataSource.</p>
<p>Hope this helps.</p>
|
<pre><code>protected void btnEdit_Click(object sender, EventArgs e)
{
GridView1.EditIndex = 1;
}
</code></pre>
<p>Tested with vs-2008. fork fine.</p>
| 25,364
|
<p>I've just started looking into M-V-VM for a WPF application. Everything makes sense so far besides this particular issue...</p>
<p>I have a ViewModel I'll call Search. This ViewModel binds to a datagrid and lists results of items. Now, I have a command that needs to bring up <strong>another view</strong>, the item's details.</p>
<p>Putting the logic to show another view in the Search View doesn't seem right, it's not testable at all.</p>
<p>Here is my ViewModel implementation, which is not testable...</p>
<pre><code>public class SearchViewModel
{
public void SelectItem()
{
// I want to call the DetailsView from here
// this seems wrong, and is untestable
var detailsView = new DetailsView();
detailsView.Show();
}
}
</code></pre>
<p><strong>Where does the logic to show a view from a ViewModel method go in this pattern?</strong></p>
|
<p>Views should never be instantiated anywhere "below" the UI layer. VMs exist below that realm, therefore this is not the place to put that logic (as you've already realized).</p>
<p>There will almost always be some UI level event that will indicate the need to create the view. In your example, it might be a row (double) click event on the datagrid. That would be the place to new-up and show your DetailsView window.</p>
|
<p>We use a variant on this pattern, Here we have controllers that represent the VM, so the datacontext of the View is the VM and our DTOs are properties of the VM/Controller. We call it a controller still as we use this as the control point and thus handle certain command from the View. This is (I think) where we would implement the command such as yours.</p>
| 38,924
|
<p>A have a design question. I have wrote a couple of c# applications. Most of these apps have their own sql or access database, but then they also share a common database, but they are entirely different apps which have their own responsibilities in their own business domains.</p>
<p>Some people I spoke with believe the following : Applications should be silos. They should share nothing. No sharing of assemblies, components or databases.</p>
<p>I need advice on this. When is it acceptable to share, or is it never a good idea.</p>
<p>Thanks</p>
|
<p>There is a line, somewhere... sharing library code is positively encouraged - but you need to be a <em>little</em> bit careful when apps consume each-other, simply to prevent spaghetti code and circular references.</p>
<p>If the code you mention is really library code (i.e. neither project is the "master" for this data), then it should be fine (versioning issues aside). If it is the case that Project A wants Project B's data, then it usually isn't long before Project B wants Project A's data, and you have a spider web. In such cases, it may be preferable to use an SOA approach; have the projects expose their data via something like a WCF service, so that other projects only call into the public mex/wsdl API (ideally without assembly sharing).</p>
<p>But it is a deceptively complex question, and I don't think any single answer can cater for every scenario.</p>
|
<p>You should share everything (within the limits of common sense of course.) You are a team of developers, not a set of individual developers. Sharing code has numerous benefits: reusability means quicker development, simpler maintenance (you only need to fix a bug once), a new feature or improvement is potentially able to benefit all dependent projects immediately and it means sharing ideas as well. Personally, I have learnt a couple of tricks and good practices from the source code written by my coworkers.</p>
| 27,272
|
<p>What datatype would be used for storing video files in sql server2000?</p>
|
<p>Use BLOBs (binary large objects). <a href="http://www.microsoft.com/technet/prodtechnol/sql/2000/reskit/part3/c1161.mspx" rel="noreferrer">Documentation here</a>. More specifially:</p>
<blockquote>
<p>In SQL Server, BLOBs can be text, ntext, or image data type</p>
<p><strong>image</strong> </p>
<p>Variable-length binary data from 0 through 231 - 1 (2,147,483,647) bytes. </p>
</blockquote>
|
<p>Save yourself a headache and store them on the file system. Store the path in the DB. </p>
<p>Currently I can't think of a <em>really</em> good reason to store videos in a database, when there is a file system available. What are your's?</p>
| 47,822
|
<p>I whant to make a web interface on a server that will manage a few dns servers on another servers.</p>
<h3>How can i remotely manage a bind dns server programmaticly ?</h3>
<ul>
<li>I would like to add/edit/delete zones.</li>
<li>I see that there is rndc but that only allows reloading of zones and not adding/deleting.</li>
<li>I could NFS mount zones from dns servers and edit them but is there a better way?</li>
</ul>
|
<p>If there isn't a hard requirement on writing something like this from scratch, why not simply use an already existing interface without having to reinvent the wheel? A simple <a href="http://www.google.com/search?q=bind+dns+web+interface" rel="noreferrer">Google search for the keywords bind dns web interface</a> yields an entire list of good open source projects in the very first result link.</p>
|
<p>You could set up something that does remote SSH commands? That may be a bit insecure, though, unless the server running the commands themselves is pre-authenticated with an SSH key, and that's the only way you can access the server.</p>
| 44,297
|
<p>How do I check if an object property in JavaScript is undefined?</p>
|
<p>The usual way to check if the value of a property is the special value <code>undefined</code>, is:</p>
<pre class="lang-js prettyprint-override"><code>if(o.myProperty === undefined) {
alert("myProperty value is the special value `undefined`");
}
</code></pre>
<p>To check if an object does not actually have such a property, and will therefore return <code>undefined</code> by default when you try to access it:</p>
<pre class="lang-js prettyprint-override"><code>if(!o.hasOwnProperty('myProperty')) {
alert("myProperty does not exist");
}
</code></pre>
<p>To check if the value associated with an identifier is the special value <code>undefined</code>, <em>or</em> if that identifier has not been declared:</p>
<pre class="lang-js prettyprint-override"><code>if(typeof myVariable === 'undefined') {
alert('myVariable is either the special value `undefined`, or it has not been declared');
}
</code></pre>
<p>Note: this last method is the only way to refer to an <strong>undeclared</strong> identifier without an early error, which is different from having a value of <code>undefined</code>.</p>
<p>In versions of JavaScript prior to ECMAScript 5, the property named "undefined" on the global object was writeable, and therefore a simple check <code>foo === undefined</code> might behave unexpectedly if it had accidentally been redefined. In modern JavaScript, the property is read-only.</p>
<p>However, in modern JavaScript, "undefined" is not a keyword, and so variables inside functions can be named "undefined" and shadow the global property.</p>
<p>If you are worried about this (unlikely) edge case, you can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void" rel="noreferrer">the void operator</a> to get at the special <code>undefined</code> value itself:</p>
<pre class="lang-js prettyprint-override"><code>if(myVariable === void 0) {
alert("myVariable is the special value `undefined`");
}
</code></pre>
|
<pre><code>if (somevariable == undefined) {
alert('the variable is not defined!');
}
</code></pre>
<p>You can also make it into a function, as shown <a href="http://verens.com/archives/2005/07/25/isset-for-javascript/" rel="nofollow noreferrer">here</a>:</p>
<pre><code>function isset(varname){
return(typeof(window[varname]) != 'undefined');
}
</code></pre>
| 4,711
|
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/273209/are-memory-leaks-ever-ok">Are memory leaks ever ok?</a> </p>
</blockquote>
<p>I read somewhere that there are special cases when memory leaks are needed and actually a good thing in some rare circumstances. But i can't remember what was it exactly!</p>
<p>Does anyone know or remember such an argument?</p>
<p>Thanks, Adi</p>
|
<p>The only situations I can think of where a memory leak would be desirable are as follows:</p>
<p>(they're all a little convoluted though apart from the 1st)</p>
<ul>
<li><p>An academic situation where a memory leak would be a good learning excercise in a programming class; including <em>tracking down of</em> and <em>prevention of</em> leaks.</p></li>
<li><p>A profiling/testing scenario where we would like to see how our software behaves under leaky circumstances.</p></li>
<li><p>Writing a leaky application to test/debug a profiling application with.</p></li>
</ul>
|
<p>They're good if you're a hosting company that get to charge $$$++ for memory upgrades to servers.</p>
| 41,938
|
<p>Ok, so PHP isn't the best language to be dealing with arbitrarily large integers in, considering that it only natively supports 32-bit signed integers. What I'm trying to do though is create a class that could represent an arbitrarily large binary number and be able to perform simple arithmetic operations on two of them (add/subtract/multiply/divide).</p>
<p>My target is dealing with 128-bit integers.</p>
<p>There's a couple of approaches I'm looking at, and problems I see with them. Any input or commentary on what you would choose and how you might go about it would be greatly appreciated.</p>
<p><strong>Approach #1:</strong> Create a 128-bit integer class that stores its integer internally as four 32-bit integers. The only problem with this approach is that I'm not sure how to go about handling overflow/underflow issues when manipulating individual chunks of the two operands.</p>
<p><strong>Approach #2:</strong> Use the bcmath extension, as this looks like something it was designed to tackle. My only worry in taking this approach is the scale setting of the bcmath extension, because there can't be any rounding errors in my 128-bit integers; they must be precise. I'm also worried about being able to eventually convert the result of the bcmath functions into a binary string (which I'll later need to shove into some mcrypt encryption functions).</p>
<p><strong>Approach #3:</strong> Store the numbers as binary strings (probably LSB first). Theoretically I should be able to store integers of any arbitrary size this way. All I would have to do is write the four basic arithmetic functions to perform add/sub/mult/div on two binary strings and produce a binary string result. This is exactly the format I need to hand over to mcrypt as well, so that's an added plus. This is the approach I think has the most promise at the moment, but the one sticking point I've got is that PHP doesn't offer me any way to manipulate the individual bits (that I know of). I believe I'd have to break it up into byte-sized chunks (no pun intended), at which point my questions about handling overflow/underflow from Approach #1 apply.</p>
|
<p>The <a href="http://us2.php.net/gmp" rel="nofollow noreferrer">PHP GMP extension</a> will be better for this. As an added bonus, you can use it to do your decimal-to-binary conversion, like so:</p>
<pre><code>gmp_strval(gmp_init($n, 10), 2);
</code></pre>
|
<p>I implemented the following <a href="https://github.com/alixaxel/phunction/blob/ac2bc87e0d6d6c944a46d9714ca79004b18319c0/phunction/Math.php#L74-L143" rel="nofollow">PEMDAS complaint BC evaluator</a> which may be useful to you.</p>
<pre><code>function BC($string, $precision = 32)
{
if (extension_loaded('bcmath') === true)
{
if (is_array($string) === true)
{
if ((count($string = array_slice($string, 1)) == 3) && (bcscale($precision) === true))
{
$callback = array('^' => 'pow', '*' => 'mul', '/' => 'div', '%' => 'mod', '+' => 'add', '-' => 'sub');
if (array_key_exists($operator = current(array_splice($string, 1, 1)), $callback) === true)
{
$x = 1;
$result = @call_user_func_array('bc' . $callback[$operator], $string);
if ((strcmp('^', $operator) === 0) && (($i = fmod(array_pop($string), 1)) > 0))
{
$y = BC(sprintf('((%1$s * %2$s ^ (1 - %3$s)) / %3$s) - (%2$s / %3$s) + %2$s', $string = array_shift($string), $x, $i = pow($i, -1)));
do
{
$x = $y;
$y = BC(sprintf('((%1$s * %2$s ^ (1 - %3$s)) / %3$s) - (%2$s / %3$s) + %2$s', $string, $x, $i));
}
while (BC(sprintf('%s > %s', $x, $y)));
}
if (strpos($result = bcmul($x, $result), '.') !== false)
{
$result = rtrim(rtrim($result, '0'), '.');
if (preg_match(sprintf('~[.][9]{%u}$~', $precision), $result) > 0)
{
$result = bcadd($result, (strncmp('-', $result, 1) === 0) ? -1 : 1, 0);
}
else if (preg_match(sprintf('~[.][0]{%u}[1]$~', $precision - 1), $result) > 0)
{
$result = bcmul($result, 1, 0);
}
}
return $result;
}
return intval(version_compare(call_user_func_array('bccomp', $string), 0, $operator));
}
$string = array_shift($string);
}
$string = str_replace(' ', '', str_ireplace('e', ' * 10 ^ ', $string));
while (preg_match('~[(]([^()]++)[)]~', $string) > 0)
{
$string = preg_replace_callback('~[(]([^()]++)[)]~', __FUNCTION__, $string);
}
foreach (array('\^', '[\*/%]', '[\+-]', '[<>]=?|={1,2}') as $operator)
{
while (preg_match(sprintf('~(?<![0-9])(%1$s)(%2$s)(%1$s)~', '[+-]?(?:[0-9]++(?:[.][0-9]*+)?|[.][0-9]++)', $operator), $string) > 0)
{
$string = preg_replace_callback(sprintf('~(?<![0-9])(%1$s)(%2$s)(%1$s)~', '[+-]?(?:[0-9]++(?:[.][0-9]*+)?|[.][0-9]++)', $operator), __FUNCTION__, $string, 1);
}
}
}
return (preg_match('~^[+-]?[0-9]++(?:[.][0-9]++)?$~', $string) > 0) ? $string : false;
}
</code></pre>
<p>It automatically deals with rounding errors, just set the precision to whatever digits you need.</p>
| 5,807
|
<p>I came across this topic today while investigating something very strange. Doing certain things in our Flex app can cause the number of frames rendered to rocket, from 12fps to ~30fps: loaded animations start playing at high speed and the GUI starts to lock up.</p>
<p>Since everything I've read on Flex/Flash hammers home the point "the frame rate is capped at the fps set in the top level app", it seems the only way these extra renders can be happening is due to some events causing them (no programmatic changes to the stage's framerate are done anywhere). Since it only happens when I put my update logic in the ENTER_FRAME handler, I'm trying to figure out what might be happening which to apparently causing Flex to go render-crazy.</p>
<p>Hypothesis: something in my update function is triggering an immediate screen update, this raises another ENTER_FRAME immediately, which means my update loop gets called, which triggers another immediate screen update, ...</p>
<p>We have Flex components used in our GUI, if this is a factor. I don't really know where to go next on this.</p>
<p><strong>Clarifications</strong>:</p>
<ul>
<li>When I say things speed up, there
are two ways this manifests.</li>
<li>Firstly, my ENTER_FRAME handler gets
called far more often.</li>
<li>Secondly, a
loaded Flash SWF with a looping
animation built in suddenly speeds
up to te point it looks silly.</li>
<li>I am not using updateAfterEvent, I only
found this existed when researching
this problem. Apparently, some
events on Sprite subclasses
automatically call this and I wonder
if that's the root cause.</li>
<li>I am not doing any direct messsing about with rendering at all. Background animations play automatically as they have timelines built-in from CS3 authoring, all our update function does is change the position of DisPlayObjects or add/remove them etc</li>
</ul>
<p><strong>Update:</strong>
I added a label to my app to print out stage.frameRate, and discovered at certain times, it suddenly changes from 12 to 1000 (the maximum allowed value). While it was trivial to add a line to my ENTER_FRAME handler to reset it that's hardly a big help.
Also, even doing this, the rendering is all messed up. Certain actions (like raising an Alert popup) make it all spring back into life.
Unfortunately, I am not able to view the source of the Stage class to set a breakpoint on the setter property.</p>
<p>That's very interesting about the Flex loading 'set to 1000fps' thing. What we have are several Flex applications which all provide a common interface. A master app is in charge of loading these modules as required through the SWFLoader class. However, the loading process already takes into account the delayed loading... when the SWF loads we then wait for the APPLICATION_COMPLETE from the SystemManager. Once this is received, shouldn't the applications completion have occurred?</p>
|
<p>Flex sets the frame rate to 1000 during "phased instantiation" of Flex components, which occurs only during initial load of a flex swf. This allows it to build all components very quickly.</p>
<p>Are you waiting for the Flex app to be fully loaded and constructed? You should be waiting for FlexEvent.CREATION_COMPLETE before working with your Flex content.</p>
<p>If you would like a reference to where this occcurs, look in the Flex LayoutManager class, line 326 (using Flex SDK 3.0.194161), in the setter for the property usePhasedInstantiation.</p>
<p><b>Update:</b></p>
<p>APPLICATION_COMPLETE should have you covered for the initial load.</p>
<p>This actually happens any time components are created directly from MXML. So there are a few other cases to look for. Are you using any Repeaters? Do you use any navigation containers that are building their children on demand?</p>
|
<p>One thing I'm not clear on - are you seeing that the actual screen refreshes are occurring faster than the published framerate? Or is it that your animations are moving faster but the screen refreshes are unchanged? (i.e., it used to move 10 pixels per second, but now it moves faster than that, regardless of how often the screen is drawn.)</p>
<p>An easy way to check this would be to try publishing your content at 1 fps. It should be clear whether the screen is redrawing once per second, but animated elements are being moved more frequently than that, or whether the screen is actually updating more frequently.</p>
<p>If the latter, are you using any <code>updateAfterEvent()</code> methods in your code? This can cause actual screen refreshes to occur faster than the published framerate. It shouldn't affect <code>ENTER_FRAME</code> events though. You should still only get one of those per frame update.</p>
<p>Alternately, are the things you're animating just Sprites and so on, or are you implementing them as Flex components, and trying to redraw them with <code>invalidate()</code> methods and RENDER events and so on?</p>
<p>If you could clarify a few of these points in the question the answer might be clearer. Thanks...</p>
| 17,079
|
<p>I have been bitten by something unexpected recently. I wanted to make something like that:</p>
<pre><code>try :
thing.merge(iterable) # this is an iterable so I add it to the list
except TypeError :
thing.append(iterable) # this is not iterable, so I add it
</code></pre>
<p>Well, It was working fine until I passed an object inheriting from Exception which was supposed to be added.</p>
<p>Unfortunetly, an Exception is iterable. The following code does not raise any <code>TypeError</code>:</p>
<pre><code>for x in Exception() :
print 1
</code></pre>
<p>Does anybody know why?</p>
|
<p>Note that what is happening is not related to any kind of implicit string conversion etc, but because the <code>Exception</code> class implements <code>___getitem__</code> to return the values from the args tuple (<code>ex.args</code>). You can see this by the fact that you get the whole string as your first and only item in the iteration, rather than the character-by-character result you'd get if you iterate over the string.</p>
<p>This surprised me too, but thinking about it, I'm guessing it is for backwards compatibility reasons. Python used to (<a href="http://www.python.org/doc/essays/stdexceptions.html" rel="nofollow noreferrer">pre-1.5</a>) lack the current class hierarchy of exceptions. Instead, strings were thrown, with (usually) a tuple argument for any details that should be passed to the handling block, i.e:</p>
<pre><code>try:
raise "something failed", (42, "some other details")
except "something failed", args:
errCode, msg = args
print "something failed. error code %d: %s" % (errCode, msg)
</code></pre>
<p>It looks like this behavior was put in to avoid breaking pre-1.5 code expecting a tuple of arguments, rather than a non-iterable exception object. There are a couple of examples of this with <code>IOError</code> in the Fatal Breakage section of the above <a href="http://www.python.org/doc/essays/stdexceptions.html" rel="nofollow noreferrer">link</a></p>
<p>String exceptions have been deprecated for a while, and are gone in Python 3. Exception objects are no longer iterable in Python 3:</p>
<pre><code>>>> list(Exception("test"))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'Exception' object is not iterable
</code></pre>
|
<p>NOT VALID. Check Brian anwser.</p>
<p>Ok, I just got it :</p>
<pre><code>for x in Exception("test") :
print x
....:
....:
test
</code></pre>
<p>Don't bother ;-)</p>
<p>Anyway, it's good to know.</p>
<p>EDIT : looking to the comments, I feel like adding some explanations.</p>
<p>An exception contains a message you passed to during instantiation :</p>
<pre><code>raise Exception("test")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Exception: test
</code></pre>
<p>It's fair to say that the message is what defines the Exception the best, so str() returns it :</p>
<pre><code>print Exception("test")
test
</code></pre>
<p>Now, it happens that Exceptions are implicitly converted to string when used in something else than an Exception context.</p>
<p>So when I do :</p>
<pre><code>for x in Exception("test") :
print x
</code></pre>
<p>I am iterating over the string "test".</p>
<p>And when I do : </p>
<pre><code>for x in Exception() :
print x
</code></pre>
<p>I do iterate over an empty string. Tricky. Because when it comes to my issue :</p>
<pre><code>try :
thing.merge(ExceptionLikeObject)
except TypeError :
...
</code></pre>
<p>This won't raise anything since ExceptionLikeObject is considered as a string.</p>
<p>Well now, we know the HOW, but I still not the WHY. Maybe the built-in Exception inherit from the built-in String ? Because as far as I know :</p>
<ul>
<li>adding <strong>str</strong> does not make any object iterable.</li>
<li>I bypassed the problem by overloding <strong>iter</strong>, making it raising TypeError !</li>
</ul>
<p>Not a problem anymore, but still a mystery.</p>
| 32,229
|
<p>This is a continuation question from a previous question <a href="https://stackoverflow.com/questions/142237/integrating-external-sources-in-a-build.">I have asked</a></p>
<p>I now have a /externals directory in the root of my project tree. Inside this I have a reference to another project. I'm able to script the build of all my externals in the main project NAnt script. The result of these builds are as follows:</p>
<p>/externals/external-project1/build/buildartifacts/{dlls|html|js}</p>
<p>/externals/external-project2/build/buildartifacts/{dlls|html|js}</p>
<p>This is all well and good, but now I'm curious as to how my main project should reference these build artifacts. For example, let's say that external project builds a DLL that some of my codebase depends on. Should I simply reference the DLL in the build artifacts directory or should I implement another NAnt task that copies these to a /thirdparty/libs/ folder?</p>
<p>This means that my build is now dependent on the ability to build this external project (which could either be internal, or thirdparty). Is it a good idea to check in the latest set of build artifacts to ensure that the main build won't break because of dependent builds breaking?</p>
<p>Hope that's clear enough. Just writing this down has a least clarified the problem for me :-).</p>
<p>--Edit--</p>
<p>Thanks guys. I think I'm going to implement the "checkout a revision", but since the builds are so quick I'm not going to check in any build artifiacts. Also going to have to figure out how to deal with the dependencies of the external project (eg: prototype, swfobject, etc).</p>
|
<p>I'd recommend taking a look at the UK Government Data Standard for postcodes [link now dead; <a href="http://webarchive.nationalarchives.gov.uk/+/http://www.cabinetoffice.gov.uk/media/291370/bs7666-v2-0-xsd-PostCodeType.htm" rel="noreferrer">archive of XML</a>, see <a href="http://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom#Validation" rel="noreferrer">Wikipedia</a> for discussion]. There is a brief description about the data and the attached xml schema provides a regular expression. It may not be exactly what you want but would be a good starting point. The RegEx differs from the XML slightly, as a P character in third position in format A9A 9AA is allowed by the definition given.</p>
<p>The RegEx supplied by the UK Government was:</p>
<pre><code>([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9][A-Za-z]?))))\s?[0-9][A-Za-z]{2})
</code></pre>
<p>As pointed out on the Wikipedia discussion, this will allow some non-real postcodes (e.g. those starting AA, ZY) and they do provide a more rigorous test that you could try.</p>
|
<p>I needed a version that would work in SAS with the <code>PRXMATCH</code> and related functions, so I came up with this:</p>
<pre><code>^[A-PR-UWYZ](([A-HK-Y]?\d\d?)|(\d[A-HJKPSTUW])|([A-HK-Y]\d[ABEHMNPRV-Y]))\s?\d[ABD-HJLNP-UW-Z]{2}$
</code></pre>
<p>Test cases and notes:</p>
<pre><code>/*
Notes
The letters QVX are not used in the 1st position.
The letters IJZ are not used in the second position.
The only letters to appear in the third position are ABCDEFGHJKPSTUW when the structure starts with A9A.
The only letters to appear in the fourth position are ABEHMNPRVWXY when the structure starts with AA9A.
The final two letters do not use the letters CIKMOV, so as not to resemble digits or each other when hand-written.
*/
/*
Bits and pieces
1st position (any): [A-PR-UWYZ]
2nd position (if letter): [A-HK-Y]
3rd position (A1A format): [A-HJKPSTUW]
4th position (AA1A format): [ABEHMNPRV-Y]
Last 2 positions: [ABD-HJLNP-UW-Z]
*/
data example;
infile cards truncover;
input valid 1. postcode &$10. Notes &$100.;
flag = prxmatch('/^[A-PR-UWYZ](([A-HK-Y]?\d\d?)|(\d[A-HJKPSTUW])|([A-HK-Y]\d[ABEHMNPRV-Y]))\s?\d[ABD-HJLNP-UW-Z]{2}$/',strip(postcode));
cards;
1 EC1A 1BB Special case 1
1 W1A 0AX Special case 2
1 M1 1AE Standard format
1 B33 8TH Standard format
1 CR2 6XH Standard format
1 DN55 1PT Standard format
0 QN55 1PT Bad letter in 1st position
0 DI55 1PT Bad letter in 2nd position
0 W1Z 0AX Bad letter in 3rd position
0 EC1Z 1BB Bad letter in 4th position
0 DN55 1CT Bad letter in 2nd group
0 A11A 1AA Invalid digits in 1st group
0 AA11A 1AA 1st group too long
0 AA11 1AAA 2nd group too long
0 AA11 1AAA 2nd group too long
0 AAA 1AA No digit in 1st group
0 AA 1AA No digit in 1st group
0 A 1AA No digit in 1st group
0 1A 1AA Missing letter in 1st group
0 1 1AA Missing letter in 1st group
0 11 1AA Missing letter in 1st group
0 AA1 1A Missing letter in 2nd group
0 AA1 1 Missing letter in 2nd group
;
run;
</code></pre>
| 19,941
|
<p>I am having an VB Script. I need to log the error information in a file. I need to log every information like error number error description and in which sub routine does the error occured.</p>
<p>Please provide some code</p>
|
<p>You can make use of the <a href="http://www.w3schools.com/asp/asp_ref_filesystem.asp" rel="nofollow noreferrer">FileSystemObject</a> and the <a href="http://www.devguru.com/technologies/vbscript/QuickRef/err.html" rel="nofollow noreferrer">Error</a> object if you're using VBScript.</p>
<p>Paste the following into error.vbs and run it. It will throw an error then log the details to a file called c:\errors.log</p>
<pre><code>Option Explicit
On Error Resume Next ' Potential error coming up
Dim MyArray(5)
MyArray(7) = "BWA HA HA"
If Err.Number <> 0 Then
LogError(Err)
Err.Clear
End If
On Error Goto 0 ' Stop looking for errors
Sub LogError(Details)
Dim fs : Set fs = CreateObject("Scripting.FileSystemObject")
Dim logFile : Set logFile = fs.OpenTextFile("c:\errors.log", 8, True)
logFile.WriteLine(Now() & ": Error: " & Details.Number & " Details: " & Details.Description)
End Sub
</code></pre>
<p>If you're using an ASP page then you can make use of <a href="http://msdn.microsoft.com/en-us/library/ms524942.aspx" rel="nofollow noreferrer">ASPError</a> to get more detailed information about the error such as line number, etc (remember to replace CreateObject with Server.CreateObject).</p>
<p><strong>Edit:</strong>
To get the line number that caused the error in .vbs script you could add this as a parameter to the sub routine.</p>
|
<p>For error handling in VBScript is used "On Error" clausule.
There are 3 ways, how to handle errors:</p>
<ul>
<li>On Error Resume Next '' ignore errors</li>
<li>On Error GoTo 0 '' removes error handlning</li>
<li>On Error GoTo HandleError '' on error will code jump to specified signal</li>
</ul>
<p>Samples:</p>
<pre><code>On Error Resume Next '' ignore errors
SomeIgnorableFunction()
On Error GoTo 0 '' removes error ignoring
SomeImportantFunction()
On Error GoTo HandleError '' on error will code jump to specified signal
Dim a
a = 15 / 0
GoTo Finish '' skips error handling
HandleError:
Dim msg
Set msg = Err.Description & vbCrLf & Err.Number
MsgBox msg
Finish:
'' there is end of sciprt
</code></pre>
| 25,446
|
<p>As in the subject, how can one get the total width of an element, including its border and padding, using jQuery? I've got the jQuery dimensions plugin, and running <code>.width()</code> on my <code>760px-wide</code>, <code>10px padding</code> DIV returns <code>760</code>.</p>
<p>Perhaps I'm doing something wrong, but if my element manifests itself as <code>780 pixels wide</code> and Firebug tells me that there's <code>10px padding</code> on it, but calling <code>.width()</code> only gives 760, I'd be hard pressed to see how.</p>
<p>Thanks for any suggestions.</p>
|
<p><strong>[Update]</strong></p>
<p>The original answer was written prior to jQuery 1.3, and the functions that existed at the time where not adequate by themselves to calculate the whole width.</p>
<p>Now, as <a href="https://stackoverflow.com/questions/349705/total-width-of-element-including-padding-and-border-in-jquery/673622#673622">J-P</a> correctly states, jQuery has the functions <a href="http://docs.jquery.com/CSS/outerWidth" rel="noreferrer">outerWidth</a> and <a href="http://docs.jquery.com/CSS/outerHeight" rel="noreferrer">outerHeight</a> which include the <code>border</code> and <code>padding</code> by default, and also the <code>margin</code> if the first argument of the function is <code>true</code> </p>
<hr>
<p><strong>[Original answer]</strong></p>
<p>The <code>width</code> method no longer requires the <code>dimensions</code> plugin, because it has been added to the <code>jQuery Core</code></p>
<p>What you need to do is get the padding, margin and border width-values of that particular div and add them to the result of the <code>width</code> method</p>
<p>Something like this:</p>
<pre><code>var theDiv = $("#theDiv");
var totalWidth = theDiv.width();
totalWidth += parseInt(theDiv.css("padding-left"), 10) + parseInt(theDiv.css("padding-right"), 10); //Total Padding Width
totalWidth += parseInt(theDiv.css("margin-left"), 10) + parseInt(theDiv.css("margin-right"), 10); //Total Margin Width
totalWidth += parseInt(theDiv.css("borderLeftWidth"), 10) + parseInt(theDiv.css("borderRightWidth"), 10); //Total Border Width
</code></pre>
<p><em>Split into multiple lines to make it more readable</em></p>
<p>That way you will always get the correct computed value, even if you change the padding or margin values from the css</p>
|
<p>same browsers may return string for border width, in this parseInt will return NaN
so make sure you parse value to int properly.</p>
<pre><code> var getInt = function (string) {
if (typeof string == "undefined" || string == "")
return 0;
var tempInt = parseInt(string);
if (!(tempInt <= 0 || tempInt > 0))
return 0;
return tempInt;
}
var liWidth = $(this).width();
liWidth += getInt($(this).css("padding-left"));
liWidth += getInt($(this).css("padding-right"));
liWidth += getInt($(this).css("border-left-width"));
liWidth += getInt($(this).css("border-right-width"));
</code></pre>
| 45,499
|
<p>I've been using Eclipse pretty regularly for several years now, but I admit to not having explored all the esoterica it has to offer, particularly in the areas of what formatting features the editors offer.</p>
<p>The main thing I miss from (X)emacs is the "align-regex" command, which let me take several lines into a region and then format them so that some common pattern in all lines was aligned. The simplest example of this is a series of variable assignments:</p>
<pre><code>var str = new String('aString');
var index = 0;
var longCamelCaseObjectName = new LongNameObject();
</code></pre>
<p>After doing align-regex on "=", that would become:</p>
<pre><code>var str = new String('aString');
var index = 0;
var longCamelCaseObjectName = new LongNameObject();
</code></pre>
<p>Now, you may have your own thoughts on stylistic (ab)use of white space and alignment, etc., but that's just an example (I'm actually trying to align a different kind of mess entirely).</p>
<p>Can anyone tell me off-hand if there's an easy key-combo-shortcut for this in Eclipse? Or even a moderately-tricky one?</p>
|
<p>You can set the formatter to do this:</p>
<p>Preferences -> Java -> Code Style -> Formatter. Click 'Edit' on the profile (you may need to make a new one since you can't edit the default).</p>
<p>In the indentation section select 'Align fields with columns'.</p>
<p>Then, in your code <kbd>CTRL</kbd>+<kbd>SHIFT</kbd>+<kbd>F</kbd> will run that formatter.</p>
<p>That will of course run all the other rules, so you may want to peruse the various options here.</p>
|
<p>This plug-in does exactly what you want: <a href="https://github.com/eduardp/OCDFormat/" rel="nofollow">OCDFormat</a></p>
<p>It works in all text files, not only Java.</p>
| 18,211
|
<p>I'm trying to get my head around <a href="https://jira.amqp.org/confluence/display/AMQP/About+AMQP" rel="nofollow noreferrer">AMQP</a>. It looks great for inter-machine (cluster, LAN, WAN) communication between applications but I'm not sure if it is suitable (in architectural, and current implementation terms) for use as a software bus within one machine.</p>
<p>Would it be worth pulling out a current high performance message passing framework to replace it with AMQP, or is this falling into the <a href="http://steve.vinoski.net/blog/2008/07/01/convenience-over-correctness/" rel="nofollow noreferrer">same trap as RPC</a> by blurring the distinction between local and non-local communication?</p>
<p>I'm also wary of the performance impacts of using a WAN technology for intra-machine communications, although this may be more of an implementation concern than architecture.</p>
<p>War stories would be appreciated.</p>
|
<p>AMQP is not an RPC framework. It provides the building blocks to model things like shared queues, RPC, pubsub etc. but it does not mandate any specific way to use it.</p>
<p>If you want to partition your application (making it distributable on the way) and to wire it together with AMQP I think it's the right technology. There might be faster alternatives though but probably none as generic as AMQP.</p>
|
<p>AMQP looks more like a reliable transport middleware offering for SOA than something to be used internally.</p>
| 31,408
|
<p>I am using the rounded corners plugin for jquery and have it working rounding elements in my page. The only issue I have is that the elements appear on the page un-rounded and then round. What do I need to do so that the elements only appear rounded?</p>
<p>I originally put my script tags in the head element but should they go somewhere else in a master page to improve perf?</p>
|
<p>Yes, vim settings can be included within the document.</p>
<p>They are mostly found within comments, so they don't mess up the original file. An example for tab-specific settings is:</p>
<pre><code>/* ex: set tabstop=8 expandtab: */
</code></pre>
<p>Note that this command works in most cases, however, servers are often setup without <code>modeline</code> turned on for security reasons. To turn on that feature add the following in your $HOME/.vimrc or the system $VIM/vimrc:</p>
<pre><code>set modeline
</code></pre>
|
<p>You could maybe save the file as a particular type, e.g. special filename format or extension, and then define an autocommand in your .vimrc for that filetype.</p>
<p>I do this for my makefiles to ensure that I have the various settings I need for specific files.</p>
<p>For example, here's my autocommand dec.</p>
<pre><code>if has("autocmd")
autocmd BufRead,BufNewFile Makefile* :set noexpandtab
autocmd BufRead,BufNewFile mirror.conf :set noexpandtab
autocmd BufRead,BufNewFile *.html* :set shiftwidth=2
autocmd BufRead,BufNewFile diff_files :set autowrite
autocmd BufRead,BufNewFile lbnamed* :set ft=perl
autocmd BufRead,BufNewFile *.t :set ft=perl
endif
</code></pre>
| 40,415
|
<p>If A references assembly B 1.1 and C, and C references B 1.2, how do you avoid assembly conflicts?</p>
<p>I nievely assumed C's references would be encapsulated away and would not cause any problems, but it appears all the dll's are copied to the bin, which is where the problem occurs.</p>
<p>I understand the two ways around this are to use the GAC or assembly bindings? The GAC doesn't seem like the best approach to me, as I don't like assuming dlls will be there, I prefer to reference dlls from a lib directory in my solution.</p>
<p>Where as assembly bindings don't seem robust to me, what if one version of the assembly has functionality that the other doesn't, will this not produce problems?</p>
<hr>
<p>In my case its because I'm using a 3rd party dll uses a older version of nHibernate, than I'm using myself.</p>
|
<p>I've achieved the same results using the GAC in the past, but you should question your reasons for having to reference more than one version and try to avoid it if possible. If you must do it, a <a href="http://msdn.microsoft.com/en-us/library/2fc472t2(VS.80).aspx" rel="noreferrer">binding redirect</a> may help in your case.</p>
<p>Also, have you read <a href="http://blogs.msdn.com/abhinaba/archive/2005/11/30/498278.aspx" rel="noreferrer">this</a> yet?</p>
|
<p>You can add a <a href="http://msdn.microsoft.com/en-us/library/eftw1fys.aspx" rel="nofollow noreferrer">bindingRedirect element</a> to your configuration file to specify which version of the assembly you want to use at runtime.</p>
<pre><code><configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="myAssembly"
publicKeyToken="32ab4ba45e0a69a1"
culture="neutral" />
<bindingRedirect oldVersion="1.0.0.0"
newVersion="2.0.0.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
</code></pre>
| 27,552
|
<p>Is it possible to integrate <a href="http://hudson.dev.java.net/" rel="noreferrer" title="hudson: an extensible continuous integration engine">Hudson</a> with MS Test?</p>
<p>I am setting up a smaller CI server on my development machine with Hudson right now, just so that I can have some statistics (ie. <a href="http://blogs.msdn.com/fxcop/" rel="noreferrer" title="Code Analysis Team Blog">FxCop</a> and compiler warnings). Of course, it would also be nice if it could just run my unit tests and present their output.</p>
<p>Up to now, I have added the following batch task to Hudson, which makes it run the tests properly.</p>
<pre><code>"%PROGRAMFILES%\Microsoft Visual Studio 9.0\Common7\IDE\MSTest.exe" /runconfig:LocalTestRun.testrunconfig /testcontainer:Tests\bin\Debug\Tests.dll
</code></pre>
<p>However, as far as I know, Hudson does not support analysis of MS Test results, yet. Does anyone know whether the TRX files generated by <code>MSTest.exe</code> can be transformed to the <a href="http://www.junit.org/" rel="noreferrer">JUnit</a> or <a href="http://www.nunit.org/" rel="noreferrer">NUnit</a> result format (because those are supported by Hudson), or whether there is any other way to integrate MS Test unit tests with Hudson?</p>
|
<p>Hudson has a new plugin for MSTest. Just specify the location of the .trx file and the work is done for you. It wouldn't surprise me if the plugin used Allen's solution.</p>
|
<p>Hudson has a <a href="http://hudson.gotdns.com/wiki/display/HUDSON/Plot+Plugin" rel="nofollow noreferrer">Plot Plugin</a> which can be used to plot generic data. It's not the easiest plugin to configure and use if you have multiple data points per graph, but if you can parse your MS Test output and generate input files for the plugin, you can at the very least plot the trends of failed, successful, and total tests.</p>
| 45,938
|
<p>I'm using Visual Studio 2008 for an ASP .Net application, and Visual Studio keeps adding blank lines to my aspx file whenever I save, switch to design mode and back to code view, switch to split mode, or switch between files. Before I save, I will have:</p>
<pre><code> </ContentTemplate></asp:UpdatePanel>
</ContentTemplate>
</ajax:TabPanel>
</ajax:TabContainer>
</code></pre>
<p>Then, it will magically transform into:</p>
<pre><code> </ContentTemplate></asp:UpdatePanel>
</ContentTemplate>
</ajax:TabPanel>
</ajax:TabContainer>
</code></pre>
<p>I know it's mostly an aesthetics issue, but it's also adding 17 lines of nothing to each tab container (and making the file that much longer to scroll through) and it's very annoying. I've checked that I don't have a misplaced quotation mark, there's no misaligned tags earlier in the file, any ideas?</p>
|
<p>The only time I've seen Visual Studio do something close to this is when the XML/HTML in question is invalid, for example you are missing a closing tag somewhere.</p>
|
<p>I can't say I've ever experience this with any Visual Studio yet, but try this</p>
<p><strong>Ctrl-E, D</strong> command will automatically reformat the document. (Assuming C# Development Enviroment)</p>
<p><strong>Ctrl-K, Ctrl-D</strong> for Web Development Enviroment</p>
<p>If the document remains as it is with the incorrect spacing then the auto format is the problem. Simple disable the auto-format inside <strong>Options</strong>-><strong>Text Editors</strong>-><strong>HTML</strong>-><strong>Formatting</strong></p>
| 10,338
|
<p>I need to convert a bunch of files to utf-8 in Python, and I have trouble with the "converting the file" part.</p>
<p>I'd like to do the equivalent of:</p>
<pre><code>iconv -t utf-8 $file > converted/$file # this is shell code
</code></pre>
<p>Thanks!</p>
|
<p>You can use the <a href="https://docs.python.org/2/library/codecs.html" rel="noreferrer">codecs module</a>, like this:</p>
<pre><code>import codecs
BLOCKSIZE = 1048576 # or some other, desired size in bytes
with codecs.open(sourceFileName, "r", "your-source-encoding") as sourceFile:
with codecs.open(targetFileName, "w", "utf-8") as targetFile:
while True:
contents = sourceFile.read(BLOCKSIZE)
if not contents:
break
targetFile.write(contents)
</code></pre>
<p><strong>EDIT</strong>: added <code>BLOCKSIZE</code> parameter to control file chunk size.</p>
|
<p>This is my brute force method. It also takes care of mingled \n and \r\n in the input.</p>
<pre><code> # open the CSV file
inputfile = open(filelocation, 'rb')
outputfile = open(outputfilelocation, 'w', encoding='utf-8')
for line in inputfile:
if line[-2:] == b'\r\n' or line[-2:] == b'\n\r':
output = line[:-2].decode('utf-8', 'replace') + '\n'
elif line[-1:] == b'\r' or line[-1:] == b'\n':
output = line[:-1].decode('utf-8', 'replace') + '\n'
else:
output = line.decode('utf-8', 'replace') + '\n'
outputfile.write(output)
outputfile.close()
except BaseException as error:
cfg.log(self.outf, "Error(18): opening CSV-file " + filelocation + " failed: " + str(error))
self.loadedwitherrors = 1
return ([])
try:
# open the CSV-file of this source table
csvreader = csv.reader(open(outputfilelocation, "rU"), delimiter=delimitervalue, quoting=quotevalue, dialect=csv.excel_tab)
except BaseException as error:
cfg.log(self.outf, "Error(19): reading CSV-file " + filelocation + " failed: " + str(error))
</code></pre>
| 23,237
|
<p>I'm trying to control the main timeline of my flash application from a MovieClip that is a child of the main stage. Apparently, in ActionScript 2, you could do that using _root, but using root (since _root no longer exists) now gives an error:</p>
<pre><code>root.play();
</code></pre>
<p>"1061: Call to a possibly undefined method play through a reference with static type flash.display:DisplayObjectContainer."</p>
<p>Using the Stage class also doesn't work:</p>
<pre><code>stage.play();
</code></pre>
<p>"1061: Call to a possibly undefined method play through a reference with static type flash.display:Stage."</p>
<p>Is there any way to do this?</p>
|
<p>You need to cast it to a MovieClip</p>
<pre><code>(root as MovieClip).play()
</code></pre>
|
<p>Another way is separate your movieclip code into separate class while setting document class for your main fla.</p>
<p>Assume the document class of your main fla is Main.as and your movieclip's class file is Movie.as, you can add Main class pointer as parameter in the Movie class constructor</p>
<p>In Main.as</p>
<p><code>public class Main() {
var m = new Movie(this);
}</code></p>
<p>In Movie.as</p>
<pre><code>public class Movie(m:Main) { m.gotoAndPlay("somewhere"); }
</code></pre>
| 33,722
|
<p>If I have two UIColors, what's the best way to draw an even gradient between them over an arbitrarily-sized area?</p>
<p>I am guessing you would create a UIView subclass and use the CG drawing methods in the drawRect method. I just don't know which ones, or if there are any pitfalls to watch out for, like performance. Has anyone done this?</p>
|
<pre><code>#import <QuartzCore/QuartzCore.h>
- (void) setGradient {
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = self.view.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor whiteColor] CGColor], (id)[[UIColor blackColor] CGColor], nil];
[self.view.layer insertSublayer:gradient atIndex:0];
}
</code></pre>
<p>Don't forget to add QuartzCore library to your project.</p>
|
<p>I found that using CAGradientLayer produced a gradient with noticeable stepping
Ended up using this</p>
<blockquote>
<p><a href="http://evilrockhopper.com/tag/cggradient/" rel="nofollow noreferrer">http://evilrockhopper.com/tag/cggradient/</a></p>
</blockquote>
<p>As per this question <a href="https://stackoverflow.com/questions/422066/gradients-on-uiview-and-uilabels-on-iphone">Gradients on UIView and UILabels On iPhone</a></p>
| 28,085
|
<p>From my understanding, the power of heater must higher than heat dissipate to ambient air so the bed can heat up. The reason why a bed heats up too slowly is due to its heat capacity compared to heater power.</p>
<p>As the heater is a resistive load, I think we can put higher voltage to get more heating power.</p>
<p>The PCB heater has two parts: copper and laminate. The reason of failure is that the copper can come off the board due to high temperatures. In this case we can control temperature with firmware. The questions are:</p>
<ol>
<li>Will this method work?</li>
<li>What can go wrong or what is the risk of this method?</li>
</ol>
|
<p>Yes, this method will work. Some (LED) power supplies have a small potentiometer that you can use to slightly adjust the voltage. On a 12 V printer, adjusting the supply from 12 V to 14 V will give a 36% increase in power.</p>
<p>Obviously there is a limit to how much you can increase the voltage. The voltage itself is unlikely to be the limiting factor, but there is a limit to how much heat the bed can dissipate.</p>
<blockquote>
<p>The PCB heater have 2-part copper and laminate. the reason of failire is the copper go off the board due to high temperature. In this case we can control temperature with firmware.</p>
</blockquote>
<p>This is true, but you have to consider that firmware is not infallible. If you increase the voltage (and thus wattage) of the bed a lot, you risk creating a dangerous situation if something fails. Ideally, you should choose the wattage of the bed such that it does not create a dangerous situation even if it is left on permanently by accident. In extreme cases (e.g. 220V to a nominally 12V heated bed) damage will be almost instantaneous before the firmware can intervene.</p>
<p>You also have to consider that increasing the voltage also increases the current. The wires need to be thick enough to handle the additional current. You also have to pay special attention to the MOSFET that is used to switch the bed; it also needs to be able to handle the current (and voltage, though this is usually less of a problem). Usually the integrated MOSFETs on 3D printer control boards can only handle about ~10 A which is what the bed might normally draw. Also pay attention to fuses and to screw terminal connections. They might not be able to handle the increased current either.</p>
|
<h1>Not necessarily</h1>
<p><strong>Potential differential U</strong>, aka <em>Voltage</em> of a part, is not to be ignored: a 24 V part needs only 24 V, not 36 V. A 12 V heartbeat is only safe for 12 V. There is a little tolerance for those measurements, but rule of thumb is about 10-15% of the rated voltage, so a 12 V bed should not be operated at more than 13.8 V for an extended period.</p>
<p>What actually facilitates heating is the <strong>Current I</strong> aka <em>Amperage</em> going through an item, as the formula for the Work P<sub>h</sub> (dissipated in the shape of heat) of the electric resistance R is <span class="math-container">$P_h=R I^2$</span>.</p>
<p>As long as you stay below or at the maximum <strong>rated Power P<sub>r</sub></strong> or <em>Wattage</em> of the heating pad <span class="math-container">$P_r=U I$</span>, you can increase the Current up to the limit of <span class="math-container">$\frac {P_r} U=I$</span>. On the bench, with a regulated power supply, we can use that to get a perfect, maximum output as we want it. But the printer isn't a bench with an expensive PSU, we get only something akin to 12 V out of it, so... what to do?</p>
<h2>DON'T route in extra Power!</h2>
<p>Yea, in DC circuits we can just add batteries behind one another to get twice the Voltage and push a circuit. Or we can put them in parallel, to sum up the current. But that doesn't work just as straightforward in AC circuits (phase shift between parts has to be taken into account). And routing in an extra pair of wires providing 12 V into an already 12 V part would get us something in the order of 24 V and fry the part. You'd accomplish nothing more than turn your heated bed into a fire hazard or a hunk of scrap!</p>
<p>So straight routing in another 12 V on top of what is rated? <strong>NOPE!</strong></p>
<h2>Unhooking from the same PSU?</h2>
<p>Some printers unhook the bed from the board's PSU, running a (differently) regulated power source. In the best case, it's set up to a Voltage/Current pair that maximizes the bed's heating. In such a setup, the whole heating power runs through a MOSFET that acts as a switch: A signal comes from the board to the MOSFET to allow current to flow. No signal on the Gate of the MOSFET leads to no current reaching the bed and no heating.</p>
<p>However, that is a complicated setup - yet one of the only ways how a "mains voltage bed heater" can be done with a board that runs on 5 V. You <em>also</em> will have to route the high power through a properly rated set of wires and connectors. These thicker wires will need proper strain relief as they need larger bending radii than what is installed before. In other words: <strong>you need to know what you do!</strong></p>
<h2>Finetuning the power supply to the bed!</h2>
<p>In many printers, there's also a less invasive method to finetune the power curve of a bed. usually, there is a Potentiometer that is used to tune the output of the heating wires. Altering the potentiometer's setting with a screwdriver results in the output voltage shifting. <span class="math-container">$U=R I$</span> does not change when flipping to AC but U and I became wave functions instead of constants. However, R of a long wire (such as a bed) does depend only on the frequency of the signal and not on either the current nor the driving potential, we can assume R to be constant. So, we know we want to maximize I². So what can we do easily?</p>
<p>A 24 V heatbed has something in the order of 2 Ω and accompanied mainboard in my Ender3 is - according to the labeling - good for about 13 A on the bed output, while a typical 12 V bed runs in the order of 1.2 Ω while such boards typically are limited to 10-11 A. <span class="math-container">$U= RI$</span> to the resuce and... Voila: For the 11 A/1.2 Ω case we can tune the potentiometer to get just a smidge below 13.2 V - just at the 10 % point, for the 13 A/2 Ω case is <em>technically</em> safe at 26 V - and still well within the 10% rule of thumb. However, if you have a 1.2 Ω bed and your borard only allows to draw 10 A, then you are limited to 12 V.</p>
| 1,824
|
<p>My Windows application runs under Wine, but the installation is a bit of a headache for laymen, and the wrappers I've seen online (PlayOnLinux, Wine Doors) require even more packages to be installed. Is there a way to make a package that will install Wine if the user needs it to be installed, install the application and shortcuts, all with minimal user hassle?</p>
|
<p>I don't believe there's any pre-made way to do this, but you could probably make a Debian package pretty easily that would depend on Wine, copy an MSI onto the machine, then run Wine's <code>msiexec /i /q</code> as the post-install script</p>
<p>Edit: Make sure to think about the uninstall case too! I.e. in the pre-uninstall script, run <code>msiexec</code> again as well.</p>
|
<p>Answer is simple:</p>
<ol>
<li>Create Elf installer.</li>
<li>Pack Elf installer onto Exe installer resources.</li>
<li>Exe installer should unpack Elf installer on startup.</li>
<li>Exe installer must tries to run Elf installer after unpack (system call or some think).</li>
<li>If operation fail, we do normal install.</li>
<li>If operation didn't fail, we close Exe installer.</li>
</ol>
| 47,760
|
<p>I'm specifying my doctype as xhtml strict, but it's being sent over the wire as a content type of text/html. I'd like to specify that the content type is application/xhtml+xm, but I can't figure out where, or if, I can configure this from within my application</p>
|
<p>You can specify it in the @ page attributes section, like this:</p>
<pre><code><%@ Page ContentType="application/xhtml+xm" %>
</code></pre>
<p>...more on <a href="http://msdn.microsoft.com/en-us/library/ydy4x04a(v=vs.100).aspx" rel="noreferrer">MSDN</a>.</p>
|
<p>=========aspx===============</p>
<pre><code><%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<asp:literal runat="server" id="dt"></asp:literal>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
</code></pre>
<p>==============code behind=========</p>
<pre><code>protected void Page_Load(object sender, EventArgs e)
{
this.dt.Text= "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0
Transitional//EN\"
\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">";
}
</code></pre>
| 21,093
|
<p>I'm trying to send messages to Objective-C objects in gdb.</p>
<pre><code>(gdb) p $esi
$2 = (void *) 0x1268160
(gdb) po $esi
<NSArray: 0x1359c0>
(gdb) po [$esi count]
Target does not respond to this message selector.
</code></pre>
<p>I can't send any message to it. Am I missing something? Do I really need the symbols, or something else?</p>
|
<p>If you must override gdb and send a message to an object when it will not let you, you can use performSelector:</p>
<pre><code>(gdb) print (int)[receivedData count]
Target does not respond to this message selector.
(gdb) print (int)[receivedData performSelector:@selector(count) ]
2008-09-15 00:46:35.854 Executable[1008:20b] *** -[NSConcreteMutableData count]:
unrecognized selector sent to instance 0x105f2e0
</code></pre>
<p>If you need to pass an argument use withObject:</p>
<pre><code>(gdb) print (int)[receivedData performSelector:@selector(count) withObject:myObject ]
</code></pre>
|
<p>@[John Calsbeek]</p>
<p>Then it complains about missing symbols.</p>
<pre><code>(gdb) p (NSUInteger)[(NSObject*)$esi retainCount]
No symbol table is loaded. Use the "file" command.
(gdb) p [(NSArray *)$esi count]
No symbol "NSArray" in current context.
</code></pre>
<p>I tried to load the symbols for Foundation:</p>
<pre><code>(gdb) add-symbol-file /System/Library/Frameworks/Foundation.framework/Foundation
add symbol table from file "/System/Library/Frameworks/Foundation.framework/Foundation"? (y or n) y
Reading symbols from /System/Library/Frameworks/Foundation.framework/Foundation...done.
</code></pre>
<p>but still no luck:</p>
<pre><code>(gdb) p [(NSArray *)$esi count]
No symbol "NSArray" in current context.
</code></pre>
<p>Anyway, I don't think casting is the solution to this problem, you shouldn't have to know what kind of object it is, to be able to send messages to it.
The weird thing is that I found an NSCFArray I have no problems sending messages to:</p>
<pre><code>(gdb) p $eax
$11 = 367589056
(gdb) po $eax
<NSCFArray 0x15e8f6c0>(
file://localhost/Users/ask/Documents/composing-fractals.pdf
)
(gdb) p (int)[$eax retainCount]
$12 = 1
</code></pre>
<p>so I guess there was a problem with the object I was investigating... or something.</p>
<p>Thanks for your help!</p>
| 8,041
|
<p>What is a good way to select all or select no items in a listview without using:</p>
<pre><code>foreach (ListViewItem item in listView1.Items)
{
item.Selected = true;
}
</code></pre>
<p>or</p>
<pre><code>foreach (ListViewItem item in listView1.Items)
{
item.Selected = false;
}
</code></pre>
<p>I know the underlying Win32 listview common control supports <a href="http://msdn.microsoft.com/en-us/library/bb761196(VS.85).aspx" rel="nofollow noreferrer">LVM_SETITEMSTATE message</a> which you can use to set the selected state, and by passing -1 as the index it will apply to all items. I'd rather not be PInvoking messages to the control that happens to be behind the .NET Listview control (I don't want to be a bad developer and rely on undocumented behavior - for when they change it to a fully managed ListView class)</p>
<h2>Bump</h2>
<p><a href="https://stackoverflow.com/questions/87101/how-to-selectall-selectnone-in-net-2-0-listview/87209#87209">Pseudo Masochist</a> has the <strong>SelectNone</strong> case:</p>
<pre><code>ListView1.SelectedItems.Clear();
</code></pre>
<p>Now just need the <strong>SelectAll</strong> code</p>
|
<p>EASTL is a possibility, but still not perfect. Paul Pedriana of Electronic Arts did an investigation of various STL implementations with respect to performance in game applications the summary of which is found here:
<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2271.html" rel="noreferrer">http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2271.html</a></p>
<p>Some of these adjustments to are being reviewed for inclusion in the C++ standard.</p>
<p>And note, even EASTL doesn't optimize for the non-optimized case. I had an excel file w/ some timing a while back but I think I've lost it, but for access it was something like:</p>
<pre><code> debug release
STL 100 10
EASTL 10 3
array[i] 3 1
</code></pre>
<p>The most success I've had was rolling my own containers. You can get those down to near array[x] performance.</p>
|
<p>STL containers should not run "really slowly" in debug or anywhere else. Perhaps you're misusing them. You're not running against something like ElectricFence or Valgrind in debug are you? They slow anything down that does lots of allocations.</p>
<p>All the containers can use custom allocators, which some people use to improve performance - but I've never needed to use them myself.</p>
| 11,260
|
<p>When prototyping initial GUI functionality with a customer is it better to use a pen/paper drawing or to mock something up using a tool and show them that ?</p>
<p>The argument against a tool generated design being that the customer can sometimes focus on the low-level specifics of the mock-up rather than taking a higher level functional view of the GUI overall.</p>
|
<p>Always start with paper or paper-like mock-ups first. You do not want to fall into a trap of giving the impression of completeness when the back-end is completely hollow.</p>
<p>A polished prototype or pixel-perfect example puts too much emphasis on the design. With an obvious sketch, you have a better shot of discussing desired functionality and content rather than colors, photos, and other stylistic matters. There will be time for that discussion later in the project.</p>
<p>Jeff discusses paper prototyping in his Coding Horror article <a href="http://www.codinghorror.com/blog/archives/001091.html" rel="noreferrer">UI-First Software Development</a></p>
<p>Click the "Watch a video!" link at <a href="http://twitter.com/" rel="noreferrer">twitter.com</a> to see an interesting take on the idea from <a href="http://www.commoncraft.com/" rel="noreferrer">Common Craft</a>.</p>
|
<p>You can try out <a href="http://www.foreui.com/" rel="nofollow noreferrer">ForeUI</a>, it allow prototyping with different styles, what's more, it can make interactive prototype and run it in browser.</p>
| 2,580
|
<p>Is it okay to run Hibernate applications configured with <code>hbm2ddl.auto=update</code> to update the database schema in a production environment?</p>
|
<p>No, it's unsafe.</p>
<p>Despite the best efforts of the Hibernate team, you simply cannot rely on automatic updates <strong>in production</strong>. Write your own patches, review them with DBA, test them, then apply them manually.</p>
<p>Theoretically, if <strong>hbm2ddl update</strong> worked in development, it should work in production too. But in reality, it's not always the case. </p>
<p>Even if it worked OK, it may be sub-optimal. DBAs are paid that much for a reason.</p>
|
<p>I agree with Vladimir. The administrators in my company would definitely not appreciate it if I even suggested such a course.</p>
<p>Further, creating an SQL script in stead of blindly trusting Hibernate gives you the opportunity to remove fields which are no longer in use. Hibernate does not do that.</p>
<p>And I find comparing the production schema with the new schema gives you even better insight to wat you changed in the data model. You know, of course, because you made it, but now you see all the changes in one go. Even the ones which make you go like "What the heck?!".</p>
<p>There are tools which can make a schema delta for you, so it isn't even hard work. And then you know exactly what's going to happen.</p>
| 27,282
|
<pre><code>SELECT NR_DZIALU, COUNT (NR_DZIALU) AS LICZ_PRAC_DZIALU
FROM PRACOWNICY
GROUP BY NR_DZIALU
HAVING NR_DZIALU = 30
</code></pre>
<p>or</p>
<pre><code>SELECT NR_DZIALU, COUNT (NR_DZIALU) AS LICZ_PRAC_DZIALU
FROM PRACOWNICY
WHERE NR_DZIALU = 30
GROUP BY NR_DZIALU
</code></pre>
|
<p>The theory (by theory I mean <a href="http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt" rel="noreferrer">SQL Standard</a>) says that WHERE restricts the result set before returning rows and HAVING restricts the result set after bringing all the rows. So WHERE is faster. On SQL Standard compliant DBMSs in this regard, only use HAVING where you cannot put the condition on a WHERE (like computed columns in some RDBMSs.)</p>
<p>You can just see the execution plan for both and check for yourself, nothing will beat that (measurement for your specific query in your specific environment with your data.)</p>
|
<p>Both the statements will be having same performance as SQL Server is smart enough to parse both the same statements into a similar plan.</p>
<p>So, it does not matter if you use WHERE or HAVING in your query.</p>
<p>But, ideally you should use WHERE clause syntactically.</p>
| 42,579
|
<p>Came across this:</p>
<p><a href="http://www.eggheadcafe.com/articles/adonet_source_code_generator.asp" rel="nofollow noreferrer">http://www.eggheadcafe.com/articles/adonet_source_code_generator.asp</a></p>
<p>And wondering if this is the right solution as I am not that big of a fan of creating a class for every stored procedure or do I use Enterprise Library for ASP.net 2.0 project.</p>
|
<p>You definitely shouldn't be creating a class for every stored procedure. There are a number of approaches you can take to handling your database interactions. You should have a good look at the major frameworks out there and decide which one best suits you. The Castle Project solution is great, and relies on nHibernate (<a href="http://www.hibernate.org/343.html" rel="nofollow noreferrer">nHibernate</a>). LINQ is a similar offering by Mircrosoft (<a href="http://msdn.microsoft.com/en-us/netframework/aa904594.aspx" rel="nofollow noreferrer">LINQ Project</a>). Both of these solutions are full ORM frameworks (Object Relational Mapping) and will generate dynamic SQL to persist your objects in the database. Each also has it's own quirks and likes you to structure your objects in particular ways. If you don't want to manage the SQL your system uses, I would definitely recommend one of these approaches.</p>
<p>I come from a database background, and prefer a bit more control over my SQL. In particular I like to have my interractions handled by stored procedures. I find this enables me to control both the SQL better for optimisation, but helps me manage database security in a more friendly manner. To accommodate this approach, I recommend something like iBatis (<a href="http://ibatis.apache.org/" rel="nofollow noreferrer">iBatis</a>). iBatis isn't a full ORM, but rather a simple SQL mapper. The downside to my approach is that you need to write a lot more code (SQL), but I don't mind the trade-off.</p>
|
<p>Is there any possibility of upgrading to framework 3.5? if so take a look at LINQ to SQL and Entity Framework as this will accomplish alot of this for you. </p>
<p>If not then as long as it generates standard code that doesnt tie you into 3rd party libraries then you could certainly use it. At my workplace we have our own generator similar to this and it works well although we will shortly be moving to LINQ to SQL. </p>
| 27,078
|
<p>I'm trying add a tab to my web page that looks like this: <img src="https://i.stack.imgur.com/DT3e7.png" alt="alt text"></p>
<p>Using <a href="http://mattberseth.com/blog/2007/09/using_css_image_sprites_with_t.html" rel="nofollow noreferrer">this example</a> as a basis, I've gotten it partially working. My case differs because I want the text section to be a fixed with, but the tail section to dynamically resize to take up the rest of the tab's container.</p>
<p>It looks good in IE 6, but doesn't really take up the full width of the container.
In Firefox 3 it doesn't render well at all:<img src="https://i.stack.imgur.com/Zeypv.png" alt="alt text"> (the red is a blank area between the spans).</p>
<p>How do I get this to render properly in both IE6 and Firefox to take up the full width specified for #Tab? #Tab4 is the area I'd like to size to take up as much room as possible.</p>
<pre><code> <style type="text/css">
#Tab
{
width: 300px;
}
#Tab1
{
background: #000 url(BlueTabSprite.png) no-repeat 0 -136px;
display: inline-block;
height: 23px;
padding-left: 4px;
}
#Tab2
{
background: #000 url(BlueTabSprite.png) repeat-x 0 -242px;
display: inline-block;
overflow: hidden;
padding-top: 4px;
height: 19px;
width: 100px;
}
#Tab3
{
background: #000 url(BlueTabSprite.png) no-repeat right -30px;
display: inline-block;
height: 23px;
padding-right: 6px;
}
#Tab4
{
background: #000 url(BlueTabSprite.png) repeat-x 0 -83px;
display: inline-block;
height: 23px;
width:60%
}
#Tab5
{
background: #000 url(BlueTabSprite.png) no-repeat right -189px;
display: inline-block;
height: 23px;
padding-right:6px;
}
</style>
<div id="Tab">
<span id="Tab1">
<span id="Tab3">
<span id="Tab2">Test Tab</span>
</span>
</span>
<span id="Tab5">
<span id="Tab4"></span>
</span>
</div>
</code></pre>
|
<p>I think the <a href="http://alistapart.com/articles/slidingdoors/" rel="nofollow noreferrer">Sliding Doors Technique</a> may be what you're looking for.</p>
|
<p>This <a href="http://www.pagecolumn.com/tool/top_tabs_generator.htm" rel="nofollow noreferrer">tool</a> may be a help.</p>
| 21,181
|
<p>What is a tool or technique that can be used to perform spell checks upon a whole source code base and its associated resource files?</p>
<p>The spell check should be <em>source code aware</em> meaning that it would stick to checking string literals in the code and not the code itself. Bonus points if the spell checker understands common resource file formats, for example text files containing name-value pairs (only check the values). Super-bonus points if you can tell it which parts of an XML DTD or Schema should be checked and which should be ignored.</p>
<p>Many IDEs can do this for the file you are currently working with. The difference in what I am looking for is something that can operate upon a whole source code base at once.</p>
<p>Something like a Findbugs or PMD type tool for mis-spellings would be ideal.</p>
|
<p>Set the existing TotalLogins property as either private or protected and remove the readonly attribute. You may also want to rename it e.g. InternalTotalLogins.</p>
<p>Then create a new property by hand in the partial class that exposes it publically as a read-only property:</p>
<pre><code>Public ReadOnly Property TotalLogins() As System.Nullable(Of Integer)
Get
Return Me.InternalTotalLogins
End Get
End Property
</code></pre>
|
<pre><code>Make a second property that is protected or internal(?)
<Column(Name:="totalLogins", Storage:="_TotalLogins", DbType:="Int", UpdateCheck:=UpdateCheck.Never)> _
protected Property TotalLogins2() As System.Nullable(Of Integer)
Get
Return Me._TotalLogins
End Get
Set(byval value as System.Nullable(Of Integer))
Return Me._TotalLogins
End Get
End Property
</code></pre>
<p>and then update that . I think it won't save readonly properties by default. And why should it anyway. I now it's a hack but hey that's life.</p>
| 12,096
|
<p>I'm dealing with an issue with my current employer that has seriously made me consider seeking employment elsewhere. They are under the impression that 100% of custom development should be eliminated and replaced with COTS products, such as SharePoint. While I realize that this is not a realistic expectation, I've found it impossible to argue my points with the people in management that share these views. Their argument usually involves something along the lines of a feature already existing in SharePoint that covers feature X, therefore there is less risk involved and testing doesn't have to be done against it.</p>
<p>Case in point, we have a situation where a SharePoint list is completely <strong>incapable</strong> of meeting customer expectations and requirements. Saving this data in a SQL database, however, would easily satisfy the requirements. Any time our development team suggests going outside of the boundaries of SharePoint, however, management goes up in flames about how every line of code adds to the complexity of the project and increases risk. While this is certainly true in some situations, it's not always the case. Their argument, however, is that since SharePoint provides a mechanism for storing data, that we should use it 100% of the time. Regardless of if it meets customer requirements, or not.</p>
<p>I've gotten to the point that I hate coming to work because I'm constantly forced into doing things that I know (with 100% certainty) are not right and that could be made right by doing custom development. It's simply what seems to be an impossible argument where I work, however.</p>
<p>Have any of you experienced a similar situation? If so, what have you done to work through these challenges?</p>
|
<p>If you don't share the vision of the company and if you can't enlighten them then sure, it is a good time to start looking.</p>
<p>Have you pointed out that there is risk in forcing a "solution" on a client that does not help them or is missing functionality or is unusable? </p>
<p>Perhaps come up with plans to address and mitigate their perceived risks. </p>
|
<p>how about not calling it custom code. If instead you call it 'anticipated SharePoint user extensions' or something it may soften the misconception surrounding a specific term.</p>
<p>also, as has been said, there may be other hidden from you reasons that management is pushing this agenda. It is probably best to not second guess these too quickly, as many would be valid.</p>
<p>Finally, there are alot of places that need development. it doesnt hurt to look for a better match.</p>
<p>good luck.</p>
| 43,982
|
<p>I have a problem with time<br>
My server is in the USA and I'm in Denmark (Europa) and I would like to have my site show the time in my local time. How can I do that?</p>
<p>I try this </p>
<pre><code>Datetime localtime = DateTimeOffset.Now.ToOffset(new TimeSpan(1,0,0)).DateTime;
</code></pre>
<p>and it works, but it will only work when I'm in GMT+1 / UTC+1 and not when I'm in GMT+2 / UTC+2.
Is there another way of doing this - a simpler way of doing it?</p>
|
<p>The only way you should do it is as follows:</p>
<pre><code>string zoneId = "Central European Standard Time";
TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById(zoneId);
DateTime result = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow,tzi);
Console.WriteLine("Time is " + result + " in Denmark");
</code></pre>
<p>Using the TimeZoneInfo class is the only reliable way in .Net to convert to/from different timezones AND get proper DST conversions.</p>
<p><code>TimeZoneInfo.ConvertTimeToUtc(dtLocal,tzi)</code> is the reverse converting from a local time to a utc time.</p>
<hr>
<p>For the TimeZone Id strings, you can run the bit of code here...</p>
<pre><code>foreach( var tz in TimeZoneInfo.GetSystemTimeZones() )
{
Console.WriteLine(tz.DisplayName + " is Id=','" + tz.Id + "'");
}
</code></pre>
|
<p>You can get the time off the server and do this.</p>
<pre><code>DateTime myTimeGMT = ServerTime.ToUniversalTime();
</code></pre>
<p>This do this:</p>
<pre><code>DateTime myTimeLocal = myTimeGMT.ToLocalTime();
</code></pre>
<p>The only restriction here is the computer you are on must be set to the time zone you are converting to.</p>
<p>In my experience, .NET has trouble converting between timezones when neither the 'From' time or the 'To' time are the local time zone.</p>
<p>I hope this helps.</p>
| 41,290
|
<p>I am using LINQ to query a generic dictionary and then use the result as the datasource for my ListView (WebForms).</p>
<p>Simplified code:</p>
<pre><code>Dictionary<Guid, Record> dict = GetAllRecords();
myListView.DataSource = dict.Values.Where(rec => rec.Name == "foo");
myListView.DataBind();
</code></pre>
<p>I thought that would work but in fact it throws a <strong>System.InvalidOperationException</strong>: </p>
<blockquote>
<p>ListView with id 'myListView' must
have a data source that either
implements ICollection or can perform
data source paging if AllowPaging is
true.</p>
</blockquote>
<p>In order to get it working I have had to resort to the following:</p>
<pre><code>Dictionary<Guid, Record> dict = GetAllRecords();
List<Record> searchResults = new List<Record>();
var matches = dict.Values.Where(rec => rec.Name == "foo");
foreach (Record rec in matches)
searchResults.Add(rec);
myListView.DataSource = searchResults;
myListView.DataBind();
</code></pre>
<p>Is there a small gotcha in the first example to make it work?</p>
<p>(Wasn't sure what to use as the question title for this one, feel free to edit to something more appropriate)</p>
|
<p>Try this:</p>
<pre><code>var matches = dict.Values.Where(rec => rec.Name == "foo").ToList();
</code></pre>
<p>Be aware that that will essentially be creating a new list from the original Values collection, and so any changes to your dictionary won't automatically be reflected in your bound control.</p>
|
<p>Just adding knowledge the next sentence doesn´t recover any data from de db. Just only create the query (for that it is iqueryable type). For launching this query you must to add .ToList() or .First() at the end.</p>
<pre><code>dict.Values.Where(rec => rec.Name == "foo")
</code></pre>
| 5,164
|
<p>How can I make a style have all of the properties of the style defined in <code>.a .b .c</code> except for <code>background-color</code> (or some other property)? This does not seem to work.</p>
<pre><code>.a .b .c
{
background-color: #0000FF;
color: #ffffff;
border: 1px solid #c0c0c0;
margin-top: 4px;
padding: 3px;
text-align: center;
font-weight: bold;
}
.a .b .c .d
{
background-color: green;
}
</code></pre>
|
<pre><code>.a, .b, .c {color: #ffffff; border: 1px solid #c0c0c0; margin-top: 4px; padding: 3px; text-align: center; font-weight: bold; }
.a {background-color: red;}
.b {background-color: blue;}
.c {background-color: green;}
</code></pre>
|
<p>I think you're thinking about this a little backwards, so let's try to sort out the language your are using. </p>
<pre><code>.a .b .c{
background-color: #0000FF;
color: #ffffff;
}
</code></pre>
<p>Looking at the above CSS, the ".a .b .c" part is the <strong>selector</strong>, and the part between the braces is the style. That selector says 'find me all of the elements with a class with "c" who are inside of elements that have a class of "b" who are inside of elements with a class "a", and apply these styles to them' -- it's a rule the says which elements on the page will get the look you want. </p>
<p>More than one selector can match the same element on the page, and there are rules for what order they are applied to the element (<a href="http://www.w3.org/TR/CSS2/cascade.html" rel="nofollow noreferrer">http://www.w3.org/TR/CSS2/cascade.html</a>). The simple rule is that more "Specific" selectors override less "specific" selectors. "div.blueBanner p a:hover.highlight" is much more "specific" than ".blueBanner". If two rules have the same specificity, then the one that comes later in the CSS file overrides. </p>
<p>html sample:</p>
<pre><code><div class="a">
<div class="b">
<div class="c">foo</div>
<div class="c d">bar</div>
</div>
</div>
</code></pre>
<p>So, you have a selector ".a .b .c" (as you listed above) and two elements (foo and bar) on the page match that selector, so they all get the background color and all the other styles you defined.</p>
<p>Now, you also want the second element to have a green background color. It has another class assigned to it "d", so you can just define another selector which matches only that second element ".a .b .d" and set's it's background-color. The "bar" element still gets all the other styles from the ".a .b .c" selector (font, color, etc), but the background color from ".a .b .d".</p>
| 13,551
|
<p>I am learning Python for a class now, and we just covered tuples as one of the data types. I read the Wikipedia page on it, but, I could not figure out where such a data type would be useful in practice. Can I have some examples, perhaps in Python, where an immutable set of numbers would be needed? How is this different from a list?</p>
|
<ul>
<li>Tuples are used whenever you want to return multiple results from a function.</li>
<li>Since they're immutable, they can be used as keys for a dictionary (lists can't).</li>
</ul>
|
<p>In addition to the places where they're syntactically required like the string % operation and for multiple return values, I use tuples as a form of lightweight classes. For example, suppose you have an object that passes out an opaque cookie to a caller from one method which is then passed into another method. A tuple is a good way to pack multiple values into that cookie without having to define a separate class to contain them.</p>
<p>I try to be judicious about this particular use, though. If the cookies are used liberally throughout the code, it's better to create a class because it helps document their use. If they are only used in one place (e.g. one pair of methods) then I might use a tuple. In any case, because it's Python you can start with a tuple and then change it to an instance of a custom class without having to change any code in the caller.</p>
| 6,344
|
<p>I've been using Linq to SQL for some time now and I find it to be really helpful and easy to use. With other ORM tools I've used in the past, the entity object filled from the database normally has a property indicating the length of the underlying data column in the database. This is helpful in databinding situations where you can set the MaxLength property on a textbox, for example, to limit the length of input entered by the user.</p>
<p>I cannot find a way using Linq to SQL to obtain the length of an underlying data column. Does anyone know of a way to do this? Help please.</p>
|
<p>Using the LINQ ColumnAttribute to Get Field Lengths from your Database :</p>
<p><a href="http://www.codeproject.com/KB/cs/LinqColumnAttributeTricks.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/cs/LinqColumnAttributeTricks.aspx</a></p>
|
<p>If you need to know the exact column length you can resort to the System.Data classes themselves. Something a bit like this:</p>
<pre><code>var context = new DataContextFromSomewhere();
var connection = context.Connection;
var command = connection.CreateCommand( "SELECT TOP 1 * FROM TableImInterestedIn" );
var reader = command.ExecuteReader();
var table = reader.GetSchemaTable();
foreach( var column in table.Columns )
{
Console.WriteLine( "Length: {0}", column.MaxLength );
}
</code></pre>
| 4,101
|
<p>Today I was printing some parts and I got these burn marks at the corners:</p>
<p><a href="https://i.stack.imgur.com/D8b3n.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/D8b3n.jpg" alt="1"></a></p>
<p>This is the first time I see this on this printer (Anycubic I3 Mega). I was using more or less the same settings (in Cura) as always, although I was using a new roll of PLA from a brand I haven't used before.</p>
<p>I was printing several parts in one job:</p>
<p><a href="https://i.stack.imgur.com/p56Kp.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/p56Kp.jpg" alt="2"></a></p>
<p>Most of them are somewhat affected:</p>
<p><a href="https://i.stack.imgur.com/8MqTq.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8MqTq.jpg" alt="3"></a></p>
<pre><code>Printing temperature: 200 °C
Build Plate Temperature: 60 °C
Printing Speed: 60 mm/s
Travel speed: 200 mm/s
</code></pre>
|
<p>In addition to <a href="https://3dprinting.stackexchange.com/a/7933/5740">this answer</a> which addresses <strong><em>what</em></strong> is actually the cause (<em>but doesn't explain where the burnt corners come from</em>), I've added some information <strong><em>why</em></strong> this is showing burnt corners.</p>
<p>You are printing PLA at a too high of a temperature and do not have sufficient print part cooling enabled (either in the slicer or limited by the fan duct design). The <strong><em>higher the temperature the larger the shrinkage</em></strong> of the filament is. When printing overhangs like the slanted models you print, the last deposited layer has less surface contact area with the previous layer and therefore the shrink stresses may overcome the adhering stresses (it is also more easily weakened by the heat input of the last layer). This results in curling up, especially in corners as the heat input comes from two sides. When the corners curl up, the change of hitting the sides of the nozzle increases. When the outside of the nozzle is covered in burnt filament, the curling corners may pick that up. This results as if the corners are actually burnt.</p>
|
<p>Could be a dirty nozzle and temperature too high. When the head changes direction on the corner, the nozzle wipes off burnt PLA. This might explain why there are no dark marks on the long runs and only the corners.</p>
<p>Heat nozzle up and clean with acetone and then see if the problem persists.</p>
| 1,175
|
<p>I'm working on an application developed by another mob and am confounded by the use of a char field instead of bit for all the boolean columns in the database. It uses "Y" for true and "N" for false (these have to be uppercase). The type name itself is then aliased with some obscure name like <em>ybln</em>.</p>
<p>This is very annoying to work with for a lot of reasons, not the least of which is that it just looks downright aesthetically unpleasing.</p>
<p>But maybe its me that's stupid - why would anyone do this? Is it a database compatibility issue or some design pattern that I am not aware of?</p>
<p>Can anyone enlighten me?</p>
|
<p>I've seen this practice in older database schemas quite often. One advantage I've seen is that using CHAR(1) fields provides support for more than Y/N options, like "Yes", "No", "Maybe".</p>
<p>Other posters have mentioned that Oracle might have been used. The schema I referred to was in-fact deployed on Oracle and SQL Server. It limited the usage of data types to a common subset available on both platforms.</p>
<p>They did diverge in a few places between Oracle and SQL Server but for the most part they used a common schema between the databases to minimize the development work needed to support both DBs.</p>
|
<p>They probably were used to using Oracle and didn't properly read up on the available datatypes for SQL Server. I'm in exactly that situation myself (and the Y/N field is driving me nuts).</p>
| 32,019
|
<p>I have been playing around with creating scripts to generate some custom G-code for a Malyan M180 and I am having trouble understand what commands to use to switch nozzles. Sometimes I can get the nozzles to switch and it doesn't recenter but sometimes it does.
I have been using:</p>
<pre><code>G54
M108 T0; switch to left
</code></pre>
<p>and</p>
<pre><code>G55
M108 T1; switch to right
</code></pre>
<p>Has anyone else looked into this and have any idea what commands or sequence of commands should be used to change nozzles?</p>
|
<p>No, M108 does not do that. You are looking for <strong>T#</strong>, where # is the tool position you want:</p>
<pre><code>T1 ; switch to tool position 1
T3 ; switch to tool position 3
</code></pre>
<p>This tells the processor to send all heating, cooling and flow commands to this tool until another tool change is specified, and invokes the X/Y(/Z) offset for the new tool position.</p>
<p>See <a href="http://reprap.org/wiki/G-code#T:_Select_Tool" rel="nofollow noreferrer">http://reprap.org/wiki/G-code#T:_Select_Tool</a></p>
|
<p>As @tbm0115 has mentioned - it differs. Your <code>M108 T{index of tool}</code> command is perfectly fine on some FlashForge printers, a company known for its different sorts of proprietary code. It is indeed used for tool changing here.</p>
<p>While on the common Marlin firmware (e.g. used on the popular Creality Ender printers), <code>M108</code> does a completely different thing-namely acting as a break sequence if the G-code parser is in a closed-loop-condition (after certain commands like <code>M109</code> that wait until a certain action takes place).</p>
| 538
|
<p>I just learned about the C++ construct called "placement new". It allows you to exactly control where a pointer points to in memory. It looks like this:</p>
<pre><code> #include <new> // Must #include this to use "placement new"
#include "Fred.h" // Declaration of class Fred
void someCode()
{
char memory[sizeof(Fred)];
void* place = memory;
Fred* f = new(place) Fred(); // Create a pointer to a Fred(),
// stored at "place"
// The pointers f and place will be equal
...
}
</code></pre>
<p>(example from <a href="http://www.parashift.com/c++-faq-lite/dtors.html#faq-11.10" rel="noreferrer" title="C++ FAQ Lite">C++ FAQ Lite</a>)<br><br>
In this example, the <code>this</code> pointer of Fred will be equal to <code>place</code>.</p>
<hr>
<p>I've seen it used in our team's code once or twice. In your experience, what does this construct enable? Do other pointer languages have similar constructs? To me, it seems reminiscent of <code>equivalence</code> in FORTRAN, which allows disparate variables to occupy the same location in memory.</p>
|
<p>It is also used for embedded programming, where IO devices are often mapped to specific memory addresses</p>
|
<p>seems to me like a way of allocating an object on the stack .. </p>
| 47,375
|
<p>I would like to make my Java/Swing application compatible with the Services-menu available on Mac OS X. For example, so that the user could select some text in JTextArea and have it converted into speech by <strong>Services -> Speech -> Start Speaking Text</strong>.
Is there a simple way to achieve that?
(The application should still be able to run on platforms other than Mac OS X.)</p>
|
<p>Have a look at apple's <a href="https://developer.apple.com/samplecode/OSXAdapter/index.html" rel="nofollow noreferrer">OSXAdapter package</a> (link requires free apple developer login) for java development. The samples included in the package shows you how to integrate nicely to the OS X application menu in a way that is only activated when your application is running under OS X.</p>
|
<p>If all you want is the end result of the text being converted to speech, you could try invoking the "<strong>say</strong>" command using ProcessBuilder, something like this:</p>
<pre><code>String stuffYouWantToSay = "StackOverflow Rocks!";
Process p = null;
try {
ProcessBuilder pb = new ProcessBuilder("/usr/bin/say", stuffYouWantToSay);
p = pb.start();
} catch (Exception e) {
// handle the error
return;
}
</code></pre>
<p>This won't add it to the services menu, but you can still get the same effect.</p>
<p>Be sure to check out the man page for "say" as you can change the voice.</p>
| 33,451
|
<p>I cannot use the Resource File API from within a file system plugin due to a PlatSec issue:</p>
<pre><code>*PlatSec* ERROR - Capability check failed - Can't load filesystemplugin.PXT because it links to bafl.dll which has the following capabilities missing: TCB
</code></pre>
<p>My understanding of the issue is that:</p>
<p>File system plugins are dlls which are executed within the context of the file system process. Therefore all file system plugins must have the <code>TCB</code> PlatSec privilege which in turn means they cannot link against a dll that is not in the <code>TCB</code>.</p>
<p>Is there a way around this (without resorting to a text file or an intermediate server)? I suspect not - but it would be good to get a definitive answer.</p>
|
<p>The Symbian file server has the following capabilities:</p>
<pre><code>TCB ProtServ DiskAdmin AllFiles PowerMgmt CommDD
</code></pre>
<p>So any DLL being loaded into the file server process must have at least these capabilities. There is no way around this, short of writing a new proxy process as you allude to.</p>
<p>However, there is a more fundamental reason why you shouldn't be using <code>bafl.dll</code> from within a fileserver plugin: this DLL provides utility functions which interface to the file servers client API. Attempting to use it from within the filer server will not work; at best, it will lead to the file server deadlocking as it attempts to connect to itself.</p>
<p>I'd suggest rethinking that you're trying to do, and investigating an internal file-server API to achieve it instead.</p>
|
<p>Tell us what kind of data you are storing in the resource file.</p>
<p>Things that usually go into resource files have no place in a file server plugin, even that means hardcoding a few values.</p>
<p>Technically, you can send data to a file server plugin using RFile.Write() but that's not a great solution (intercept RFile.Open("invalid file name that only your plugin understands") in the plugin).
EDIT: Someone indicated that using an invalid file name will not let you send data to the plugin. hey, I didn't like that solution either. for the sake of completness, I should clarify. make up a filename that looks OK enough to go through to your plugin. like using a drive letter that doesn't have a real drive attached to it (but will still be considered correct by filename-parsing code).</p>
<p>Writing code to parse the resource file binary in the plugin, while theoratically possible, isn't a great solution either.</p>
| 11,911
|
<p>I have the following class:</p>
<pre><code>public abstract class AbstractParent {
static String method() {
return "OriginalOutput";
}
}
</code></pre>
<p>I want to mock this method. I decide to use <a href="http://jmockit.dev.java.net" rel="noreferrer">JMockit</a>. So I create a mock class:</p>
<pre><code>public class MockParent {
static String method() {
return "MOCK";
}
}
</code></pre>
<p>And my test code looks like this:</p>
<pre><code>public class RealParentTest {
@Before
public void setUp() throws Exception {
Mockit.redefineMethods( AbstractParent.class, MockParent.class );
}
@Test
public void testMethod() {
assertEquals(MockParent.method(),AbstractParent.method());
}
}
</code></pre>
<p>Unfortunately this test says that AbstractParent returns "OriginalOutput" instead of "MOCK". Any ideas why? Am I doing something wrong? I've tried declaring my mock class as abstract as well, to no avail.</p>
<p><strong>Edit</strong> Note that making the method public causes the test to run without a problem... this is weird because with JMockit you are supposed to be able to mock methods of any scope.</p>
<p><strong>Answer</strong> Only the mock method needs to be public, you can leave the original method as is.</p>
|
<p>Found the solution: you simply need to make the mock's method public (the original method can stay in its original visibility).</p>
<p>I don't know why this works while the original way doesn't (someone who does is more than welcome to chime in), but all you need to do is simply change the mock class in the example above to:</p>
<pre><code>public class MockParent {
public static String method() {
return "MOCK";
}
}
</code></pre>
|
<p>Apparently the new way to do this is to use <code>MockUp<T></code></p>
<pre><code>new MockUp<AbstractParent>(){
@Mock String method() {
return "MOCK";
}
};
assertEquals("MOCK" AbstractParent.method());
</code></pre>
<p>Another alternative is apparently to continue with something like <code>MockParent</code> with a <code>@MockClass</code> annonation. Haven't done this myself as the another inline version does the job.</p>
<p>I've implemented this in an example <a href="https://github.com/gid79/q224721-jmockit-non-public-methods" rel="nofollow">project on github</a>.</p>
| 27,774
|
<p>I have a list of States in an ItemsControl, the DataTemplate is a CheckBox. I would like to add a function to select(check) all states. However I need to loop through the CheckBoxs rather then the data items since the checked state is stored in a separate data structure then the list of states the ItemsControl's ItemSource is bound to.</p>
|
<p>Have a property in your DataObject called IsChecked and bind that to the Checkbox in DataTemplate(Default is TwoWay)</p>
|
<p>Have a property in your DataObject called IsChecked and bind that to the Checkbox in DataTemplate(Default is TwoWay)</p>
| 22,960
|
<p>How do I remove the last character of a string if it is a newline?</p>
<pre><code>"abc\n" --> "abc"
</code></pre>
|
<p>Try the method <code>rstrip()</code> (see doc <a href="http://docs.python.org/2/library/stdtypes.html#str.rstrip" rel="noreferrer">Python 2</a> and <a href="https://docs.python.org/3/library/stdtypes.html#str.rstrip" rel="noreferrer">Python 3</a>)</p>
<pre><code>>>> 'test string\n'.rstrip()
'test string'
</code></pre>
<p>Python's <code>rstrip()</code> method strips <em>all</em> kinds of trailing whitespace by default, not just one newline as Perl does with <a href="http://perldoc.perl.org/functions/chomp.html" rel="noreferrer"><code>chomp</code></a>.</p>
<pre><code>>>> 'test string \n \r\n\n\r \n\n'.rstrip()
'test string'
</code></pre>
<p>To strip only newlines:</p>
<pre><code>>>> 'test string \n \r\n\n\r \n\n'.rstrip('\n')
'test string \n \r\n\n\r '
</code></pre>
<p>In addition to <code>rstrip()</code>, there are also the methods <code>strip()</code> and <code>lstrip()</code>. Here is an example with the three of them:</p>
<pre><code>>>> s = " \n\r\n \n abc def \n\r\n \n "
>>> s.strip()
'abc def'
>>> s.lstrip()
'abc def \n\r\n \n '
>>> s.rstrip()
' \n\r\n \n abc def'
</code></pre>
|
<p>A catch all:</p>
<pre><code>line = line.rstrip('\r|\n')
</code></pre>
| 34,655
|
<p>How do I force Python's <code>print</code> function to flush the buffered output to the screen?</p>
|
<p>In Python 3, <a href="https://docs.python.org/library/functions.html#print" rel="noreferrer"><code>print</code></a> can take an optional <code>flush</code> argument:</p>
<pre><code>print("Hello, World!", flush=True)
</code></pre>
<p>In Python 2, after calling <code>print</code>, do:</p>
<pre><code>import sys
sys.stdout.flush()
</code></pre>
<p>By default, <a href="https://docs.python.org/2/reference/simple_stmts.html#the-print-statement" rel="noreferrer"><code>print</code></a> prints to <a href="https://docs.python.org/2/library/sys.html#sys.stdout" rel="noreferrer"><code>sys.stdout</code></a> (see the documentation for more about <a href="https://docs.python.org/2/library/stdtypes.html#file-objects" rel="noreferrer">file objects</a>).</p>
|
<p>I did it like this in Python 3.4:</p>
<pre><code>'''To write to screen in real-time'''
message = lambda x: print(x, flush=True, end="")
message('I am flushing out now...')
</code></pre>
| 28,564
|
<p>Using <code>add(new Include())</code> syntax, I was able to include jsps which are at the top level. </p>
<p>However those which are present inside 'WEB-INF' cannot be referenced, is there any way to achieve this?</p>
|
<p>I think the Include class makes an external request instead of including/forwarding current one, which makes your case impossible. WEB-INF is not available to external requests, only include/forward if I remember correctly.</p>
|
<p>Why are you trying to include both inside one application? If I were you, and if you are in fact trying to migrate from JSP to Wicket, I would create a new Wicket application which you could mount under a separate context path on your server, and let Wicket sit by itself. You can then also include resources such as css and js from the other application directly, avoiding any repetition.</p>
| 22,992
|
<p>I'm trying to grab a div's ID in the code behind (C#) and set some css on it. Can I grab it from the DOM or do I have to use some kind of control?</p>
<pre><code><div id="formSpinner">
<img src="images/spinner.gif" />
<p>Saving...</p>
</div>
</code></pre>
|
<p>Add the <code>runat="server"</code> attribute to it so you have:</p>
<pre><code><div id="formSpinner" runat="server">
<img src="images/spinner.gif">
<p>Saving...</p>
</div>
</code></pre>
<p>That way you can access the class attribute by using:</p>
<pre><code>formSpinner.Attributes["class"] = "classOfYourChoice";
</code></pre>
<p>It's also worth mentioning that the <code>asp:Panel</code> control is virtually synonymous (at least as far as rendered markup is concerned) with <code>div</code>, so you could also do:</p>
<pre><code><asp:Panel id="formSpinner" runat="server">
<img src="images/spinner.gif">
<p>Saving...</p>
</asp:Panel>
</code></pre>
<p>Which then enables you to write:</p>
<pre><code>formSpinner.CssClass = "classOfYourChoice";
</code></pre>
<p>This gives you more defined access to the property and there are others that may, or may not, be of use to you.</p>
|
<p>If all you want to do is conditionally show or hide a <div>, then you could declare it as an <asp:panel > (renders to html as a div tag) and set it's .Visible property.</p>
| 21,143
|
<p>I am working on an ASP.NET web application, it seems to be working properly when I try to debug it in Visual Studio. However when I emulate heavy load, IIS crashes without any trace -- log entry in the system journal is very generic, "The World Wide Web Publishing service terminated unexpectedly. It has done this 4 time(s)."
How is it possible to get more information from IIS to troubleshoot this problem?</p>
|
<p>Crash dump of <a href="http://blogs.msdn.com/tess/archive/tags/ASP.NET/default.aspx" rel="nofollow noreferrer">asp.net process</a> should give you <a href="http://blogs.msdn.com/tess/pages/net-debugging-demos-information-and-setup-instructions.aspx" rel="nofollow noreferrer">tons of info</a>..If you want to quickly get some info on why the process got recycled, <a href="http://weblogs.asp.net/scottgu/archive/2005/12/14/433194.aspx" rel="nofollow noreferrer">try this tip from Scott Gu</a>..
<a href="http://odetocode.com/Blogs/scott/archive/2005/11/01/2402.aspx" rel="nofollow noreferrer">Health monitoring</a> feature of asp.net 2.0 is also worth looking at..</p>
|
<p>The key is <em>"without any trace"</em>. You need to put your own trace logging in to create some chatter. Then you'll be able to spot where the chatter stops.</p>
| 8,823
|
<p>Is there a PHP class/library that would allow me to query an XHTML document with CSS selectors? I need to scrape some pages for data that is very easily accessible if I could somehow use CSS selectors (jQuery has spoiled me!). Any ideas?</p>
|
<p>After Googling further (initial results weren't very helpful), it seems there is actually a Zend Framework library for this, along with some others:</p>
<ul>
<li><a href="https://github.com/PHPPowertools/DOM-Query" rel="noreferrer">DOM-Query</a></li>
<li><a href="http://code.google.com/p/phpquery/" rel="noreferrer">phpQuery</a></li>
<li><a href="https://github.com/tburry/pquery" rel="noreferrer">pQuery</a></li>
<li><a href="http://querypath.org/" rel="noreferrer">QueryPath</a></li>
<li><a href="http://simplehtmldom.sourceforge.net/" rel="noreferrer">Simple HTML DOM Parser</a></li>
<li><a href="https://github.com/cubiclesoft/ultimate-web-scraper/" rel="noreferrer">Ultimate Web Scraper Toolkit</a></li>
<li><a href="https://github.com/zendframework/zend-dom" rel="noreferrer">Zend-Dom</a></li>
</ul>
|
<p>I wrote mine, based on Mootools CSS selector engine <a href="http://selectors.svn.exyks.org/" rel="nofollow noreferrer">http://selectors.svn.exyks.org/</a>. it rely on simplexml extension ability (so, it's read-only)</p>
| 32,583
|
<p>I have a <a href="http://www.visualsvn.com/server/" rel="nofollow noreferrer">VisualSVN Server</a> installed on a Windows server, serving several repositories.</p>
<p>Since the web-viewer built into VisualSVN server is a minimalistic subversion browser, I'd like to install <a href="http://websvn.tigris.org/" rel="nofollow noreferrer">WebSVN</a> on top of my repositories.</p>
<p>The problem, however, is that I can't seem to get authentication to work. Ideally I'd like my current repository authentication as specified in VisualSVN to work with WebSVN, so that though I see all the repository names in WebSVN, I can't actually browse into them without the right credentials.</p>
<p>By visiting the cached copy of the topmost link on <a href="http://www.google.com/search?q=WebSVN+authentication+with+IIS+and+VisualSVN" rel="nofollow noreferrer">this google query</a> you can see what I've found so far that looks promising.<br>
(the main blog page seems to have been destroyed, domain of the topmost page I'm referring to is the-wizzard.de)</p>
<p>There I found some php functions I could tack onto one of the php files in WebSVN. I followed the modifications there, but all I succeeded in doing was make WebSVN ask me for a username and password and no matter what I input, it won't let me in.</p>
<p>Unfortunately, php and apache is largely black magic to me.</p>
<p>So, has anyone successfully integrated WebSVN with VisualSVN hosted repositories?</p>
|
<p>I got WebSVN authentication working with VisualSVN server, albeit with a lot of hacking/trial-error customization of my own.</p>
<p>Here's how I did it:</p>
<ol>
<li><p>If you haven't already, install PHP manually by downloading the zip file and going through the online php manual install instructions. I installed PHP to C:\PHP</p></li>
<li><p>Extract the websvn folder to C:\Program Files\VisualSVN Server\htdocs\</p></li>
<li><p>Go through the steps of configuring the websvn directory, i.e. rename configdist.php to config, etc. My repositories were located in C:\SVNRepositories, so to configure the authentication file, I set the config.php line so: $config->useAuthenticationFile('C:/SVNRepositories/authz'); // Global access file</p></li>
<li><p>Add the following to C:\Program Files\VisualSVN Server\conf\httpd-custom.conf : </p></li>
</ol>
<pre>
# For PHP 5 do something like this:
LoadModule php5_module "c:/php/php5apache2_2.dll"
AddType application/x-httpd-php .php
# configure the path to php.ini
PHPIniDir "C:/php"
<IfModule dir_module>
DirectoryIndex index.html index.php
</IfModule>
<Location /websvn/>
Options FollowSymLinks
AuthType Basic
AuthName "Subversion Repository"
Require valid-user
AuthUserFile "C:/SVNRepositories/htpasswd"
AuthzSVNAccessFile "C:/SVNRepositories/authz"
SVNListParentPath on
SVNParentPath "C:/SVNRepositories/"
</Location>
</pre>
<p>This worked for me, and websvn will only show those directories that are authorized for a given user. Note that in order for it to work right, you have to provide "Main Level" access to everybody, and then disable access to certain sub-directories for certain users. For example, I have one user who doesn't have main level access, but does have access to a sub-level. Unfortunately, this person can't see anything in websvn, even if he links directly to filedetails.php for a file he's authorized to see. In my case it's not a big deal because I don't want him accessing websvn anyway, but it's something you'll want to know.</p>
<p>Also, this sets the server up for an ssl connection, so once you've set it up, the address will be and https:// address, not the regular http://.</p>
|
<p>I am the author of the article you mentioned. The information I published was only meant for WebSVN running on IIS. It is my understanding that the software should "just work" when you use PHP on Apache, although I have never set it up in that environment. Have you tried doing some "echo"-debugging (for the lack of a better term) to see where exactly the authentication fails?</p>
| 3,826
|
<p>When I disable input elements the text is taking the font color: <code>#000000</code> in Firefox. This is not happening in IE. Please check the below page in IE and Firefox. Let me know how to give it a gray look as in IE.<br />
<a href="http://shivanand.in/tmp/test.html" rel="nofollow noreferrer">test</a></p>
|
<p>Different browsers style disabled elements differently. Here is how you can control the style of disabled elements in Firefox.</p>
<pre><code>[disabled] {
color:#ff0000;
background-color:#00ff00;
}
</code></pre>
|
<p>Reenable it, change the color, disable it again. It will only take .001 seconds.</p>
| 48,910
|
<p>I'm new to .Net and do not understand the difference. Can someone point me in the right direction?</p>
|
<p>ASP.NET Web services was developed for building applications that send and receive messages by using the Simple Object Access Protocol (SOAP) over HTTP.</p>
<p>WCF is for enabling .NET Framework applications to exchange messages with other software entities. SOAP is used by default, but the messages can be in any format, and conveyed by using any transport protocol.</p>
<p>You can view ASP.NET web services as a subset of WCF services.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/aa738737.aspx" rel="noreferrer">Here</a> is a link comparing the two frameworks.</p>
|
<p>They are two different things all together. WCF is a more generic framework through which you can write one service type component and deploy it in many ways (even as an Asp.Net Web Service).</p>
<p>Here's a brief thread about this <a href="http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/2d6a7ff2-f15c-4599-a389-a81cfffcc852/" rel="nofollow noreferrer">http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/2d6a7ff2-f15c-4599-a389-a81cfffcc852/</a></p>
| 26,671
|
<p>I'm having a problem with IE7 when clicking on images that open up using the Lightbox 2 javascript image viewer. Instead of overlaying the image on the current page it opens the image into a separate page.</p>
<p>Not sure if this is an AJAX problem possibly ? Works fine in Firefox.</p>
<p>Anybody else come across this before ?</p>
|
<p>Your page is performing the fall-back behaviour you would expect in the following scenarios...</p>
<ol>
<li>JavaScript is disabled</li>
<li>There is an error in the JavaScript that is creating the lightbox effect (look out for a very brief flash of the yellow error icon before the next page loads - or fire up some dev tools)</li>
<li>There is a JavaScript error on the page <em>before</em> the image is clicked, which has stopped execution of JavaScript on the page (look out for the yellow error icon in the status bar again!)</li>
</ol>
|
<p>The only thing I can think of is that I have google toolbar amd McAfee security installed that may be blocking the overlay (????) but don't think that should make any difference.</p>
| 26,085
|
<p>I'm looking for a PHP (with MYSQL) nested sets class with all needed functions.
For example:</p>
<p>createLeftNode, createRightNode,createRootNode, createSubNode,deleteNode and <strong>moveTree</strong>. Not only 1 left, 1 right, 1 up and 1 down but also a part of a tree in a nother tree.</p>
<p>Thanks!</p>
|
<p>Well nested sets are great if you are working with hierarchical data. It's much more complex to implement it only with php arrays especially if you want to save these information in a database.</p>
<p>you could try this on. Never used it but after a short code screening it looks almost complete.</p>
<p><a href="http://www.edutech.ch/contribution/nstrees/index.php" rel="nofollow noreferrer">http://www.edutech.ch/contribution/nstrees/index.php</a></p>
|
<p>It was long overdue, but I updated <a href="https://github.com/fpietka/Zend-Nested-Set" rel="nofollow">https://github.com/fpietka/Zend-Nested-Set</a> (even with unit tests).</p>
| 34,233
|
<p>Normally to attach a debuger to a running jvm you would need start the jvm with arguments such as the following:</p>
<pre><code>> java -Xdebug -Xrunjdwp:transport=dt_socket,address=1000,server=y,suspend=n
</code></pre>
<p>Now if I want to debug a process that wasn't started in debug mode, what can I do?</p>
<p>This situation arrises when a production system (i.e. started without debug args) exhibits a 'random' (I use the term loosely) bug. So I can't restart the jvm with the appropriate arguments, because nobody knows how to reproduce the bug again. Is it impossible to attach to the JVM in this situation?</p>
<p>Just to clarify it is not possible to use tools like jdb to attach to already running JVMs unless they were started in debug mode</p>
<p>from the JVM man page</p>
<blockquote>
<p><strong>Another way to use jdb is by attaching it to a Java VM that is
already running. A VM that is to be
debugged with jdb must be started with
the following options:</strong></p>
</blockquote>
|
<p>You may be able to use <a href="http://docs.oracle.com/javase/7/docs/technotes/tools/share/jsadebugd.html" rel="noreferrer">jsadebugd</a> (<a href="http://docs.oracle.com/javase/7/docs/technotes/tools/" rel="noreferrer">JDK</a>) to attach a debug server to the process (available on Windows with the <a href="http://msdn.microsoft.com/en-US/windows/hardware/gg463009" rel="noreferrer">Debugging Tools for Windows</a>). It is marked as experimental, so you may want to try it out on a test machine first.</p>
<p>Usage:</p>
<pre><code>jsadebugd <pid>
jdb -connect sun.jvm.hotspot.jdi.SADebugServerAttachingConnector:debugServerName=localhost
</code></pre>
<p>The connector name withe arg can be found using <code>jdb -listconnectors</code>.</p>
|
<p>You can always use jdb and debug by hand :P </p>
| 49,242
|
<p>SVN and CVS are two very different systems that aim to address the same basic issue - source control.</p>
<p>They both work in distinct ways, so it's probably difficult to deal with them exactly the same.</p>
<p>What I'm wondering is, would it be conceivable to develop a programming library or API that exposes the same interface, but under the hood, can be set up to work with either an SVN or CVS repository?</p>
<p>I'm aiming to develop such a library in either .NET or Java (most likely .NET), but I wanted to get some thoughts on how feasible this would be, and if there's a better way to approach the problem.</p>
<p>The context of this is: I'm building a web-based service that will involve source control hosting, and I want to support both SVN and CVS so as to serve the largest amount of developers possible.</p>
|
<p>Personally I would ignore CVS for a new product. My feeling would be that the enormous extra effort to coerce it into looking like SVN would be better spent on other other stuff. I don't know your market, so I might be wrong, but that's got to be worth thinking about.</p>
|
<p>The MSSCCI API does something very similar: </p>
<p><a href="http://alinconstantin.homeip.net/webdocs/scc/msscci.htm" rel="nofollow noreferrer">http://alinconstantin.homeip.net/webdocs/scc/msscci.htm</a></p>
<p>The MSSCCI tries to make all source controls look the same from the perspective of the IDE.</p>
| 40,355
|
<p>I got a little stuck and I'm hoping someone can point me in the right direction. I have an NSMutableArray that stores a sequence. I created an enumerator so that a while loop can get the content of the array one by one.</p>
<p>Everything works fine however I want the methods to be called with a 10 second gap in between each call. Right now it plays all at once (or in very quick order). What should I look at to create a delay in between method calls?</p>
<p>Below is what I got so far. Thanks!</p>
<pre><code>NSEnumerator * enumerator = [gameSequenceArray objectEnumerator];
id element;
while(element = [enumerator nextObject])
{
NSLog(element);
int elementInt = [element intValue];
[self.view showButton:elementInt];
}
</code></pre>
|
<p>You almost certainly don't want to stick a "delay" in your loop, which will block the thread until it's over (and, unless your app is multi-threaded, block the entire thing). You could use multiple threads, but instead I'd probably split the loop out over repeated timed calls of another selector. Store the enumerator (or current index), and then look at NSObject's performSelector:awithObject:afterDelay:</p>
<p>So something like</p>
<pre><code>[NSObject performSelector:@selector(some:selector:name:) withObject:objInstance afterDelay: 10]
</code></pre>
<p>where the selector will pickup the current enumerator, use it, advance it and schedule another call. Make sure you don't allow changes to the collection whilst this set of timed methods is executing.</p>
|
<p>So here was the solution that I came up with based on everyones input.</p>
<pre><code>NSEnumerator * enumerator = [gameSequenceArray objectEnumerator];
NSTimeInterval time = 5;
for (NSString *element in enumerator) {
id elementId = element;
time++;
[self.view performSelector:@selector(showButton:) withObject:elementId afterDelay:time];
}
</code></pre>
<p>Thanks again for pointing me in the right direction everyone.</p>
| 47,746
|
<p>Is anybody using JSON.NET with nHibernate? I notice that I am getting errors when I try to load a class with child collections.</p>
|
<p>I was facing the same problem so I tried to use @Liedman's code but the <code>GetSerializableMembers()</code> was never get called for the proxied reference.
I found another method to override:</p>
<pre><code> public class NHibernateContractResolver : DefaultContractResolver
{
protected override JsonContract CreateContract(Type objectType)
{
if (typeof(NHibernate.Proxy.INHibernateProxy).IsAssignableFrom(objectType))
return base.CreateContract(objectType.BaseType);
else
return base.CreateContract(objectType);
}
}
</code></pre>
|
<p>The problem can happen when NHibernate wraps the nested collection properties in a PersistentGenericBag<> type.</p>
<p>The GetSerializableMembers and CreateContract overrides cannot detect that these nested collection properties are "proxied". One way to resolve this is to override the CreateProperty method. The trick is to get the value from the property using reflection and test whether the type is of PersistentGenericBag. This method also has the ability to filter any properties that generated exceptions.</p>
<pre><code> public class NHibernateContractResolver : DefaultContractResolver
{
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty property = base.CreateProperty(member, memberSerialization);
property.ShouldSerialize = instance =>
{
try
{
PropertyInfo prop = (PropertyInfo)member;
if (prop.CanRead)
{
var value = prop.GetValue(instance, null);
if (value != null && typeof(NHibernate.Collection.Generic.PersistentGenericBag<>).IsSubclassOfRawGeneric(value.GetType()))
return false;
return true;
}
}
catch
{ }
return false;
};
return property;
}
}
</code></pre>
<p>The IsSubclassOfRawGeneric extension used above:</p>
<pre><code>public static class TypeExtensions
{
public static bool IsSubclassOfRawGeneric(this Type generic, Type? toCheck)
{
while (toCheck != null && toCheck != typeof(object))
{
var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
if (generic == cur)
{
return true;
}
toCheck = toCheck?.BaseType;
}
return false;
}
}
</code></pre>
| 36,455
|
<h2>What should happen when I call <code>$user->get_email_address()</code>?</h2>
<h3>Option 1: Pull the email address from the database on demand</h3>
<pre><code>public function get_email_address() {
if (!$this->email_address) {
$this->read_from_database('email_address');
}
return $this->email_address;
}
</code></pre>
<h3>Option 2: Pull the email address (and the other User attributes) from the database on object creation</h3>
<pre><code>public function __construct(..., $id = 0) {
if ($id) {
$this->load_all_data_from_db($id);
}
}
public function get_email_address() {
return $this->email_address;
}
</code></pre>
<p>My basic question is whether it's best to minimize the number of database queries, or whether it's best to minimize the amount of data that gets transferred from the database.</p>
<p>Another possibility is that it's best to load the attributes that you'll need the most / contain the least data at object creation and everything else on demand.</p>
<p>A follow-up question: What do ORM abstraction frameworks like Activerecord do?</p>
|
<p>There really isn't a correct answer for this. Depends on how many users you're loading at once, how many text/blob fields are in your User table, whether your user table loads any associated child objects. As aaronjensen says, this pattern is called <strong>lazy loading</strong> - and the opposite behaviour (loading <em>everything</em> up front just in case you need it) is known as <strong>eager loading</strong>. </p>
<p>That said, there is a third option you might want to consider, which is lazy-loading the entire User object when any of its properties are accessed:</p>
<pre><code>public function get_email_address() {
if (!$this->email_address) {
$this->load_all_data_from_db($this->id)
}
return $this->email_address;
}
</code></pre>
<p>Advantages of this approach are that you can create a collection of users (e.g. a list of all users whose passwords are blank, maybe?) based on their IDs only, without the memory hit of fully loading every single user, but then you only require a single database call for each user to populate the rest of the user fields.</p>
|
<p>I would agree with aaronjensen, except when the amount of data you are pulling is to so great that you'll start to use up an excessive amount of memory. I'm thinking where a row has 3 text fields that are all quite large and all you want is the ID field.</p>
| 20,496
|
<p>I'm using a small site to experiment with the uploading of pictures and displaying them.</p>
<p>When someone clicks "add a picture", they get taken to a page with a form on it. They can select a file and click the submit button.</p>
<p>But what I want to do now is this: put a second submit button labeled "Cancel" next to the normal confirmation button. If someone then chooses to upload, selects and hits submit, if they press the cancel button before the file is fully uploaded, PHP should stop the uploading of the file and delete it. And then just go back to the overview.</p>
<p>No Javascript used whatsoever.</p>
<p>I only have localhost, so testing this in kindof impossible, since I just copy a file the millisecond I press the submit button. There's no upload-time with a localhost and I'm not going to buy a server somewhere just for this.</p>
<p>Basically what's happening now is that the PHP detects which button was sent. If the submit button was sent, the file is uploaded, if the cancel button is sent, it just goes back to the overview.</p>
<p>But PHP does its tasks one in a row. So I don't think this will work. How do I tell PHP to stop doing the upload?</p>
|
<p>You can't look at the button with php - the whole request will have been sent before PHP gets that information.</p>
<p>What you could do is put the cancel button in a different <code><form></code>, like this:</p>
<pre><code><form> <input type="file> <input type="submit" value="upload"> </form>
<form> <input type="submit" value="cancel"> </form>
</code></pre>
<p>(This is just an example of course - there's bits missing).</p>
<p>When they click cancel, the browser should abandon its request and start a new one, cancelling the upload.</p>
|
<p>There's no way for PHP to stop a file upload in progress. Your PHP code isn't even started until the file upload is done, so by the time it's running, it's too late.</p>
| 28,562
|
<p>Might be subjective and/or discussion.. but here goes.</p>
<p>I've been asked to estimate a feature for the next big thing at work. I break it down.. use story points come up with a estimate. The feature however calls for interfacing with GoDiagrams a third party diagramming component in addition to various other company initiatives.. (a whole set of 2008_Limited_Edition frameworks/services:). I've been tracking myself using a burn-up chart and I find that I'm unable to sustain my pace primarily due to "spikes".. <a href="http://www.think-box.co.uk/blog/2006/01/spike.html" rel="nofollow noreferrer">Definition</a></p>
<p>I estimate for 2 points a week and then I find myself working weekends (well trying to.. end up neither here nor there) because I can't figure out where to hook in so that I can preview user-actions, show a context menu, etc. In the end I spend time making spikes that throw my schedule off-track... and decreases its value.. doesn't give the right picture.</p>
<p>Spikes are needed to drive nails through the planks of ignorance. But how are they factored into the estimation equation? Doing all required spikes before the feature seems wrong.. (might turn out to be YAGNI) Doing it in between disrupts my flow. Right now it's during pre-iteration planning.. but this is pushing the touchline out on a weekly basis.</p>
|
<p>I guess you are constantly <strong>underestimating</strong> </p>
<ul>
<li>what you do already know about the 3rd party component </li>
<li>how long it takes you to create usable/helpful spikes for unknown areas</li>
</ul>
<p><strong>1. Get better at estimating those two things.</strong></p>
<p>So, it's all about experience. No matter what methodology you use, they will help you to use your experience better, not replace it.</p>
<p><strong>2. Try not to get lose track when working on those spikes.</strong></p>
<p>They should be short, time boxed sessions. They are not about playing around with all the possible features listed on the marketing slides.
Give them focus, two or three options to explore. Expect them to deliver one concrete result.</p>
<p><em>Update(Gishu): To summarize</em></p>
<ul>
<li>Spikes need to be explicit tasks defined in the iteration planning step.</li>
<li>If spikes exceed the timebox period, stop working on it. Shelve the associated task. Complete the other tasks in the current iteration bucket. Return to the shelved task or add a more elaborate/broken down spike to the next iteration along with the associated task. Tag a more conservative estimate to the generation 1 spike the next time.</li>
</ul>
|
<p>@pointernil..
It's more of no estimation coupled with a Indy-Jones Head-First approach to tackling a story. I estimate stories by their content.. currently I don't take into account the time required to find the right incantation for the control library to play nice. That sometimes takes more time than my application logic.. So to rephrase the Original question, <strong>should spikes be separate tasks in the iteration plan, added on a JIT basis before you start working on a particular story?</strong></p>
<p>My Spikes are extremely focussed.. I just can't wait to get back to the "real" problems. e.g. 'How do I show a context menu from this control?' I may be guilty of not reading the entire 150+ page manual or code samples.. but then time is scarce. The first solution that solves the problem gets the nod and I move on. But when you're unable to find that elusive event or NIH pattern of notification used by the component, spikes can be time-consuming. <strong>How do I timebox something that is unknown?</strong> e.g. My timebox has elapsed and I still have no clue for plugging-in my custom context menu. How do I proceed? Keep hacking away?</p>
<p>Maybe this comes in the "Buffering Uncertainity" scheme of things.. I'll look if I find something useful in Mike Cohn's book. </p>
| 13,689
|
<p>How do I start a process, such as launching a URL when the user clicks a button?</p>
|
<p>As suggested by Matt Hamilton, the quick approach where you have limited control over the process, is to use the static Start method on the System.Diagnostics.Process class...</p>
<pre><code>using System.Diagnostics;
...
Process.Start("process.exe");
</code></pre>
<p>The alternative is to use an instance of the Process class. This allows much more control over the process including scheduling, the type of the window it will run in and, most usefully for me, the ability to wait for the process to finish.</p>
<pre><code>using System.Diagnostics;
...
Process process = new Process();
// Configure the process using the StartInfo properties.
process.StartInfo.FileName = "process.exe";
process.StartInfo.Arguments = "-n";
process.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
process.Start();
process.WaitForExit();// Waits here for the process to exit.
</code></pre>
<p>This method allows far more control than I've mentioned.</p>
|
<p>You can use this syntax:</p>
<pre><code>private void button1_Click(object sender, EventArgs e) {
System.Diagnostics.Process.Start(/*your file name goes here*/);
}
</code></pre>
<p>Or even this:</p>
<pre><code>using System;
using System.Diagnostics;
//rest of the code
private void button1_Click(object sender, EventArgs e) {
Process.Start(/*your file name goes here*/);
}
</code></pre>
<p>Both methods would perform the same task.</p>
| 21,940
|
<p>I have an install that upgrades a previous version of an app if it exits. I'd like to skip certain actions when the install is upgrade mode. How can I determine if the install is running in upgrade mode vs. first time install mode?</p>
<p>I'm using Wise Installer, but I don't think that matters. I'm assuming that Windows Installer has a property that is set when the installer is in upgrade mode. I just can't seem to find it. If the property exists, I'm assuming I could use it in a conditional statement.</p>
|
<p>Can you elaborate what kind of tools are you using to create this installer?</p>
<p>I use Windows Installer XML(<a href="http://wix.sourceforge.net/" rel="nofollow noreferrer">WIX</a>). In WIX you could do something like this:</p>
<pre><code> <!-- Property definitions -->
<?define SkuName = "MyCoolApp"?>
<?define ProductName="My Cool Application"?>
<?define Manufacturer="Acme Inc."?>
<?define Copyright="Copyright © Acme Inc. All rights reserved."?>
<?define ProductVersion="1.1.0.0"?>
<?define RTMProductVersion="1.0.0.0" ?>
<?define UpgradeCode="{EF9D543D-9BDA-47F9-A6B4-D1845A2EBD49}"?>
<?define ProductCode="{27EA5747-9CE3-3F83-96C3-B2F5212CD1A6}"?>
<?define Language="1033"?>
<?define CodePage="1252"?>
<?define InstallerVersion="200"?>
</code></pre>
<p>And define upgrade options: </p>
<pre><code><Upgrade Id="$(var.UpgradeCode)">
<UpgradeVersion Minimum="$(var.ProductVersion)"
IncludeMinimum="no"
OnlyDetect="yes"
Language="$(var.Language)"
Property="NEWPRODUCTFOUND" />
<UpgradeVersion Minimum="$(var.RTMProductVersion)"
IncludeMinimum="yes"
Maximum="$(var.ProductVersion)"
IgnoreRemoveFailure="no"
IncludeMaximum="no"
Language="$(var.Language)"
Property="OLDIEFOUND" />
</Upgrade>
</code></pre>
<p>Then further you could use <code>OLDIEFOUND</code> and <code>NEWPRODUCTFOUND</code> properties depending on what you want to do:</p>
<pre><code><!-- Define custom actions -->
<CustomAction Id="ActivateProduct"
Directory='MyCoolAppFolder'
ExeCommand='"[MyCoolAppFolder]activateme.exe"'
Return='asyncNoWait'
Execute='deferred'/>
<CustomAction Id="NoUpgrade4U"
Error="A newer version of MyCoolApp is already installed."/>
</code></pre>
<p>The above defined actions have to be define in <code>InstallExcecuteSequence</code> </p>
<pre><code><InstallExecuteSequence>
<Custom Action="NoUpgrade4U"
After="FindRelatedProducts">NEWPRODUCTFOUND</Custom>
<Custom Action="ActivateProduct"
OnExit='success'>NOT OLDIEFOUND</Custom>
</InstallExecuteSequence>
</code></pre>
|
<p>I am not sure I understood your question.<br>
If you are writting the install script yourself, the best way, on Windows, is to check the registry keys such program usually creates. Unlike install directory (and start menu entries, etc.), it is an invariant. One of these keys can even be the version number of the software, to check in case a user tries to install an oldver version (or to know if some files must be removed, etc.).</p>
| 17,588
|
<p>Does anyone know of an application or system out there for tracking changes (files added/removed, diffs on text files) to a <em>non-source controlled</em> directory over time? Something that would let you</p>
<ol>
<li><p>Take a snapshot of a certain directory tree at time A</p></li>
<li><p>Come back at time period B and see what has changed</p></li>
<li><p>Come back at time period C and see what's changed since time period A, and what's changed since time period B</p></li>
</ol>
<p>A source control repository isn't an option here. I want something that works on a directory structure that isn't under any kind of revision control. My group isn't in control of the servers or directory trees in question, but changes to those trees impact us and we'd like to keep track of them. The objects to "source control" are</p>
<ol>
<li><p>Objections to any kind of centralized repository that requires document authors to check-in, check-out.</p></li>
<li><p>Objections to having to hand-roll/automate a bunch of tasks that can leverage a version control system's feature set</p></li>
</ol>
<p>I want a semi-mature package where people have spent some time thinking about the problem. If there's a version control system that's been built to handle this kind of thing, it applies. </p>
|
<p>Write a scripted scheduled task which copies the directory tree to another place, perhaps on a different machine, which is part of a version controlled repostiory. Then, the scheduled task would automatically commit changes, using the version control system of your choice (Mercurial should work nicely for this system, since <code>hg commit -A -m "automated snapshot"</code> will quickly do what you need without any interactive prompts).</p>
<p>I'd suggest rsync for the copy, which is available for many platforms, and is fast and efficient since it won't copy files which haven't changed. Configure the copy to delete files from your copy which have been deleted on the main directory. </p>
|
<p>I'd like something that looks, tastes and smells just like milk. But it shouldn't be milk. </p>
<p>In other words: you're describing a vcs. If you tell us why a vcs can't be used, it might be easier to answer.</p>
<p>Only thing I can think of is Apple's Time Machine, which (again) is basically vcs for the masses.</p>
| 19,696
|
<p>I'm having trouble getting a rails app on Dreamhost's Passenger to see compiled libraries in my ~/opt/lib directory. I have to put them here because I don't have root access. </p>
<p>I can boot up my app in ./script/console and it sees them libraries just fine because I updated my .bash_profile's <code>LD_LIBRARY_PATH</code> environment variable to include ~/opt/lib.</p>
<p>I've tried putting <code>ENV['LD_LIBRARY_PATH'] = '~/opt/lib'</code> in my environment.rb file but it doesn't seem too help. I get the following error from Passenger when I navigate to my site:
libodbcinst.so.1: cannot open shared object file: No such file or directory - /home/username/opt/lib/odbc.so</p>
<p>Anyone have experience with this?</p>
<p>Thanks</p>
|
<p>I had similar issue with Passenger that I described in <a href="http://blog.rayapps.com/2008/05/21/using-mod_rails-with-rails-applications-on-oracle/" rel="nofollow noreferrer">http://blog.rayapps.com/2008/05/21/using-mod_rails-with-rails-applications-on-oracle/</a></p>
<p>But in your case this migth not work as you will not be able to change Dreamhost's httpd.conf file.</p>
<p>Other thing that you can try is to set LD_LIBRARY_PATH in .bashrc - according to <a href="http://www.wavethenavel.com/jonathanpenn/2008/09/08/bootstrapping-a-dreamhost-account-for-rails-and-git/" rel="nofollow noreferrer">http://www.wavethenavel.com/jonathanpenn/2008/09/08/bootstrapping-a-dreamhost-account-for-rails-and-git/</a> this has worked in Dreamhost's case. Have not verified that Passenger will execute .bashrc before launching ruby.</p>
|
<p>This is an old thread, but for completeness this is how to achieve your goal:</p>
<ol>
<li>Do not set the LD_LIBRARY_PATH if possible - it's horrendous.</li>
<li>As you do not have control over the environment that the Apache
user's environment, attempting to set a LD_LIBRARY_PATH env var per
the methods above will not work anyway.</li>
<li><p>Set the LDFLAGS environment variable with link and record path flags set prior to compiling the library files to set the correct search paths - e.g.:</p>
<p>export LDFLAGS="-L$HOME/opt/lib -R$HOME/opt/lib"</p></li>
</ol>
<p>Once compiled, the files will have the correct links set to the relevant libraries. You can check this using the ldd command line tool - e.g.:</p>
<pre><code>ldd /$HOME/your/custom/complied/library/file.so
</code></pre>
| 31,196
|
<p>This is probably a simple question but I am not an ASP.NET developer and I am quite stuck.</p>
<p>I have a simple search routine that returns between zero and several hundred results. Each of these must be added to the page as a button and I want to set the text of the button and the CommandArgument property so that when the button is clicked I can read the CommandArgument back and react accordingly.</p>
<p>However, when I click the button the event does not run at all. How can I get it to run?</p>
<p>The code for building the button list (simplified for readability) is as follows:</p>
<pre><code> foreach (SearchResult sr in searchResults)
{
Button result = new Button();
result.Text = sr.name;
result.CommandArgument = sr.ID.ToString();
AccountSearchResults.Controls.Add(result);
result.Click += new EventHandler(SearchResultClicked);
AccountSearchResults.Controls.Add(new LiteralControl("<br/>"));
}
</code></pre>
<p>At the minute to test, I have popped a label on the form to put the CommandArgument in. This code is never executed though.</p>
<pre><code> void SearchResultClicked(object sender, EventArgs e)
{
Label1.Text = ((Button)sender).CommandArgument;
}
</code></pre>
|
<p>You mentioned in another answer that you are adding these when a button is clicked. Looking at your code, I would suggest that you try setting a unique ID for each button added, then ensure that on loading the page that buttons with the same IDs and CommandArgument values are reloaded. When a dynamically loaded button is clicked, it must still exist on the page after postback for the event to fire.</p>
<p>I think the ID is all you need, plus your requirement for the CommandArgument). You could put the ID information in the ViewState if you can't get it repeat without a long search process.</p>
|
<p>I think you need to use the OnCommand event handler, rather than the OnClick i.e. try changing this:</p>
<pre><code>result.Click += new EventHandler(SearchResultClicked);
</code></pre>
<p>to this:</p>
<pre><code>result.Command += new EventHandler(SearchResultClicked);
</code></pre>
<h2>UPDATE</h2>
<p>Try changing the type of second argument to your event hander from <em>EventArgs</em> to <strong>CommandEventArgs</strong>. You might also have to set the CommandName property on your button i.e.</p>
<pre><code>result.CommandName = "foo";
</code></pre>
| 46,360
|
<p>I have some code that effectively does this :</p>
<pre><code>File file = new File("C:\\Program Files (x86)\\Something\\fred.txt");
System.out.println("file.canWrite() = " + file.canWrite());
</code></pre>
<p>It prints true.
Now the odd thing is, I can create the file without any exceptions. Furthermore, another program can read the file I've created. The thing is, in Windows Explorer, the file doesn't show up at all!</p>
<p>Show hidden files you may be thinking, but no, I've got that option turned on.</p>
<p>I've also found out about 'super hidden files' in Vista, so I've turned that option on and I still can't see the file! Maybe I haven't edited my registry correctly - I can only assume the file is super hidden - where else could it be?</p>
<p>Now the problem is that I'm creating an html file and the when I fire up a browser, it can't see the html file because it's super hidden.</p>
<p>How can I prevent Java creating a super hidden file? This is running under JRE 6 update 6.</p>
|
<p>You are most likely a "victim" of folder redirection. When UAC is enabled, any writes to Program Files is redirected to somewhere else when you're not running the program as an administrator.</p>
<p>You should find your file in C:\Users\<username>\AppData\Local\VirtualStore\<insert>\<expected>\<path>\<here>.</p>
<p>The proper fix, of course, is to not write to Program Files in the first place. Instead, use somewhere in the user's home directory (the exact location you should write to depends on the purpose of the app).</p>
|
<p>I believe that update 10 might have changed this behavour. I know the reimplemented a lot of the browser stuff to work better with vista. I'm not 100% certain though but I suggest you take a look.</p>
| 35,488
|
<p>I specifically want to test </p>
<ul>
<li>calibration</li>
<li>tolerances</li>
<li>precision</li>
<li>accuracy</li>
</ul>
<p>I'm having trouble with Print in Place models and I'm trying to find out if there's something I can do to improve my print quality. </p>
<p>The printer I am using is a Kossel clone, specifically a FLSUN QQ and assume FDM printing.</p>
|
<p>This is a fairly open ended subject, but the different calibration/test models can be broken down into a few different groups. Although there are a few common 'standards', as soon as you get to looking at a specific parameter, you will need to look for something that is a good match for your problem (not everything on thingiverse is really 'useful), and work out how to use it for your adjustments. Ultimately, the specific model you're working on is the best test - and it may also be that this model is not optimal in some way.</p>
<p>Here is a print from my own test model which shows the slicer not handling my model very well, partly because the model doesn't respect the filament dimensions. It also shows how a variety of print details can be captured in a small (20 min) print.
<a href="https://i.stack.imgur.com/xXK9zm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xXK9zm.jpg" alt="Small Tower Tester by tsh2"></a></p>
<h2>Basic Calibration</h2>
<p>This is a step that you might be tempted to skip on a non-diy printer, since it mainly focuses on the construction. The <a href="https://www.thingiverse.com/thing:1278865" rel="nofollow noreferrer">basic 20mm calibration cube</a> (just a square) can be used to test that your printer is dimensionally accurate, and is also one way to check your extruder steps/mm (extrusion is variable, x/y steps generally only change when the belt skips).
You can also use bigger shapes if you suspect that there are drive problems, and <a href="https://www.thingiverse.com/thing:2664146" rel="nofollow noreferrer">bed leveling</a> might come into this group too, where you could use a one or two layer print.</p>
<h2>Test Parts</h2>
<p>These are small parts that might once have been considered hard to print, but now seem to be a standard reference for a 'good' print. Most people who have been printing for a while have a collection of <a href="http://www.3dbenchy.com" rel="nofollow noreferrer">benchie</a> and <a href="https://www.3dhubs.com/hub-academy/your-first-order-marvin-test-print" rel="nofollow noreferrer">marvin</a> prints. You might use these to quickly test a new filament, although the benchie is borderline large.</p>
<p><a href="https://i.stack.imgur.com/6Q9H0m.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6Q9H0m.jpg" alt="Marvin"></a>
<a href="https://i.stack.imgur.com/SMa9wm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SMa9wm.jpg" alt="Benchie"></a></p>
<h2>Detail calibration</h2>
<p>Depending what you want to focus on, there will be different things you can use. Temperature calibration towers, overhang and bridging tests, ripple tests (for acceleration), fan tests, etc. This is an area where finding a 'good' test part can be hard. You would want to make sure that the previous two classes of test show good all round performance (or have identified a specific problem) first, before trying this sort of test.</p>
<p>For the print-in-place example, you might need to check extrusion/ooze/coasting, as well as checking linearity and orthogonality (it's no use if a circular part turns out to be more like a diamond with rounded corners). You also need to make sure your first layer is good, without a rim or warping.</p>
<h2>Torture tests</h2>
<p>I put this in a group on it's own because it may not be as useful for tuning a printer as some of the others. This is a little bit more about showing off how good your printer is tuned - and is the origin of the benchie and marvin type models, just with the difficulty turned up a notch or two. Some print-in-place models might fit into this category.</p>
|
<p>The best place to start looking is to go to <a href="http://www.thingiverse.com" rel="nofollow noreferrer">Thingiverse</a> and search on '<a href="https://www.thingiverse.com/search?q=benchmark" rel="nofollow noreferrer">benchmark</a>'. There are a great many models there intended to test various aspects of printing. In fact you could search for example '<a href="https://www.thingiverse.com/search?q=calibration%20benchmark" rel="nofollow noreferrer">calibration benchmark</a>' or '<a href="http://www.thingiverse.com/search?q=calibration%20test" rel="nofollow noreferrer">calibration test</a>' and get more specific examples.</p>
<p>Actually, <a href="https://www.thingiverse.com/nebogipfel/collections/benchmarks" rel="nofollow noreferrer">here</a> is a collection I just made today of the benchmarks I thought most promising. Disclaimer: I haven't tried them yet!</p>
| 975
|
<p>Can anyone help me to put a vertical scroll bar for an <code><asp:CheckBoxList></code>?</p>
|
<p>I've actually just figured out the answer. Thank you both for your answers, but it turns out that all i had to do was this:</p>
<pre><code>p.StandardInput.Close()
</code></pre>
<p>which causes the program I've spawned to finish reading from stdin and output what i need.</p>
|
<p>Try actually sending the Key Combination Ctrl+C, instead of directly terminating the process:</p>
<pre><code> [DllImport("user32.dll")]
public static extern int SendMessage(
int hWnd, // handle to destination window
uint Msg, // message
long wParam, // first message parameter
long lParam // second message parameter
);
</code></pre>
<p>Look it up on the MSDN, you should find what you need there in order to send the Ctrl+Key combination...
I know that the message you need for sending Alt+Key is WM_SYSTEMKEYDOWN and WM_SYSTEMKEYUP, can't tell you about Ctrl...</p>
| 35,876
|
<p>So I got this question from one of the developers in my team: What is domain driven design? I could of course point to the book from Evans but is that actually an answer? </p>
<p>How would you explain DDD in a few sentences to junior software engineers in your team?</p>
|
<p>I would say this practice promotes concentrating your efforts on the 'problem space' rather than the 'solution space'. Driving an emergent solution (the design) by studying and really getting to know and understand the domain. One of the practices (taken from XP) would be the writing of stories that occur in the problem domain. From these you can identify your use cases and objects for your design. They 'emerge' and tell you what needs to be in the solution, and how they will need to interact with each other.</p>
|
<p>An important part of DDD is the so called ubiquitous language; i.e. speak the same language as the business experts. And make your code / architecture so that it reflects this language to avoid impedance problems.</p>
| 12,631
|
<p>This may not be the correct way to use controllers, but I did notice this problem and hadn't figured out a way to correct it. </p>
<pre><code>public JsonResult SomeControllerAction() {
//The current method has the HttpContext just fine
bool currentIsNotNull = (this.HttpContext == null); //which is false
//creating a new instance of another controller
SomeOtherController controller = new SomeOtherController();
bool isNull = (controller.HttpContext == null); // which is true
//The actual HttpContext is fine in both
bool notNull = (System.Web.HttpContext.Current == null); // which is false
}
</code></pre>
<p>I've noticed that the HttpContext on a Controller isn't the "actual" HttpContext that you would find in System.Web.HttpContext.Current. </p>
<p>Is there some way to manually populate the HttpContextBase on a Controller? Or a better way to create an instance of a Controller?</p>
|
<p>For now I'm going to do the following. This seems to be an acceptable fix...</p>
<pre><code>public new HttpContextBase HttpContext {
get {
HttpContextWrapper context =
new HttpContextWrapper(System.Web.HttpContext.Current);
return (HttpContextBase)context;
}
}
</code></pre>
<p>Where this is added to a Controller class these Controllers are inheriting from.</p>
<p>I'm not sure if the HttpContext being null is the desired behavior, but this will fix it in the meantime for me.</p>
|
<p>Is it that you want to use some functionality from the controller? Or have the controller perform an action?</p>
<p>If it's the former, maybe that's some code that should be split out into another class. If it's the latter, you can do this to simply have that controller do a specific action:</p>
<pre>
<code>
return RedirectToAction("SomeAction", "SomeOtherController", new {param1 = "Something" });
</code>
</pre>
| 27,568
|
<p>If I create an index on columns (A, B, C), in that order, my understanding is that the database will be able to use it even if I search only on (A), or (A and B), or (A and B and C), but not if I search only on (B), or (C), or (B and C). Is this correct?</p>
|
<p>There are actually three index-based access methods that Oracle can use when a predicate is placed on a non-leading column of an index.</p>
<p>i) Index skip-scan: <a href="http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/optimops.htm#PFGRF10105" rel="noreferrer">http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/optimops.htm#PFGRF10105</a></p>
<p>ii) Fast full index scan: <a href="http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/optimops.htm#i52044" rel="noreferrer">http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/optimops.htm#i52044</a></p>
<p>iii) Index full scan: <a href="http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/optimops.htm#i82107" rel="noreferrer">http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/optimops.htm#i82107</a></p>
<p>I've most often seen the fast full index scan "in the wild", but all are possible.</p>
|
<p>That is not correct. Always best to come up with a test case that represents your data and see for yourself. If you want to really understand the Oracle SQL Optimizer google Jonathan Lewis, read his books, read his blog, check out his website, the guy is amazing, and he always generates test cases.</p>
<pre><code>create table mytab nologging as (
select mod(rownum, 3) x, rownum y, mod(rownum, 3) z from all_objects, (select 'x' from user_tables where rownum < 4)
);
create index i on mytab (x, y, z);
exec dbms_stats.gather_table_stats(ownname=>'DBADMIN',tabname=>'MYTAB', cascade=>true);
set autot trace exp
select * from mytab where y=5000;
Execution Plan
----------------------------------------------------------
0 SELECT STATEMENT Optimizer=CHOOSE (Cost=1 Card=1 Bytes=10)
1 0 INDEX (SKIP SCAN) OF 'I' (INDEX) (Cost=1 Card=1 Bytes=10)
</code></pre>
| 8,231
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.