instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>I have issues with this overhang:</p>
<p><a href="https://i.stack.imgur.com/7dMhQ.jpg" rel="nofollow noreferrer" title="Damaged overhang"><img src="https://i.stack.imgur.com/7dMhQ.jpg" alt="Damaged overhang" title="Damaged overhang"></a></p>
<p>The whole part always breaks in this overhang during the print.</p>
<p>I tried to increase the count of wall lines and decrease printing speed, but none of those things help. Do you have any idea how to fix it? Is possible to create support inside a model to print this overhang?</p>
<p>(I´m using Cura 4.1.0.)</p>
<p>I´m using 3 wall´s lines and 15% gyroid infill. My bed has 70 °C and nozzle 205 °C. I am using PLA Prusament galaxy black. The part is oriented the right way. By overhang I mean damaged part above holes.</p>
|
<p>When you get upwards facing things failing it can be because the slicer has too few top layers which makes angled faces have gaps. While you may think it is a wall the slicer sees it as top layer. Try increasing the number of top layers and check in the preview how it appears.</p>
<p>Infill will normally support those faces so no separate support is needed. Just make sure you have enough top layers that no gaps form, 3-5 layers should be alright.</p>
|
<p>As @r-ahlskog pointed out, it was due to the top layers count being too low. Adding some, now it looks perfect:</p>
<p><a href="https://i.stack.imgur.com/DEdbO.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DEdbO.jpg" alt="enter image description here"></a></p>
| 1,383
|
<p>Folks, we all know that IP blacklisting doesn't work - spammers can come in through a proxy, plus, legitimate users might get affected... That said, blacklisting seems to me to be an efficient mechanism to stop a persistent attacker, given that the actual list of IP's is determined dynamically, based on application's feedback and user behavior. </p>
<p>For example:
- someone trying to brute-force your login screen
- a poorly written bot issues very strange HTTP requests to your site
- a script-kiddie uses a scanner to look for vulnerabilities in your app</p>
<p>I'm wondering if the following mechanism would work, and if so, do you know if there are any tools that do it: </p>
<ul>
<li>In a web application, developer has a hook to report an "offense". An offense can be minor (invalid password) and it would take dozens of such offenses to get blacklisted; or it can be major, and a couple of such offenses in a 24-hour period kicks you out. </li>
<li>Some form of a web-server-level block kicks in on before every page is loaded, and determines if the user comes from a "bad" IP. </li>
<li>There's a "forgiveness" mechanism built-in: offenses no longer count against an IP after a while.</li>
</ul>
<p>Thanks!</p>
<p><b>Extra note: it'd be awesome if the solution worked in PHP, but I'd love to hear your thoughts about the approach in general, for any language/platform</b></p>
|
<p>are you on a *nix machine? this sort of thing is probably better left to the OS level, using something like <a href="http://en.wikipedia.org/wiki/Iptables" rel="nofollow noreferrer">iptables</a></p>
<p>edit:</p>
<p>in response to the comment, yes (sort of). however, the idea is that iptables can work independently. you can set a certain threshold to throttle (for example, block requests on port 80 TCP that exceed x requests/minute), and that is all handled transparently (ie, your application really doesn't need to know anything about it, to have dynamic blocking take place).</p>
<p>i would suggest the iptables method if you have full control of the box, and would prefer to let your firewall handle throttling (advantages are, you don't need to build this logic into your web app, and it can save resources as requests are dropped before they hit your webserver)</p>
<p>otherwise, if you expect blocking won't be a huge component, (or your app is portable and can't guarantee access to iptables), then it would make more sense to build that logic into your app.</p>
|
<p>I think it should be a combination of user-name plus IP block. Not just IP.</p>
| 13,817
|
<p>I want to implement a paperless filing system and was looking to use WIA with C# for the image acquisition. There are quite a few sample projects on CodeProject, etc. However, after downloading every one of them that I can find, I have run into a problem.</p>
<p>In each and every one of them, the reference to WIALib is broken. When I go to add "Microsoft Windows Image Acquisition" as a reference, the only version available on my development workstation (also the machine that will run this) is 2.0.</p>
<p>Unfortunately, every one of these sample projects appear to have been coded against 1.x. The reference goes in as "WIA" instead of "WIALib". I took a shot, just changing the namespace import, but clearly the API is drastically different.</p>
<p>Is there any information on either implementing v2.0 or on upgrading one of these existing sample projects out there?</p>
|
<p>To access WIA, you'll need to add a reference to the COM library, "Microsoft Windows Image Acquisition Library v2.0" (wiaaut.dll).
add a "using WIA;"</p>
<pre><code>const string wiaFormatJPEG = "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}";
CommonDialogClass wiaDiag = new CommonDialogClass();
WIA.ImageFile wiaImage = null;
wiaImage = wiaDiag.ShowAcquireImage(
WiaDeviceType.UnspecifiedDeviceType,
WiaImageIntent.GrayscaleIntent,
WiaImageBias.MaximizeQuality,
wiaFormatJPEG, true, true, false);
WIA.Vector vector = wiaImage.FileData;
</code></pre>
<p>(System.Drawing)</p>
<pre><code>Image i = Image.FromStream(new MemoryStream((byte[])vector.get_BinaryData()));
i.Save(filename)
</code></pre>
<p>Thats a basic way, works with my flatbed/doc feeder. If you need more than one document/page at a time though, there is probably a better way to do it (from what I could see, this only handles one image at a time, although I'm not entirely sure). While it is a WIA v1 doc, Scott Hanselman's <a href="http://blogs.msdn.com/coding4fun/archive/2006/10/31/912546.aspx" rel="noreferrer">Coding4Fun article on WIA</a> does contain some more info on how to do it for multiple pages, I think (I'm yet to go further than that myself)</p>
<p>If its for a paperless office system, you might want also check out MODI (Office Document Imaging) to do all the OCR for you.</p>
|
<p>It doesn't <strong>need</strong> to be WIA. I was mostly looking at the WIA setup because it offers the same basic interface for different scanners. I've got 3 scanners on this machine and the TWAIN drivers/software for all of them suck (like blocking the screen during scanning).</p>
<p>For document management, I'm really looking for simple 200dpi grayscale scans, so most of the stuff in the TWAIN drivers is overkill. </p>
<p>That said, asking here was part of my last attempt to figure out how to do it in WIA before moving on to TWAIN.</p>
| 3,043
|
<p>The following have been proposed for an upcoming C++ project.</p>
<ul>
<li>C++ Coding Standards, by Sutter and Alexandrescu</li>
<li>JSF Air Vehicle C++ coding standards</li>
<li>The Elements of C++ Style</li>
<li>Effective C++ 3rd Edition, by Scott Meyers</li>
</ul>
<p>Are there other choices? Or is the list above what be should used on a C++ project?</p>
<p>Some related links</p>
<ul>
<li><a href="https://stackoverflow.com/questions/145508/do-you-think-a-software-company-should-impose-developers-a-coding-style">Do you think a software company should impose developers a coding-style?</a></li>
<li><a href="https://stackoverflow.com/questions/66268/what-is-the-best-cc-coding-style-closed">https://stackoverflow.com/questions/66268/what-is-the-best-cc-coding-style-closed</a></li>
</ul>
|
<p>I really think it does not matter which one you adopt, as long as everyone goes along with it. Sometimes that can be hard as it seems that some styles don't agree with peoples tases. I.e. it comes down to arguing about whether prefixing all member variable with <code>m_</code> is <em>pretty</em> or not.</p>
<p>I have been using and modifying the <a href="http://geosoft.no/development/cppstyle.html" rel="nofollow noreferrer">Geosoft</a> standards for a while, these are for C++. There are some other at the <a href="https://stackoverflow.com/questions/409/what-is-your-favorite-coding-guidelines-checklist#139459">what-is-your-favorite-coding-guidelines-checklist</a> thread</p>
|
<p><a href="http://www.appinf.com/download/CppCodingStyleGuide.pdf" rel="nofollow noreferrer">Poco C++ Coding Style Guide.pdf</a></p>
| 17,551
|
<p>I am looking for a solid and easy to pick up .NET Web Application Framework for company-wide development use. I am considering DotNetNuke. Is it good ? What else can you recommend ?</p>
|
<p>If you're wanting a framework for "Web Applications" in .NET, then your choices boil down to ASP.NET or ASP.NET MVC (both from Microsoft), or an open source alternative like Castle Monorail.</p>
<p>ASP.NET would be the way to go if you want to have maximum use of vendor controls, and you're putting together small, form based applications.</p>
<p>For anything larger or more complex, and if you can do without vendor controls, ASP.NET MVC or Castle Monorail are going to give you a better result because they forces you into better practices.</p>
<p>However, if you're looking for an existing web application to use as a basis for customization, then your starting point needs to be to tell us more detail about what you want to achieve. </p>
<p>Depending on your requirements, Dotnetnuke may be a great fit for your needs, or it might be a spectaularly bad choice. Without more information we can't tell.</p>
|
<p>SharePoint is an option but I don't recommend it. I've always wanted to try DotNetNuke. It has a strong community and a lot of growth.</p>
<p>Our team worked on SharePoint features for 5 months before we ditched it. Deployment and debugging are awful experiences. We had to resort to lengthy build scripts within Visual Studio and we used a few open source tools (<a href="http://www.codeplex.com/wspbuilder" rel="nofollow noreferrer">WspBuilder</a>, <a href="http://www.codeplex.com/sharepointinstaller" rel="nofollow noreferrer">SharePoint Installer</a>, etc.) just to make the process half-way manageable.</p>
<p>Maybe SharePoint will grow up and get real Visual Studio integration some day (I hear that is the plan with VS 2010). Until then, it is just too much trouble. The learning curve is steep and you will have to spend <em>a lot</em> of time searching XML config files to track down problems. SharePoint will probably make you despise XML configurations!</p>
<p><strong>UPDATE:</strong>
Sharepoint is getting some much needed attention in VS2010. See: <a href="http://www.cmswire.com/cms/enterprise-cms/new-sharepoint-developer-tools-in-visual-studio-2010-004050.php" rel="nofollow noreferrer">http://www.cmswire.com/cms/enterpr...</a></p>
| 44,576
|
<p>I am trying to modify this <a href="https://www.thingiverse.com/thing:2516525" rel="noreferrer">thing</a>. It's prints OK, but there are some design choices I don't like, so, since the previous makers uploaded their source files, I tried my hand at Sketchup.</p>
<p>My latest round of changes have produced a weird phenomenon, and I'm not sure how to describe it. The slicer sees the GCODE as I intend, but for some reason the printer is printing something different than what the slicer is showing me. I am primarily concerned with the top of this case, but the base does not have the additional screw holes I made, so the phenomenon, whatever it is, is not limited to a single part.</p>
<ul>
<li>Sketchup v17.2.25555</li>
<li>Cura v3.0.3</li>
<li>OctoPi/OctoPrint 1.2.7</li>
<li>PrintrBot LC custom</li>
<li>Grey Inland PLA+ @~180C, bed @~60C (my temps are higher than the software thinks they are, so I have to put the temp lower in the software)</li>
</ul>
<p>You can see the parts in Sketchup:</p>
<p><a href="https://i.stack.imgur.com/FCSH7.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/FCSH7.jpg" alt="enter image description here"></a></p>
<p>The corner on the left was giving me no end of trouble! I left it with a messed up hole because I could more easily clean it up with a drill bit than spend another few hours futzing with that corner.</p>
<p><a href="https://i.stack.imgur.com/9ay0V.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/9ay0V.jpg" alt="enter image description here"></a></p>
<p>This is in Cura, after I have sliced it. Looks fine to me! There is a bit of red in that problematic corner, but I only noticed that after the print came out weird.</p>
<p><a href="https://i.stack.imgur.com/5RYPm.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/5RYPm.jpg" alt="enter image description here"></a></p>
<p>This is the output of the printer. Notice how the edge near the GPIO pins is shorter than the rest, and how the hole is inverted into a protrusion. This is the opposite of what I want, and the opposite of what I see in the other softwares.</p>
<p><a href="https://i.stack.imgur.com/DYrkP.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/DYrkP.jpg" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/QRpAo.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/QRpAo.jpg" alt="enter image description here"></a></p>
|
<h1>first issue</h1>
<p>bed inclination. it has to be heavy issue :)</p>
<p>if you have any other printouts then please reveal them so we could see if it's the problem</p>
<h1>next issue</h1>
<p>inversion of hole into solid object</p>
<p>i would say it's caused by wrong calculation of <a href="https://en.wikipedia.org/wiki/Normal_(geometry)" rel="nofollow noreferrer">normal vector</a> to some face(s)</p>
<p>algorithm uses normal to calculates what is "inside" and what is not</p>
<p>it's hard to say if it's an issue of </p>
<ul>
<li>object itself</li>
<li>application in which you modify it (even if duplicating or joining with other objects)</li>
<li>slicer engine</li>
</ul>
<p>to fix the issue, you can try edit your object (recreate this hole)</p>
<p>but first - definitelly i'd align your bed properly ;)</p>
<p><strong>EDIT</strong></p>
<p>after closer look i bet it's the issue of bad object. it looks like pointed line is kinda remnant of some operations made on object in the past</p>
<p>in other words - it's possible place where normals are reverted and doesn't "create" inside but outside</p>
<p>all above this line is reverted. <strong>part of body disappeared and part of hole appeared</strong></p>
<p>this is the issue for sure!</p>
<p><a href="https://i.stack.imgur.com/QupM7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QupM7.png" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/ZTVh2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZTVh2.png" alt="enter image description here"></a></p>
|
<p>Looks like you are over extruding.</p>
<p>check out this visual guide for example (I like it a lot):</p>
<p><a href="http://support.3dverkstan.se/article/23-a-visual-ultimaker-troubleshooting-guide" rel="nofollow noreferrer">http://support.3dverkstan.se/article/23-a-visual-ultimaker-troubleshooting-guide</a></p>
<p>For the protruding thingy, it seems (as the other hole is filled up with over extruded filament, it seems) that it's the "hole" printed. For the rest of the "wall" where that hole should have been, it seems it was just not printed. What size is it (if too thin, the slicer might just discard it, doesn't seems like it but you didn't tell nozzle size etc).</p>
<p>I don't know, but I think you should start with calibrating your machine first so that you actually <em>can</em> print small holes like that.</p>
<p>For the missing wall, what does the slice result look like?</p>
| 722
|
<p>I have a dynamic query that returns around 590,000 records. It runs successfully the first time, but if I run it again, I keep getting a <code>System.OutOfMemoryException</code>. What are some reasons this could be happening?</p>
<p>The error is happening here:</p>
<pre><code> public static DataSet GetDataSet(string databaseName,string
storedProcedureName,params object[] parameters)
{
//Creates blank dataset
DataSet ds = null;
try
{
//Creates database
Database db = DatabaseFactory.CreateDatabase(databaseName);
//Creates command to execute
DbCommand dbCommand = db.GetStoredProcCommand(storedProcedureName);
dbCommand.CommandTimeout = COMMAND_TIMEOUT;
//Returns the list of SQL parameters associated with that stored proecdure
db.DiscoverParameters(dbCommand);
int i = 1;
//Loop through the list of parameters and set the values
foreach (object parameter in parameters)
{
dbCommand.Parameters[i++].Value = parameter;
}
//Retrieve dataset and set to ds
ds = db.ExecuteDataSet(dbCommand);
}
//Check for exceptions
catch (SqlException sqle)
{
throw sqle;
}
catch (Exception e)
{
throw e; // Error is thrown here.
}
//Returns dataset
return ds;
}
</code></pre>
<p>Here is the code the runs on the button click:</p>
<pre><code>protected void btnSearchSBIDatabase_Click(object sender, EventArgs e)
{
LicenseSearch ls = new LicenseSearch();
DataTable dtSearchResults = new DataTable();
dtSearchResults = ls.Search();
Session["dtSearchResults"] = dtSearchResults;
Response.Redirect("~/FCCSearch/SearchResults.aspx");
}
else
lblResults.Visible = true;
}
</code></pre>
|
<blockquote>
<p>It runs successfully the first time,
but if I run it again, I keep getting
a System.OutOfMemoryException. What
are some reasons this could be
happening?</p>
</blockquote>
<p>Regardless of what the others have said, the error has nothing to do with forgetting to dispose your DBCommand or DBConnection, and you will not fix your error by disposing of either of them.</p>
<p>The error has everything to do with your dataset which contains nearly 600,000 rows of data. Apparently your dataset consumes more than 50% of the available memory on your machine. Clearly, you'll run out of memory when you return another dataset of the same size before the first one has been garbage collected. Simple as that.</p>
<p>You can remedy this problem in a few ways:</p>
<ul>
<li><p>Consider returning fewer records. I personally can't imagine a time when returning 600K records has ever been useful to a user. To minimize the records returned, try:</p>
<ul>
<li><p>Limiting your query to the first 1000 records. If there are more than 1000 results returned from the query, inform the user to narrow their search results.</p></li>
<li><p>If your users really insist on seeing that much data at once, try paging the data. Remember: Google never shows you all 22 bajillion results of a search at once, it shows you 20 or so records at a time. Google probably doesn't hold all 22 bajillion results in memory at once, it probably finds its more memory efficient to requery its database to generate a new page.</p></li>
</ul></li>
<li><p>If you just need to iterate through the data and you don't need random access, try returning a datareader instead. A datareader only loads one record into memory at a time.</p></li>
</ul>
<p>If none of those are an option, then you need to force .NET to free up the memory used by the dataset before calling your method using one of these methods:</p>
<ul>
<li><p>Remove all references to your old dataset. Anything holding on to a refenence of your dataset will prevent it from being reclaimed by memory.</p></li>
<li><p>If you can't null all the references to your dataset, clear all of the rows from the dataset and any objects bound to those rows instead. This removes references to the datarows and allows them to be eaten by the garbage collector.</p></li>
</ul>
<p>I don't believe you'll need to call <code>GC.Collect()</code> to force a gen cycle. Not only is it generally a bad idea to call <code>GC.Collect()</code>, because sufficient memory pressure will cause .NET invoke the garbage collector on its own.</p>
<p><em>Note: calling Dispose on your dataset does not free any memory, nor does it invoke the garbage collector, nor does it remove a reference to your dataset. Dispose is used to clean up unmanaged resources, but the DataSet does not have any unmanaged resources. It only implements IDispoable because it inherents from MarshalByValueComponent, so the Dispose method on the dataset is pretty much useless.</em></p>
|
<p>Where does it fail?</p>
<p>I agree that your issue is probably that your dataset of 600,000 rows is probably just too large. I see that you are then adding it to Session. If you are using Sql session state, it will have to serialize that data as well.</p>
<p>Even if you dispose of your objects properly, you will always have at least 2 copies of this dataset in memory if you run it twice, once in session, once in procedural code. This will never scale in a web application.</p>
<p>Do the math, 600,000 rows, at even 1-128 bit guid per row would yield 9.6 megabytes (600k * 128 / 8) of just data, not to mention the dataset overhead.</p>
<p>Trim down your results.</p>
| 46,502
|
<p>3 fields: FirstName, MiddleName, LastName</p>
<p>Any field can be null, but I don't want extra spaces. Format should be "First Middle Last", "First Last", "Last", etc.</p>
|
<pre><code> LTRIM(RTRIM(
LTRIM(RTRIM(ISNULL(FirstName, ''))) + ' ' +
LTRIM(RTRIM(ISNULL(MiddleName, ''))) + ' ' +
LTRIM(ISNULL(LastName, ''))
))
</code></pre>
<p>NOTE: This won't leave trailing or leading spaces. That's why it's a little bit uglier than other solutions.</p>
|
<p><code>LTrim(RTrim(Replace(IsNull(Firstname + ' ', '') +
isNull(MiddleName, '') +
IsNull(' ' + LastName, ''), ' ', ' ')))</code></p>
| 45,739
|
<p>I'm working on a C# program, and right now I have one <code>Form</code> and a couple of classes. I would like to be able to access some of the <code>Form</code> controls (such as a <code>TextBox</code>) from my class. When I try to change the text in the <code>TextBox</code> from my class I get the following error:</p>
<blockquote>
<p>An object reference is required for the non-static field, method, or property 'Project.Form1.txtLog' </p>
</blockquote>
<p>How can I access methods and controls that are in <code>Form1.cs</code> from one of my classes?</p>
|
<p>You are trying to access the class as opposed to the object. That statement can be confusing to beginners, but you are effectively trying to open your house door by picking up the door on your house plans.</p>
<p>If you actually wanted to access the form components directly from a class (which you don't) you would use the variable that instantiates your form. </p>
<p>Depending on which way you want to go you'd be better of either sending the text of a control or whatever to a method in your classes eg</p>
<pre><code>public void DoSomethingWithText(string formText)
{
// do something text in here
}
</code></pre>
<p>or exposing properties on your form class and setting the form text in there - eg</p>
<pre><code>string SomeProperty
{
get
{
return textBox1.Text;
}
set
{
textBox1.Text = value;
}
}
</code></pre>
|
<p>JUST YOU CAN SEND FORM TO CLASS LIKE THIS</p>
<pre><code>Class1 excell = new Class1 (); //you must declare this in form as you want to control
excel.get_data_from_excel(this); // And create instance for class and sen this form to another class
</code></pre>
<p>INSIDE CLASS AS YOU CREATE CLASS1</p>
<pre><code>class Class1
{
public void get_data_from_excel (Form1 form) //you getting the form here and you can control as you want
{
form.ComboBox1.text = "try it"; //you can chance Form1 UI elements inside the class now
}
}
</code></pre>
<p>IMPORTANT : But you must not forgat you have declare modifier form properties as PUBLIC and you can access other wise you can not see the control in form from class</p>
| 26,716
|
<p>To pop up the UAC dialog in Vista when writing to the HKLM registry hive, we opt to not use the Win32 Registry API, as when Vista permissions are lacking, we'd need to relaunch our entire application with administrator rights. Instead, we do this trick:</p>
<pre><code>ShellExecute(hWnd, "runas" /* display UAC prompt on Vista */, windir + "\\Reg", "add HKLM\\Software\\Company\\KeyName /v valueName /t REG_MULTI_TZ /d ValueData", NULL, SW_HIDE);
</code></pre>
<p>This solution works fine, besides that our application is a 32-bit one, and it runs the REG.EXE command as it would be a 32-bit app using the WOW compatibility layer! :( If REG.EXE is ran from the command line, it's properly ran in 64-bit mode. This matters, because if it's ran as a 32-bit app, the registry keys will end up in the wrong place due to <a href="http://msdn.microsoft.com/en-us/library/aa384235(VS.85).aspx" rel="noreferrer">registry reflection</a>.</p>
<p>So is there any way to launch a 64-bit app programmatically from a 32-bit app and not have it run using the WOW64 subsystem like its parent 32-bit process (i.e. a "*" suffix in the Task Manager)?</p>
|
<p>try this (from a 32bit process):</p>
<pre><code>> %WINDIR%\sysnative\reg.exe query ...
</code></pre>
<p>(found that <a href="http://ovidiupl.spaces.live.com/blog/cns!1E8A6038167E4BE9!925.entry" rel="noreferrer">here</a>).</p>
|
<p>One thing that I've done as a solution for myself is to PInvoke disabling redirection:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa365744(v=vs.85).aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/windows/desktop/aa365744(v=vs.85).aspx</a></p>
<p>You can always turn it right back on.</p>
| 19,631
|
<p>I came across a problem in my current application that required fiddling with the query string in a base <code>Page</code> class (which all my pages inherit from) to solve the problem. Since some of my pages use the query string I was wondering if there is any class that provides clean and simple query string manipulation.</p>
<p>Example of code:</p>
<pre><code>// What happens if I want to future manipulate the query string elsewhere
// (e.g. maybe rewrite when the request comes back in)
// Or maybe the URL already has a query string (and the ? is invalid)
Response.Redirect(Request.Path + "?ProductID=" + productId);
</code></pre>
|
<p>Use <code>HttpUtility.ParseQueryString</code>, as someone suggested (and then deleted).</p>
<p>This will work, because the return value from that method is actually an <code>HttpValueCollection</code>, which inherits <code>NameValueCollection</code> (and is internal, you can't reference it directly). You can then set the names/values in the collection normally (including add/remove), and call <code>ToString</code> -- which will produce the finished querystring, because <code>HttpValueCollection</code> overrides <code>ToString</code> to reproduce an actual query string.</p>
|
<p>What I usually do is just rebuild the querystring. Request has a QueryString collection. </p>
<p>You can iterator over that to get the current (unencoded) parameters out, and just join them together (encoding as you go) with the appropriate separators.</p>
<p>The advantage is that Asp.Net has done the original parsing for you, so you don't need to worry about edge cases such as trailing & and ?s.</p>
| 49,099
|
<p>I'm trying to drop a SQL Server database using the following code:</p>
<pre><code>SqlCommand command = new SqlCommand("USE MASTER; ALTER DATABASE @database SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE @Database", connection);
command.Parameters.AddWithValue("@database", TestingEnvironment.DatabaseName);
command.ExecuteNonQuery();
</code></pre>
<p>When I execute it, I get the error:</p>
<blockquote>
<p>Incorrect syntax near '@database'.
Incorrect syntax near the keyword
'with'. If this statement is a common
table expression or an xmlnamespaces
clause, the previous statement must be
terminated with a semicolon. Incorrect
syntax near 'IMMEDIATE'.</p>
</blockquote>
<p>What am I doing wrong?</p>
|
<p>putting it simply the Alter Database command doesn't support parameters as you want it to. you'll have to concat strings here.</p>
|
<p>Are the Params case sensitive? You have a capital D in the 2nd @Database.</p>
| 35,160
|
<p>Does the silverlight clr support access to a sql compact database placed in the silverlight application's isolated storage?</p>
<p>If so, any pointers to code samples.</p>
<p>I would like to cache information retrieved from the server in previous sessions. </p>
|
<p>Even if it was stored in Isolated Storage, there is no Silverlight library to read in SQL Server Compact Edition. Perhaps in a future version. I have heard of a couple of open source projects that are trying to do this but there are not any that have releases yet. I tried to wrap the Google Gears DB in Beta 2 to no success.</p>
|
<p>I have a sample here, using SQL Server Compact and Silverlight (OOB and elevated and on Windows only) - <a href="http://erikej.blogspot.com/2010/02/access-local-sql-compact-database-from.html" rel="nofollow">http://erikej.blogspot.com/2010/02/access-local-sql-compact-database-from.html</a></p>
| 42,996
|
<p>Well this is incredibly frustrating. After being nagged by Rails that I need to install the C-based MySQL adaptor, I did so... and then discovered that it won't work with MySQL under version 6. Now 'gem uninstall mysql' results in 'unknown gem mysql'. </p>
<p>I just spent half an hour trying to get the thing to install in the first place (by juggling all the "where the hell is my config file, anyway?" type of options).</p>
<p>Anyway, I can't find hints anywhere on how to use the ORIGINAL MySQL adaptor now that I've discovered that it's either that or an upgrade to MySQL 6, which I don't want to do since I'm using an XAMPP package that works very nicely already </p>
<p>(This is on my local box for testing, this is not a dev or production server issue. I'll deal with that later.)</p>
<p>So how do I either make sure Rails uses the built in version (using command line options?) OR remove the MySQL gem? </p>
<p>(Optional third option: Suck it up and upgrade my local copy of MySQL.)</p>
<p>edit: Turns out I was wrong about the version of MySQL I needed in the first place, and I fixed and upgraded a bunch of stuff. </p>
<p>However, my answer to the ORIGINAL question still stands: Delete the gem. If gem itself can't delete it, just delete all traces of it and RoR will default to the original adapter. This probably doesn't work in newer version of Rails, which (I think) REQUIRE the new adapter.</p>
|
<p>If you have a contended lock, the second thread has to wait until the first releases the lock.</p>
<p>Your plan sounds <em>nearly</em> okay - but you need to lock when <em>reading</em> data as well, to make sure you get the most recent values, and consistent ones. Otherwise you could be half way through writing some values in one thread, and see some of the new values - but possibly not all - and the old values, all at the same time in a different thread.</p>
<p>If you can avoid doing this as much as possible, your life will be easier :) Immutable types make threading a lot simpler.</p>
<p>Don't forget that if you ever have code which will need two locks at the same time (e.g. adding one RServer and modifying another, atomically) you <em>must</em> make sure that you always aquire locks in the same order - if one thread tries to acquire lock B while it's holding lock A, and a different thread tries to acquire lock A while it's holding lock B, you'll end up with deadlock.</p>
<p>See my <a href="http://pobox.com/~skeet/csharp/threads" rel="noreferrer">threading tutorial</a> or <a href="http://www.albahari.com/threading/default.aspx" rel="noreferrer">Joe Albahari's</a> for more details. Also, if you're interested in concurrency, Joe Duffy has an <a href="https://rads.stackoverflow.com/amzn/click/com/032143482X" rel="noreferrer" rel="nofollow noreferrer">excellent book</a> which is coming out very soon.</p>
|
<p>That is safe. If one thread has acquired the lock, other threads will have to wait until the lock is released.</p>
<p>However, improbable as it is, you could hit a performance problem since the lock may be TOO global. It really depends on what your state is and how it is mutated by those threads, so I can't help you with that.</p>
| 27,628
|
<p>I'm calling a bunch of methods that return a list. The list may be empty. If the list is non-empty, I want to return the first item; otherwise, I want to return <code>None</code>. This code works:</p>
<pre class="lang-py prettyprint-override"><code>def main():
my_list = get_list()
if len(my_list) > 0:
return my_list[0]
return None
</code></pre>
<p>but it seems to me that there should be a simple one-line idiom for doing this. Is there?</p>
|
<h2>Python 2.6+</h2>
<pre><code>next(iter(your_list), None)
</code></pre>
<p>If <code>your_list</code> can be <code>None</code>:</p>
<pre><code>next(iter(your_list or []), None)
</code></pre>
<h2>Python 2.4</h2>
<pre><code>def get_first(iterable, default=None):
if iterable:
for item in iterable:
return item
return default
</code></pre>
<p>Example:</p>
<pre><code>x = get_first(get_first_list())
if x:
...
y = get_first(get_second_list())
if y:
...
</code></pre>
<p>Another option is to inline the above function:</p>
<pre><code>for x in get_first_list() or []:
# process x
break # process at most one item
for y in get_second_list() or []:
# process y
break
</code></pre>
<p>To avoid <code>break</code> you could write:</p>
<pre><code>for x in yield_first(get_first_list()):
x # process x
for y in yield_first(get_second_list()):
y # process y
</code></pre>
<p>Where:</p>
<pre><code>def yield_first(iterable):
for item in iterable or []:
yield item
return
</code></pre>
|
<p>You could use <a href="http://www.refactoring.com/catalog/extractMethod.html" rel="nofollow noreferrer">Extract Method</a>. In other words extract that code into a method which you'd then call.</p>
<p>I wouldn't try to compress it much more, the one liners seem harder to read than the verbose version. And if you use Extract Method, it's a one liner ;)</p>
| 47,511
|
<p>How to balance "zone" time against open and active communication within a development team?</p>
|
<p>Read "Peopleware"</p>
<p>Offices with doors.</p>
<p>phones you can turn off.</p>
<p>emails</p>
<p>Usable common areas with whiteboards.</p>
<p>There are some phases of development when lots of collaboration is very productive and other times where individual focus is important. Also, people work differently - you don't wantt o interrupt folks who do better when left alone and you don't want to isolate those who need feedback and help. I would avoid rules and just make it clear to t ateam that this is an issue and it is up to each developer to enforce their own desired environment. Management should support it.</p>
<p>USEFUL meetings are great, but open bullpens as work environments for "open communication" is a fantasy dreamed up by beancounters or managers who want to keep an eye on all their staff.</p>
|
<p>Read "Peopleware"</p>
<p>Offices with doors.</p>
<p>phones you can turn off.</p>
<p>emails</p>
<p>Usable common areas with whiteboards.</p>
<p>There are some phases of development when lots of collaboration is very productive and other times where individual focus is important. Also, people work differently - you don't wantt o interrupt folks who do better when left alone and you don't want to isolate those who need feedback and help. I would avoid rules and just make it clear to t ateam that this is an issue and it is up to each developer to enforce their own desired environment. Management should support it.</p>
<p>USEFUL meetings are great, but open bullpens as work environments for "open communication" is a fantasy dreamed up by beancounters or managers who want to keep an eye on all their staff.</p>
| 47,168
|
<p>I have a draggable div that represents a little info popup that the user can drag around the screen. But this div is anchored to a point on the screen, and I would like there to be a caret drawn between the div and the point that it is anchored to.</p>
<p>An example of this can be found on Google maps, when you hover over a store or point of interest that you've searched for. You'll see a caret drawn between the point and the popup. This is simple enough, but their popup is not draggable while mine is.</p>
<p>So what is the best way to implement this? I'm thinking of using a series of caret images that are resized depending on the orientation of the popup relative to the anchor point. It'll get tricky in that I'll have to use a different type of caret depending on the angle at which the popup is placed relative to the anchor. Is there a better way to do this?</p>
<p>Thanks!</p>
|
<p>So you're essentially trying to draw a dynamic image between two points on the screen? I'm not sure how practical this is in HTML. The dom does not support image rotations and image resizing is limited in quality. You can do server-size image generation but that will be slow and give you high server load.</p>
<p>Some newer browsers (not IE) support the Canvas object which may allow you to do this if you're willing to exclude 80% of users.</p>
<p>In the end, I'm not sure there is a better solution than what you're already thinking - and I'm not sure how well that will work.</p>
|
<p>This tutorial on <a href="http://www.p01.org/releases/Drawing_lines_in_JavaScript/" rel="nofollow noreferrer">Drawing lines in JavaScript</a> may be of some use to you, as it shows you how to do relatively efficient dynamic line drawings using JavaScript (see examples at the bottom of the page).</p>
<p>Also I have used the <a href="http://www.walterzorn.com/jsgraphics/jsgraphics_e.htm" rel="nofollow noreferrer">jsgraphics</a> library to achieve something similar by clearing the current line and drawing a new one each time the user moves the endpoint of the line.</p>
| 48,718
|
<p>I require a star rating control (which allows partial rating like 4.5) for my application built on asp.net mvc.</p>
<p>Any pointers in this direction will be helpful?</p>
|
<p>Rogie, over at <a href="http://www.komodomedia.com/blog/" rel="noreferrer">Komodomedia</a>, has spent far too long on this <a href="http://www.komodomedia.com/blog/2005/08/creating-a-star-rater-using-css/" rel="noreferrer">topic</a> <a href="http://www.komodomedia.com/blog/2005/08/creating-a-star-rater-using-css/" rel="noreferrer">writing</a> 3 <a href="http://www.komodomedia.com/blog/2007/01/css-star-rating-redux/" rel="noreferrer">articles</a> on the topic.</p>
<p><a href="http://www.komodomedia.com/blog/2007/01/css-star-rating-redux/" rel="noreferrer">Just in case anyone got lost in the link-soup this is the latest.</a></p>
<p>It's not MVC specific, but it is cross browser and allows you to get the value back via postback or ajax.</p>
|
<p>I know this is an old post but I like to answer it for everybody who will find this post through search engines.</p>
<p>This article explains how to implement a star rating system for MVC.
I have implemented it and it works like a charm.</p>
<p><a href="http://www.codecapers.com/post/Building-a-Star-Rating-System-with-ASPNET-MVC-and-jQuery.aspx" rel="nofollow">http://www.codecapers.com/post/Building-a-Star-Rating-System-with-ASPNET-MVC-and-jQuery.aspx</a></p>
| 42,864
|
<p>I want to read all thumbnails from a folder with images in Windows XP.
But if I read image file to get thumbnail, it seems a bit slow, so I wish I can first read the windows image thumbnail cache:thumb.db.
Is there any lib in c++ or c to read thumbnails from thumb.db.</p>
|
<p>The Thumbs.db file is stored in OLE <a href="http://msdn.microsoft.com/en-us/library/ms693383.aspx" rel="noreferrer">Compound Document</a> format, the same format that many Microsoft Office products use.</p>
<p>You could also try to look into <a href="http://www.petedavis.net/MySite/DynPageView.aspx?pageid=31" rel="noreferrer">ThumbsDBLib</a>. It is in C# but you can probably see what they do to read the data and convert it to C++.</p>
<p>Note: Windows Vista and later doesn't use Thumbs.db. See the <a href="http://msdn.microsoft.com/en-us/library/bb774628(VS.85).aspx" rel="noreferrer">IThumbnailCache interface</a> for Vista and later.</p>
<p>For Vista and later they are stored here: %homedrive%\Users\%username%\AppData\Local\Microsoft\Windows\Explorer</p>
|
<p>You might find this useful:</p>
<p>ThumbsDBLib in C++</p>
<p><a href="http://www.windameister.org/blog/index.php/thumbslib-in-cpp" rel="nofollow noreferrer">http://www.windameister.org/blog/index.php/thumbslib-in-cpp</a></p>
| 28,256
|
<p>So I've got a Ruby method like this:</p>
<pre><code>def something(variable, &block)
....
end
</code></pre>
<p>And I want to call it like this:</p>
<pre><code>something 'hello' { do_it }
</code></pre>
<p>Except that isn't working for me, I'm getting a syntax error. If I do this instead, it works:</p>
<pre><code>something 'hello' do
do_it
end
</code></pre>
<p>Except there I'm kind of missing the nice look of it being on one line.</p>
<p>I can see why this is happening, as it could look like it's a hash being passed as a second variable, but without a comma in between the variables...but I assume that there must be a way to deal with this that I'm missing. Is there?</p>
|
<p>You need to parenthesize your argument:</p>
<pre><code>something('hello') { do_it }
</code></pre>
<p>That should work.</p>
|
<p>Uh, what about:</p>
<pre><code>>> def something(arg1 , &block)
>> yield block
>> end
=> nil
>> def do_it
>> puts "Doing it!"
>> end
=> nil
>> something('hello') { do_it }
"Doing it!"
=> nil
</code></pre>
| 31,907
|
<p>If you are starting to develop a new web application from scratch and the only two requirements you have is that it will be deployed to Windows 2008 Server and that standard ASP.NET incl. VS2008 doesn't cut it (doesn't matter why, let's say it's the license cost, you won't be hosting Windows 2008 Server yourself). Which web framework would you choose under this circumstances?</p>
|
<p>I read a benchmark article some time ago that suggested running an open source web stack on top of Windows was the best performer out of all the variations (i.e. WAMP). I don't know how much faith to put in those types of articles, and IIRC it beat out LAMP by some really small margin. You might find WAMP to be a good fit for your situation, but I think you should save yourself the Windows tax and use a LAMP (or use Postgres instead of MySQL... I like it better). </p>
|
<p>I'm stuck wondering why you'd host on a Windows server and not use ASP.Net. It is the best of the server-side frameworks for a windows environment, as it works most intuitively with IIS.</p>
<p>But there's another problem there: If memory serves, all the other frameworks require additional software to run on the server. <a href="http://us2.php.net/install.windows" rel="nofollow noreferrer">PHP requires PHP runtime to be installed as a CGI Extension in IIS</a>, <a href="http://codebetter.com/blogs/ben.reichelt/archive/2006/02/21/138812.aspx" rel="nofollow noreferrer">Rails requires Ruby</a>, CGI style options (C, Perl, Python) require not only the compiler/runtimes but also some poking under the hood in regards to how IIS handles those files, JSP requires... I'm not sure, I've never used JSP, and <a href="http://www.adobe.com/products/coldfusion/buy/" rel="nofollow noreferrer">ColdFusion requires that framework and it really is a hefty licensing cost</a> (as opposed to ASP.Net which is a free download for the server).</p>
<p>So, in the end, you're left with basically picking an option, installing the necessary software and going forward. Personally, if forced to make this choice, I would choose either PHP or Ruby on Rails, but there's no valid reason for that outside of a random, and subjective choice.</p>
| 37,787
|
<p>I want to create a history table to track field changes across a number of tables in DB2. </p>
<p>I know history is usually done with copying an entire table's structure and giving it a suffixed name (e.g. user --> user_history). Then you can use a pretty simple trigger to copy the old record into the history table on an UPDATE.</p>
<p>However, for my application this would use too much space. It doesn't seem like a good idea (to me at least) to copy an entire record to another table every time a field changes. So I thought I could have a generic 'history' table which would track individual field changes:</p>
<pre><code>CREATE TABLE history
(
history_id LONG GENERATED ALWAYS AS IDENTITY,
record_id INTEGER NOT NULL,
table_name VARCHAR(32) NOT NULL,
field_name VARCHAR(64) NOT NULL,
field_value VARCHAR(1024),
change_time TIMESTAMP,
PRIMARY KEY (history_id)
);
</code></pre>
<p>OK, so every table that I want to track has a single, auto-generated id field as the primary key, which would be put into the 'record_id' field. And the maximum VARCHAR size in the tables is 1024. Obviously if a non-VARCHAR field changes, it would have to be converted into a VARCHAR before inserting the record into the history table.</p>
<p>Now, this could be a completely retarded way to do things (hey, let me know why if it is), but I think it it's a good way of tracking changes that need to be pulled up rarely and need to be stored for a significant amount of time. </p>
<p>Anyway, I need help with writing the trigger to add records to the history table on an update. Let's for example take a hypothetical user table:</p>
<pre><code>CREATE TABLE user
(
user_id INTEGER GENERATED ALWAYS AS IDENTITY,
username VARCHAR(32) NOT NULL,
first_name VARCHAR(64) NOT NULL,
last_name VARCHAR(64) NOT NULL,
email_address VARCHAR(256) NOT NULL
PRIMARY KEY(user_id)
);
</code></pre>
<p>So, can anyone help me with a trigger on an update of the user table to insert the changes into the history table? My guess is that some procedural SQL will need to be used to loop through the fields in the old record, compare them with the fields in the new record and if they don't match, then add a new entry into the history table. </p>
<p>It'd be preferable to use the same trigger action SQL for every table, regardless of its fields, if it's possible.</p>
<p>Thanks!</p>
|
<blockquote>
<p>The error is really nasty, but boils down to the fact that it can't figure out which set::insert to use, since there's three overloads.</p>
</blockquote>
<p>You can work around the ambiguity by giving bind a helpful hand, by specifying a pointer to the function you wish to use:</p>
<pre><code>typedef std::set<std::string> s_type;
typedef std::pair<s_type::iterator, bool>(s_type::*insert_fp)(const s_type::value_type&);
std::for_each(s_vector.begin(), s_vector.end(), boost::bind(static_cast<insert_fp>(&s_type::insert), &s_set, _1));
</code></pre>
<p>It's not pretty, but it should work.</p>
|
<p>Unfortunately, this:</p>
<pre><code>std::for_each(s_vector.begin(), s_vector.end(),
lambda::bind(&std::set<std::string>::insert, s_set, lambda::_1));
</code></pre>
<p>doesn't work. (Note that I used set::insert, because that's what s_set is.) The error is really nasty, but boils down to the fact that it can't figure out which set::insert to use, since there's three overloads. The one that I'm trying to use is the set that will return pair::iterator, bool> (the value insert). Obviously, that's not working.</p>
<p>I noticed you used boost::bind, not boost::lambda::bind -- was that intentional? (They appear to work a bit differently.)</p>
<p>I think you're right about expecting a functor as opposed to a function call result; I'm sure this can be turned into a functor, but my brain is not seeing the answer right now.</p>
<p>Thanks.</p>
| 35,345
|
<p>I'm in need of a lightweight library for 2d & 3d vectors and 3x3 & 4x4 matrices. In basic C.
Just so I don't reinvent the wheel suboptimally.</p>
<p>Any suggestions?</p>
|
<p><a href="http://www.math.uiowa.edu/~dstewart/meschach/" rel="noreferrer">Meschach</a> is a c-only vector/matrix library, significantly smaller than e.g. LAPACK (according to the FAQ, at least :)</p>
|
<p>You may also want to have a look at the <a href="http://arma.sourceforge.net" rel="nofollow noreferrer">Armadillo C++ library</a></p>
| 24,252
|
<p>I've gotten comfy with SVN, and now I need a way to deploy my code to staging or live servers more easily. I'd also like some method for putting build info in the footer of this site to aid in testing. Site is PHP/MySQL.</p>
|
<p>A script to svn update on an as needed basis. </p>
<p>SVN supports keywords. You can add which keywords you want to expand to the keywords property, and SVN will expand then. See $Id$ or $Rev$, or keywords described in the SVN book.</p>
|
<p>A really simple way to manage this is to setup your app in the following way:</p>
<p>Simply make your deployment app a working copy of your trunk (<code>svn co</code> the project to your /www root) and you run an <code>svn up</code> through an ssh console (<code>ssh user@host.com svn up /path/to/project</code>) when you need to update. You can also rollback with the appropriate checkout mechanisms. This is important: <strong>if you do this, add RewriteRules (or equivalent) to your .htaccess (or equivalent) to disallow access to .svn directories</strong>. If you can't do the above, run an <code>svn export</code> through ssh instead (so it won't be a 'working copy'), but this will naturally be slower than doing an <code>up</code>.</p>
<p>Also, you can look at what Ruby on Rails does with Capistrano.. it's the same basic concept but supports transactional backups if the update goes wrong in the middle by storing each checkout in a separate folder and symlinking the "latest" to your /www directory.</p>
| 9,218
|
<p>I need a RegEx pattern for extracting all the properties of an image tag.</p>
<p>As we all know, there are lots of malformed HTML out there, so the pattern has to cover those possibilities.</p>
<p>I was looking at this solution <a href="https://stackoverflow.com/questions/138313/how-to-extract-img-src-title-and-alt-from-html-using-php" title="How to Extract img src title and alt">https://stackoverflow.com/questions/138313/how-to-extract-img-src-title-and-alt-from-html-using-php</a> but it didn't quite get it all:</p>
<p>I come up something like:</p>
<pre><code>(alt|title|src|height|width)\s*=\s*["'][\W\w]+?["']
</code></pre>
<p>Is there any possibilities I'll be missing or a more efficient simple pattern?</p>
<p>EDIT:
<br>Sorry, I will be more specific, I'm doing this using .NET so it's on the server side.
<br>I've already a list of img tags, now I just need to parse the properties.</p>
|
<blockquote>
<p>As we all know, there are lots of malformed HTML out there, so the pattern has to cover those possibilities.</p>
</blockquote>
<p>It won't. Use a HTML parser if you have to parse "evil" (from an unknown source) HTML.</p>
|
<p>If you want <strong>all</strong> attribute values, might I suggest using the DOM? Something like <code>element.attributes</code> will work well.</p>
<p>If you insist on a regex <code>//\b\w+="[^"]+"//</code> should get everything.</p>
| 45,584
|
<p>I currently work with an Oracle database and we use stored procedures for all our SQL queries. The problem I have is that we do not really having a coding standard for our packages. So what happens is that every developer has a different style (or in some cases no sense of style) in how they format there packages. Making them difficult to read and work on with out first reformatting. We all pretty much just use Notepad or Notepad2 to write our packages. </p>
<p>I am unfortunately not in a position to mandate a coding standard and enforce it (just a code monkey at this point) so I was hoping to find a free SQL code formatter that I can use myself, and possibly suggest to others on the team to use, to make my life easier.</p>
<p>I have considered writing a small application that would essentially take a file as input and reformat everything, but before I did this I figured I would ask if anyone new of such a tool that is already available and is free.</p>
<p>So does anyone now of any such tools available? </p>
|
<ul>
<li><a href="http://www.vim.org/scripts/script.php?script_id=492" rel="nofollow noreferrer">VIM script</a> </li>
<li><a href="http://www.aquafold.com/" rel="nofollow noreferrer">Aqua Data studio</a> $ I use this one all the time.</li>
</ul>
|
<p>I like <a href="http://www.toadsoft.com/toad_oracle.htm" rel="nofollow noreferrer">TOAD for Oracle</a>. It has a format feature that's decent. I see there's a freeware version, though I have not used it.</p>
| 5,403
|
<p>Is it possible to retrieve the CPUID and MAC address of a client machine from a Ruby on Rails application?. Are there any plugins available for this?</p>
|
<p>I'm pretty sure it is not possible to parse the /proc filesystem of a client computer through a Rails applications (and thank God for that).</p>
<p>What you could do is make use of Javascript to some extent. There are quite some sites on the internet (mainly privacy scanners) which make use of Javascript to show extensive information about a client system. This might even work for the type of CPU of the client uses (assuming that is what you mean by 'CPUID').</p>
<p>What neither Javascript nor Rails can do for you though, is show you the MAC address of a client (assuming with 'macid' you mean a MAC address). If you take a deeper look into the way TCP/IP networking is done, you'll notice that this is by design. A computer in another network segment (say, the internet) is never intended to know your MAC address, nor does it need to.</p>
<p>If you really want to know someone's MAC, you'll need to use something like a Java applet or an ActiveX control (though that limits you to a certain platform). Those things should prompt your user for confirmation / permission before sending out privacy sensitive information like MAC addresses, which is a Good Thing.</p>
|
<p>If the are computers on the localhost network (intranet) you could use ruby to call some command line admin tools. For example you could do a reverse lookup on the ip address to get the computers name. Not sure about Mac Address... You might be able to call a vbscript to do that.</p>
| 35,885
|
<p>I often switch my print material, i.e. ABS / PLA / Wood / Flex,</p>
<p>How can I best clean out my extruder between them to ensure I don't contaminate my next print?</p>
|
<p>If you feel you need to <em>clean</em> the nozzle the best approach is a <em>cold pull</em>. You can perform this procedure with many printers, however, you should seek advice from your printer manufacturer before attempting this process if you have any doubts.</p>
<p>With the previously filament still loaded and the tool head cold:</p>
<ul>
<li><p>Begin to raise the temperature of the tool to the printing temperature of <em>the next filament you intend to load</em></p></li>
<li><p>As it begins to warm up perform any tasks you normally perform during filament unloading (open the idler, for example). <strong>You should not be fighting against the extruder drive gear or any other part of the tool during this process!</strong></p></li>
<li><p>With a fair amount of pressure begin pulling on the filament</p></li>
<li><p>The old filament should eventually release from inside of the tool leaving the end of the filament roughly in a nice molded shape of the inside of the tool. Begin loading the next filament you intend to print and manually feed some filament through as the tool finishes heating</p></li>
</ul>
<p>Anything left over from the previous filament including pigment or other residue should be stuck to the end of the filament.</p>
<p>You can perform <em>cold pulls</em> as many times as you wish by loading new filament, extruding a small amount, letting it completely cool and repeating the steps.</p>
|
<p>Some people use a nylon "cleaning" filament when switching types of filaments. It heats well to a variety of temperatures and seems to stick well to whatever is in there when pulling it back out. Be sure to heat it up to the temperature of the filament being removed to get that to bind with the nylon.</p>
| 136
|
<p>Often multiple applications share a large codebase of libraries that change often in development. In these cases, I prefer to create a solution named after the suite, and include separate projects for each application and the shared libraries.</p>
<p>Is this a good approach? How do others structure their code bases for things like a suite of applications?</p>
|
<p>It really depends on your organization's particular needs. MSDN has a <a href="http://msdn.microsoft.com/en-us/library/ee817674.aspx" rel="noreferrer">good page</a> that goes through the various recommended solution layouts, including:</p>
<ol>
<li>The Single Solution model (preferred)</li>
<li>The Partitioned Single Solution model</li>
<li>The Multi-solution model (Only if strictly necessary)</li>
</ol>
<p>The <a href="http://msdn.microsoft.com/en-us/library/ee817674.aspx" rel="noreferrer">MSDN page</a> also discusses the pros and cons of each model in more detail so you can decide which one makes sense for you. :)</p>
<p>In general, for an application suite such as you describe, I would consider the partitioned, single solution model. There's a single master solution that builds everything, and a number of separate solutions for each individual application within the suite (assuming the applications are of appreciable size). </p>
<p>If the applications in the suite are small and build quickly (e.g., a suite of command line tools), I might not even generate the separate solution files. That's really a judgement call we can't make for you. :)</p>
|
<p>The actual structure of your solution(s) really depends on the internal workflow. Having a very agile, <strong>everyone-refactors-everything approach</strong> would point towards <strong>one solution</strong> with many projects. If your shop has <strong>a dedicated library team</strong> and various application teams, which do regular internal releases, then <strong>separate solutions</strong> might help through stronger decoupling, and <strong>reduced build times</strong>.</p>
| 24,533
|
<p>I'm trying to register an externally hosted SQL 2000 server through Enterprise Manager which isn't on the default port and I can't see anywhere to change it within Enterprise Manager.</p>
<p>So, the question is, how do I connect to the database if:</p>
<p>I.P. Address is 123.456.789 (example)</p>
<p>Port is 1334</p>
|
<p>I found this via <a href="http://www.avianwaves.com/Blog/Default.aspx?id=25&t=Connecting-SQL-Server-Management-Studio" rel="nofollow noreferrer">Google</a>:</p>
<blockquote>
<p>You add a comma and the port number to the end of the server name.</p>
<p>So if you want to connect to MySqlServer.MyDomain.com on port 3821, you type...</p>
<p>MySqlServer.MyDomain.com,3821</p>
</blockquote>
|
<p>Rob is correct - I have a SQL 2000 server running on the non-default port on a different instance name and the way I access it is like this:</p>
<blockquote>
<p>[ip or dns name]\[instance], [port]</p>
</blockquote>
<p>example:</p>
<blockquote>
<p>my.server.com\MSSQLSERVER2, 12345</p>
</blockquote>
<p>You don't need <code>\\[instance]</code> if you used the default sql server instance when you installed.</p>
| 11,051
|
<p>Anyone know of a way to use SVK with perforce? The docs <a href="http://svk.bestpractical.com/view/MirrorVCP" rel="nofollow noreferrer">seem to imply</a> it used to be possible, but some <a href="http://lists.bestpractical.com/pipermail/svk-devel/2007-February/000604.html" rel="nofollow noreferrer">mailing list messages</a> claim that is no longer the case?</p>
|
<p>For a private repository, you should try <a href="http://www.releng.com/p5layer.html" rel="nofollow noreferrer">P5</a></p>
|
<p>Why use SVK to mirror Perforce? Surely using a <a href="http://www.perforce.com/perforce/products/p4p.html" rel="nofollow noreferrer">Perforce Proxy</a> is the best way to make your repository distributed?</p>
| 7,602
|
<p>As the title: How would I tell NHibernate, once and for all, that all table and column names are to be quoted in the SQL it generates?</p>
|
<p>You can also try:</p>
<pre><code>SchemaMetadataUpdater.QuoteTableAndColumns(configuration);
</code></pre>
|
<p>I've not tried this, but as far as i can determine based on the <a href="http://www.hibernate.org/hib_docs/nhibernate/1.2/reference/en/html/session-configuration.html#configuration-namingstrategy" rel="nofollow noreferrer">documentation</a> a custom implementation of the naming strategy allows you to rewrite the table/column names thus also enables you to quote them.</p>
| 24,377
|
<p>So I started using Cura a few weeks ago, and when I print it goes to 204 Celsius instead of 200. It doesn't really affect my print quality but I just want to know if there's a fix for it. My printer is a Da Vinci Jr 1.0.</p>
|
<p>Its mainly due to the regulation loop of the PID Regulator implemented in the Firmware of the Da vinci jr. The P-Factor is a little bit too high. This is the reason why the temperature "overshoots". Because the Printerhead and Nozzle has some volume which is heated up. It takes time to cool down after it has detected an overshoot. </p>
<p>here you can find additional informations about it: <a href="https://innovativecontrols.com/blog/basics-tuning-pid-loops" rel="nofollow noreferrer">https://innovativecontrols.com/blog/basics-tuning-pid-loops</a></p>
|
<p>That's called PID overshoot. All control loops have varying types of outliers like this. Sometimes, you can't overshoot, sometimes you cant undershoot. But it's a remnant of the math. </p>
<p>The solution here, is to <a href="http://reprap.org/wiki/PID_Tuning" rel="nofollow noreferrer">PID Tune</a>. Once you get an established Kp Ki and Kd constants, then you can either save it to eeprom or you can recompile your firmware with this change.</p>
<p>It's pretty common, especially if you have different hotends without known profiles. PID tuning also works on heated beds as well. But usually those use what's called <a href="http://reprap.org/wiki/ExtruderIO#Bang-bang_control" rel="nofollow noreferrer">Bang-bang</a>.</p>
| 709
|
<p>I have a class with some abstract methods, but I want to be able to edit a subclass of that class in the designer. However, the designer can't edit the subclass unless it can create an instance of the parent class. So my plan is to replace the abstract methods with stubs and mark them as virtual - but then if I make another subclass, I won't get a compile-time error if I forget to implement them.</p>
<p>Is there a way to mark the methods so that they have to be implemented by subclasses, without marking them as abstract?</p>
|
<p>Well you could do some really messy code involving <code>#if</code> - i.e. in <code>DEBUG</code> it is virtual (for the designer), but in <code>RELEASE</code> it is abstract. A real pain to maintain, though.</p>
<p>But other than that: basically, no. If you want designer support it can't be abstract, so you are left with "virtual" (presumably with the base method throwing a <code>NotImplementedException</code>).</p>
<p>Of course, your unit tests will check that the methods have been implemented, yes? ;-p</p>
<p>Actually, it would probably be quite easy to test via generics - i.e. have a generic test method of the form:</p>
<pre><code>[Test]
public void TestFoo() {
ActualTest<Foo>();
}
[Test]
public void TestBar() {
ActualTest<Bar>();
}
static void ActualTest<T>() where T : SomeBaseClass, new() {
T obj = new T();
Assert.blah something involving obj
}
</code></pre>
|
<p>I know its not quite what you are after but you could make all of your stubs in the base class throw the NotImplementedException. Then if any of your subclasses have not overridden them you would get a runtime exception when the method in the base class gets called.</p>
| 29,620
|
<p>I want to change a flash object enclosed within with jQuery after an onClick event. The code I wrote, essentially:</p>
<pre><code>$(enclosing div).html('');
$(enclosing div).html(<object>My New Object</object>);
</code></pre>
<p>works in Firefox but not in IE. I would appreciate pointers or suggestions on doing this. Thanks.</p>
|
<p>The <code>empty()</code> method is the better way of deleting content. Don't know if that will solve your problem though :)</p>
<pre><code>$('#mydiv').empty();
</code></pre>
<p>You could also try the <code>replaceWith(content)</code> method.</p>
|
<p>Try the <code>$().remove()</code> method. This also removes event handlers to avoid memory leak problems and is one of the reasons why just setting the HTML to empty is not a good idea.</p>
| 27,413
|
<p>Please let me know why there is lot of white space below the page content and also why horizontal scroll bar is displayed. Attaching link to zip folder below. Unzip and open index.html.<br />
<a href="http://shivanand.in/tmp/Basic_Profile.zip" rel="nofollow noreferrer">link text</a></p>
|
<p>First lead:</p>
<p>The rule <code>div#content</code> almost works in IE, and does put extra width in FireFox:</p>
<p>The extra width is applied to your div class "<code>content</code>"</p>
<pre><code>div#content { margin: 3px 3px 3px 188px; background: rgb(255, 255, 255) none
repeat; min-height: 392px; }
</code></pre>
<p>within the div class "<code>container</code>"</p>
<pre><code>div#container { margin: auto; padding: 10px; background: rgb(255, 255, 255)
none repeat; position: relative; min-height: 400px;
max-width: 100%; min-width: 750px; }
</code></pre>
<p>horizontal scroll bar is displayed is for the 188px added to the right of the content. Of course, they need to stay: do not remove them.</p>
<p><strong>add <code>overflow: hidden</code>; to your <code>div#container</code> css rule</strong></p>
<p>On a more general note, you may want to follow the <a href="http://alistapart.com/articles/progressiveenhancementwithcss" rel="nofollow noreferrer">"Progressive Enhancement with CSS"</a> best practice, and separate your css rules in several files (up until actual deployment into production, where you may regroup and compress all your css rules into one tight file)</p>
|
<p>VonC is right. Add overflow: hidden; to div#container rule.
Line 274 of index.css.</p>
| 46,318
|
<pre><code>('1' * N) !~ /^1?$|^(11+?)\1+$/
</code></pre>
<p>On the net, I found this piece of Ruby code that works for N >= 0 that determines whether or not N is a prime. From what I can tell, it looks like play with regex but I have no idea how it works. Could someone tell me how it works?</p>
|
<p>You can find a lengthy explanation of this code here:
<a href="http://www.noulakaz.net/weblog/2007/03/18/a-regular-expression-to-check-for-prime-numbers/" rel="noreferrer">http://www.noulakaz.net/weblog/2007/03/18/a-regular-expression-to-check-for-prime-numbers/</a></p>
|
<p>Greatest Common Divisor (gcd):</p>
<pre><code>/^(1+)\1*=\1+$/.match('1' * x + '=' + '1' * y)[1].length
</code></pre>
<p>Both this and the is_prime one works in about the same way. It tries all combinations before giving up.</p>
<p>This one will try to split the first number in even parts, and match the second number with one or more of those parts. If it finds a match it returns the length of the selected part.</p>
| 17,727
|
<p>I cleaned up my Flashforge Creator Dual tonight, and loaded some transparent ABS prepping for a print. The filament extruded fine, then started to wiggle, then became fine again. Hot end is 0.4 mm and was heated to 230C. What sort of steps should I take to troubleshoot the issue? Has anyone seen this before?</p>
<p><a href="https://i.stack.imgur.com/ffssj.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ffssj.jpg" alt="Photo of extruded filament exhibiting wiggles"></a></p>
|
<p>No, that's not (entirely) true. There might be some loss of quality if you print multiple objects at once, because when the printhead "hops" from one object to another it might leave a mark or ooze out some material. Also, a large number of retractions in a short period of time might lead to inconsistent extrusion.</p>
<p>However, none of this is particular to "filling out the board" as it happens even if you print only two objects at a time (or even when you're printing only one object with multiple islands).</p>
<p>It all depends on your printer (and in particular how well it handles retractions). If you're willing to do a small amount of cleanup afterwards (to remove the strings and blobs) then printing multiple objects at a time is completely viable.</p>
|
<p>Just to add to the other answers already here, I've also had problems with layer adhesion when filling up the print bed on an extrusion printer. The longer the print head spends working on details around a single layer, the more chance the layer has to cool off before the next layer gets started. I've started to suspect that layers that take longer to print end up with less adhesion to the next layer.</p>
| 425
|
<p>I recently started using Rake to build some of my (non-ruby) packages. Rake is nice, but what I found missing is a way to do hierarchical builds (aggregate Rakefiles in subdirectories). Since this is a common feature in most other build tools, I'm wondering if someone more familiar with Rake has a good solution.</p>
|
<p>I would recommend Buildr for non-Ruby build tasks. It is based on Rake (sits on top of it, allowing you to use all of Rake's features) but fits the semantics of compiled languages better. It also supports hierarchical builds.</p>
|
<p>The fix I've used to get around this is:</p>
<pre><code>Dir.chdir(File.dirname(Rake.application.rakefile))
</code></pre>
<p>This statement has to be run at every level in the hierarchy except for the root, at the start of every rakefile. A shortened example of how this works in practice:</p>
<p>/rakefile:</p>
<pre><code>task :default do
sh "rake -f component/rakefile"
end
</code></pre>
<p>/component/rakefile</p>
<pre><code>Dir.chdir(File.dirname(Rake.application.rakefile))
task :binary => OBJECTS do
sh "gcc #{SOURCES} -Iinclude -o #{TARGET}"
end
</code></pre>
<p>As I'm new to rake I'm not convinced it's the cleanest method of solving it, but it was how I eventually got it to work.</p>
| 11,574
|
<p>I have a piece of server-ish software written in Java to run on Windows and OS X. (It is not running on a server, but just a normal user's PC - something like a torrent client.) I would like the software to signal to the OS to keep the machine awake (prevent it from going into sleep mode) while it is active.</p>
<p>Of course I don't expect there to be a cross platform solution, but I would love to have some very minimal C programs/scripts that my app can spawn to inform the OS to stay awake.</p>
<p>Any ideas?</p>
|
<p>I use this code to keep my workstation from locking. It's currently only set to move the mouse once every minute, you could easily adjust it though.</p>
<p>It's a hack, not an elegant solution.</p>
<pre><code>import java.awt.*;
import java.util.*;
public class Hal{
public static void main(String[] args) throws Exception{
Robot hal = new Robot();
Random random = new Random();
while(true){
hal.delay(1000 * 60);
int x = random.nextInt() % 640;
int y = random.nextInt() % 480;
hal.mouseMove(x,y);
}
}
}
</code></pre>
|
<p>One simple way which i use to avoid "Windows desktop Auto lock" is "Switch On/Off NumLock" every 6 seconds.</p>
<p>Here a Java Program to Switch ON/OFF NumLock.</p>
<pre><code>import java.util.*;
import java.awt.*;
import java.awt.event.*;
public class NumLock extends Thread {
public void run() {
try {
boolean flag = true;
do {
flag = !flag;
Thread.sleep(6000);
Toolkit.getDefaultToolkit().setLockingKeyState(KeyEvent. VK_NUM_LOCK, flag);
}
while(true);
}
catch(Exception e) {}
}
public static void main(String[] args) throws Exception {
new NumLock().start();
}
}
</code></pre>
<p>Run this Java program in a separate command prompt; :-)</p>
| 7,621
|
<p>I've got a number of non-technical users that all share a set of project files. It would be ideal to have them using version control, but I think that both subversion and git are too technical for non-technical office staff.</p>
<p>Is there any distributed source control software that would work well for normal people?</p>
|
<p>If source control is too technical they can use <a href="http://svnbook.red-bean.com/en/1.2/svn.webdav.autoversioning.html" rel="noreferrer">Subversion with WebDav</a>.</p>
<p>The less technical people will just save files normally from whatever application they use, without worrying/thinking about source control. They get the benefit of auto-versioning without doing anything. </p>
<p>When ever they need more functionality they can learn to use TortoiseSVN to view diffs, revert to old version that were made automatically for them etc... </p>
<p>From the subversion book :</p>
<blockquote>
<p>Because so many operating systems already have integrated WebDAV clients, the use case for this feature borders on fantastical: imagine an office of ordinary users running Microsoft Windows or Mac OS. Each user “mounts” the Subversion repository, which appears to be an ordinary network folder. They use the shared folder as they always do: open files, edit them, save them. Meanwhile, the server is automatically versioning everything. Any administrator (or knowledgeable user) can still use a Subversion client to search history and retrieve older versions of data.</p>
</blockquote>
|
<p>Have you tried Adobe's version cue? This is not open source / free but it may be easier to use for the end-user.</p>
<p><a href="http://www.adobe.com/products/creativesuite/versioncue/" rel="nofollow noreferrer">http://www.adobe.com/products/creativesuite/versioncue/</a></p>
| 7,291
|
<p>As you can see <a href="https://stackoverflow.com/questions/301854/set-selected-value-in-selectlist-after-instantiation">here</a> and <a href="https://stackoverflow.com/questions/295313/modelbinding-with-selectlist">here</a> I'm not a good friend of asp.net MVC's SelectList.<br>
This time I'm wondering how to count the items in it. I want to show a label instead of a dropdown if the possible items don't offer any choice (items.count <2).</p>
<p><strong>--EDIT--</strong> </p>
<p>Although Will's answer probably works too, the easy way to go is call</p>
<pre><code>.GetListItems().Count()
</code></pre>
<p>This disables any lazy fetching you would have, but since they're gonna be in a dropdown anyway, I don't think that should be a problem.</p>
|
<p>Linq has an extension method for <a href="http://www.hookedonlinq.com/CountOperator.ashx" rel="nofollow noreferrer">IEnumerable called Count().</a></p>
|
<p>Linq does not have an extension method for IEnumerable called Count(). Count() is implemented for IEnumerable, which is a big difference.</p>
| 38,750
|
<p>I'm storing a tree in a DB using nested sets. The table's fields are id, lft, rgt, and name. </p>
<p>Given a node ID, I need to find all of its direct children(not grandchildren) that are themselves leaf nodes.</p>
|
<p>The article <a href="http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/" rel="nofollow noreferrer">Managing Hierarchical Data in MySQL</a> gives a great example of how to use Nested Sets, and gives examples of many common queries, including this one.</p>
<p>here's how to find the immediate children of a node:</p>
<pre><code>SELECT node.name, (COUNT(parent.name) - (sub_tree.depth + 1)) AS depth
FROM nested_category AS node,
nested_category AS parent,
nested_category AS sub_parent,
(
SELECT node.name, (COUNT(parent.name) - 1) AS depth
FROM nested_category AS node,
nested_category AS parent
WHERE node.lft BETWEEN parent.lft AND parent.rgt
AND node.name = '**[[MY NODE]]**'
GROUP BY node.name
ORDER BY node.lft
)AS sub_tree
WHERE node.lft BETWEEN parent.lft AND parent.rgt
AND node.lft BETWEEN sub_parent.lft AND sub_parent.rgt
AND sub_parent.name = sub_tree.name
GROUP BY node.name
HAVING depth = 1
ORDER BY node.lft;
</code></pre>
<p>and then combine that with the fact that a leaf node will have <code>rgt</code> equal to <code>lft + 1</code>, and you're set. <sub>pardon the pun.</sub></p>
|
<p>In order to specify and differentiate leaf nodes, keep them with left=right. This changes two things:</p>
<ol>
<li>Leaves are easily identifiable. </li>
<li>When doing an insertion, you will add
only one to the values (left where >
new leaf, right where >= leaf).</li>
</ol>
| 40,835
|
<p>I have a project to recognize the footprint of animals. It is similar to facial recognition.<br>
There is a need to store footprint images in a database and compare them with images captured by camera.</p>
<p>What is the appropriate programming language to do this?</p>
|
<p>Any language can be used for image processing, pattern recognition and object detection, which is what you're trying to do here. But you're better off finding a library or even an application instead, and then picking the language based on that choice.</p>
<p>Matlab is fine if you're familiar with it, unless you plan on delivering a working system that will be used by others to add or annotate data. In that case, you'll need something easier to deploy beyond your own workstation. </p>
<p><a href="http://sourceforge.net/projects/opencvlibrary/" rel="nofollow noreferrer">OpenCV</a> might be a good place to start, and <a href="http://www.cs.iit.edu/~agam/cs512/lect-notes/opencv-intro/opencv-intro.html#SECTION00021000000000000000" rel="nofollow noreferrer">there's an OpenCV tutorial here.</a></p>
<p>Since it's a similar problem, you may want to check out the <a href="http://www.face-rec.org/" rel="nofollow noreferrer">Face Recognition Homepage</a> for more detailed information.</p>
|
<p>Your biggest problem here is developing the algorithm, not choosing the language. My advice would be to prototype your project in Matlab, if you have access to it. What you are trying to do is an active area of research, and many researchers prefer Matlab and publish their Matlab code. This means that you may be able to find Matlab code on the web that may do at least some of what you need, such as image segmentation.</p>
<p>I would advise against using C++, unless you actually get your algorithm to work, and speed becomes important. Matlab would allow you to quickly try out ideas, and avoid spending most of your time on implementation details. Once you develop your algorithm to the point when you are happy with the results, then you can think about implementing it as a usable system in a "real" programming language.</p>
| 32,497
|
<p>I just updated my Maker Select Plus from the stock (I believe RepRap-based) firmware to Advi3pp, which is Marlin based. The printer starts up and everything seems okay, but I haven't actually tried a print yet and there was a message during the upgrade about deleting incompatible settings. </p>
<p>What do I need to do to recalibrate the printer following the firmware upgrade?</p>
|
<p>If it is Marlin based or RepRap based, many parameters are stored in EEPROM memory. A G-code command <a href="https://reprap.org/wiki/G-code#M502:_Read_parameters_from_.22configuration.h.22" rel="nofollow noreferrer">M502: Read parameters from "configuration.h"</a> would reset all parameters that can be changed to their default value as defined in your configuration file. Don't forget to follow the <code>M502</code> command with a <code>M500</code> command to store the loaded parameters to EEPROM. This would overwrite all previous settings.</p>
<p><sub><em>From the linked source, <code>M502</code>:</em></sub></p>
<blockquote>
<p>This command resets all tunable parameters to their default values, as set in the firmware. This doesn't reset any parameters stored in the EEPROM, so it must be followed with M500 if you want to do that.</p>
</blockquote>
<p>You can send these commands over a terminal interface to the printer using applications such as Pronterface, OctoPrint, Repetier-Host, and probably many more, or store the commands in a G-code file (e.g. a text file with a <code>.g</code> extension) and print the file using an SD card.</p>
|
<p>Looks like I don't need to do anything. I printed a 20 mm calibration cube, and aside from some elephant footing it came out as clean and as close to the model dimensions as anything else I've ever put through the machine, with no changes. </p>
<p>So I'll recommend this as a first step to anyone else: start a 20 mm cube going, watch it closely early on to be sure you're getting adequate extrusion and bed adhesion. If it fails here you may need to adjust settings. When it's done, measure it and see where you are. You might not need to do anything else.</p>
| 1,348
|
<p>I've been printing small quantities from a PLA filament spool on a Craftbot printer for about two months now. Recently the printed objects have been coming out very brittle. Some structures that printed fine two months ago are now difficult to re-print. The print head gets clogged easily, and when the object does print, it's quite brittle and 1/4" to 1/8" rods will easily snap off if not handled gently.</p>
<p>I'll admit to not following the precautions for storage of PLA. It's much easier to just leave the filament installed rather than trying to remove it after each print, so this one spool has just been sitting on the back of the printer for all these weeks now. I'm sure it's been humid some of the days, we've had some rain here.</p>
<p>Has the spool of PLA been damaged just by leaving it exposed to room air for two months? Could that be the sole cause of the brittle prints, or are there other possible causes? Is there any way to fix the spool or future prints from this spool, or do I have to scrap it and get a new spool?</p>
|
<p>Increase nozzle temperature. When the filament is new it will print easier, requiring less heat to print well. So if you didn't store your filament properly to begin with, increasing print temperature will make it jam less and increase layer bonding. </p>
<p>The reason for this is because the moisture that accumulates in the filament will absorb heat and evaporate when printed, meaning that the filament itself isn't getting the same amount of heating as it used to.</p>
<p>That being said, the storage suggestions mentioned by tbm should be your first priority. I personally put my filament in Zip Lock plastic bags and store these in a dry location not exposed to sun or temperature changes.</p>
|
<p>PLA absorbs moisture, so keeping the filament dry is a key factor. Aside from that, PLA is naturally more brittle than other plastics like ABS and Nylon Sorry, tried to find a graph to prove it, but couldn't find one.</p>
<p>There's a good <a href="https://groups.google.com/forum/#!topic/makerbot/Rdx2ZnJeQzs">Google Group discussion</a> and many other resources that go over good storage habits, but as for fixing the existing filament.</p>
<p>Try the following: </p>
<ul>
<li>Place PLA in an enclosure (plastic bin, Zip-loc bag, etc.)</li>
<li>If you have some, add some moisture absorber(s)</li>
<li>Place the tub in a warm environment (naturally or artificially) and make sure the area is dry as possible (not in the shed in the back, by the woods...). Possibly next to a heater vent or space heater in your house?</li>
</ul>
<p>Essentially, you're trying to treat the material. When the material goes through a heat treatment (aka the heat block in the extruder), the mechanical properties are beginning to change. The brittleness can be set by how quickly the material cools. I'm speculating that the moisture does any of the following:</p>
<ol>
<li>Keeps the filament from heating up to the desired extrusion temperature.</li>
<li>Burns the filament.</li>
<li>The moisture is evaporated, leaving gaps in the extruded filament (under microscope).</li>
</ol>
<p>I looked into this a few years ago and have forgotten most of what I found out, but I'll keep looking and update my answer here.</p>
| 325
|
<p>Shoes has some built in dump commands (Shoes.debug), but are there other tools that can debug the code without injecting debug messages throughout? Something like gdb would be great.</p>
|
<p>You can also use Shoes.show_log to automatically open a debug console.</p>
|
<p>I was a bit confused about the Apple-/ (or Alt-/) bit mentioned here. What I ended up doing was running <em>./shoes</em> with no arguments, which popped up the console, then started my app with <em>./shoes my_app.rb</em>. </p>
| 8,903
|
<p>I'm looking at a new project where both Native and Managed approaches sound like a good idea. This is a Windows desktop application which should support an MDI interface. The client area will make extensive use of Direct3D. The developers on the project are equally skilled on C#, C++/CLI and MFC.</p>
<p>MFC Advantages:</p>
<ul>
<li>Doc/View Architecture</li>
<li>Most Direct3D online resources still use C++</li>
</ul>
<p>Managed Code Advantages:</p>
<ul>
<li>The .NET Framework</li>
<li>C#</li>
</ul>
<p>What more can I add to the lists above? Don't flame this. Two lists. Just add to them.</p>
<p>Note: I have very good reasons (to do with the IDE and debugging) not to use mixed mode. So count that out.</p>
|
<p>Why not use both?</p>
<p>You can write the UI (forms) using C#/VB.NET and render the window using C++.</p>
<p>Basically all you need to do is pass the HWND (Window Handle) from the C# to the C++ and initialize the C++ using that value.</p>
<p>You can see an example on my blog: <a href="http://blogs.microsoft.co.il/blogs/dhelper/archive/2008/11/24/how-to-render-managed-net-form-using-native-directx.aspx" rel="nofollow noreferrer">How-to Render managed (.NET) form using native DirectX</a></p>
|
<p>This doesn't directly add to either list, but the current "recommended" way to do 3D with .NET is using XNA - Managed DirectX is being deprecated.</p>
<p>Edit: Of course, WPF 3D is also an option! Forgot about that :}</p>
| 30,490
|
<p>How do people usually detect the MIME type of an uploaded file using ASP.NET?</p>
|
<p>in the aspx page:</p>
<pre><code><asp:FileUpload ID="FileUpload1" runat="server" />
</code></pre>
<p>in the codebehind (c#):</p>
<pre><code>string contentType = FileUpload1.PostedFile.ContentType
</code></pre>
|
<p>Get MIME type from a file in ASP.NET Core</p>
<pre><code>public string GetMimeType(string filePath)
{
var provider = new FileExtensionContentTypeProvider();
if (!provider.TryGetContentType(filePath, out var contentType))
contentType = "application/octet-stream"; // fallback: unknown binary type
return contentType;
}
</code></pre>
| 10,688
|
<p>The <a href="http://docs.jquery.com/Events/bind#typedatafn" rel="noreferrer">jQuery documentation</a> says the library has built-in support for the following events: blur, focus, load, resize, scroll, unload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and error.</p>
<p>I need to handle cut, copy, and paste events. How best to do that? FWIW, I only need to worry about WebKit (lucky me!).</p>
<p>UPDATE: I'm working on a "widget" in a Dashboard-like environment. It uses WebKit, so it only really matters (for my purposes) whether these events are supported there, which it looks like they are.</p>
|
<p>You can add and remove events of any kind by using the <a href="http://api.jquery.com/on/" rel="noreferrer"><code>.on()</code></a> and <a href="http://api.jquery.com/off" rel="noreferrer"><code>off()</code></a> methods</p>
<p>Try this, for instance</p>
<pre><code>jQuery(document).on('paste', function(e){ alert('pasting!') });
</code></pre>
<p>jQuery is actually quite indifferent to whether the event type you assign is supported by the browser, so you can assign arbitrary event types to elements (and general objects) such as:</p>
<pre><code>jQuery('p').on('foobar2000', function(e){ alert(e.type); });
</code></pre>
<p>In case of custom event types, you must <a href="http://api.jquery.com/trigger" rel="noreferrer"><code>.trigger()</code></a> them "manually" in your code, like this:</p>
<pre><code>jQuery('p').trigger('foobar2000');
</code></pre>
<p>Neat eh?</p>
<p>Furthermore, to work with proprietary/custom DOM events in a cross-browser compatible way, you may need to use/write an "jQuery event plugin" ... example of which may be seen in <del><a href="http://plugins.jquery.com/files/jquery.event.wheel.js.txt" rel="noreferrer">jquery.event.wheel.js</a></del> Brandon Aaron's <a href="https://github.com/brandonaaron/jquery-mousewheel" rel="noreferrer">Mousewheel plugin</a></p>
|
<p>As jQuery 1.7 you can use <strong>bind(...)</strong> and <strong>unbind(...)</strong> methods for attaching and removing respectively handlers.</p>
<p>Here are examples align your questuion:</p>
<pre><code>$('#someElementId').bind('paste', function(){return false;});
</code></pre>
<p>- this one will block any attempts to paste from clipboard into element body. You can use also <strong>cut</strong>, <strong>copy</strong> and others as event types (see links bellow)</p>
<pre><code>$('#someElementId').bind('copy', function(){return alert('Hey fella! Do not forget about copyrights!');});
</code></pre>
<p>So, in other cases, when you want to remove those handlers, you can use <strong>unbind()</strong> method:</p>
<pre><code>$('#someElementId').unbind('copy');
</code></pre>
<p>Here some useful links:</p>
<ul>
<li><a href="http://api.jquery.com/bind/" rel="nofollow">bind()</a></li>
<li><a href="http://api.jquery.com/unbind/" rel="nofollow">unbind()</a></li>
<li><a href="http://api.jquery.com/category/events/" rel="nofollow">full list of event types</a></li>
</ul>
| 29,361
|
<p>When Internet Explorers AutoComplete is turned on for Forms the entries for each field in the HTML form should be cached and displayed as a prompt when the user starts entering content into the form the second time around. </p>
<p>On my website the AutoComplete feature is never displayed for any forms that exist on that site. But yet other websites retain and deliver that content without problem.</p>
<p>My site is using PHP as the scripting language and all content is delivered over SSL.</p>
|
<p>I have determined that the problem is related to the Cache-Headers PHP sends out when the start_session() command is issued and the site is running SSL.</p>
<p>I have been able to get a hold of a person on the IE security team at Microsoft and they have confirmed that this is how IE is supposed to work. Here is a direct quote from the email.</p>
<p><strong><em>"This is considered a feature of the autocomplete system. Significant code was written to make it behave this way."</em></strong></p>
<p>When session_start(); is issued the default http headers php sends out are a no-cache header. Here is another quote from the Microsoft representitive.</p>
<p><strong><em>If a secure page says "Don't cache me", that's an indication that the data is sensitive, and hence the autocomplete data itself is likely sensitive. Admittedly, it is a simple heuristic. Personally, I think it's a bit silly, but it's been there forever.
It's probably a good suggestion to support "autocomplete=on" to override the default heuristic.</em></strong></p>
<p>In order to re-enable the autoComplete feature I had to issue this command in php <strong>before</strong> the start_session() command:</p>
<pre><code>session_cache_limiter ('private, must-revalidate');
</code></pre>
<p>I'm sure there are other ways of manipulating the header cache-controls to allow the autoComplete to function as well.</p>
<p><a href="http://gavey.ca/autocomplete/index.php" rel="noreferrer">Here is a link to 3 examples forms I made so you can test with IE.</a></p>
|
<p>Do you have <code>autocomplete="off"</code> as an attribute in your form elements?</p>
| 47,528
|
<p>I'd like to ignore multiple wildcard routes. With asp.net mvc preview 4, they ship with:</p>
<pre><code>RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
</code></pre>
<p>I'd also like to add something like:</p>
<pre><code>RouteTable.Routes.IgnoreRoute("Content/{*pathInfo}");
</code></pre>
<p>but that seems to break some of the helpers that generate urls in my program. Thoughts?</p>
|
<p>There are two possible solutions here.</p>
<ol>
<li><p>Add a constraint to the ignore route to make sure that only requests that should be ignored would match that route. Kinda kludgy, but it should work.</p>
<pre><code>RouteTable.Routes.IgnoreRoute("{folder}/{*pathInfo}", new {folder="content"});
</code></pre></li>
<li><p>What is in your content directory? By default, Routing does not route files that exist on disk (actually checks the VirtualPathProvider). So if you are putting static content in the Content directory, you might not need the ignore route.</p></li>
</ol>
|
<p>This can be quite tricky.</p>
<p>When attempting to figure out how to map route data into a route, the system currently searches top-down until it finds something where all the required information is provided, and then stuffs everything else into query parameters.</p>
<p>Since the required information for the route "Content/{*pathInfo}" is entirely satisfied always (no required data at all in this route), and it's near the top of the route list, then all your attempts to map to unnamed routes will match this pattern, and all your URLs will be based on this ("Content?action=foo&controller=bar")</p>
<p>Unfortunately, there's no way around this with action routes. If you use named routes (f.e., choosing Html.RouteLink instead of Html.ActionLink), then you can specify the name of the route to match. It's less convenient, but more precise.</p>
<p>IMO, complex routes make the action-routing system basically fall over. In applications where I have something other than the default routes, I almost always end up reverting to named-route based URL generation to ensure I'm always getting the right route.</p>
| 5,019
|
<p>Recently I ran into this error in my web application:</p>
<blockquote>
<p>java.lang.OutOfMemoryError: PermGen space</p>
</blockquote>
<p>It's a typical Hibernate/JPA + IceFaces/JSF application running on Tomcat 6 and JDK 1.6.
Apparently this can occur after redeploying an application a few times.</p>
<p>What causes it and what can be done to avoid it?
How do I fix the problem?</p>
|
<p>The solution was to add these flags to JVM command line when Tomcat is started:</p>
<pre><code>-XX:+CMSClassUnloadingEnabled -XX:+CMSPermGenSweepingEnabled
</code></pre>
<p>You can do that by shutting down the tomcat service, then going into the Tomcat/bin directory and running tomcat6w.exe. Under the "Java" tab, add the arguments to the "Java Options" box. Click "OK" and then restart the service.</p>
<p>If you get an error <em>the specified service does not exist as an installed service</em> you should run:</p>
<pre><code>tomcat6w //ES//servicename
</code></pre>
<p>where <em><strong>servicename</strong></em> is the name of the server as viewed in services.msc</p>
<p>Source: orx's comment on <a href="https://web.archive.org/web/20160124133922/http://www.jroller.com/agileanswers/entry/preventing_java_s_java_lang" rel="noreferrer">Eric's Agile Answers</a>.</p>
|
<p>If any one is struggling with the same error in netbeans, then here is how I fixed it.</p>
<p><strong>In Netbeans:</strong></p>
<p>Go to services tab --> Right on server -->Choose properties --> go to platform tab -->Inside vm options type -Xms1024m</p>
<p>In my case, I have given -Xms4096m</p>
<p>Here is the screenshot:</p>
<p><a href="https://i.stack.imgur.com/PrpdN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PrpdN.png" alt="enter image description here"></a></p>
| 11,382
|
<p>We're using the Eclipse CDT 5 C++ IDE on Windows to develop a C++ application on a remote AIX host. </p>
<p>Eclipse CDT has the ability to perform remote debugging using gdbserver. Unfortunately, gdbserver is not supported on AIX. </p>
<p>Is anyone familiar with a way to debug remotely using Eclipse CDT without gdbserver? Perhaps using an SSH shell connection to gdb?</p>
|
<p>finally I got gdb run remotly anyhow now. At the Bug-symbol on the taskbar I took Debug Configurations - GDB Hardware Debugging.</p>
<p>In Main C/C++ Applications I set the full path on the Samba share of the executable (<code>X:\abin\vlmi9506</code>). I also set a linked folder on <code>X:\abin</code> in the project. Then I modified my batch-script in GDB Setup. It's not directly calling gdb in the plink-session but a unix-shell-script, which opens gdb. By this I have the possibility to set some unix environment-variables for the program before doing debug. The call in my batch: </p>
<pre><code>plink.exe prevoax1 -l suttera -pw XXXXX -i /proj/user/dev/suttera/vl/9506/test/vlmi9506ddd.run 20155 dev o m
</code></pre>
<p>In the unix script I started gdb with the command line params from eclipse, that I found in my former tryals. The call in the shell command looks like this:</p>
<pre><code>gdb -nw -i mi -cd=$LVarPathExec $LVarPathExec/vlmi9506
</code></pre>
<p>Then IBM just gives gdb 6.0 for AIX. I found version 6.8 in the net at <a href="http://www.perzl.org/aix/index.php?n=Main.Gdb" rel="noreferrer">http://www.perzl.org/aix/index.php?n=Main.Gdb</a>. Our Admin installed it.</p>
<p>I can now step through the program and watch variables. I even can write gdb-commands directly in the console-view. yabadabadooooooo</p>
<p>Hope that helps to others as well. Can not tell, what was really the winner-action.
But each answer gives more new questions. Now I got 3 of them.</p>
<ol>
<li>When I start the debug config I have to click restart in the toolbar to come really in the main procedure. Is it possible to come directly in main without restarting?</li>
<li>On AIX our programs are first preprocessed for embedded sql. The preprocessed c-source is put in another directory. When I duble-click the line to set a breakpoint, I get the warning "unresolved breakpoint" and in the gdb-console I see, that the break is set to the preprocessed source which is wrong. Is it possible to set the breakpoints on the right source?</li>
<li>We are using CICS on AIX. With the xldb-Debugger and the CDCN-command of CICS we manage that debugging is started, when we come in our programs. Is it possible to get that remotely (in plink) with gdb-eclipse as well?</li>
</ol>
|
<p>tried also to remotly debug an aix-appl with windows eclipse-cdt-gdb.
Got blocked at the end with unix/windows path-problems. Maybe my result can help u a little further - maybe you already got it work. I'm interested in your comment. asked on eclipse news portal- following the answer of martin oberhuber (thanks again) tried dsp dd (also blocked with path problem) and set an request in eclipse bugzilla.</p>
<p>here the link to news:
<a href="http://www.eclipse.org/newsportal/article.php?id=406&group=eclipse.dsdp.tm" rel="nofollow noreferrer">http://www.eclipse.org/newsportal/article.php?id=406&group=eclipse.dsdp.tm</a>
Here my bugzilla:
<a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=252758" rel="nofollow noreferrer">https://bugs.eclipse.org/bugs/show_bug.cgi?id=252758</a></p>
<p>At the moment we still debug localy with xldb but I am trying ddd-gdb at the moment. At least locally gdb is running.</p>
| 10,677
|
<p>How do you create a static class in C++? I should be able to do something like:</p>
<pre><code>cout << "bit 5 is " << BitParser::getBitAt(buffer, 5) << endl;
</code></pre>
<p>Assuming I created the <code>BitParser</code> class. What would the <code>BitParser</code> class definition look like?</p>
|
<p>If you're looking for a way of applying the "static" keyword to a class, like you can in C# for example, then you won't be able to without using Managed C++.</p>
<p>But the looks of your sample, you just need to create a public static method on your BitParser object. Like so:</p>
<p><strong>BitParser.h</strong></p>
<pre><code>class BitParser
{
public:
static bool getBitAt(int buffer, int bitIndex);
// ...lots of great stuff
private:
// Disallow creating an instance of this object
BitParser() {}
};
</code></pre>
<p><strong>BitParser.cpp</strong></p>
<pre><code>bool BitParser::getBitAt(int buffer, int bitIndex)
{
bool isBitSet = false;
// .. determine if bit is set
return isBitSet;
}
</code></pre>
<p>You can use this code to call the method in the same way as your example code.</p>
|
<p>One case where namespaces may not be so useful for achieving "static classes" is when using these classes to achieve composition over inheritance. Namespaces cannot be friends of classes and so cannot access private members of a class.</p>
<pre><code>class Class {
public:
void foo() { Static::bar(*this); }
private:
int member{0};
friend class Static;
};
class Static {
public:
template <typename T>
static void bar(T& t) {
t.member = 1;
}
};
</code></pre>
| 3,075
|
<p>I am using Borland Turbo C++ with some inlined assembler code, so presumably Turbo Assembler (TASM) style assembly code. I wish to do the following:</p>
<pre><code>void foo::bar( void )
{
__asm
{
mov eax, SomeLabel
// ...
}
// ...
SomeLabel:
// ...
}
</code></pre>
<p>So the address of SomeLabel is placed into EAX. This doesn't work and the compiler complains of: Undefined symbol 'SomeLabel'.</p>
<p>In Microsoft Assembler (MASM) the dollar symbol ($) serves as the current location counter, which would be useful for my purpose. But again this does not seem to work in Borlands Assember (expression syntax error).</p>
<p>Update: To be a little more specific, I need the compiler to generate the address it moves into eax as a constant during compilation/linking and not at run time, so it will compile like "mov eax, 0x00401234".</p>
<p>Can anybody suggest how to get this working?</p>
<p>UPDATE: To respond to Pax's question (see comment), If the base address is changed at run time by the Windows loader the DLL/EXE PE image will still be relocated by the Windows loader and the labels address will be patched at run time by the loader to use the re-based address so using a compile/link time value for the label address is not an issue.</p>
<p>Many thanks in advance.</p>
|
<p>Last time I tried to make some assembly code Borland-compatible I came across the limitation that you can't forward-reference labels. Not sure if that's what you're running into here.</p>
|
<p>From what I recall, you can't use an external (C++) label in your inline assembly, although you can have TASM-style labels in the asm block that can be referenced by the assembly instructions itself. I think I would use a flag and a post-assembler switch statement to handle branching. For example:</p>
<pre><code>int result=0;
__asm__ {
mov result, 1
}
switch (result){
case 1: printf("You wanted case 1 to happen in your assembler\n"); break;
case 0: printf("Nothing changed with the result variable.. defaulting to:\n");
default: printf("Default case!\n"); break;
}
</code></pre>
| 25,668
|
<p>I wanted to compare the datetime which is in this format "7/20/2008" with the ones in the database which is in format "7/20/2008 7:14:53 AM".</p>
<p>I tried using "like" clause but it did not work beacuse the "like" clause uses only string and the one which I am using is date time format.</p>
<p>Can anyone tell how to convert and compare it in database and pull up datetime.</p>
<pre><code> protected void User_Querytime()
{
DataClasses2DataContext dc1 = new DataClasses2DataContext();
DateTime date1;
string date = Request.QueryString.Get("TimeOfMessage");
date1 = Convert.ToDateTime(date);
var query7 = from u in dc1.syncback_logs
where u.TimeOfMessage = date1
orderby u.TimeOfMessage descending
select u;
GridView1.DataSource = query7;
GridView1.DataBind();
}
</code></pre>
|
<p>I assume you're having a problem because <code>date1</code> contains a date only, while your database contains full date/time values. To find matches you need to pick one of these approaches:</p>
<p>1) Remove the time information from the database values before comparing them to your target
2) Convert your target into a range, then find database values in that range.</p>
<pre><code>List<DateTime> dateTimes = new List<DateTime>();
dateTimes.Add(DateTime.Parse("7/20/2008 7:14:53 AM"));
dateTimes.Add(DateTime.Parse("7/20/2008 12:12:01 AM"));
dateTimes.Add(DateTime.Parse("7/21/2008 9:00:00 AM"));
dateTimes.Add(DateTime.Parse("7/20/2009 7:14:53 AM"));
DateTime targetDate = Convert.ToDateTime("7/20/2008");
// Remove time info from data in database
var matchingDates = from date in dateTimes
where date.Date == targetDate
select date;
// Or use your target date to create a range
DateTime rangeStart = new DateTime(targetDate.Year, targetDate.Month, targetDate.Day, 0, 0, 0);
DateTime rangeEnd = new DateTime(targetDate.Year, targetDate.Month, targetDate.Day, 23, 59, 59);
var matchingDates2 = from date in dateTimes
where (date >= rangeStart) && (date <= rangeEnd)
select date;
</code></pre>
|
<p>Instead of comparing the date directly, compare it two the min/max you'd accept. So instead of "DbDateCol = mydate" do "DbDateCol >= myDate.Date and DbDateCol < myDate.Date.AddDays(1)".</p>
<p>By using the Date property, you'll lop off the time component (force it to 0). By adding a day, you'll get the start of the next day, bounding it on the date of your DateTime instance.</p>
| 27,489
|
<p><strong>problem solved by resetting cura.</strong></p>
<p>I have problems like this: How can I fix this? I can't find the right setting.</p>
<p><a href="https://i.stack.imgur.com/2cf9Q.png" rel="nofollow noreferrer" title="No top layer"><img src="https://i.stack.imgur.com/2cf9Q.png" alt="No top layer" title="No top layer"></a></p>
<p>Also, what are these yellow lines? Do you know how to remove them? They disappear when I disable to show the brim/raft/skirt.</p>
<p><a href="https://i.stack.imgur.com/Bj7Sx.png" rel="nofollow noreferrer" title="Yellow lines #1"><img src="https://i.stack.imgur.com/Bj7Sx.png" alt="Yellow lines #1" title="Yellow lines #1"></a></p>
<p><a href="https://i.stack.imgur.com/BnAc4.png" rel="nofollow noreferrer" title="Yellow lines #2"><img src="https://i.stack.imgur.com/BnAc4.png" alt="Yellow lines #2" title="Yellow lines #2"></a></p>
|
<p>This problem appears when a face is inverted, so the slicer confuses and expect the other wall to close the object. So you need to reverse that face to show the face out and the back face inside the shape to be filled</p>
<p><a href="https://i.stack.imgur.com/OklcS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OklcS.png" alt="enter image description here"></a> </p>
<p><em>I will edit this answer with more examples</em></p>
|
<p>I'm pretty sure the yellow lines are showing the full path of the extruder head, including where it's retracted. Somewhere in Cura's maze of menus, there's an option to turn on/off various displays related to the slicing. </p>
<p>As to why the top layer isn't there -- most likely it's too thin in your source model. You might try enabling "Print thin walls" options in the Preferences advanced list. BTW, if you post the original STL or CAD file, we might be able to provide more accurate diagnosis.</p>
| 1,036
|
<p>Would like to programmically change the connecton string for a database which utilizes the membership provider of asp.net within a windows application. The system.configuration namespace allows changes to the user settings, however, we would like to adjust a application setting? Does one need to write a class with utilizes XML to modify the class? Does one need to delete the current connections (can one select a connection to clear) and add a new one? Can one adjust the existing connection string?</p>
|
<p>You can programatically open the configuration with using the System.configuration namespace: </p>
<p><code>Configuration myConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);</code></p>
<p>Then you can access the connection strings collection at:</p>
<p><code>myConfig.ConnectionStrings.ConnectionStrings</code></p>
<p>You can modify the collection however you want, and when done call <code>.Save()</code> on the configuration object.</p>
|
<p>Use the ConnectionStringsSection class. The documentation even provides an example on how to create a new ConnectionString and have the framework save it to the config file without having to implement the whole XML shebang.</p>
<p>See <a href="http://msdn.microsoft.com/en-us/library/system.configuration.connectionstringssection(VS.80).aspx" rel="nofollow noreferrer">here</a> and browse down for an example.</p>
| 8,898
|
<p>We're deploying some new WCF calls in our SQL 2005 DB using the CLR. In testing, I hardcoded in the code the endpoint to connect to, and deployed it to our test server. When we go to deploy this to production, we will be deploying it to many different SQL DBs, and using different endpoints to connect to (same service running on different servers). How can something like this be done? Is there a config file that can be referenced for the deployment of the dll into SQL?</p>
|
<p>The solutions above would work, but we found that the best practice approach would be to create a new table storing all of the different endpoints into the DB. Then, we updated the CLR to make a call to this table to get the endpoint(s) that were needed. So each server would have the proper metadata loaded for it, and it would all be retrieved from the DB. No hardcoding this way, and there's no need to worry about external text files on the SQL server. It's all contained in the DB.</p>
|
<p><a href="http://www.sqljunkies.ddj.com/Article/6CA864E9-E107-408E-B30A-4BA15B0CD11C.scuk" rel="nofollow noreferrer">Accessing Application Configuration Settings from SQL CLR</a> </p>
<p>another <a href="http://blogs.neudesic.com/blogs/shaun_collett/archive/2007/04/29/6050.aspx" rel="nofollow noreferrer">technique</a>..</p>
| 14,935
|
<p>I've been working on my own DIY 3-D printer recently, and I've been trying to experiment a little with different materials for the body. Someone suggested using HDPE (high-density polyethylene), since it works well on a CNC machine, which would make creating a number of prototypes easy. I know HDPE can also be used for filament, but I've never tried it before. Does anybody have any input on HDPE, or other potential materials for the body? I'm trying to avoid using wood, as I've had some poor experiences with it.</p>
|
<p>I've used what is commonly described as UHMW-PE, aka, Ultra-high Molecular Weight Polyethylene for various projects. You may know this material is often used in cutting boards, as it cleans easily and doesn't cut easily.</p>
<p>it does machine in a manner similar to aluminum, although the tool should be cooled/lubricated to prevent a build-up of melted plastic on the cutting edges. You can get away without coolant or lubricant if cutting speeds are slow and the swarf is cleared away from the cutter.</p>
<p>I'd not considered such a material for constructing a 3d printer, as it's expensive, but I've also not compared the prices to equivalent sizes of aluminum. </p>
<p>I'd consider that the use in a 3d printer would be a good substitute for lexan, as one can tighten the bolts without fear of cracking. For bolts subject to rotation or vibration, self-locking nuts are a good idea. If you have use of a broach, cutting out a pocket for the nuts would be easily accomplished.</p>
<p>I have downloaded the plans for the open-source 3d printer known as DICE, which calls for aluminum, but the pricing I've found was excessive for the right quantities. I think I'll explore the same bill of materials in HDPE or UHMW-PE (which may be different names for the same substance).</p>
<p>Equally useful to know is that the material is very slippery, effectively self-lubricating under the right conditions. Unfortunately, for a 3d printer application, I don't believe the self-lubricating part would work for carriages but might be fun to try with linear slides.</p>
<p>It is not as stiff as aluminum, so where stiffness is needed and not provided by the architecture, a thicker piece may be indicated. I can just barely bend with my fingers a piece of 3 mm (1/8") a small amount, but cannot do so for aluminum.</p>
<p>Here's the result of a quick search for UHMWPE:
<a href="https://www.interstateplastics.com/Uhmw-Natural-Virgin-Sheet-UHMNV~~SH.php?thickness=0.125&dim2=12&dim3=24" rel="nofollow noreferrer">https://www.interstateplastics.com/Uhmw-Natural-Virgin-Sheet-UHMNV~~SH.php?thickness=0.125&dim2=12&dim3=24</a> which gives a price for 1/8" white sheet 24 x 12" as US\$ 26.06 while the black version is available only as thin as 1/4" for about US$ 28.00</p>
<p>The equivalent size in aluminum 6061T6 at onlinemetals.com is about US\$ 3.00 more expensive. That is lower than I expected, skewing the idea farther away from UHMWPE than one might hope. The equivalent for 1/4" is almost US\$ 60, quite a bit higher. </p>
<p>It would appear that if you need the thicker stuff, the price is better for plastic, not so good for the aluminum.</p>
|
<p>I've tried this material (8 mm thickness) for a Prusa i3 clone of my own design but needed to abandon using it as it doesn't allow to be cut by laser easily on my friends laser cutting machine (not a hobby laser cutting machine, it is his business). </p>
<p>HDPE requires lower speed than cutting Plexiglas or Acrylic resulting in more heat input and a small top cut and a large bottom cut width leaving the edges far from being straight.</p>
| 303
|
<p>Hey I was wondering if there were any way to upload images in ASP? I am working on my school's server and I don't really know what is installed and what isn't I Googled a little and came up with "Persits.Upload.1" I tried to instantiate the object with this line:</p>
<p><code>Set Upload = Server.CreateObject("Persits.Upload.1")</code></p>
<p>It gave me this error, </p>
<blockquote>
<p>Server object error 'ASP 0177 : 800401f3'<br>
Server.CreateObject Failed </p>
</blockquote>
<p>Am I to assume the component is not installed on the server and/or what should I do for uploading images?</p>
<p>Thanks</p>
|
<p>Sounds like it couldn't load the class, my ASP very rusty though. </p>
<p>That component is a commercial one, so unless someone has paid for it, you probably don't have it installed. </p>
<p>I have used free asp upload <a href="http://www.freeaspupload.net/" rel="nofollow noreferrer">http://www.freeaspupload.net/</a> a few times, although it was a while a go, that might be a reasonably easy option for you.</p>
|
<p>If it's for educational purposes it may be worth droping <a href="http://www.aspupload.com/support.html" rel="nofollow noreferrer">Persits</a> an email to see if they will give you a free license.</p>
<p>They offer a 30-day free trial on their site.</p>
<p>Good luck</p>
| 47,027
|
<p>I have an extrusion problem with my creality CR 10 3D printer while printing.
I am using a standard 0.4 mm nozzle with a 1.75 mm diameter PLA and I use Cura as my slicer.</p>
<p>This printer worked perfectly fine and I stopped using it a few months ago right after the problem started.</p>
<p>When I try printing a <code>.gcode</code> file, the first layer is very thin but visible (it seems like the glass bed is engraved). However, after the first layer is complete, the extruder stops working properly. It moves forward then jumps backwards so it looks like the filament isn’t moving (I can also see the extruder’s marks on the filament). Also, the axis seem to move fine in all directions as I’m able to see a clear first layer.</p>
<p>However, when I go into the “prepare” menu of my printer and move the extruder, it works great as the filament flow is very smooth.</p>
<p>Hence, the problem is only visible while printing. I don’t think there’s a problem with the <code>.gcode</code> files as I printed them perfectly fine beforehand.</p>
|
<p>Without images of the problem it is difficult to diagnose, but, the described symptoms sounds as if the nozzle is too close to the bed. If the nozzle is too close to the bed, and the extruder not strong enough, the filament flow is very limited due to pressure caused by a very small opening between the nozzle and the bed. Skipping of the extruder may wear out (grind) the filament and stop extrusion altogether.</p>
<p>Re-level the bed with a (thicker) piece of paper or with a feeler gauge. Alternatively, increase the height of the nozzle by re-defining the height or add an extra Z raise in the slicer (see question: "<a href="https://3dprinting.stackexchange.com/questions/13330/how-can-i-add-an-offset-to-the-first-layer-to-increase-clearance/13334">How can I add an offset to the first layer to increase clearance?</a>").</p>
|
<p>Clearly you're having an extrusion problem. Extrusion problems usually come either from a clogged nozzle (as @Adam S. said) or from the extruder it self. To determine where the problem is located I would first do a flow rate test using <a href="https://www.youtube.com/watch?v=lWBkPIXTOlo&feature=emb_logo" rel="nofollow noreferrer">this</a>. When doing this test you can determine if the extruder is grinding the filament or if it's not grabbing it too much. After the calibration of the flowrate you can be certain that the printer is (by .gcode) pushing the correct amount of filament. If the problem persist I would first do an unclogging (since it's cheaper than the following option) using something like <a href="https://www.youtube.com/watch?v=XR7tUVLku14" rel="nofollow noreferrer">this</a>. </p>
<p>If both previous options do not solve the problem, I would highly recommend you to by a mk-8 like metal extruder. After a while, the plastic one that comes with the printer loses force and you'll lose steps. Personally, I had a similar problem where the first layer was printed in a droplet pattern and was solved by changing the extruder to a metal one.</p>
<p>Try these options and if the problem persist you could upload some pictures of the first layer or a video. Other possibilities I think of are that the filament is having trouble passing through the Bowden tube or maybe you'll have to reasemble the hotend.</p>
| 1,659
|
<p>I was looking through the plans for C++0x and came upon <code>std::initializer_list</code> for implementing initializer lists in user classes. This class could not be implemented in C++
without using itself, or else using some "compiler magic". If it could, it wouldn't be needed since whatever technique you used to implement <code>initializer_list</code> could be used to implement initializer lists in your own class.</p>
<p>What other classes require some form of "compiler magic" to work? Which classes are in the Standard Library that could not be implemented by a third-party library?</p>
<p>Edit: Maybe instead of implemented, I should say instantiated. It's more the fact that this class is so directly linked with a language feature (you can't use initializer lists without <code>initializer_list</code>). </p>
<p>A comparison with C# might clear up what I'm wondering about: IEnumerable and IDisposable are actually hard-coded into language features. I had always assumed C++ was free of this, since Stroustrup tried to make everything implementable in libraries. So, are there any other classes / types that are inextricably bound to a language feature.</p>
|
<p><code>std::type_info</code> is a simple class, although populating it requires <code>typeinfo</code>: a compiler construct.</p>
<p>Likewise, exceptions are normal objects, but throwing exceptions requires compiler magic (where are the exceptions allocated?).</p>
<p>The question, to me, is "how close can we get to <code>std::initializer_list</code>s without compiler magic?"</p>
<p>Looking at <a href="http://en.wikipedia.org/wiki/C%2B%2B0x#Initializer_lists" rel="nofollow noreferrer">wikipedia</a>, <code>std::initializer_list<typename T></code> can be initialized by something that looks a lot like an array literal. Let's try giving our <code>std::initializer_list<typename T></code> a conversion constructor that takes an array (i.e., a constructor that takes a single argument of <code>T[]</code>):</p>
<pre><code>namespace std {
template<typename T> class initializer_list {
T internal_array[];
public:
initializer_list(T other_array[]) : internal_array(other_array) { };
// ... other methods needed to actually access internal_array
}
}
</code></pre>
<p>Likewise, a class that uses a <code>std::initializer_list</code> does so by declaring a constructor that takes a single <code>std::initializer_list</code> argument -- a.k.a. a conversion constructor:</p>
<pre><code>struct my_class {
...
my_class(std::initializer_list<int>) ...
}
</code></pre>
<p>So the line:</p>
<pre><code> my_class m = {1, 2, 3};
</code></pre>
<p>Causes the compiler to think: "I need to call a constructor for <code>my_class</code>; <code>my_class</code> has a constructor that takes a <code>std::initializer_list<int></code>; I have an <code>int[]</code> literal; I can convert an <code>int[]</code> to a <code>std::initializer_list<int></code>; and I can pass that to the <code>my_class</code> constructor" (<strong>please read to the end of the answer before telling me that C++ doesn't allow two implicit user-defined conversions to be chained</strong>).</p>
<p>So how close is this? First, I'm missing a few features/restrictions of initializer lists. One thing I don't enforce is that initializer lists can only be constructed with array literals, while my <code>initializer_list</code> would also accept an already-created array:</p>
<pre><code>int arry[] = {1, 2, 3};
my_class = arry;
</code></pre>
<p>Additionally, I didn't bother messing with rvalue references.</p>
<p>Finally, this class only works as the new standard says it should if the compiler implicitly chains two user-defined conversions together. This is specifically prohibited under normal cases, so the example still needs compiler magic. But I would argue that (1) the class itself is a normal class, and (2) the magic involved (enforcing the "array literal" initialization syntax and allowing two user-defined conversions to be implicitly chained) is less than it seems at first glance.</p>
|
<p>I think you're pretty safe on this score. C++ mostly serves as a thick layer of abstraction around C. Since C++ is <em>also</em> a superset of C itself, the core language primitives are almost always implemented sans-classes (in a C-style). In other words, you're not going to find many situations like Java's <code>Object</code> which is a class which has special meaning hard-coded into the compiler.</p>
| 30,746
|
<p>I have an ASP.NET page with a gridview control on it with a CommandButton column with delete and select commands active.</p>
<p>Pressing the enter key causes the first command button in the gridview to fire, which deletes a row. I don't want this to happen. Can I change the gridview control in a way that it does not react anymore to pressing the enter key?</p>
<p>There is a textbox and button on the screen as well. They don't need to be responsive to hitting enter, but you must be able to fill in the textbox. Currently we popup a confirmation dialog to prevent accidental deletes, but we need something better than this.</p>
<p>This is the markup for the gridview, as you can see it's inside an asp.net updatepanel (i forgot to mention that, sorry): (I left out most columns and the formatting)</p>
<pre><code><asp:UpdatePanel ID="upContent" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnFilter" />
<asp:AsyncPostBackTrigger ControlID="btnEdit" EventName="Click" />
</Triggers>
<ContentTemplate>
<div id="CodeGrid" class="Grid">
<asp:GridView ID="dgCode" runat="server">
<Columns>
<asp:CommandField SelectImageUrl="~/Images/Select.GIF"
ShowSelectButton="True"
ButtonType="Image"
CancelText=""
EditText=""
InsertText=""
NewText=""
UpdateText=""
DeleteImageUrl="~/Images/Delete.GIF"
ShowDeleteButton="True" />
<asp:BoundField DataField="Id" HeaderText="ID" Visible="False" />
</Columns>
</asp:GridView>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</code></pre>
|
<p>Every once in a while I get goofy issues like this too... but usually I just implement a quick hack, and move on :)</p>
<pre><code>myGridView.Attributes.Add("onkeydown", "if(event.keyCode==13)return false;");
</code></pre>
<p>Something like that should work.</p>
|
<p>In Page_Load, set the focus on the textbox.</p>
| 18,343
|
<p>I know Flex pretty good but also started to use Java FX. I am a little bit confused. Java FX seems to focus more on low level drawing operations and animations. Less on creating standard UIs like Flex.</p>
<p>So is JavaFX more like Flash than Flex?</p>
<p>On the other side JavaFX also supports Swing components as well as data binding, which makes it appear more like Flex.</p>
|
<p>I think JavaFX is more like Flex, because JavaFX is more about building applications than animations (which is, I gather, one of the sensitive distinctions between Flex and Flash). </p>
<p>I think of JavaFX and Flex as the future heirs to Rich Internet Application programming. They're both intended to stretch the realm of what's possible with RIA.</p>
<p>One of the biggest benefits of JavaFX that I see is that <b>you can use your existing Java business logic by simply importing it</b>. </p>
<p>Some of the language features, such as <b>binding</b> and <b>duration as a data type</b>, are paradigm-shifting, because they make certain functionality possible and readily available:</p>
<ul>
<li>Binding: Connecting two values together, so you can automatically update one value when the other updates. Example: "name: bind textfield.getValue". Much easier than setting up Observer patterns to watch for changes to variables.</li>
<li>Duration can be used as a data type: "var frameDelay = 5ms". Having Duration as an integral part of the language seems like a no-brainer when dealing with animations.</li>
</ul>
|
<p>I'd say it's more like Flash - or at least it's about bringing Flash-like abilities to Java. Don't forget that Flex is built on top of Flash. JavaFX script from what I've seen is quite similar to ActionScript, and not at all like MXML. Sun seem to be stressing the importance of things like video and the ability to work with vector graphics from industry standard design programs.</p>
<p>I think beauty of Flash is the ability to create your own, nice-looking UI components, whereas Flex is about laying out standard components using tags. So again, it's more like Flash. </p>
| 35,005
|
<p>We are deploying our ASP.NET 3.5 app to a production server for beta testing.</p>
<p>Each page is secured using SSL.</p>
<p>On our homepage (default.aspx) we have web services which populate flash objects.</p>
<p>I am getting an error:</p>
<p>The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was 'Negotiate,NTLM'.</p>
<p>Also, when using firefox, receive the Windows Login pop up screen.</p>
<p>Does anyone have any clue what or why this is happening?</p>
<p>Much thanks!</p>
|
<p>I would think that the request from Flash to the secure web services doesn't have credentials or that the secure certificate in the response can't be validated.</p>
<p>Probably both.</p>
<p>So in flash there will probably need to be some code like:</p>
<pre><code>request.Username = "xyz"
request.Password = "***"
</code></pre>
<p>or something similar </p>
<p>In .net there is a way to manually override the validation of a certificate for the request. I'm not sure how you would do that in Flash.</p>
<p>I'll update this if I find a sample for the .net way. </p>
|
<p>Sounds like IIS isn't configured for <a href="http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/9ded7af2-fcb7-4ed2-b007-e19f971f6e13.mspx?mfr=true" rel="nofollow noreferrer">anonymous access</a>. </p>
<p>If you believe you have it setup correctly (sounds like it isn't), then you might try troubleshooting your connection with <a href="http://support.microsoft.com/kb/284285" rel="nofollow noreferrer">Wfetch</a>. </p>
| 30,874
|
<p>We have an application that has one or more text console windows that all essentially represent serial ports (text input and output, character by character). These windows have turned into a major performance problem in the way they are currently code... we manage to spend a very significant chunk of time in them.</p>
<p>The current code is structured by having the window living its own little life, and the main application thread driving it across "SendMessage()" calls. This message-passing seems to be the cause of incredible overhead. Basically, having a detour through the OS feels to be the wrong thing to do.</p>
<p>Note that we do draw text lines as a whole where appropriate, so that easy optimization is already done. </p>
<p>I am not an expert in Windows coding, so I need to ask the community if there is some other architecture to drive the display of text in a window than sending messages like this? It seems pretty heavyweight.</p>
<p>Note that this is in C++ or plain C, as the main application is a portable C/C++/some other languages program that also runs on Linux and Solaris.</p>
<p>We did some more investigations, seems that half of the overhead is preparing and sending each message using SendMessage, and the other half is the actual screen drawing. The SendMessage is done between functions in the same file...</p>
<p>So I guess all the advice given below is correct:</p>
<ul>
<li>Look for how much things are redrawn</li>
<li>Draw things directly </li>
<li>Chunk drawing operations in time, to not send every character to the screen, aiming for 10 to 20 Hz update rate of the serial console.</li>
</ul>
<p>Can you accept ALL answers?</p>
|
<p>I agree with Will Dean that the drawing in a console window or a text box is a performance bottleneck by itself. You first need to be sure that this isn't your problem. You say that you draw each line as a whole, but even this could be a problem, if the data throughput is too high. </p>
<p>I recommend that you don't use the SendMessage to pass data from the main application to the text window. Instead, use some other means of communication. Are these in the same process? If not, you could use shared memory. Even a file in the disk could do in some circumstances. Have the main application write to this file and the text console read from it. You could send a SendMessage notification to the text console to inform it to update the view. But do not send the message whenever a new line arrives. Define a minimum interval between two subsequent updates.</p>
|
<blockquote>
<p>Are the output windows part of the
same application? It almost sounds
like they aren't...</p>
</blockquote>
<p>Yes they are, all in the same process.</p>
<p>I did not write this code... but it seems like SendMessage is a bit heavy for this all in one application case. </p>
<blockquote>
<p>You describe these are 'text console
windows', but then say you have
multiple of them - are they actually
Windows Consoles? Or are they
something your application is drawing?</p>
</blockquote>
<p>Our app is drawing them, they are not regular windows consoles.</p>
<p>Note that we also need to get data back when a user types into the console, as we quite often have interactive serial sessions. Think of it as very similar to what you would see in a serial terminal program -- but using an external application is obviously even more expensive than what we have now. </p>
<blockquote>
<p>If you can't make a change like that,
perhaps you could buffer your output
for something like 100ms so that you
don't have so many out-going messages
per second, but it should also update
at a comfortable rate.</p>
</blockquote>
<p>Good point. Right now, every single character output causes a message to be sent.</p>
<p>And when we scroll the window up when a newline comes, then we redraw it line-by-line.</p>
<p>Note that we also have a scrollback buffer of arbitrary size, but scrolling back is an interactive case with much lower performance requirements.</p>
| 49,862
|
<p>There is someone in my team that swears by using some kind of GVim feature to do manually code folding.</p>
<p>As I'm using another editor and do not really need the folding feature, I think it only pollutes the source code with tags like:</p>
<pre><code>/* {{{1 */
</code></pre>
<p>Convincing the person not to use this folding is not an option (got into some heated discussions before).</p>
<p>I'm not really a GVim guy, I'm wondering if there are not any other ways to do the folding without changing the team's code? </p>
<ul>
<li>Maybe putting the folding directions in a separate file, or </li>
<li>Doing some kind of smart folding that takes the syntax of the programming language into account without changing the source code?</li>
</ul>
|
<p>I would imagine he could just add the following to his .vimrc: </p>
<pre><code>set foldmethod=syntax
</code></pre>
<p>Assuming he is using a version of VIM that supports that. :)</p>
|
<p>You should try it yourself. Once you start using foldmethod=marker there is just no going back. I am working on a project now where I can't use marker folding and it feels like washing clothes in a time before there were washing machines.</p>
| 49,643
|
<p>Using online interfaces to a version control system is a nice way to have a published location for the most recent versions of code. For example, I have a LaTeX package here (which is released to CTAN whenever changes are verified to actually work):</p>
<p><a href="http://github.com/wspr/pstool/tree/master" rel="nofollow noreferrer">http://github.com/wspr/pstool/tree/master</a></p>
<p>The package itself is derived from a single file (in this case, pstool.tex) which, when processed, produces the documentation, the readme, the installer file, and the actual files that make up the package as it is used by LaTeX.</p>
<p>In order to make it easy for users who want to download this stuff, I include all of the derived files mentioned above in the repository itself as well as the master file pstool.tex. This means that I'll have double the number of changes every time I commit because the package file pstool.sty is a generated subset of the master file.</p>
<p>Is this a perversion of version control?</p>
<hr>
<p>@<a href="https://stackoverflow.com/questions/39154/do-you-version-derived-files#39157">Jon Limjap</a> raised a good point:</p>
<blockquote>
<p>Is there another way for you to publish your generated files elsewhere for download, instead of relying on your version control to be your download server?</p>
</blockquote>
<p>That's really the crux of the matter in this case. Yes, released versions of the package can be obtained from elsewhere. So it does really make more sense to only version the non-generated files.</p>
<p>On the other hand, @<a href="https://stackoverflow.com/questions/39154/do-you-version-derived-files#39179">Madir</a>'s comment that:</p>
<blockquote>
<p>the convenience, which is real and repeated, outweighs cost, which is borne behind the scenes </p>
</blockquote>
<p>is also rather pertinent in that if a user finds a bug and I fix it immediately, they can then head over to the repository and grab the file that's necessary for them to continue working without having to run any "installation" steps.</p>
<p>And this, I think, is the more important use case <em>for my particular set of projects</em>.</p>
|
<p>I am using Tortoise SVN for small system ASP.NET development. Most code is interpreted ASPX, but there are around a dozen binary DLLs generated by a manual compile step. Whilst it doesn't make a lot of sense to have these source-code versioned in theory, it certainly makes it convenient to ensure they are correctly mirrored from the development environment onto the production system (one click). Also - in case of disaster - the rollback to the previous step is again one click in SVN. </p>
<p>So I bit the bullet and included them in the SVN archive - the convenience, which is real and repeated, outweighs cost, which is borne behind the scenes.</p>
|
<p>In some cases we do, but it's more of a sysadmin type of use case, where the generated files (say, DNS zone files built from a script) have intrinsic interest in their own right, and the revision control is more linear audit trail than branching-and-tagging source control.</p>
| 6,024
|
<p>Given a table structure like this:</p>
<pre><code>CREATE TABLE `user` (
`id` int(10) unsigned NOT NULL auto_increment,
`name` varchar(32) NOT NULL,
`username` varchar(16) NOT NULL,
`password` char(32) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`)
);
</code></pre>
<p>Is there any use in using the LIMIT keyword when searching by username, or is the DB smart enough to know that there can only possibly be one result, and therefore stop searching once it's found one?</p>
<pre><code>SELECT * FROM `user` WHERE `username` = 'nick';
-- vs --
SELECT * FROM `user` WHERE `username` = 'nick' LIMIT 1;
</code></pre>
<hr>
<p><em>Update:</em> Thanks for the answers, they've been enlightening. It seems like, even though it's unnecessary, putting <code>LIMIT 1</code> on the query doesn't hurt, and probably increases readability (you don't have to go looking into the DB schema to know that only one is going to be returned). Special shoutout for JR's answer - I didn't even know you could do that with indices.</p>
<p>Also, there's a similar question I've found <a href="https://stackoverflow.com/questions/34488/does-limiting-a-query-to-one-record-improve-performance">here</a>, which might also help.</p>
|
<p>I've always been told and read that you should include the <code>LIMIT</code> everytime you only want 1 result. This just tells the DB that it should stop so matter what. In your case, you're probably right it doesn't make a difference, but I think it's better just to always do than always deciding and leaving it out one time when you need it.</p>
|
<p>The sql query optimizer should be smart enough to figure this out.</p>
| 23,059
|
<p>Having recently produced an HTML/CSS/Javascript based report from various word and excel files sent to me I'm trying to work out how to do this better in future, ideally enabling non-technical users in the office to do many of the tasks currently handed to me.</p>
<p>There are a range of HTML editors out there but none of them seem obviously adept at doing this kind of task. For example, most tables in the document are displayed via a thickbox (jquery plugin). In addition to the table, this requires that I enclose them in a div with various id and class attributes and then create a link at the top of the page looking something like this:</p>
<pre><code><a href="#TB_inline?height=300&amp;width=700&amp;inlineId=tbtable2"
class="thickbox tablelink" title="Municipal Operating Expenditure (A$m)">Municipal Operating Expenditure</a>
</code></pre>
<p>I need a solution that will be careful with my templates, have a WYSIWYG interface, but also provide easy input for this kind of thing without frustrating those in the office with no HTML knowledge, ideally keeping them totally away from the code.</p>
|
<p>You can't give your non-technial users such a complex HTML template and hope they will not break it. There is no HTML editor that can enforce such rules for structures that are more complex than a class attribute on an element.</p>
<p>This scenario calls for the use of XML: you need to separate your content and presentation. </p>
<p>You should define an XML flavour to describe your report. Then write an XSLT that will transform your <thickbox/> XML element into the HTML structure you describe above.</p>
<p>To allow non-technical users to do some of your tasks, you could use <a href="http://xopus.com" rel="nofollow noreferrer">Xopus</a> to make the XML editable (<a href="http://xopus.com/files/demo/xopus/xopus.html#/files/demo/examples/Recipe/start.html" rel="nofollow noreferrer">demo</a>). You could do the initial conversion from OOXML, or you could use the copy/paste functionality in Xopus to allow them to copy content from Excel and automatically convert it into your <thickbox/> element.</p>
|
<p>Have you tried <a href="http://www.fckeditor.net/" rel="nofollow noreferrer">FCKEditor</a>. It is very popular and used in a number of blogs, wikis and CMSs. It can produce very clean HTML and is highly customizable.</p>
| 18,501
|
<p>I've just started experimenting with SDL in C++, and I thought checking for memory leaks regularly may be a good habit to form early on. </p>
<p>With this in mind, I've been running my 'Hello world' programs through Valgrind to catch any leaks, and although I've removed everything except the most basic <code>SDL_Init()</code> and <code>SDL_Quit()</code> statements, Valgrind still reports 120 bytes lost and 77k still reachable.</p>
<p>My question is: Is there an acceptable limit for memory leaks, or should I strive to make all my code completely leak-free? </p>
|
<p>Be careful that Valgrind isn't picking up false positives in its measurements.</p>
<p>Many naive implementations of memory analyzers flag lost memory as a leak when it isn't really.</p>
<p>Maybe have a read of some of the papers in the external links section of the <a href="http://en.wikipedia.org/wiki/IBM_Rational_Purify" rel="noreferrer">Wikipedia article on Purify</a>. I know that the documentation that comes with Purify describes several scenarios where you get false positives when trying to detect memory leaks and then goes on to describe the techniques Purify uses to get around the issues.</p>
<p>BTW I'm not affiliated with IBM in any way. I've just used Purify extensively and will vouch for its effectiveness.</p>
<p>Edit: Here's an <a href="http://www.ibm.com/developerworks/rational/library/06/0822_satish-giridhar/" rel="noreferrer">excellent introductory article</a> covering memory monitoring. It's Purify specific but the discussion on types of memory errors is very interesting.</p>
<p>HTH.</p>
<p>cheers,</p>
<p>Rob</p>
|
<p>As per Rob Wells' comments on Purify, download and try out some of the other tools out there. I use BoundsChecker and AQTime, and have seen different false positives in both over the years. Note that the memory leak might also be in a third party component, which you may want to exclude from your analysis. From example, MFC had a number of memory leaks in the first view versions.</p>
<p>IMO, memory leaks should be tracked down for any code that is going into a code base that may have a long life. If you can't track them down, at least make a note that they exist for the next user of the same code.</p>
| 28,876
|
<p>I've just introduced a friend to <strong>GNU Screen</strong> and they're having a hard time getting used to it. That makes me think about the essential things he needs to know about the excellent <strong>Screen</strong> utility, the same things that you'd think worthwhile to teach someone, a beginner, from the ground up. What are some analogies and handy tips for remembering binds, etc.?</p>
<p>It would be awesome.</p>
|
<p>I've been using <code>Screen</code> for over 10 years and probably use less than half the features. So it's definitely not necessary to learn all its features right away (and I wouldn't recommend trying). My day-to-day commands are:</p>
<pre><code>^A ^W - window list, where am I
^A ^C - create new window
^A space - next window
^A p - previous window
^A ^A - switch to previous screen (toggle)
^A [0-9] - go to window [0-9]
^A esc - copy mode, which I use for scrollback
</code></pre>
<p>I think that's it. I sometimes use the split screen features, but certainly not daily. The other tip is if screen seems to have locked up because you hit some random key combination by accident, do both <code>^Q</code> and <code>^A ^Q</code> to try to unlock it.</p>
|
<p>^A A switches back to the screen you just came from.</p>
| 9,605
|
<p>I'm struggling to find examples/explanations of coding a MS Certificate Authority exit module. </p>
<p>If anybody has any help or resources they can point me at I'd be grateful.</p>
|
<p>Perhaps this article will help you? <a href="http://msdn.microsoft.com/en-us/library/aa388214.aspx" rel="nofollow noreferrer">Writing Custom Exit Modules</a></p>
|
<p>The Windows 7 SDK contains a sample in directory security/certificateservices/exit/c++/.</p>
<p>You can download only the sample here: <a href="https://github.com/Microsoft/Windows-classic-samples/tree/master/Samples/Win7Samples/security/certificateservices/exit/c%2B%2B/WindowsServer2008R2" rel="nofollow noreferrer">https://github.com/Microsoft/Windows-classic-samples/tree/master/Samples/Win7Samples/security/certificateservices/exit/c%2B%2B/WindowsServer2008R2</a></p>
| 25,515
|
<p>I have inherited some legacy PHP code what was written back when it was standard practice to use <a href="http://php.net/register_globals" rel="nofollow noreferrer"><code>register_globals</code></a> (As of PHP 4.2.0, this directive defaults to off, released 22. Apr 2002).</p>
<p>We know now that it is bad for security to have it enabled. The problem is how do I find all the places in the code where I need to use <code>$_GET</code> or <code>$_POST</code>? My only thought was to set the error reporting to warn about uninitialized variables and then test each part of the site. Is there an easier way? Will I have to test each code path in the site or will PHP give a warning on a file basis?</p>
|
<p>If you set error reporting to E_ALL, it warns in the error log about undefined variables complete with filename and line number (assuming you are logging to a file). However, it will warn only if when it comes across an undefined variable, so I think you will have to test each code path. Running php from the command line doesn't seem to help also.</p>
<p>There is a debugging tool named xdebug, haven't tried it, but maybe that can be useful?</p>
|
<p>I know that there's a way to set php.ini values for that script with a certain command, I thus went looking and found this too - <a href="http://forums.macosxhints.com/archive/index.php/t-8538.html" rel="nofollow noreferrer">Goto last post on page</a></p>
<p>I also found the following post which may be of use - <a href="http://www.webmasterworld.com/forum88/1584.htm" rel="nofollow noreferrer">Goto last post on the page</a></p>
<p>I will add to this more if nobody has found an answer but I must now catch a train.</p>
| 2,836
|
<p>In Apple's NSObject documentation, NSZoneFree is called in the - (void)dealloc example code:</p>
<pre><code>- (void)dealloc {
[companion release];
NSZoneFree(private, [self zone])
[super dealloc];
}
</code></pre>
<p>You can find it in context <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html#//apple_ref/doc/uid/20000050-dealloc" rel="nofollow noreferrer">over here</a>.</p>
<p>I never had the notion that I should be calling NSZoneFree in my own NSObject subclasses (or what NS_WhateverClass_ subclasses) and can't find anything conclusive on the topic anywhere in the docs.</p>
<p>All I can find about using NSZoneFree is a brief mention in the <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/MemoryMgmt/Concepts/Zones.html" rel="nofollow noreferrer">Memory Management Programming Guide</a>, and an explanation of the function in the <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Functions/Reference/reference.html#//apple_ref/c/func/NSZoneFree" rel="nofollow noreferrer">Foundation Functions Reference</a>, but none of these docs make it clear to me whether I should worry about it in the context of a dealloc method.</p>
<p>Can anybody clarify when I should put an NSZoneFree call in my own classes' dealloc implementations?</p>
<p>Edit: Thanks for your replies, it's clearer to me now :) — Dirk</p>
|
<p><code>NSZoneFree()</code> balances out a call to <code>NSZoneMalloc()</code>, just like <code>-release</code> balances a call to <code>-alloc</code> or <code>-copy</code> and <code>CFRelease()</code> balances a call to <code>CFRetain()</code> or <code>CF*Create*()</code> or, for that matter, <code>free()</code> balances a call to <code>malloc()</code> or <code>calloc()</code>.</p>
<p>Given the allocator(s) that the C library uses on Mac OS X, much of this is academic, but best practices say that you release your hold on memory the same way you got it, and in the case of that class, the instance variable <code>private</code> had previously been allocated with <code>NSZoneMalloc()</code>.</p>
|
<p>According to the <a href="https://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Functions/Foundation_Functions.pdf" rel="nofollow noreferrer">Foundation Reference</a>:</p>
<blockquote>
<p>Returns memory to the zone from which it was allocated. The standard C function free does the same, but spends time finding which zone the memory belongs to.</p>
</blockquote>
<p>So, you basically use NSZoneFree(), instead of free(), when cleaing up malloc'd and calloc'd memory. You generally don't need to call it, however.</p>
| 42,194
|
<p>I am developing a web application using Struts 2.1.2 and Hibernate 3.2.6.GA. I have an entity, <code>User</code>, which I have mapped to a table <code>USERS</code> in the DB using Hibernate. I want to have an image associated with this entity, which I plan to store as a <code>BLOB</code> in the DB. I also want to display the image on a webpage along with other attributes of the <code>User</code>.</p>
<p>The solution I could think of was to have a table <code>IMAGES(ID, IMAGE)</code> where <code>IMAGE</code> is a <code>BLOB</code> column. <code>USERS</code> will have an <code>FK</code> column called <code>IMAGEID</code>, which points to the <code>IMAGES</code> table. I will then map a property on <code>User</code> entity, called <code>imageId</code> mapped to this <code>IMAGEID</code> as a Long. When rendering the page with a JSP, I would add images as <code><img src="images.action?id=1"/></code> etc, and have an Action which reads the image and streams the content to the browser, with the headers set to cache the image for a long time.</p>
<p>Will this work? Is there a better approach for rendering images stored in a DB? Is storing such images in the DB the right approach in the first place?</p>
|
<p>Yes your suggested solution will work. Given that you are working in a Java environment storing the images in the database is the best way to go. If you are running in a single server environment with an application server that will let you deploy in an exploded format technically you could store the images on disk but that wouldn't be the best practice. One suggestion would be to use a servlet instead of a JSP. To get good browser behavior you want the browser to think that the file type that it is displaying matches the file type that it is expecting. Despite the existence of mime type headers the file extension is still really important. So you want a link that looks like this:</p>
<pre><code><a href="foo.jsp"><img src="imageservlet/123456789.png"></a>
</code></pre>
<p>Where 123456789 is the primary key of your image in the database. Your servlet mapping would look like this:</p>
<pre><code><servlet>
<servlet-name>ImageServlet</servlet-name>
<servlet-class>com.example.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ImageServlet</servlet-name>
<url-pattern>/imageservlet/*</url-pattern>
</servlet-mapping>
</code></pre>
<p>Then in your servlet simply parse the request URL for the image ID rather than using the query string as the query string will confuse some browsers. Using the query string won't break browsers outright but you'll get odd behavior with regards to caching and some browsers may report the content as unsafe.</p>
|
<p>If you want to display the user image directly with their properties perhaps you can consider embedding the image data directly in the HTML.</p>
<p>Using a special data: URL scheme you are able to embed any mime data inside a HTML page, the format is as follows:</p>
<blockquote>
<pre><code>data:<mimetype>;base64,<data>
</code></pre>
</blockquote>
<p><strong></strong> needs to be replaced by the mime-type of your data (image/png for instance) and
<strong></strong> is the base64 encoded string of the actual bytes of the file.</p>
<p>See <a href="http://www.ietf.org/rfc/rfc2557.txt" rel="nofollow noreferrer">RFC 2557</a>.</p>
<p><a href="http://rifers.org/blogs/gbevin/2005/4/11/embedding_images_inside_html" rel="nofollow noreferrer">Example</a>:</p>
<pre><code><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEYAAAAmCAYAAAB52u3eAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsSAAALEgHS3X78AAAAB3RJTUUH1AkICzQgAc6C2QAACrxJREFUeNrtmnl0VdUVxn/3vnnIPBKmJECYkoAEERArgxGqCDIUkKVoqRZKUVREnC1SXXWJlKo4VrEi4EAUEARUtM5oVcAwZhZIyEySlzfe4fSPlzwSEzGUuLpa2Gu9te49Z99zzvvu3vt8e58rCSEAUBWNoyV1wZtzVHokR0pGkwEASQhB2bF6sX/vCZxhFjzuwDkJSlWFm4LDVYyf1I9ho3pKRiWg8f23ZfTPTCQ+0XkuGwzPr/qCZ1Z8zsDBXTCWFNYKq81EVIwNm910TgNzwbBufPlxCR9uzxMyQEO9j/MSlLpaLwDyeSjal3MOmBunb/gvABNQoepku12qqrVpUxTtjKdQVY1mivFTY7Wn09x/rKSuQ/MYOwsTUViKOn0RxifvRYqLAuDw/goeuO1dIiJtVJa7+PWUAcy//WJUVWPhdTl43AFqqz0sXT4utDOOndCHS/r/jb88fRUjLk1mRvbLbNw1FyEEdy14h9Kj9TS6/MyZfyEDMhP50+LtGI0GMrOSWLJsbBudSTPSmTfzDVRVJyrG1uGX0SnAiGPlKBfPhIp6pAG9Wrw5nfJSF6/tvB6AsYNWM/OGC/j0g0Ji4uw8u2EGleUuZmS/zCNPTmT7pkN07R5Ot56RfLSzAGe4hR4pQZB3bjmMxWrk1W3XoSgaEy58llVrplBZ3sgHexYgyzI7Nh9qo2M0yvRIieLBFRMoKaxl6ugXfxlgPn6vgEaXnyunDQy1abPvRVQUIPfMgghHK/0BgxKR5aDH9ktP4GjxSQrzasjM6gpAfGIYHneArBHdWb50J8m9orlx0QjWrP6K6Bgbo8amhqxv3zel3HJ9DkIIEpPC8HlVBrYYvz2d/XvLSb+gCwDJvaIJj7R2PjB+v8q82a+zbMUVoTZ966fon+1CIgoMMhgMrZ4pyqtudZ3ULYJuPSM5cqAyuD2e9GKxGLFYjERG2di6cT/rts8h59V9bM05yMubZof+VGZWV5avOjX3/r0nkGUpdN+ezptr94bWUHHChauD1OSMgHl4yXvU1LhbWYu+ZjMgBeO4xwdeP9gsp6xJE9w8ZyMN9X4uvbw3cQlOrvrNQN5ev49b575FcX4Ndz+SDcCosal8sO0IdruZkaNTOLD3BPGJYQBMnD6Q9945wtyp64mJc+DzKsy7/eJW62tP57HnJ3PdxFdZMm8zXo9CWETHLIa8g5Vi8+u5or7OK04ne746JszcJn7V/4lTjQFFBLqNF376Cz8Zwm+4QOiFx0PduXvKxC3XbxQeT0DUVLvbjFlZ7hJeb0CcidSd9IiqCtcZ6ei6LsrLGoSmaad97uP3C8T4oc+ILW/kig5ZjM+rMP/aN9EReNwBVFXHaJQRpZWI8uomwzOAVof4OhcpNRg/TGYD0bEObDYTNlvbdCMu4cxzs4hI2xnrSJJEQpewM5qnQ8DcOW8L3+QfJRYHxcdqKThcRb/0BHC5QQ00uRKAhL5+J/KsCQD0HRDPgyuC17ouePetgxQX1+JtCODxBBCAxWIgLSOecdlpRMXaQ3OWHq1n08bvkZGwWc1cM3cIFquRb3cf47PPi7DJrYEWgCo0ps0cRGLXcHLW7aO8ogGT1Drm+XWVPr3imHB1/7MDZlvOQZ5b+wWxOJGABuFh82u59PtzAiTFg8MJblcTV3Sgb9+FOFKC1De51TiapnPLDTkUu6uxYMKPH9AAMyYMJMVE8OTT07hqRnqzi7Nw8euAgXicTJ6ZjsVqZMemQ9z3aA5mnE2AnCJyCl769I4jsWs4j96/i38VF2HG8iMdH9lDMn4WmNMyX0XRePiu9zBjCNmEAwuvvfQdXo+CFBOBPDwD8DT1GkB1oT3wTLvjRUbZiMSBAzNTRw9h0Q3ZpMd1wYmFkzUefjdrAyUFtUE3NBkIw0E0dqIi7UhScAU2uwlTU3skNpxYQj+wUF/na3InK2E4iMFORAs9Ezb8PvXsXCnvQBWHCspxYA61WTGSd6KK3Z+WMGZ8H+SbpqHv2tniqXD0NzYhbr4GadTgdsd1E+Dmu37F6PG9OV5Sx5ispzhZ66FGePhwRx5zFw7/2YV7CHDRkJ489txkmtm/puskp0a30qvHx9LFlzF5VgZCCHQhsNtMZx9jNFrnHBLgR6XgUFUQmKljkVLSEcWFgLXJCHXUBY9g2vNakNv8SCQkGl1+ALolR9KvTwL//CofCfC4lY7lTGhERdsZNLTr6dM3NNIHd2HQ0KTOC7590+MZc3Eftnz+PTE4kZHwoiAh0T8zMahkMiIvmIG25IEmYACciNzd6C9tRr5pStsUAoHDGbTC/XtO8P2BUkwYUNAYfknPDma/Mu7GAOVlLhDBKCJJEvGJzlakz46JbW8foK7Oi6bp+ITCyOEpZA3v/p8DYzTKrNk0m6W3OPloZz5+j0pKagyLbrs0RNUB5EmXot0ZCUJvEbasaE9tQL7xapCkVuM6sbBi2UesWf0Vn35YhMvjJ4DG0lsvY+jIHh0CxomFPV8fZ3ivlUELEjp2q5kv8xcRE+dspffGW3v4x1tfIwEqHpbdMeXsgAGIjrXzwvpZNPh0PPUeEtvjHj4/COVHw9kQ+/MRxWUhXtMsFozs2H0QkIjGhkDw1FPTuOGPF3XY1CUk/LpKua8hSAfQsfstaFpr19cR2DFjx4xAUAtYOyPGhEJqVTnh3dv3U23VOsAHhLeORroXyirhR8D4UZkyZhBF+dUUHa/BgMQLT+9m0swMoltwmdPmbSik9IhhyZxxoaBqMhlwhlnaBN/77x7PtGsHAQJNEx0q+ncYGPXxdYj9uRiX34E0dACYjIii4+grX0Ffsx5oj1kawNGWqTbiZ8mysST3jubCtMfxNip8ebCYh+7YwaqXp3ZoPT4UeqXFsnT5uNPqKWik9okhbUDcL1PalC/KQN+1DWXkNSi9rkJJm4zS92q01X8HHC3Y76n9QIpLaEP0mt2gsryRhC5hLL5rDHV4icXBhrXf8UNRbYdd6XRFJ10PupQJmd2fleD1KPh9Kj6vis+nInTRScBkD0dypAX3lGM/IPLzmtKBiHZAkYB65N9PA3v72WxzPL7+D8PoER6FjqBGd7Nx7b5OqSiaTAY0dCKw8epL3zAs5XEuSl3J0NQVjOj9V8qO13dSzTc2EsOdvwXqAHPT1mz4CeVqpCGXYLjvxlatrnof9Xjx4Q297choG5df0Zca6tDQWP/itwgBQghceKnHS0O9L1TD9ftUFLy48eJu/OlT04nTB+LBSx1eGvFzqLKC3BMnOFBeRnFpNRarsfPqMYYHbkLk/YC+7pUmYGwtsBWAH2hEGp2NaeMqsJ4KhLIkMWlmBhXVjShCpXvPqFDfnPnDqPG6sUtmZCQ87gBJ3SO4ZvJQjJJMuMOK2RJc6sDBXZg+aRhGSWZw+k+Tu4VLL8HuMPHJJ4VIASlkoQo6MZF2nGHWzqnHtBRt7VYRGDFb+K1Zwk9f4SdN+MkUgfRJQn1infhflTOux7Txv2uvRL72SkRZJZSUgaJC13ik3j34f5GzOiWQkuKDpYfzJ5Hnj2jPAwNQUdZwHolmolHZGAwTAb/KPTdvFWHhVkaNTTmnQVkybwtVFY0cqrlHMprMBq6elcnKhz7i689+CJUGzzWpq/VQW+1h5YtTcDjNwW/wABpdft7feuSc/jgxe2JfqTk7/zeNpiqnFESz8wAAAABJRU5ErkJggg==">
</code></pre>
| 18,218
|
<p>I'm developing a web tool using JSP, where there are many users of multiple kind (i.e. administrators, guest, write-enabled users, ...). Since this will be a subscription based system (i.e. user pay for a 3/6/12 month subscription), I need to enforce at most 1 login per user at the same time.
For example, say Mr. John Smith subscribes to this system; I don't want him to give his login info to a friend of his so that they'll both be using the system from 2 different computers at the same time.
How can I manage this situation?</p>
|
<ol>
<li>When a user logs in, store the <code>HttpSession.getId()</code> for that user. This could be in an application scope Map from user names to session IDs, or in the database.</li>
<li>For each subsequent request, for a logged-in user, check that <code>request.getSession().getId()</code> is the one stored for that user.</li>
<li>If the request session ID is not the one stored for that user, then it must be the ID of a newer session, for a later log in with the same user name. In this case, inform the user that another log in has taken over, and call <code>request.getSession().invalidate()</code> to log out the user.</li>
</ol>
<p>The main thing to remember is that given the stored session ID for another session - not the current session - you cannot cancel that other session.</p>
<p>Also, unless you clear the stored session ID after a time-out, you cannot reject the second log in attempt because you cannot tell whether the first session is still active.</p>
|
<p>When a user logs in you will want to invalidate any other login they might have at the time. This means doing a check on every request that is made, but you should have that for basic validation anyway. For example you can check the IP address they are accessing from, or the servlet session id, etc. These are all good things to keep track of anyway, especially for fact/report logging.</p>
<p>Then you can use annoyance of being logged out to enforce your policy, without making it impossible to go from one system to another and continue using the interface.</p>
<p>Use the aforementioned fact/report logs to analyse logins to see if any appear to have usage patterns that don't match a typical single user - sessions swapping frequently between two or more computers for example, especially at similar times.</p>
| 42,264
|
<p>This may be simple one, but 5 mins of Googling didn't give me the answer.
How do you save and load bitmaps using .Net librabries?</p>
<p>I have an Image object and I need to save it to disk in some format (preferably png) and load back in later.
A C# example would be great.</p>
|
<p>Here's a really simple example.</p>
<p><strong>Top of code file</strong></p>
<pre><code>using System.Drawing;
</code></pre>
<p><strong>In code</strong></p>
<pre><code>Image test = new Bitmap("picture.bmp");
test.Save("picture.png", System.Drawing.Imaging.ImageFormat.Png);
</code></pre>
<p>Remember to give write permissions to the ASPNET user for the folder where the image is to be saved.</p>
|
<p>About 10 seconds of google lead me to <a href="http://msdn.microsoft.com/en-us/library/9t4syfhh.aspx" rel="nofollow noreferrer">this example</a> for the save method, you can dig around a bit more for the others.</p>
| 20,996
|
<p>I need to reverse engineer a Microsoft SQL Server 2008 in order to create a Microsoft Visio 2007 Database Model Diagram. So I choose "Reverse Engineer" from the Database menu to connect to the DB.</p>
<p>I configured the Microsoft SQL Server Visio driver so that is uses SQL Server Native Client 10.0 as the ODBC driver. Afterwards I created a User DSN which connects to my DB. This DSN works (at least the provided test is successful). After clicking next in the Reverse Engineer Wizard, Visio kindly asks for my credentials which I properly provide, but after clicking OK I receive the following message:</p>
<blockquote>
<p>The currently selected Visio driver is not compatible with the data source.</p>
</blockquote>
<p>I tried using the old SQL Server ODBC driver, by also reconfiguring the Visio driver of course. It does not work too. </p>
|
<p>From <a href="http://forums.microsoft.com/TechNet/ShowPost.aspx?PostID=3825120&SiteID=17" rel="noreferrer">Microsoft support</a> via the Microsoft forums:</p>
<blockquote>
<p>Further investigation reveals that this is expected behavior for Visio 2007. When Visio opens a connection using the Visio SQL Server Driver it checks the server version and since SQL Server 2008 shipped after Visio 2007 it doesn't recognise SQL Server 2008 as a supported version and closes the connection. You can wait for a future version of Visio to ship which does recognise SQL Server 2008 or use the Visio Generic ODBC driver which can successfully open connections to SQL Server 2008. A third option is to use a copy of SQL Server 2005 for initial reverse engineering. The Visio team is aware of this issue.</p>
</blockquote>
|
<p>I also had this problem as above what i found worked </p>
<ol>
<li>was using the Reverse engineer wizard </li>
<li>using the Generic OLE Db provider in the first step </li>
<li>then setting the connection provider in
the next step to the highest SQL native driver shown ( I am using
SQL2016 with SQL native 11.0 on a windows 10 surface pro 4 for
reference ) </li>
<li><p>then entering the correct destination and credentials
in the connection tab ( testing the connection if you aren`t sure)</p>
<p>and that seemed to work for me,( I then had the ability to bring
through tables indexes views primary and foreign keys and stored
procedures).</p></li>
</ol>
<p>I also found that visio kept locking up on me ... apparently this is common ( and there I was feeling special) after finally getting sick of it i looked at these links </p>
<p><a href="https://dhondiyals.wordpress.com/2011/07/29/microsoft-visio-2010-crashes-very-frequently-resolved/" rel="nofollow noreferrer">https://dhondiyals.wordpress.com/2011/07/29/microsoft-visio-2010-crashes-very-frequently-resolved/</a></p>
<p><a href="https://answers.microsoft.com/en-us/msoffice/forum/msoffice_visio-mso_windows8/visio-2010-frozen-on-surface-pro/df1df27a-6585-4b0c-8442-a4363c541e08" rel="nofollow noreferrer">https://answers.microsoft.com/en-us/msoffice/forum/msoffice_visio-mso_windows8/visio-2010-frozen-on-surface-pro/df1df27a-6585-4b0c-8442-a4363c541e08</a></p>
<p>I found my problem to be in the later, ( the touchscreen and handwriting running application) .So ended it, and now I have the experience I was expecting </p>
| 11,828
|
<p>HI,</p>
<p>I am trying to write a query in vba and to save its result in a report.
I am a beginner. this is what i have tried
can somebody correct me</p>
<pre><code>Dim cn As New ADODB.Connection, rs As New ADODB.Recordset
Dim sql As String
Set cn = CurrentProject.Connection
sql = "Select * from table1 where empno is 0"
rs.Open sql, cn
While Not rs.EOF
' here i think i should save the result in a report but i am not sure how
rs.MoveNext
Wend
rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing
</code></pre>
<p>Also how do i change this query to run this on all tables in a database</p>
|
<p><strong>IF you are wanting to create a report using MS Access's report generator</strong>, you will have to use a Query Object (there might be a way to trick MS Access into running it off of your record set, but it's probably not worth your effort). </p>
<p>You can create the Query Object on the "Database" window. Click the Query button in the objects list, and then click on New. In the resulting editor you can create the query graphically or if you prefer with SQL. Save the query and give it a meaning full name.</p>
<p>Similarly the report can be created on the "Database" window. Click on the Report button and then on New. In the resulting wizard, you'll link the report to the query you just created.<br>
<strong><em>Update:</strong> As D.W. Fenton said, you can embed the query right within the Report Object without creating a separate Query Object. My preference is to create one anyway.</em></p>
<p>The problem with this method is you would have to create a separate query and report for each table.</p>
<p><strong>IF you just want to dump the result out to a text file (to read/print later)</strong>, then you can do it using recordsets like you are in your VBA code. It will look something like this</p>
<pre><code>'...
dim strFoo as string
dim strBar as string
'...
if not rs.bof then
rd.MoveFirst
end if
While Not rs.EOF
strFoo = rs("foo") 'copy the value in the field
'named "foo" into strFoo.
strBar = rs("bar")
'... etc. for all fields you want
'
'write out the values to a text file
'(I'll leave this an exercise for the reader)
'
rs.MoveNext
Wend
'...
</code></pre>
<p>Parsing all of the tables can be done in a loop something like this:</p>
<pre><code>dim strTableName as string
dim db As Database
'...
Set db = CurrentDb
db.TableDefs.Refresh
For Each myTable In db.TableDefs
If Len(myTable.Connect) > 0 Then
strTableName = myTable.Name
'...
'Do something with the table
'...
End If
Next
set db = nothing
</code></pre>
<p><strong>=======================UPDATE=======================</strong><br>
<strong>It is possible to run an MS-Access Report from a record set.</strong> To repease what I said to <a href="https://stackoverflow.com/questions/242504/accesshow-can-i-generate-a-report-of-a-recordset">tksy's question</a>
From <a href="http://www.mvps.org/access/reports/rpt0014.htm" rel="nofollow noreferrer">Access Web</a> you can use the "name" property of a recordset. You resulting code would look something like this:</p>
<p><em>In the report</em> </p>
<pre><code>Private Sub Report_Open(Cancel As Integer)
Me.RecordSource = gMyRecordSet.Name
End Sub
</code></pre>
<p><em>In the calling object (module, form, etc.)</em> </p>
<pre><code>Public gMyRecordSet As Recordset
'...
Public Sub callMyReport()
'...
Set gMyRecordSet = CurrentDb.OpenRecordset("Select * " & _
"from foo " & _
"where bar='yaddah'")
DoCmd.OpenReport "myReport", acViewPreview
'...
gMyRecordSet.Close
Set gMyRecordSet = Nothing
'...
End Sub
</code></pre>
<p><strong>Q.E.D.</strong></p>
|
<p>Normally you would design the report based on a data source. Then after your report is done and working properly you use VBA to display or save the report.</p>
| 29,656
|
<p>How do I totally disable caching in nHibernate?</p>
|
<p>Use the IStatelessSession to bypass the first level cache: <a href="http://darioquintana.com.ar/blogging/?p=4" rel="noreferrer">http://darioquintana.com.ar/blogging/?p=4</a></p>
<p>In order to use the second level cache you must explicitly configure it. You will not use it if you don't.</p>
<p>You can also turn off lazy loading in your mappings. lazy=false.</p>
|
<p>Note IStatelessSession is I think new in Nhibernate 2.0</p>
<p>second level cache configuration details : <a href="http://nhibernate.info/doc/nhibernate-reference/caches.html" rel="nofollow noreferrer">Chapter 25. NHibernate.Caches</a></p>
| 14,377
|
<p>Ok, I am trying to use Tail to monitor a log file, but I cannot get the same behavior programatically as when I manually run it through cmd prompt using the same parameters.</p>
<p>When run through cmd prompt it displays the new lines <strong>instantly</strong>. Programatically though, I have to wait for about <strong>75+ new lines</strong> in log file before the 'buffer' unleashes all the lines.</p>
<p>Here's the code I have now.</p>
<pre><code>private const string tailExecutable = @"C:\tail.exe";
private const string logFile = @"C:\test.log";
private static void ReadStdOut()
{
var psi = new ProcessStartInfo
{
FileName = tailExecutable,
Arguments = String.Format("-f \"{0}\"", logFile),
UseShellExecute = false,
RedirectStandardOutput = true
};
// Running same exe -args through cmd.exe
// works perfectly, but not programmatically.
Console.WriteLine("{0} {1}", psi.FileName, psi.Arguments);
var tail = new Process();
tail.StartInfo = psi;
tail.OutputDataReceived += tail_OutputDataReceived;
tail.Start();
tail.BeginOutputReadLine();
}
static void tail_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
Console.WriteLine(e.Data);
}
</code></pre>
<p>I have used the OutputDataReceived event before but never had these buffering/spamming problems.</p>
<p>I am so confused with about right now.</p>
<h2>* <strong>Edit</strong> *</h2>
<p>I found <a href="http://www.codeproject.com/KB/cs/wintail.aspx" rel="nofollow noreferrer">this wintail project on CodeProject</a> and am going to be switching to that because the buffer makes this solution way too slow.</p>
<p>Thanks for the answers.</p>
|
<p>Process.StandardOutput, when redirected, defaults to a StreamReader with a 4096-byte buffer, so the answer is yes.</p>
|
<p>In most languages and operating systems the standard stream is usually buffered, but the error stream is not.</p>
<p>Try using:
<code>
System.Console.Error
</code></p>
| 29,431
|
<p>We have a few very large Excel workbooks (dozens of tabs, over a MB each, very complex calculations) with many dozens, perhaps hundreds of formulas that use the dreaded INDIRECT function. These formulas are spread out throughout the workbook, and target several tables of data to look-up for values.</p>
<p>Now I need to move the ranges of data that are targeted by these formulas to a different location in the same workbook.</p>
<p>(The reason is not particularly relevant, but interesting on its own. We need to run these things in Excel Calculation Services and the latency hit of loading each of the rather large tables one at a time proved to be unacceptably high. We are moving the tables in a contiguous range so we can load them all in one shot.)</p>
<p><strong>Is there any way to locate all the INDIRECT formulas that currently refer to the tables we want to move?</strong></p>
<p>I don't need to do this on-line. I'll happily take something that takes 4 hours to run as long as it is reliable.</p>
<p>Be aware that the .Precedent, .Dependent, etc methods only track direct formulas.</p>
<p>(Also, rewriting the spreadsheets in <em>whatever</em> is not an option for us).</p>
<p>Thanks!</p>
|
<p>You could iterate over the entire Workbook using vba (i've included the code from @PabloG and @euro-micelli ):</p>
<pre><code>Sub iterateOverWorkbook()
For Each i In ThisWorkbook.Worksheets
Set rRng = i.UsedRange
For Each j In rRng
If (Not IsEmpty(j)) Then
If (j.HasFormula) Then
If InStr(oCell.Formula, "INDIRECT") Then
j.Value = Replace(j.Formula, "INDIRECT(D4)", "INDIRECT(C4)")
End If
End If
End If
Next j
Next i
End Sub
</code></pre>
<p>This example substitues every occurrence of "indirect(D4)" with "indirect(C4)". You can easily swap the replace-function with something more sophisticated, if you have more complicated indirect-functions. Performance is not that bad, even for bigger Workbooks.</p>
|
<p>You can use something like this in VBA:</p>
<pre><code>Sub ListIndirectRef()
Dim rRng As Range
Dim oSh As Worksheet
Dim oCell As Range
For Each oSh In ThisWorkbook.Worksheets
Set rRng = oSh.UsedRange
For Each oCell In rRng
If InStr(oCell.Formula, "INDIRECT") Then
Debug.Print oCell.Address, oCell.Formula
End If
Next
Next
End Sub
</code></pre>
<p>Instead of Debug.Print you can add code to suit your taste</p>
| 5,474
|
<p>I want to, from JavaScript, access as a variable the file that is loaded as an image in an img tag. </p>
<h2>I don't want to access its name, but the actual data.</h2>
<p>The reason for this is that I want to be able to copy it to and from variables so that I can , among other things, change the image without reloading it.</p>
<p>Can this be done? If so, how?</p>
<p>Note: I'm slightly more interested in <em>reading</em> the data than writing it.</p>
|
<pre><code>// Download the image data using AJAX, I'm using jQuery
var imageData = $.ajax({ url: "MyImage.gif", async: false }).responseText;
// Image data updating magic
imageDataChanged = ChangeImage(imageData);
// Encode to base64, maybe try the webtoolkit.base64.js library
imageDataEncoded = Base64Encode(imageDataChanged);
// Write image data out to browser (FF seems to support this)
document.write('<img src="data:image/gif;base64,' + imageDataEncoded + '">');
</code></pre>
|
<p>Try this:</p>
<pre><code>img = new Image();
img.src = "imagefile.jpg";
</code></pre>
| 38,146
|
<p>When I maximize 1 MDI child form, all MDI child forms would be maximized too. Is it possible to have 1 form maximized and another one not?</p>
<p>Thanks in advance.</p>
|
<p>A maximized MDI child form should occupy the entire child area and so the state of the other children should not really matter as they are not visible. </p>
|
<p>Not possible. Only thing you can do is to set the window in front non MDI and taskbar = no</p>
| 39,725
|
<p>A couple of recent questions discuss strategies for naming columns, and I was rather surprised to discover the concept of embedding the notion of foreign and primary keys in column names. That is</p>
<pre><code>select t1.col_a, t1.col_b, t2.col_z
from t1 inner join t2 on t1.id_foo_pk = t2.id_foo_fk
</code></pre>
<p>I have to confess I have never worked on any database system that uses this sort of scheme, and I'm wondering what the benefits are. The way I see it, once you've learnt the N principal tables of a system, you'll write several orders of magnitude more requests with those tables.</p>
<p>To become productive in development, you'll need to learn which tables are the important tables, and which are simple tributaries. You'll want to commit an good number of column names to memory. And one of the basic tasks is to join two tables together. To reduce the learning effort, the easiest thing to do is to ensure that the column name is the same in both tables:</p>
<pre><code>select t1.col_a, t1.col_b, t2.col_z
from t1 inner join t2 on t1.id_foo = t2.id_foo
</code></pre>
<p>I posit that, as a developer, you don't need to be reminded that much about which columns are primary keys, which are foreign and which are nothing. It's easy enough to look at the schema if you're curious. When looking at a random</p>
<pre><code>tx inner join ty on tx.id_bar = ty.id_bar
</code></pre>
<p>... is it all that important to know which one is the foreign key? Foreign keys are important only to the database engine itself, to allow it to ensure referential integrity and do the right thing during updates and deletes.</p>
<p>What problem is being solved here? (I know this is an invitation to discuss, and feel free to do so. But at the same time, I <em>am</em> looking for an answer, in that I may be genuinely missing something).</p>
|
<p>I agree with you that the foreign key column in a child table should have the same name as the primary key column in the parent table. Note that this permits syntax like the following:</p>
<pre><code>SELECT * FROM foo JOIN bar USING (foo_id);
</code></pre>
<p>The USING keyword assumes that a column exists by the same name in both tables, and that you want an equi-join. It's nice to have this available as shorthand for the more verbose:</p>
<pre><code>SELECT * FROM foo JOIN bar ON (foo.foo_id = bar.foo_id);
</code></pre>
<p>Note, however, there are cases when you can't name the foreign key the same as the primary key it references. For example, in a table that has a self-reference:</p>
<pre><code>CREATE TABLE Employees (
emp_id INT PRIMARY KEY,
manager_id INT REFERENCES Employees(emp_id)
);
</code></pre>
<p>Also a table may have multiple foreign keys to the same parent table. It's useful to use the name of the column to describe the nature of the relationship:</p>
<pre><code>CREATE TABLE Bugs (
...
reported_by INT REFERENCES Accounts(account_id),
assigned_to INT REFERENCES Accounts(account_id),
...
);
</code></pre>
<p>I don't like to include the name of the table in the column name. I also eschew the obligatory "id" as the name of the primary key column in every table.</p>
|
<p>I agree with you--I take a different approach that I have seen recommended in many corporate environments:</p>
<p>Name columns in the format <em>TableNameFieldName</em>, so if I had a Customer table and UserName was one of my fields, the field would be called CustomerUserName. That means that if I had another table called Invoice, and the customer's user name was a foreign key, I would call it InvoiceCustomerUserName, and when I referenced it, I would call it Invoice.CustomerUserName, which immediately tells me which table it's in.</p>
<p>Also, this naming helps you to keep track of the tables your columns are coming from when you're joiining. </p>
<p>I only use FK_ and PK_ in the ACTUAL names of the foreign and primary keys in the DBMS.</p>
| 26,313
|
<p>I've got a PHP application which needs to grab the contents from another web page, and the web page I'm reading needs a cookie.</p>
<p>I've found info on how to make this call once i have the cookie ( <a href="http://groups.google.com/group/comp.lang.php/msg/4f618114ab15ae2a" rel="nofollow noreferrer">http://groups.google.com/group/comp.lang.php/msg/4f618114ab15ae2a</a> ), however I've no idea how to generate the cookie, or how / where the cookie is saved.</p>
<p>For example, to read this web page via wget I do the following:</p>
<pre><code>wget --quiet --save-cookies cookie.file --output-document=who.cares \
http://remoteServer/login.php?user=xxx&pass=yyy
wget --quiet --load-cookies cookie.file --output-document=documentiwant.html \
http://remoteServer/pageicareabout.html
</code></pre>
<p>... my question is how do I do the '--save-cookies' bit in PHP so that I can use the cookie in the follow-up PHP stream_context_create / file_get_contents block:</p>
<pre><code>$opts = array(http'=> array(
'method'=> "GET",
'header'=>
"Accept-language: en\r\n" .
"Cookie: **NoClueAtAll**\r\n"
)
);
$context = stream_context_create($opts);
$documentiwant = file_get_contents("http://remoteServer/pageicareabout.html",
0, $context);
</code></pre>
|
<p>You'd probably be better off using <a href="http://www.php.net/curl" rel="noreferrer">cURL</a>.
Use <a href="http://www.php.net/manual/en/function.curl-setopt.php" rel="noreferrer">curl_setopt</a> to set up the cookie handling options.</p>
<p>If this is just a one-off thing, you could use Firefox with <a href="http://livehttpheaders.mozdev.org/" rel="noreferrer">Live HTTP Headers</a> to get the header, then paste it into your PHP code.</p>
|
<p>You'd probably be better off using <a href="http://www.php.net/curl" rel="noreferrer">cURL</a>.
Use <a href="http://www.php.net/manual/en/function.curl-setopt.php" rel="noreferrer">curl_setopt</a> to set up the cookie handling options.</p>
<p>If this is just a one-off thing, you could use Firefox with <a href="http://livehttpheaders.mozdev.org/" rel="noreferrer">Live HTTP Headers</a> to get the header, then paste it into your PHP code.</p>
| 30,673
|
<p>I'm having an issue with an ObservableCollection getting new items but not reflecting those changes in a ListView. I have enough quirks in the way I'm implementing this that I'm having a hard time determining what the problem is.</p>
<p>My ObservableCollection is implemented thusly:</p>
<pre><code>public class MessageList : ObservableCollection<LobbyMessage>
{
public MessageList(): base()
{
Add(new LobbyMessage() { Name = "System", Message = "Welcome!" });
}
}
</code></pre>
<p>I store the collection in a static property (so that its easily accessible from multiple user controls):</p>
<pre><code>static public MessageList LobbyMessages { get; set; }
</code></pre>
<p>In the OnLoad event of my main NavigationWindow I have the following line:</p>
<pre><code>ChatHelper.LobbyMessages = new MessageList();
</code></pre>
<p>My XAML in the UserControl where the ListView is located reads as:</p>
<pre><code> <ListBox IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding Mode=OneWay}"
x:Name="ListBoxChatMessages"
d:UseSampleData="True"
ItemTemplate="{DynamicResource MessageListTemplate}"
IsEnabled="True">
<ListBox.DataContext>
<Magrathea_Words_Tools:MessageList/>
</ListBox.DataContext>
</ListBox>
</code></pre>
<p>The initial message that I added in the constructor appears in the UI just fine.</p>
<p>Now, the way I add new items to the collection is from a CallBack coming from a WCF service. I had this code working in a WinForms application and it was neccessary to marshall the callback to the UI thread so I left that code in place. Here is an abbreviated version of the method:</p>
<pre><code>Helper.Context = SynchronizationContext.Current;
#region IServiceMessageCallback Members
/// <summary>
/// Callback handler for when the service has a message for
/// this client
/// </summary>
/// <param name="serviceMessage"></param>
public void OnReceivedServiceMessage(ServiceMessage serviceMessage)
{
// This is being called from the WCF service on it's own thread so
// we have to marshall the call back to this thread.
SendOrPostCallback callback = delegate
{
switch (serviceMessage.MessageType)
{
case MessageType.ChatMessage:
ChatHelper.LobbyMessages.Add(
new LobbyMessage()
{
Name = serviceMessage.OriginatingPlayer.Name,
Message = serviceMessage.Message
});
break;
default:
break;
}
};
Helper.Context.Post(callback, null);
}
</code></pre>
<p>While debugging I can see the collection getting updated with messages from the service but the UI is not reflecting those additions.</p>
<p>Any ideas about what I'm missing to get the ListView to reflect those new items in the collection?</p>
|
<p>I resolved this issue.</p>
<p>Neither the static property or the context of the incoming data had anything to do with the issue (which seems obvious in hindsight).</p>
<p>The XAML which was generated from Expression Blend was not up to the task for some reason. All I did to get this to work was assign the ItemSource to the collection in C#.</p>
<pre><code>ListBoxChatMessages.ItemsSource = ChatHelper.LobbyMessages.Messages;
</code></pre>
<p>My XAML is now more simplified.</p>
<pre><code><ListBox IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding Mode=OneWay}" Background="#FF1F1F1F"
Margin="223,18.084,15.957,67.787" x:Name="ListBoxChatMessages"
ItemTemplate="{DynamicResource MessageListTemplate}"
IsEnabled="True"/>
</code></pre>
<p>I'm a little confused as to why this works. I was reading the MSDN articles on how to bind data in WPF and they included several binding objects, referencing properties on object, etc. I don't understand why they went to all the trouble when one line of code in the UserControl's constructor does the trick just fine.</p>
|
<p>You need to make your poco class within the ObservableCollection implement INotifyPropertyChanged.</p>
<p>Example:</p>
<pre><code><viewModels:LocationsViewModel x:Key="viewModel" />
.
.
.
<ListView
DataContext="{StaticResource viewModel}"
ItemsSource="{Binding Locations}"
IsItemClickEnabled="True"
ItemClick="GroupSection_ItemClick"
ContinuumNavigationTransitionInfo.ExitElementContainer="True">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" Margin="0,0,10,0" Style="{ThemeResource ListViewItemTextBlockStyle}" />
<TextBlock Text="{Binding Latitude, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Style="{ThemeResource ListViewItemTextBlockStyle}" Margin="0,0,5,0"/>
<TextBlock Text="{Binding Longitude, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Style="{ThemeResource ListViewItemTextBlockStyle}" Margin="5,0,0,0" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
public class LocationViewModel : BaseViewModel
{
ObservableCollection<Location> _locations = new ObservableCollection<Location>();
public ObservableCollection<Location> Locations
{
get
{
return _locations;
}
set
{
if (_locations != value)
{
_locations = value;
OnNotifyPropertyChanged();
}
}
}
}
public class Location : BaseViewModel
{
int _locationId = 0;
public int LocationId
{
get
{
return _locationId;
}
set
{
if (_locationId != value)
{
_locationId = value;
OnNotifyPropertyChanged();
}
}
}
string _name = null;
public string Name
{
get
{
return _name;
}
set
{
if (_name != value)
{
_name = value;
OnNotifyPropertyChanged();
}
}
}
float _latitude = 0;
public float Latitude
{
get
{
return _latitude;
}
set
{
if (_latitude != value)
{
_latitude = value;
OnNotifyPropertyChanged();
}
}
}
float _longitude = 0;
public float Longitude
{
get
{
return _longitude;
}
set
{
if (_longitude != value)
{
_longitude = value;
OnNotifyPropertyChanged();
}
}
}
}
public class BaseViewModel : INotifyPropertyChanged
{
#region Events
public event PropertyChangedEventHandler PropertyChanged;
#endregion
protected void OnNotifyPropertyChanged([CallerMemberName] string memberName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(memberName));
}
}
}
</code></pre>
| 45,545
|
<p>I am new to grails.I am doing web application that uploads the image from client side and it stores that in server.</p>
<p>My Gsp code is:</p>
<pre><code><g:uploadForm action="saveImage">
<input type="file" name="image">
<input type="submit" value="Submit">
</g:uploadForm>
</code></pre>
<p>My saveImage action in controller is:</p>
<pre><code>def saveImage={
def file = request.getFile('image')
if (file && !file.empty) {
file.transferTo(new java.io.File("image.jpg"))
flash.message = 'Image uploaded'
redirect(action: 'uploadImage')
}
}
</code></pre>
<p>In this code if i upload some other files like text files it throws Exception.For that i want to check the file Extension and I want to use If loop that ensures the uploaded file is image file or not.But i dont know how to find the file extension in grails.</p>
<p>Is there any other way to upload images in grails application.It has to accept only image files.</p>
<p>can anyone provide help?</p>
<p>thanks.</p>
|
<p>I dont know the following answer is a right way to find the extension of the file.I am also new to this.But this answer is working</p>
<p>Use <strong>file.getOriginalFilename()</strong> method.It returns a string like "test.jpg".Then you split the filename using tokenize method by ".".Then you take the last string element from the splitted list.That is extension of the file.Now you can do the remaining process.</p>
|
<p>Okay, this is really late. But what I found the best solutions (as extensions don't really say something about the content) was to use <code>file.getContentType()</code> ...</p>
<p>E.g., for jpeg images the return value will be a string <code>image/jpeg</code> that you can easily test. Same for other file formats (png, gif, ...).</p>
<p>Hope this helps. </p>
| 47,380
|
<p>I use Struts v1.3 and have following input form:</p>
<p>In struts-config.xml:</p>
<pre><code> <form-bean name="testForm"
type="org.apache.struts.validator.DynaValidatorForm">
<form-property name="displayName" type="java.lang.String" />
</form-bean>
</code></pre>
<p>In validation.xml:</p>
<pre><code> <form name="testForm">
<field property="displayName" depends="required">
<arg key="input.displayName" />
</field>
</form>
</code></pre>
<p>How do I trim value of "displayName"? How do I trim values of all "java.lang.String" input fields of the form?</p>
|
<p>You may have a chance to trim the string right at the moment, the request processor updates the data from the input fields to the form. This was not tested, but what happens when you modify the setter setDisplayName(String displayName) to something like </p>
<pre><code>public void setDisplayName(String displayName) {
this.displayName = displayName.trim();
}
</code></pre>
<p>This is not a very good solution, because it migrates logic into a setter.</p>
<p>regards</p>
|
<p>Alternatively try using javascript regexp in the jsp that will trim onfocus or onblur</p>
<blockquote>
<p>< html:text name="testForm" property="displayName" onfocus="javascript:this.value=this.value.replace(/^\s+|\s+$/g,'')" onblur="javascript:this.value=this.value.replace(/^\s+|\s+$/g,'')" /></p>
</blockquote>
| 29,746
|
<p>I'm trying to call the SQL statement below but get the following error:</p>
<blockquote>
<p>System.Data.SqlClient.SqlException: Conversion failed when converting
the varchar value '+@buildingIDs+' to data type int.</p>
</blockquote>
<pre><code>@"SELECT id, startDateTime, endDateTime
FROM tb_bookings
WHERE buildingID IN ('+@buildingIDs+')
AND startDateTime <= @fromDate";
</code></pre>
<p><code>buildingID</code> is an <code>int</code> type column in the db. Will I need to pass the IDs as an array of ints?</p>
|
<p>Bravax's way is a bit dangerous. I'd go with the following so you don't get attacked with SQL Injections:</p>
<pre><code>int[] buildingIDs = new int[] { 1, 2, 3 };
/***/ @"SELECT id, startDateTime, endDateTime From tb_bookings WHERE buildingID IN (" +
string.Join(", ", buildingIDs.Select(id => id.ToString()).ToArray())
+ ") AND startDateTime <= @fromDate";
</code></pre>
|
<p>It's trying to compare an int with the string value '+@buildingsIDs+'<br>
So it tries to convert the string to convert it to an int and fails.</p>
<p>So do the following:<br>
<code>
buildingsIDs = "1, 5, 6";<br>
@"SELECT id, startDateTime, endDateTime From tb_bookings WHERE buildingID IN (" + buildingIDs + ") AND startDateTime <= @fromDate";
</code></p>
| 22,016
|
<p>Say I'm mapping a simple object to a table that contains duplicate records and I want to allow duplicates in my code. I don't need to update/insert/delete on this table, only display the records.</p>
<p>Is there a way that I can put a fake (generated) ID column in my mapping file to trick NHibernate into thinking the rows are unique? Creating a composite key won't work because there could be duplicates across all of the columns.</p>
<p>If this isn't possible, what is the best way to get around this issue?</p>
<p>Thanks!</p>
<p>Edit: Query seemed to be the way to go</p>
|
<p>The NHibernate mapping makes the assumption that you're going to want to save changes, hence the requirement for an ID of some kind.</p>
<p>If you're allowed to modify the table, you could add an identity column (SQL Server naming - your database may differ) to autogenerate unique Ids - existing code should be unaffected.</p>
<p>If you're allowed to add to the database, but not to the table, you could try defining a view that includes a RowNumber synthetic (calculated) column, and using that as the data source to load from. Depending on your database vendor (and the products handling of views and indexes) this <em>may</em> face some performance issues.</p>
<p>The other alternative, which I've not tried, would be to map your class to a SQL query instead of a table. IIRC, NHibernate supports having named SQL queries in the mapping file, and you can use those as the "data source" instead of a table or view.</p>
|
<p>If you're data is read only one simple way we found was to wrapper the query in a view and build the entity off the view, and add a newguid() column, result is something like </p>
<p>SELECT NEWGUID() as ID, * FROM TABLE</p>
<p>ID then becomes your uniquer primary key. As stated above this is only useful for read-only views. As the ID has no relevance after the query.</p>
| 32,394
|
<p>Lets say I have an array like this:</p>
<pre><code>string [] Filelist = ...
</code></pre>
<p>I want to create an Linq result where each entry has it's position in the array like this:</p>
<pre><code>var list = from f in Filelist
select new { Index = (something), Filename = f};
</code></pre>
<p>Index to be 0 for the 1st item, 1 for the 2nd, etc.</p>
<p>What should I use for the expression Index= ?</p>
|
<p>Don't use a query expression. Use <a href="http://msdn.microsoft.com/en-us/library/bb534869.aspx" rel="noreferrer">the overload of <code>Select</code> which passes you an index</a>:</p>
<pre><code>var list = FileList.Select((file, index) => new { Index=index, Filename=file });
</code></pre>
|
<p>You <strong>cannot get an index</strong> using pure LINQ query expressions (those with <code>from.. where.. select..</code> clauses).</p>
<p>However, this doesn't mean you have to completely give up on this LINQ query style. </p>
<p>You just have to <strong>get out of the LINQ query expression</strong> and use a <code>.Select(item, index)</code> method overload.</p>
<pre><code>var newestExistingFilesWithIndexes =
(from f in Filelist
// we love LINQ query expressions
where f.Exists
// and we use it anywhere possible
orderby f.LastModified descending
select f)
// but sometimes we have to get out and use LINQ extension methods
.Select((f, index) => new { Index = index, Filename = f.Fullname});
</code></pre>
<p>or suppose, you need to filter a list based on item index ...</p>
<pre><code>var newestExistingFilesOnlyEvenIndexes =
// use the Select method overload to get the index
(from f in Filelist.Select((file, index) => new { file, index })
// only take item with an even index
where f.index % 2 == 0
where f.file.Exists
orderby f.file.LastModified descending
select f.file);
</code></pre>
| 33,783
|
<p>What's the best way to consume REST web services from .NET?</p>
|
<p>A straight forward and easy approach would be to use WebClient which is in the System.Net namespace. </p>
<p>Pretty much all you need to do is pass in the Uri required with any parameters needed in the form of a query string and you should get back the response in the form of a string, be it json or xml. For example.</p>
<pre><code>using System.Net;
string param = "hello";
string url = String.Format("http://somedomain.com/samplerequest?greeting={0}",param);
WebClient serviceRequest = new WebClient();
string response = serviceRequest.DownloadString(new Uri(url));
</code></pre>
<p>Then, like Nick mentioned, you can use XmlDocument or JavaScriptSerializer to manipulate the results as needed. Anyway I suggest checking out the documentation on it to see if it meets your needs. <a href="http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx</a></p>
|
<p>Do you want to consume or publish. If you want to consume, such as making requests the best way to interact with it is to figure out the type it will comback as, usually JSON or XML. After you have your type you can use XmlDocument or JavaScriptSerializer to pull back the information and use it. </p>
<p>If you want to produce a REST interface then you probably want to use either MVC a REST View or WCF as @Brian said.</p>
| 42,668
|
<p>I got myself a new 8 gig USB key and I'm looking for a decent solution to have a portable RoR environment to learn on. I did the google on it and found a few possibilities, but I'm curious to hear some real life experiences and opinions. Thanks!</p>
|
<p>I like <a href="http://instantrails.rubyforge.org" rel="noreferrer">InstantRails</a>, very easy to use, no installer, and does not modify your system environment.</p>
|
<p>Assuming you're on Windows, I'd go for <a href="http://instantrails.rubyforge.org/" rel="nofollow noreferrer">Instant Rails</a> and <a href="http://www.netbeans.org/" rel="nofollow noreferrer">Netbeans</a> (with a JVM for Netbeans).</p>
<p>Netbeans is a bit heavy-weight, but it supports lots of nice rails focused IDE features and is the best IDE for Rails on Windows IMO. </p>
<p>You'll get all of that on a lot less than 1 gig.</p>
| 32,315
|
<p>Not a programming question per se, but interesting for people who do commercial web development.</p>
<p>How do you track all of your clients' hosting, domain registration, and SSL certificate expiry dates?</p>
<p>Do you just keep a spreadsheet or is there some useful piece of software for this?</p>
<p>I've searched extensively and can't find a usable piece of software and am tempted to write something. With 100+ customers to manage, and with hosting and domain names spread across several hosting companies and registrars, my ad hoc means are failing.</p>
|
<p>How about we turn it into a programming question! You could use this code (C#), though I would recommend modifying it a bit (e.g. put url's in a file) and throwing it into a service.</p>
<p>This code sets up a certificate validation callback which the HttpWebRequest will call anytime it encounters a certificate. This lets us take a look at the certificate, usually this is used to validate the cert but we are going to look at the expiration time and if it within 3 months we will send an email to ourselves. A timer is setup to run the check once a day.</p>
<pre><code>using System.Net;
using System.Diagnostics;
using System.Net.Mail;
using System.Threading;
static void Main(string[] args)
{
// List of URL's to check
string[] urls = new string[]{
"https://www.6bit.com/",
"https://www.google.com/"
};
HttpWebRequest req = null;
// Certificate check callback
ServicePointManager.ServerCertificateValidationCallback = (state, cert, certChain, sslerr) =>
{
DateTime expiration = DateTime.Parse(cert.GetExpirationDateString());
if (expiration < DateTime.Now.AddMonths(3))
{
Debug.WriteLine("Cert expiring on " + expiration.ToShortDateString());
MailMessage msg = new MailMessage("SSLCheck@example.com", "josh@example.com", "SSL Certificate Expiring", "The ssl certificate for" + req.RequestUri.ToString() + " will expire on " + expiration.ToShortDateString());
SmtpClient sc = new SmtpClient();
sc.Send(msg);
}
return true;
};
// Request each url once a day so that the validation callback runs for each
Timer t = new Timer(s =>
{
Array.ForEach(urls, url =>
{
try
{
req = (HttpWebRequest)HttpWebRequest.Create(url);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
resp.Close();
}
catch (Exception ex)
{
Debug.WriteLine("Error checking site: " + ex.ToString());
}
});
}, null, TimeSpan.FromSeconds(0), TimeSpan.FromDays(1)); // Run the timer now and schedule to run once a day
}
</code></pre>
|
<p>Give a try to <a href="https://epazote.io" rel="nofollow">epazote</a> basically you can create a list of sites (services) on a yaml file and receive an email/alert/hipchat notification before the certificate expires, example:</p>
<pre><code>services:
google:
url: https://www.google.com
seconds: 60
expect:
status: 302
ssl:
hours: 72
</code></pre>
<p>In this case an email could be sent, 72 hours before the certificate expires.</p>
<p>More details here: <a href="https://epazote.io/post/how-to-use-it/" rel="nofollow">https://epazote.io/post/how-to-use-it/</a></p>
| 47,206
|
<p>I have a scenario where users of my ASP.NET web application submit testimonials consisting of text info and images. The submit process has the following steps:</p>
<ul>
<li>First the user inputs the content and chooses a path to an image</li>
<li>When he clicks preview, the info is once again shown so that he can confirm</li>
<li>Once confirmed the info is persisted in the database</li>
</ul>
<p>The problem with this is that I don't want to store uploaded images in the DB before the user actually confirms. Instead I store them as temporary files and put them in DB only after final confirmation.</p>
<p>Since I also want my application to run in medium trust, I have write permissions only to the application directory and nowhere outside. I even want to limit write permissions for the ASPNET / NETWORK SERVICE user to the ~/App_Data folder. The problem with my scenario is that once a temporary file is created in this folder, the application pool is recycled and I don't want that on every testimonial submit.</p>
<p>How do you advise I keep these temp files instead? The pool is not restarted if I update a file - only on create or rename. But I don't think I can store whole images in a single file for all users. What do you think?</p>
<p><b>UPDATE</b>: I should note that I'm using a third party control for upload. It gives me programmatic access to the binary stream of the file contents after upload, but I cannot keep this after a second postback (the first step and postback actually does the upload).</p>
|
<p>I would recommend <a href="http://msdn.microsoft.com/en-us/library/3ak841sy(VS.80).aspx" rel="noreferrer">IsolatedStorage</a>. It's a kind of virtual folder.</p>
<p>Here is an excerpt from <a href="http://www.codeproject.com/KB/dotnet/IsolatedStorage.aspx" rel="noreferrer">an example on CodeProject</a>:</p>
<pre><code>IsolatedStorageFileStream stream =
new IsolatedStorageFileStream(ISOLATED_FILE_NAME,
FileMode.Create, isoStore);
StreamWriter writer = new StreamWriter( stream );
writer.WriteLine( "This is my first line in the isolated storage file." );
writer.WriteLine( "This is second line." );
writer.Close();
</code></pre>
<p><strong>UPDATE</strong>: To clean up your file just do this:</p>
<pre><code>string fileName = "isolatestorage.txt";
IsolatedStorageFile storage = IsolatedStorageFile.GetStore(
IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null);
string[] files = storage.GetFileNames(fileName);
foreach(string file in files) {
if(file == fileName) {
storage.DeleteFile(file);
break;
}
}
</code></pre>
|
<p>This is a reply to Leppie who commented on my question (to avoid the char limit)</p>
<p>From: <a href="http://blogs.msdn.com/johan/archive/2007/05/16/common-reasons-why-your-application-pool-may-unexpectedly-recycle.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/johan/archive/2007/05/16/common-reasons-why-your-application-pool-may-unexpectedly-recycle.aspx</a></p>
<blockquote>
<p>...sometimes your application pool inexplicably recycles for no obvious reason. This is usually a configuration issue or due to the fact that you're performing file system operations in the application directory.</p>
</blockquote>
<p>Are you sure it's not supposed to recycle?</p>
| 34,218
|
<p>A page executes a number of tasks and takes a long time to process. We want to give the user feedback as each task is completed. </p>
<p>In ASP.NET webforms we used <code>Response.Flush()</code></p>
<p>What way would you a approach this in ASP.NET MVC?</p>
|
<p>You can still use Response.Write() and Response.Flush() for whatever status you want to send down the wire. Or if you have your progress thingy in a user-control, you could do something like:</p>
<pre><code>this.PartialView("Progress").ExecuteResult(this.ControllerContext);
this.Response.Flush();
</code></pre>
<p>from your controller while doing your lengthy operation in the controller's action method.</p>
<p>It's up to you to choose this or the client-side approach as mentioned in the comments here, just wanted to point out that server-side is still possible.</p>
|
<p>You can make it in client side. In each step, you set some session variable with the current step. Then, You make another action in your controller say called: "GetProgress" and assign a view and URI for it. </p>
<p>In the action, you will check this session and return the current progress of your task. In the client side, make a timer (i.e setTimeOut) and you invoke the URI of the later controller action every specific amount of time - 1 second or so. That is it.</p>
| 26,774
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.