instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>I have a database driven website serving about 50,000 pages.</p>
<p>I want to track each webpage/record hit.
I will do this by creating logs, and then batch processing the logs once a day.
I am not concerned with how I will do the batch process, only with the quickest way to log.</p>
<p>How would you log, which do you think is quicker:</p>
<p>a) Use PHP to append to the end of a text log file.</p>
<p>b) Use MySQL to INSERT INTO a non-indexed log table.</p>
|
<ol>
<li><p>Write to file. Rotate logs.</p></li>
<li><p>Batch load the file to the database
on a scheduled basis.</p></li>
</ol>
<p>There are many, many reasons to choose this architecture -- ease of scaling (write to many logs, load them to db), lack of reliance on a SPOF in the database (if something goes wrong, you just accumulate logs for a while), ability to do cleaning and non-trivial parsing at load-time without burdening your production servers, and more.</p>
|
<p>Into file will be quicker, but into DB will be better.</p>
| 22,222
|
<p>Although I've been getting more and more familiar with Xcode while developing for the iPhone, there are times I just wished I had a better IDE, something like Eclipse.</p>
<p>So I was wondering does anyone know how to migrate iPhone projects to Eclipse, and if it's worth it?</p>
|
<p>XCode largely uses standard Unix tools for a lot of its work. iPhone applications are compiled using GCC 4.0, it uses gdb for debugging, so it should be possible to set up Eclipse to at least compile applications. </p>
<p>If you look in the Build section of the Project Info pane (select the project, hit the Info button in XCode, choose the Build tab from the top) you can see many of the options.</p>
<p>I'm not sure what is required to copy a file to the simulator and attach a debugger to do a test run, it might not be worthwhile to jump through all the hoops and Apple may require an XCode generated build to accept an app into the App Store.</p>
<p>It may be the case that for regular code editing you can work reasonably well in Eclipse, then switch to XCode for interactive debugging. </p>
<p>Most of the existing Eclipse plugins seem to be oriented towards developer iPhone-aware web applications, so I'm not sure if you'll get any help there.</p>
|
<p>There are no plugins that support Apple IOS application development in Eclipse but on windows, you can develop using Adobe CS5. This is one of the powerful tool from Adobe in which you can develop .ipa applications on windows but you need some stuff to be ready before you start developing IOS applications using Adobe CS5</p>
| 25,463
|
<p>I am trying to read an Http response stream twice via the following:</p>
<pre><code>HttpWebResponse response = (HttpWebResponse)request.GetResponse();
stream = response.GetResponseStream();
RssReader reader = new RssReader(stream);
do
{
element = reader.Read();
if (element is RssChannel)
{
feed.Channels.Add((RssChannel)element);
}
} while (element != null);
StreamReader sr = new StreamReader(stream);
feed._FeedRawData = sr.ReadToEnd();
</code></pre>
<p>However when the StreamReader code executes there is no data returned because the stream has now reached the end. I tried to reset the stream via stream.Position = 0 but this throws an exception (I think because the stream can't have its position changed manually).</p>
<p>Basically, I would like to parse the stream for XML and have access to the raw data (in string format).</p>
<p>Any ideas?</p>
|
<p>Copy it into a new MemoryStream first. Then you can re-read the MemoryStream as many times as you like:</p>
<pre><code>Stream responseStream = CopyAndClose(resp.GetResponseStream());
// Do something with the stream
responseStream.Position = 0;
// Do something with the stream again
private static Stream CopyAndClose(Stream inputStream)
{
const int readSize = 256;
byte[] buffer = new byte[readSize];
MemoryStream ms = new MemoryStream();
int count = inputStream.Read(buffer, 0, readSize);
while (count > 0)
{
ms.Write(buffer, 0, count);
count = inputStream.Read(buffer, 0, readSize);
}
ms.Position = 0;
inputStream.Close();
return ms;
}
</code></pre>
|
<p>have you tried resetting the stream position?
if this does not work you can copy the stream to a MemoryStream and there you can reset the position (i.e. to 0) as often as you want.</p>
| 17,819
|
<p>For a System.Windows.Forms.TextBox with Multiline=True, I'd like to only show the scrollbars when the text doesn't fit.</p>
<p>This is a readonly textbox used only for display. It's a TextBox so that users can copy the text out. Is there anything built-in to support auto show of scrollbars? If not, should I be using a different control? Or do I need to hook TextChanged and manually check for overflow (if so, how to tell if the text fits?)</p>
<hr/>
<p>Not having any luck with various combinations of WordWrap and Scrollbars settings. I'd like to have no scrollbars initially and have each appear dynamically only if the text doesn't fit in the given direction.</p>
<hr/>
<p>@nobugz, thanks, that works when WordWrap is disabled. I'd prefer not to disable wordwrap, but it's the lesser of two evils.</p>
<hr/>
<p>@André Neves, good point, and I would go that way if it was user-editable. I agree that consistency is the cardinal rule for UI intuitiveness.</p>
|
<p>Add a new class to your project and paste the code shown below. Compile. Drop the new control from the top of the toolbox onto your form. It's not quite perfect but ought to work for you.</p>
<pre><code>using System;
using System.Drawing;
using System.Windows.Forms;
public class MyTextBox : TextBox {
private bool mScrollbars;
public MyTextBox() {
this.Multiline = true;
this.ReadOnly = true;
}
private void checkForScrollbars() {
bool scroll = false;
int cnt = this.Lines.Length;
if (cnt > 1) {
int pos0 = this.GetPositionFromCharIndex(this.GetFirstCharIndexFromLine(0)).Y;
if (pos0 >= 32768) pos0 -= 65536;
int pos1 = this.GetPositionFromCharIndex(this.GetFirstCharIndexFromLine(1)).Y;
if (pos1 >= 32768) pos1 -= 65536;
int h = pos1 - pos0;
scroll = cnt * h > (this.ClientSize.Height - 6); // 6 = padding
}
if (scroll != mScrollbars) {
mScrollbars = scroll;
this.ScrollBars = scroll ? ScrollBars.Vertical : ScrollBars.None;
}
}
protected override void OnTextChanged(EventArgs e) {
checkForScrollbars();
base.OnTextChanged(e);
}
protected override void OnClientSizeChanged(EventArgs e) {
checkForScrollbars();
base.OnClientSizeChanged(e);
}
}
</code></pre>
|
<p>What Aidan describes is almost exactly the UI scenario I am facing. As the text box is read only, I don't need it to respond to TextChanged. And I'd prefer the auto-scroll recalculation to be delayed so it's not firing dozens of times per second while a window is being resized.</p>
<p>For most UIs, text boxes with both vertical and horizontal scroll bars are, well, evil, so I'm only interested in vertical scroll bars here.</p>
<p>I also found that MeasureString produced a height that was actually bigger than what was required. Using the text box's PreferredHeight with no border as the line height gives a better result.</p>
<p>The following seems to work pretty well, with or without a border, and it works with WordWrap on.</p>
<p>Simply call AutoScrollVertically() when you need it, and optionally specify recalculateOnResize.</p>
<pre><code>public class TextBoxAutoScroll : TextBox
{
public void AutoScrollVertically(bool recalculateOnResize = false)
{
SuspendLayout();
if (recalculateOnResize)
{
Resize -= OnResize;
Resize += OnResize;
}
float linesHeight = 0;
var borderStyle = BorderStyle;
BorderStyle = BorderStyle.None;
int textHeight = PreferredHeight;
try
{
using (var graphics = CreateGraphics())
{
foreach (var text in Lines)
{
var textArea = graphics.MeasureString(text, Font);
if (textArea.Width < Width)
linesHeight += textHeight;
else
{
var numLines = (float)Math.Ceiling(textArea.Width / Width);
linesHeight += textHeight * numLines;
}
}
}
if (linesHeight > Height)
ScrollBars = ScrollBars.Vertical;
else
ScrollBars = ScrollBars.None;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
}
finally
{
BorderStyle = borderStyle;
ResumeLayout();
}
}
private void OnResize(object sender, EventArgs e)
{
m_timerResize.Stop();
m_timerResize.Tick -= OnDelayedResize;
m_timerResize.Tick += OnDelayedResize;
m_timerResize.Interval = 475;
m_timerResize.Start();
}
Timer m_timerResize = new Timer();
private void OnDelayedResize(object sender, EventArgs e)
{
m_timerResize.Stop();
Resize -= OnResize;
AutoScrollVertically();
Resize += OnResize;
}
}
</code></pre>
| 9,879
|
<p>I want to simplify my execution of a Groovy script that makes calls to an Oracle database. How do I add the ojdbc jar to the default classpath so that I can run:</p>
<pre><code>groovy RunScript.groovy
</code></pre>
<p>instead of:</p>
<pre><code>groovy -cp ojdbc5.jar RunScript.groovy
</code></pre>
|
<p>Summarized from <em>Groovy Recipes</em>, by Scott Davis, <strong>Automatically Including JARs in the ./groovy/lib Directory</strong>:</p>
<ol>
<li>Create <code>.groovy/lib</code> in your login directory</li>
<li><p>Uncomment the following line in ${GROOVY_HOME}/conf/groovy-starter.conf</p>
<p><code>load !{user.home}/.groovy/lib/*.jar</code></p></li>
<li><p>Copy the jars you want included to <code>.groovy/lib</code></p></li>
</ol>
<p>It appears that for Groovy 1.5 or later you get this by default (no need to edit the conf), just drop the jars in the /lib dir.</p>
|
<p><code>groovy</code> is just a wrapper script for the Groovy JAR that sets up the Java classpath. You could modify that script to add the path to your own JAR, as well, I suppose.</p>
| 31,733
|
<p>Has anybody experience in building a custom style in Qt? What I have in my mind is a complete new style that affects all kind of widgets. I have seen some examples in the web for a custom combo box. But I have no idea how much time and code it takes to build a "complete" new custom style ... maybe someone can give me a hint.</p>
<p>We think of using Qt 4.3 (or even newer) ...</p>
|
<p>Check out the <a href="http://doc.qt.io/qt-4.8/stylesheet.html" rel="nofollow noreferrer">Stylesheets</a> facility in Qt 4. While it's still a hassle, it's way easier than doing a full-on custom style. You can just adjust one visual facet at a time and try it out.</p>
<p>It pays attention to inheritance. So if you style the font in QWidget, then every visual widget will also use that font. And so on.</p>
|
<p>If you don't need to radically change the widget style, you might want to try using widget style sheets:</p>
<pre><code> http://doc.qt.digia.com/4.4/stylesheet.html
</code></pre>
| 9,236
|
<p>You can see small gaps in the print which looks like under extrusion (see image below).
What is the reason for that?</p>
<p>I've tried smaller retracting distances. Temperature looks stable.</p>
<p>Print settings:</p>
<ul>
<li>PETG from Extruder</li>
<li>245 °C Printing temperature</li>
<li>50 mm/s print speed</li>
<li>25 mm/s wall speed</li>
<li>30 mm/s retracting speed</li>
<li>1 mm retraction distance -> stringing...</li>
<li>Print cooling fan is enabled</li>
</ul>
<p>Setup:</p>
<ul>
<li>E3D Titan Aero</li>
<li>Duet Wifi</li>
<li>1,5 A Motor current for feeder motor</li>
<li>250 mm/s<sup>2</sup> feeder max acceleration </li>
</ul>
<p>Slicer:</p>
<ul>
<li>Ultimaker Cura 4.0</li>
</ul>
<p><a href="https://i.stack.imgur.com/yXGPn.jpg" rel="nofollow noreferrer" title="Small gaps in the print"><img src="https://i.stack.imgur.com/yXGPn.jpg" alt="Small gaps in the print" title="Small gaps in the print"></a></p>
|
<p>Here's your problem:</p>
<blockquote>
<ul>
<li>1 mm retraction distance -> stringing...</li>
</ul>
</blockquote>
<p>If you have stringing, that means that material that was supposed to end up as part of printed lines instead ended up somewhere else, leaving less material (underextrusion) where it was actually wanted. This particular test piece may not exhibit stringing, but it's likely that it occurred interior to the piece, in the infill region. Contrary to widespread(?) opinion, stringing here is not harmless. It's just not visibly ugly. But it still messes up the surface quality, and even more importantly the strength, of your print.</p>
<p>You don't say if your printer has a bowden extruder or direct drive. If a Bowden, the 1 mm of retraction is virtually useless; a typical Bowden system has more than 1 mm just of <em>compression</em> between the extruder gear and the hotend, meaning that retracting by 1 mm does not pull the filament back out of the hotend at all, and doesn't even relieve all the pressure that's pushing melted material out. I would recommend an absolute minimum of 5 mm for Bowden type extruders, unless your printer firmware has linear advance (Marlin 1.1.9+ or comparable features in other firmware) in which case you might be able to reduce it some. For direct drive, I don't have experience, but 1 mm is still probably too low; 2.5 mm is the believable recommendation I've heard.</p>
<p>In addition to retraction, you can further reduce material loss to stringing/oozing in the infill region by turning on Ultimaker Cura's "Zig-zaggify infill" option, which helps avoid in generating travel without retraction over unprinted area within the infill zone (see e.g. <a href="https://github.com/Ultimaker/CuraEngine/issues/1084" rel="nofollow noreferrer">this issue</a>). Turning slicer setting "combing" to "off" is an even more extreme option here. Of course make sure retraction is really on (not "retract at layer change", which is a separate, mostly useless option) and make sure "retraction minimum travel" is set low (something like 150 % of the nozzle width or less) to prevent retraction from getting skipped on short travel moves.</p>
<p>I also just noticed you wrote:</p>
<blockquote>
<p>I've tried smaller retracting distances...</p>
</blockquote>
<p>This was probably based on erroneous advice. Reducing or eliminating retraction does not mitigate these sorts of problems; it creates them. The only reasons to reduce retraction distance are to fight problems with the extruder gear grinding down the filament after repeated retraction, and problems with jamming the path into the hotend due to pulling molten material back into the cool part where it then solidifies and jams. If you're not having such problems you should not reduce retraction. If you are having such problems, you should try to fix them in other ways that still let you keep the necessary amount of retraction not to have catastrophic print quality problems from material coming out in the wrong places.</p>
|
<p>I increased the retracting distance to 1.5mm. Speed was set to 30mm/s
Printing temperature is still 245°C</p>
<p>The screw which is pressing the filament to the drive gear was too tight.
So the stepper lost steps.</p>
<p>-> No stringing and no under extrusion anymore. prints are looking good now.</p>
| 1,456
|
<p>The extruder on my Prusa i3 MK3S keeps clogging while printing. Loading is fine, and each time it clogs, unloading and loading the filament seems to work.
The filament extruded just after resolving a clog looks like it has small bubbled on it.</p>
<p>The problem only seems to happen when printing certain models. Printing the Batman symbol at 0.15 mm works every time. But the model I'm trying to print always fails at most a few minutes in.</p>
<p>I've tried cleaning the nozzle. Cold pull twice, and taken it out and heated it with my airgun and trying to work on it with the acupuncture needle.</p>
<p>The print that fails is <a href="https://www.thingiverse.com/thing:3211975" rel="nofollow noreferrer">this "Small Pill Container"</a> with 0.1 mm layer height and 100 % infill, but printing a simple cylinder shape (25 mm outer diameter, 2.5 mm walls) creates the same problem. Trying to print them both at the same slicer settings with 0.15 mm layer height still fails.</p>
<p>The model was sliced using the newest version of PrusaSlicer 2.1.0 and printed with Prusament PLA at the factory recommended 215±10 °C, and tried 220 °C.</p>
<p>Any ideas what could be happening? Anybody experienced a similar issue?</p>
<p>Printing the bundled TreeFrog 50 μm sliced by Prusa for the Prusa I3 MK3S cased the same problem. Jam happened about 30 min in. I guess this rules out slicer problems as the root cause.</p>
<hr>
<p><em>After a lot of research, it seems a lot of people have problems with the MK3 clogging, especially with PLA, and especially with prints with a lot of retractions. The issue seems to be the design of the heat-break, which has a throat between 2.2 mm and 2 mm, where the PLA can get stuck. I've ordered a new heatbreak. Please read <a href="/a/11409">this answer of my findings</a>.</em></p>
|
<p>My problem was 2 things. The <strong>heatbreak</strong>, which was switched out for the MK2 version(Explantation below). And the <strong>Teflon Tube</strong> that runs down the heatsink.</p>
<h2>Heatbreak</h2>
<p>Change the heat-break to a generic E3D one. You can order the heatbreak for the <strong>MK2</strong> from prusa, or any generic heat break for the E3D hot-end assembly.</p>
<p>On the Prusa i3 MK3(s), this component has been given a 45° taper in the middle, between 2.2 and 2 mm. This is done to ease filament retraction for the MMU, and will be nothing but problematic if you are not using the multi-material upgrade. Especially with higher nozzle pressures(eq. with lower layer lines), the filament may be squeezed into this taper, clogging the hot-end.</p>
<p>You may not experience full clogs, but partial ones that will show themselves as streaks in certain layers on the print.</p>
<h2>Heatsink Teflon Tube</h2>
<p>There is a teflon tube that runs down the heatsink. It's crucial that this is mounted correctly and it is not entirely intuative how.</p>
<p>First, press the teflon tube into the heatsink all the way to the bottom. Then, try to pull it out slightly. You'll notice that the small plastic ring at the top of the heatsink will pull out slightly along with it. Now, hold this black plastic part at it's current position with your fingernail, and push the teflon tube in the extra amount. When done, there should be no play in the tube.</p>
|
<p>The problem with low layer heights is that the filament flow is low, this means that the filament is at prolonged times at temperature, filament cooking can cause clogging. Try increasing the layer height to 0.2 mm to observe if the same clogging problems still occur, furthermore, try lowering the extrusion temperature.</p>
<p>Also, heat creep is a known issue (insufficient cooling of the cold end) to cause clogging. Note that this is unlikely on the Prusa MK3S, but you could check whether the fan rotates freely and that there are no additional obstructions in the flow path. </p>
<p>It could be that a combination of too much hotend temperature and a low filament flow is causing this issue.</p>
| 1,511
|
<p>I have a GPS from u-blox.com with a USB-connection and driver. The driver installs a virual COM port that pops up when you plug the USB in. Using a hyperterminal I can then watch the flow of data from the GPS.</p>
<p>Then I want the data in my program, not so easy...</p>
<p>I have implemented some methods using the serialPort class to read from the GPS, but am unsuccessful. I have programmed several serial device readers and writers before in C#, but this one stops me.</p>
<p>As an example, the simple code in <a href="http://csharp.simpleserial.com/" rel="nofollow noreferrer">simpleSerial</a> will not give you anything unless you unplug and replug the USB.</p>
<p>Have tried reading it with matlab, which works great, but as the rest of my program that needs the GPS data is in c#, that doesn't quite fix the problem.</p>
<p>Is there some high level C# things going on in the serialPort class that I can circumvent? Or is there any known problems reading USB-serialports, which I assume works like my GPS?</p>
|
<p>If you can communicate with the GPS using HyperTerminal then in principle there's no reason why you shouldn't be able to in C#. Are you sure you've configured the serial port correctly, particularly the baud rate, data bits, stop bits, parity, and flow control settings?</p>
<p>You could use SysInternals <a href="http://technet.microsoft.com/en-us/sysinternals/bb896644.aspx" rel="nofollow noreferrer">PortMon</a> tool to look at the low-level I/O and compare how HyperTerminal and your C# program each configure the serial port. Maybe this will provide some useful information.</p>
|
<p>I ran into a similar problem in an application I was writing and the problem turned out to be that I was trying to us <code>SerialPort.WriteLine</code> which sends a <code>\r\n</code> to end the line when I really needed to just send <code>\n</code>. When I switched to <code>SerialPort.Write</code> with a <code>\n</code> appended to the end, everything worked as in HyperTerminal.</p>
| 36,065
|
<p>I am in the middle of implementing an application using ASP.NET MVC and would love to cache the data passed to user controls or the output rendering on some user controls that I render using the Html.RenderPartial, that way I don't have to query the DB with every request I do to the controller for a new view.</p>
|
<p>That appears to be one of those 1 million dollar questions!</p>
<p>It seems that a lot of people are having that problem, but the solution is not trivial.</p>
<p>Check out an <a href="http://www.codeplex.com/aspnet/WorkItem/View.aspx?WorkItemId=2062" rel="nofollow noreferrer">issue reported recently</a> on the ASP.NET MVC Codeplex site...</p>
|
<p>I would maybe suggest using the sub controllers from the MVC Contrib and then caching the controller's method using the OutputCache stuff.</p>
| 22,611
|
<p>When working in a big project that requires debugging (like every project) you realize how much people love "printf" before the IDE's built-in debugger. By this I mean</p>
<ul>
<li>Sometimes you need to render variable values to screen (specially for interactive debugging).</li>
<li>Sometimes to log them in a file</li>
<li>Sometimes you have to change the visibility (make them public) just to another class to access it (a logger or a renderer for example).</li>
<li>Some other times you need to save the previous value in a member just to contrast it with the new during debugging</li>
<li>...</li>
</ul>
<p>When a project gets huge with a lot of people working on it, all this debugging-specific code can get messy and hard to differentiate from normal code. This can be crazy for those who have to update/change someone else's code or to prepare it for a release.</p>
<p>How do you solve this?</p>
<p>It is always good to have naming standards and I guess that <em>debug-coding standards</em> should be quite useful (like marking every debug-variable with a _DBG sufix). But I also guess naming is just not enough. Maybe centralizing it into a friendly tracker class, or creating a robust base of macros in order to erase it all for the release. I don't know.</p>
<p><em>What design techniques, patterns and standards would you embrace if you are asked to write a debug-coding document for all others in the project to follow?</em></p>
<p>I am not talking about tools, libraries or IDE-specific commands, but for OO design decisions.</p>
<p>Thanks.</p>
|
<p>Don't commit debugging code, just debuggin tools.</p>
<p>Loggin OTOH has a natural place in execption handling routines and such. Also a few well placed logging statments in a few commonly used APIs can be good for debugging.</p>
<p>Like one log statment to log all SQL executed from the system.</p>
|
<p>My vote would be with what you described as a friendly tracker class. This class would keep all of that centralized, and potentially even allow you to change debug/logging strategies dynamically.</p>
<p>I would avoid things like Macros simply because that's a compiler trick, and not true OO. By abstracting the concept of debug/logging, you have the opportunity to do lots of things with it including making it a no-op if needed.</p>
| 40,344
|
<p>In C++, there isn't a de-facto standard logging tool. In my experience, shops roll their own. This creates a bit of a problem, however, when trying to create reusable software components. If everything in your system depends on the logging component, this makes the software less reusable, basically forcing any downstream projects to take your logging framework along with the components they really want. </p>
<p>IOC (dependency injection) doesn't really help with the problem since your components would need to depend on a logging abstraction. Logging components themselves can add dependencies on file I/O, triggering mechanisms, and other possibly unwanted dependencies. </p>
<p>Does adding a dependency to your proprietary logging framework sacrifice the reusability of the component?</p>
|
<p>Yes. But dependency injection will help in this case.</p>
<p>You can create an abstract logging base-class and create implementations for the logging-frameworks you want to use. Your components are just dependent on the abstract base-class. And you inject the implementations along with al their dependencies as needed.</p>
|
<p>If you are looking to build libraries which wont be recompiled, but want to provide a logging interface then perhaps a good way is to allow the user (of the library) to provide a callback.</p>
<p>On initialising logging with your library, they would need to specify the callback, and then the glue-code is up to them to make it play well with whatever they have.</p>
<p>If you can make the signature of the callback look like a standard function they might always have available to them, it provides them an easy default option if they dont actually have a logger.</p>
<p>Additionally the caller might have instanced components from the library multiple times, and for resource contention or threading issues, want to provide a different logger callback for each one.</p>
| 6,035
|
<p>When considering using performance counters as my companies' .NET based site, I was wondering how big the overhead is of using them. </p>
<p>Do I want to have my site continuously update it's counters or am I better off to only do when I measure?</p>
|
<p>The performance impact is negligible in updating. Microsoft's intent is that you always write to the performance counters. It's the monitoring of (or capturing of) those performance counters that will cause a degradation of performance. So, only when you use something like perfmon to capture the data.</p>
<p>In effect, the performance counter objects will have the effect of only "doing it when you measure."</p>
|
<p>The thing that I have found is that it is not that slow for the majority of applications. I wouldn't put one in a tight loop, or something that is called thousands of times a second.</p>
<p>Secondly, I found that programmatically creating the performance counters is very slow, so make sure that you create them before hand and not in code.</p>
| 37,056
|
<p>I'm looking for a good plugin for doing web front end work in Eclipse. I don't want something that completely takes over eclipse, or something that has masses of dependencies that need to be updated all the time, or something that is geared towards a particular server-side platform, or something that costs a heap.</p>
<p>Is there something light-weight out there that hits the sweet spot?</p>
<p>I tried aptana - found it took over my whole eclipse environment and put news feeds and other rubbish all over the place.</p>
<p>I then tried installing a subset of the aptana jar's and ended up pretty happy with the result.</p>
<p>Here's what I have in my plugins directory:</p>
<blockquote>
<p>com.aptana.ide.core_1.2.0.018852.jar
com.aptana.ide.snippets_1.2.0.018852.jar
com.aptana.ide.core.ui_1.2.0.018852.jar
com.aptana.ide.debug.core_1.2.0.018852.jar
com.aptana.ide.editor.css_1.2.0.018852.jar
com.aptana.ide.editor.html_1.2.0.018852.jar
com.aptana.ide.editor.js_1.2.0.018852.jar
com.aptana.ide.editors_1.2.0.018852.jar
com.aptana.ide.editors.codeassist_1.2.0.018852.jar
com.aptana.ide.epl_1.2.0.018852.jar
com.aptana.ide.io.file_1.2.0.018852.jar
com.aptana.ide.jface.text.source_1.2.0.018852.jar
com.aptana.ide.lexer_1.1.0.018852.jar
com.aptana.ide.libraries_1.2.0.18696
com.aptana.ide.libraries.jetty_1.2.0.018852
com.aptana.ide.logging_1.2.0.018852.jar
com.aptana.ide.parsing_1.2.0.018852.jar
com.aptana.ide.search.epl_1.2.0.018852.jar
com.aptana.ide.server_1.2.0.018852.jar
com.aptana.ide.server.core_1.2.0.018852.jar
com.aptana.ide.server.jetty_1.2.0.018852.jar
com.aptana.ide.server.ui_1.2.0.018852.jar</p>
</blockquote>
<p>..and in the features:</p>
<blockquote>
<p>com.aptana.ide.feature.editor.css_1.2.0.018852
com.aptana.ide.feature.editors_1.2.0.018852
com.aptana.ide.feature.editor.html_1.2.0.018852
com.aptana.ide.feature.editor.js_1.2.0.018852</p>
</blockquote>
|
<p>Sounds like you need the <a href="http://www.eclipse.org/webtools/" rel="nofollow noreferrer">Web Tools Project</a></p>
<p>Update: In latest 2016 Eclipse Neon, go to HELP -> Install Software and search for Eclipse Web Developer tools. For some reason it's hard to find them from the Marketplace.</p>
<p><a href="https://i.stack.imgur.com/ooTsim.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ooTsim.png" alt="help install software"></a></p>
<p><a href="https://i.stack.imgur.com/u4RfX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/u4RfX.png" alt="web developer tools"></a></p>
|
<p>As of now, Eclipse Juno has great HTML/CSS/XML/JS editors, with the PDT a good plugin for PHP</p>
| 41,739
|
<p>I am using Fluent NHibernate and having some issues getting a many to many relationship setup with one of my classes. It's probably a stupid mistake but I've been stuck for a little bit trying to get it working. Anyways, I have a couple classes that have Many-Many relationships. </p>
<pre><code>public class Person
{
public Person()
{
GroupsOwned = new List<Groups>();
}
public virtual IList<Groups> GroupsOwned { get; set; }
}
public class Groups
{
public Groups()
{
Admins= new List<Person>();
}
public virtual IList<Person> Admins{ get; set; }
}
</code></pre>
<p>With the mapping looking like this</p>
<p>Person: ...</p>
<pre><code>HasManyToMany<Groups>(x => x.GroupsOwned)
.WithTableName("GroupAdministrators")
.WithParentKeyColumn("PersonID")
.WithChildKeyColumn("GroupID")
.Cascade.SaveUpdate();
</code></pre>
<p>Groups: ...</p>
<pre><code> HasManyToMany<Person>(x => x.Admins)
.WithTableName("GroupAdministrators")
.WithParentKeyColumn("GroupID")
.WithChildKeyColumn("PersonID")
.Cascade.SaveUpdate();
</code></pre>
<p>When I run my integration test, basically I'm creating a new person and group. Adding the Group to the Person.GroupsOwned. If I get the Person Object back from the repository, the GroupsOwned is equal to the initial group, however, when I get the group back if I check count on Group.Admins, the count is 0. The Join table has the GroupID and the PersonID saved in it. </p>
<p>Thanks for any advice you may have.</p>
|
<p>The fact that it is adding two records to the table looks like you are missing an <a href="http://docs.jboss.org/hibernate/orm/4.1/manual/en-US/html_single/#example-many-to-many-mapping-file" rel="noreferrer">inverse attribute</a>. Since both the person and the group are being changed, NHibernate is persisting the relation twice (once for each object). The inverse attribute is specifically for avoiding this.</p>
<p>I'm not sure about how to add it in mapping in code, but the link shows how to do it in XML.</p>
|
<p>Are you making sure to add the Person to the Groups.Admin? You have to make both links.</p>
| 13,375
|
<p>I have a container div that holds two internal divs; both should take 100% width and 100% height within the container.</p>
<p>I set both internal divs to 100% height. That works fine in Firefox, however in IE the divs do not stretch to 100% height but only the height of the text inside them.</p>
<p>The following is a simplified version of my style sheet.</p>
<pre><code>#container
{
height: auto;
width: 100%;
}
#container #mainContentsWrapper
{
float: left;
height: 100%;
width: 70%;
margin: 0;
padding: 0;
}
#container #sidebarWrapper
{
float: right;
height: 100%;
width: 29.7%;
margin: 0;
padding: 0;
}
</code></pre>
<p>Is there something I am doing wrong? Or any Firefox/IE quirks I am missing out?</p>
|
<p>I think "works fine in Firefox" is in the <strong>Quirks mode</strong> rendering only.
In the <strong>Standard mode</strong> rendering, that might not work fine in Firefox too.</p>
<p>percentage depends on "containing block", instead of viewport.</p>
<p><a href="http://www.w3.org/TR/CSS21/visudet.html#the-height-property" rel="noreferrer">CSS Specification says</a></p>
<blockquote>
<p>The percentage is calculated with
respect to the height of the generated
box's containing block. If the height
of the containing block is not
specified explicitly (i.e., it depends
on content height), and this element
is not absolutely positioned, the
value computes to 'auto'.</p>
</blockquote>
<p>so</p>
<pre><code>#container { height: auto; }
#container #mainContentsWrapper { height: n%; }
#container #sidebarWrapper { height: n%; }
</code></pre>
<p>means</p>
<pre><code>#container { height: auto; }
#container #mainContentsWrapper { height: auto; }
#container #sidebarWrapper { height: auto; }
</code></pre>
<p>To stretch to 100% height of viewport, you need to specify the height of the containing block (in this case, it's #container).
Moreover, you also need to specify the height to body and html, because initial Containing Block is "UA-dependent".</p>
<p>All you need is...</p>
<pre><code>html, body { height:100%; }
#container { height:100%; }
</code></pre>
|
<p>I don't think IE supports the use of auto for setting height / width, so you could try giving this a numeric value (like Jarett suggests).</p>
<p>Also, it doesn't look like you are clearing your floats properly. Try adding this to your CSS for #container:</p>
<pre><code>#container {
height:100%;
width:100%;
overflow:hidden;
/* for IE */
zoom:1;
}
</code></pre>
| 20,834
|
<p>How do I create a button control (with <code>CreateWindow</code> of a <code>BUTTON</code> window class) that has a standard system-wide size (especially height) that's consistent with the rest of Windows applications?
I should of course take DPI into account and probably other settings.</p>
<blockquote>
<p><strong>Remark:</strong> Using <code>USE_CW_DEFAULT</code> for width and height results in a 0, 0 size button, so that's not a solution.</p>
</blockquote>
|
<h2>In the perfect, hassle-free world...</h2>
<p>To create a standard size button we would have to do this:</p>
<pre><code>LONG units = GetDialogBaseUnits();
m_hButton = CreateWindow(TEXT("BUTTON"), TEXT("Close"),
WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,
0, 0, MulDiv(LOWORD(units), 50, 4), MulDiv(HIWORD(units), 14, 8),
hwnd, NULL, hInst, NULL);
</code></pre>
<p>where <strong>50</strong> and <strong>14</strong> are respective DLU dimensions, <strong>4</strong> and <strong>8</strong> are horizontal and vertical dialog template units respectively, based on <a href="http://msdn.microsoft.com/en-us/library/ms645475(VS.85).aspx" rel="noreferrer"><code>GetDialogBaseUnits()</code> function</a> documentation remarks.</p>
<hr>
<h2>Nothing's perfect</h2>
<p><strong>BUT</strong> as Anders pointed out, those metrics are based on the system font. If your window uses a shell dialog font or simply anything not making your eyes bleed, you're pretty much on your own.</p>
<p>To get your own "dialog" base units, you have to retrieve current text metrics with <code>GetTextMetrics()</code> and use character height and average width (<code>tmHeight</code> and <code>tmAveCharWidth</code> of the <code>TEXTMETRIC</code> struct respectively) and translate them with MulDiv by your own, <strong>unless</strong> you are in a dialog, then <code>MapDialogRect()</code> will do all the job for you.</p>
<p>Note that <code>tmAveCharWidth</code> only approximates the actual average character width so it's recommended to use a <a href="http://msdn.microsoft.com/en-us/library/dd144938.aspx" rel="noreferrer"><code>GetTextExtentPoint32()</code></a> function on an alphabetic character set instead.</p>
<p>See:</p>
<ul>
<li><a href="http://support.microsoft.com/kb/145994" rel="noreferrer">How to calculate dialog box units based on the current font in Visual C++</a></li>
<li><a href="http://support.microsoft.com/kb/125681" rel="noreferrer">How To Calculate Dialog Base Units with Non-System-Based Font</a></li>
</ul>
<hr>
<h2>Simpler alternative</h2>
<p>If buttons are the only control you want to resize automatically, you can also use <a href="http://msdn.microsoft.com/en-us/library/bb775961(VS.85).aspx" rel="noreferrer"><code>BCM_GETIDEALSIZE</code></a> message <a href="http://msdn.microsoft.com/en-us/library/bb761851(VS.85).aspx" rel="noreferrer"><code>Button_GetIdealSize()</code></a> macro (Windows XP and up only) to retrieve optimal width and height that fits anything the button contains, though it looks pretty ugly without any margins applied around the button's text.</p>
|
<p>@macbirdie: you should NOT use GetDialogBaseUnits(), it is based on the default system font (Ugly bitmap font). You should use MapDialogRect()</p>
| 8,301
|
<p>I am used to TYPO3 where I just can upload an image within the content element an then just determine the size an so on.</p>
<p>Is there a way to handle images in drupal somehow like this?</p>
|
<p>Image upload support for Drupal is a bit of a jungle. </p>
<p>The most basic way to do this is with image.module and img_assist. This will add a link below each textarea allowing an upload, and when you upload one it inserts a custom tag into the content body that specifies the image, its title, its size and alignment, etc. Note that this inserts the image reference into the body text of the node and gives the author control over how & where the image appears. This may be all you need if the site is just for your personal use and you're looking to do something simple like insert images into your blog posts.</p>
<p>An alternative (especially if others are going to create content and you want it to always look good without a lot of hassle and user training) is to restrict the placement of images in your theme--let people upload images as attachments, and render the images in standard slots outside of the body text. This is often done using the CCK imagefield to allow specifying up to N images--so you add separate fields to the Create Content node where the relevant images are specified. One can be marked as special and you can pull that one out to be the thumbnail that goes with the teaser. (IIRC, imagefield may not be ready for D6 yet.)</p>
<p>To make this scenario work better, you probably want images auto-resized to a standard size that fits into your theme, and a thumbnail version to be auto-generated. A module like imagecache can do this, though it's not the easiest thing to set up.</p>
<p>The IMCE module is a DHTML/JavaScript uploader UI that allows the user to browse previously uploaded images on the server. (There's control over what folders they can see.) IMCE has an associated CCK IMCE ImageField field type to replace the regular imagefield. IMCE also integrates with TinyMCE and FCKeditor to replace their own uploader UIs. (IMCE and IMCE's imagefield seem to work on D6.)</p>
<p>Some people swear by the Asset module for uploading & selection of previously uploaded content; I believe it can also help embed images hosted on Flickr and videos from YouTube. Currently only available for Drupal 5.</p>
|
<p>I'm just starting to learn about drupal, but here are some of my finds in the Drupal-image-gallery department - perhaps one of these will do what you want:</p>
<p><a href="http://www.developmentseed.org/blog/2007/oct/24/unlimited-images-your-content-drupal-and-flickr" rel="nofollow noreferrer">Flickrup</a></p>
<p><a href="http://drupal.org/project/prog_gallery" rel="nofollow noreferrer">PROG Gallery</a></p>
<p><a href="http://drupal.org/project/gallery" rel="nofollow noreferrer">Gallery2</a></p>
| 14,852
|
<p>My product has several components: ASP.NET, Windows Forms App and Windows Service. 95% or so of the code is written in VB.NET.</p>
<p>For Intellectual Property reasons, I need to obfuscate the code, and until now I have been using a version of dotfuscator which is now over 5 years old. I'm thinking it is time to move to a new generation tool. What I'm looking for is a list of requirements which I should consider when searching for a new obfuscator.</p>
<p>What I know I should look for so far:</p>
<ul>
<li><strong><em>Serialization/De-serialization</em></strong>. In my current solution, I simply tell the tool <strong>not</strong> to obfuscate any class data members because the pain of not being able to load data which was previously serialized is simply too big.</li>
<li><strong><em>Integration with Build Process</em></strong></li>
<li><strong><em>Working with ASP.NET</em></strong>. In the past, I have found this problematic due to changing .dll names (you often have one per page) - which not all tools handle well.</li>
</ul>
|
<p>Back with .Net 1.1 obfuscation was essential: decompiling code was easy, and you could go from assembly, to IL, to C# code and have it compiled again with very little effort.</p>
<p>Now with .Net 3.5 I'm not at all sure. Try decompiling a 3.5 assembly; what you get is a long long way from compiling.</p>
<p>Add the optimisations from 3.5 (far better than 1.1) and the way anonymous types, delegates and so on are handled by reflection (they are a nightmare to recompile). Add lambda expressions, compiler 'magic' like Linq-syntax and <code>var</code>, and C#2 functions like <code>yield</code> (which results in new classes with unreadable names). Your decompiled code ends up a long long way from compilable. </p>
<p>A professional team with lots of time could still reverse engineer it back again, but then the same is true of any obfuscated code. What code they got out of that would be unmaintainable and highly likely to be very buggy.</p>
<p>I would recommend key-signing your assemblies (meaning if hackers can recompile one they have to recompile all) but I don't think obfuscation's worth it.</p>
|
<p>I tried Eziriz demo version....I liked it. But never brought the software.</p>
| 2,464
|
<p>Usercontrol with button - When uc is added dynamically to another page I loose the button handler.</p>
<p>ie: I have 1 usercontrol with 1 button - the button has an event handler in the code behind. When i add the UserControl to a page programatically the button handler does not fire. Any idea of an easy way to fix this.</p>
<p>Typically when ive added controls dynamically to a page, i've had to re-wire the event handlers on every post back, but i was hoping since that button was contained in a UserControl and the uc was added dynamically i wouldnt loose it - doesnt seem to be the case - is there a better way to do this? My usercontrol will eventually have MANY buttons on it and i dont want to have to re-wire them everytime from the page that is dynamically adding the usercontrol.</p>
|
<p>You'll be using Page.LoadControl to add the ascx control in the page's OnInit event handler (although I've done so in Load event handler and it works, but the documentation specifies OnInit)</p>
<p>Your user control (and page) should wire up their events for every load and postback
e.g.
this.buttonID.Click += new System.EventHandler(this.buttonID_Click);</p>
<p>If you are doing that then it should all work, if not, check your aspx/ascx markup as erronous characters such as an extra < somewhere can break the page but it'll still render OK in a browser.</p>
|
<p>Sometimes when you dynamically add controls to a page the button event handlers get messed up because the IDs of the controls get out of sync. But again I would need to see how you are dynamically loading the controls. </p>
| 26,698
|
<p>So when my Prusa I3 is heating up, a small bit of filament is coming out of the nozzle, forming a small string at.</p>
<p>When the printing starts, this results in a small plastic ball on the bed, impacting the overall printing process.</p>
<p>How can I avoid this?</p>
|
<p>On my Kossel Mini I programmed it to go to the edge of the bed and purge a small amount of filament which creates a dot. I purge enough to get the dot to stick to the bed and then go on with printing, when the head moves the dot stays attached and usually pulls excess material off the nozzle. This can be added to the "Starting G-Code" section of your slicer.</p>
|
<p>I just go and pull it off the print head with pliers when it's about to start and sometimes shortly after it starts printing, but its probably not the safest way to deal with the problem. Printing a skirt, brim, or raft should help to fix the problem.</p>
| 574
|
<p>I'm trying to consume a webmethod but it seems that my application can't resolve DNS. The problem surfaces when I configure my application with an url (e.g.: <a href="http://mywebservice.com/webservice/methods.asmx" rel="nofollow noreferrer">http://mywebservice.com/webservice/methods.asmx</a>), but it does not when I access the same webmethod through the server's IP address. </p>
<p>The thing is that I need to access the webservice using the url and not the IP address due to an existing DHCP server policy.</p>
<p>Can anyone help me ?</p>
<p>Thanks in advance.</p>
<p>UPDATE: Checking out what moocha asked me to do, I found out that: </p>
<p>D:>nslookup server.com
Server: dnsserver.mycompany.com
Address: XXX.YYY.XXX.YYY</p>
<p>*** dnsserver.mycompany.com can't find server.com: Non-existent domain</p>
|
<p>Have you tried confirming the same DNS query works via nslookup <em>from the same system on which your application runs</em>?</p>
<p>I.e.,</p>
<pre>C:\>nslookup
Default Server: whatever.dns.example.org
Address: 111.222.333.111
> set q=a
> mywebservice.com
Server: whatever.dns.example.org
Address: 111.222.333.111
Non-authoritative answer:
Name: mywebservice.com
Address: 208.254.26.139</pre>
|
<p>Digging a little bit more I found that there is a proxy in between my PC and the server. Therefore, I'm oblied to log with a valid user in order to access the internet. The problem <b>was</b> that my application's server (where the IIS is running) was configured to run using anonymous access. All I had to do was to configure in the IIS an user that has permission to access the internet (through the proxy). Finally the problem is solved.</p>
<p>There was another option, I could use the logged user's credentials to grant access through the proxy; but that required that all users use the same log in information for the application and the intranet.</p>
| 27,866
|
<p>My understanding is that C# and java differ with respect to generics in some ways, one of which is that generic type parameters are available at runtime in C#/.NET but not in Java. Why did the Java language designers do it this way? </p>
|
<p>To allow binary compatibility with pre-generics bytecode, therefore allowing new code to interface with old code.</p>
<p>From the <a href="http://java.sun.com/docs/books/tutorial/java/generics/erasure.html" rel="nofollow noreferrer">Type Erasure</a> page of The Java Tutorials:</p>
<blockquote>
<p>Type erasure enables Java applications
that use generics to maintain binary
compatibility with Java libraries and
applications that were created before
generics.</p>
<p>[...] </p>
<p>Type erasure exists so that new code
may continue to interface with legacy
code.</p>
</blockquote>
<p>For a related question, take a look at <a href="https://stackoverflow.com/questions/355060/c-vs-java-generics">C# vs Java generics</a>.</p>
|
<p>I remember reading something about this in the book Hardcore Java:</p>
<blockquote>
<p>The problem with checking elements in
a collection at runtime is that it is
extremely expensive; the order of
efficiency is only O(n). If you have
only 10 addresses in your collection,
checking elements is easy. However, if
the collection contains 15,000
addresses, then you would incur a
significant overhead whenever someone
calls the setter.</p>
<p>On the other hand, if
you can prevent users from placing
anything other than an address in your
collection at compile time, then you
wouldn't have to check the types at
runtime. If they try to give you
something that isn't an address, then
the compiler will reject the attempt.
This is exactly what parameterized
types do.</p>
</blockquote>
<p>However, "why" questions can never really be satisfactorily answered because there are just too many variable involved with people, time, place and politics. I remember reading somewhere else that the decision had a lot to do with maintaining compatibility with the way things were already being done in the Java byte code. Here is another quote from the same book:</p>
<blockquote>
<p>After the compiler has resolved the type safety introduced by generics, it erases the parameterization from the type. Therefore, the information is not available at runtime. The purpose of erasure, as stated by Sun, is to allow class libraries built with an older version of the JDK to be able to run on the JDK 1.5 virtual machine.</p>
</blockquote>
<p>I'm curious, what are the advantages offered by runtime generics?</p>
| 48,830
|
<p>With a huge influx of newbies to Xcode, I'm sure there are lots of Xcode tips and tricks to be shared.</p>
<p>What are yours? </p>
|
<h2>Switch to Header/Source File</h2>
<blockquote>
<ul>
<li><p><kbd>Option ⌥</kbd> <kbd>Command ⌘</kbd> <kbd>Up Arrow ↑</kbd></p>
</li>
<li><p><strong>View</strong> > <strong>Switch to Header/Source File</strong></p>
</li>
</ul>
</blockquote>
<p>Switches between the <code>.m</code> and <code>.h</code> files.</p>
<blockquote>
<ul>
<li>In Xcode 4 this is <kbd>ctrl</kbd> <kbd>Command ⌘</kbd> <kbd>Up Arrow ↑</kbd></li>
</ul>
</blockquote>
|
<p>I came into Xcode right from Windows world (as MANY others), and one of the first quirks which I was faced to, was trying to "indent a selected block of text" with the TAB key.</p>
<p>Typically, when using a Windows editor, you select a block of text, and whenever you press TAB (or shift TAB) keys, the selected text jumps right/left. Then, once you decide the new position of the text, you stop pressing TAB.</p>
<p>OK, in Xcode, this is completely different, because when you press TAB, the whole block of text disappears, leaving you with a silly face, and some anger inside...</p>
<p>But then, just by chance or intuition or something, one day I discovered some kind of workaround to achieve the same effect you might get under a proper windows editor.
The steps should be these:</p>
<ol>
<li>Select the text block as you might do under Windows.</li>
<li>Instead of pressing TAB, leave your instincts away, and "copy the text block" (typically CTRL+C (yuck)).</li>
<li>Then, without deselecting the text, (pressing SHIFT if needed), extend the beginning of the selection and place it on the position you would like your new text to appear.</li>
<li>Paste the beforementioned text (typically CTRL+V (yuck again)).</li>
<li>Result: The previous text block gets substituted by "the new" one (of course, itself), but the "auto indent" capabilities of Xcode (or someone else, who cares), will auto place the text starting onto the new position we chose in step 3.</li>
<li>A big smile appears on your face.</li>
</ol>
<p>It's kind of tricky, but when you get used to it, you find yourself using it a lot.</p>
<p>Enjoy!!</p>
| 17,618
|
<p>I'm a Scrum newbie and looking to implement Scrum in my company. Obtaining buy-in is not a problem, it is my company and the developers are more than happy to work like this.</p>
<p>The problem is that 75% of our revenue is derived from fixed length/fixed price projects. </p>
<p>Ken Schwaber in his book, Agile Project Management with Scrum, covers the topic of bidding on fixed length/fixed price projects in an appendix at the end of the book.</p>
<p>After much soul searching, Ken derived that Scrum is only useful in this situation when you can convince the potential client to think differently. The client would have to be okay with a lot of uncertainty (about the final cost and the final delivery date) in return for getting something much sooner that may be usuable and the possibility of not having to implement every feature could save them money.</p>
<p>I'm not convinced that this is the only way to implement Scrum in fix length/fix price projects.</p>
<p>I want to know how others have successfully bid on and profitted from fix length/fix price projects.</p>
|
<p>Yes. I think you can. See <a href="http://homepage.mac.com/s_lott/iblog/architecture/C551260341/E20080211062302/index.html" rel="noreferrer">The Waterfall's Not Working</a>. </p>
<p>The "getting outside the fixed-price box" isn't that hard a conversation to have. Customers have seen failures also. They've seen the long delays getting to a requirements document. They've seen the endless change orders. They don't like it either.</p>
<p>But, if you're convinced that the customer's doesn't want to manage things differently, you have to take a hybrid approach.</p>
<p>Making up a price isn't Agile -- it can't be. You must, for purposes of placating intransigent customers, make up a price. Clearly, you'll have some kind of master plan here to justify the price. Mostly, all you want from this master plan is the backlog. Other details are nothing more than hypothetical planning assumptions. [They're <strong>always</strong> planning assumptions, but some PM's think the initial plan is a divine oracle which must be followed. It's not.]</p>
<p>Then, you execute in small, Agile, incremental steps. You have to engage the users early and often, and you have to let the conversations happen. But! Each change in the backlog has to be examined as a potential change in scope, cost or schedule. </p>
<p>At the end of every sprint, any backlog changes will potentially be project scope and contract changes. </p>
<p>Agile reduces your risks because you're actively working the scope changes earlier and more productively with the customer. Trying to define (and freeze) scope isn't a value-add activity, so just stop doing it. Treat scope as the guess it is, and work the scope changes at each sprint.</p>
|
<p>I'm not sure about the bidding and profits but the scrum methodology can certainly be applied to a fixed-length/price project. If the requirements are known and solid they can be put in the product backlog and the sprints can be planned according to the requirements and the time limit. You can still leverage the benefits of the daily scrum meetings, burn-down charts, etc to make sure the project stays on track.</p>
| 33,249
|
<p>Personally I like this one:</p>
<p><img src="https://i.stack.imgur.com/ZNtvc.jpg" alt=""></p>
<p>P.S. Do not hotlink the cartoon without the site's permission please. </p>
|
<p>Another one from <a href="http://xkcd.com/327/" rel="nofollow noreferrer">xkcd</a>
<img src="https://imgs.xkcd.com/comics/exploits_of_a_mom.png" alt="Exploits of a Mom" title="Her daughter is named Help I'm trapped in a driver's license factory."></p>
|
<p><img src="https://i.somethingawful.com/jeffk/computarfunnys/4-17-00-02.gif" alt="alt text"></p>
| 11,010
|
<p>Has anyone considered using something along the lines of the Amazon SimpleDB data store as their backend database?</p>
<p>SQL Server hosting (at least in the UK) is expensive so could something like this along with cloud file storage (S3) be used for building apps that could grow with your application.</p>
<p>Great in theory but would anyone consider using it. In fact is anyone actually using it now for real production software as I would love to read your comments.</p>
|
<p>This is a good analysis of Amazon services from <a href="http://www.25hoursaday.com/weblog/2008/08/21/SomeThoughtsOnAmazonsElasticBlockStore.aspx" rel="nofollow noreferrer">Dare</a>.</p>
<p><em>S3 handled what I've typically heard described as "blob storage". A typical Web application typically has media files and other resources (images, CSS stylesheets, scripts, video files, etc) that is simply accessed by name/path. However a lot of these resources also have metadata (e.g. a video file on YouTube has metadata about it's rating, who uploaded it, number of views, etc) which need to be stored as well. This need for queryable, schematized storage is where SimpleDB comes in. EC2 provides a virtual server that can be used for computation complete with a local file system instance which isn't persistent if the virtual server goes down for any reason. With SimpleDB and S3 you have the building blocks to build a large class of "Web 2.0" style applications when you throw in the computational capabilities provided by EC2.
However neither S3 nor SimpleDB provides a solution for a developer who simply wants the typical LAMP or WISC developer experience of building a database driven Web application or for applications that may have custom storage needs that don't fit neatly into the buckets of blob storage or schematized storage. Without access to a persistent filesystem, developers on Amazon's cloud computing platform have had to come up with sophisticated solutions involving backing data up manually from EC2 to S3 to get the desired experience.</em> </p>
|
<p>But do you really need SQL Server? Can't you live with PostgreSQL or MySQL? Both have proven to be ok for most tasks. </p>
<p>Now if you need SQL Server features then you're out of luck. </p>
<p>Another option is to rent a server. How expensive is expensive?</p>
<p>(I've used Amazon S3 to store images for an application, it's ok and works fine, at least for that)</p>
| 7,723
|
<p>varchar(255), varchar(256), nvarchar(255), nvarchar(256), nvarchar(max), etc?</p>
<p>256 seems like a nice, round, space-efficient number. But I've seen 255 used a lot. Why?</p>
<p>What's the difference between varchar and nvarchar?</p>
|
<p>VARCHAR(255). It won't use all 255 characters of storage, just the storage you need. It's 255 and not 256 because then you have space for 255 plus the null-terminator (or size byte).</p>
<p>The "N" is for Unicode. Use if you expect non-ASCII characters.</p>
|
<p>If you will be supporting languages other than English, you will want to use nvarchar.</p>
<p>HTML should be okay as long as it contains standard ASCII characters. I've used nvarchar mainly in databases that were multi-lingual support. </p>
| 7,812
|
<p>We're developing a windows mobile 6.1 application and would like to make the user interface look better than the standard battleship grey. Has anyone had any experience with 3rd party controls that can make a windows mobile app look like a WPF/Silverlight/Iphone - like interface?</p>
|
<p>There might be some useful-ish replies in <a href="https://stackoverflow.com/questions/35907/3rd-party-ui-components-for-net-compact-framework">this</a> question.</p>
|
<p>There might be some useful-ish replies in <a href="https://stackoverflow.com/questions/35907/3rd-party-ui-components-for-net-compact-framework">this</a> question.</p>
| 21,030
|
<p>Say you have 2 database servers, one database is the 'master' database where all write operations are performed, it is treated as the 'real/original' database. The other server's database is to be a mirror copy of the master database (slave?), which will be used for read only operations for a certain part of the application.</p>
<p>How do you go about setting up a slave database that mirrors the data on the master database? From what I understand, the slave/readonly database is to use the master db's transaction log file to mirror the data correct?<br>
What options do I have in terms of how often the slave db mirrors the data? (real time/every x minutes?).</p>
|
<p>What you want is called Transactional Replication in SQL Server 2005. It will replicate changes in near real time as the publisher (i.e. "master") database is updated.</p>
<p><a href="http://blogs.techrepublic.com/howdoi/?p=123" rel="nofollow noreferrer">Here is a pretty good walk through of how to set it up.</a></p>
|
<p>The answer to this will vary depending on the database server you are using to do this.</p>
<p>Edit: Sorry, maybe i need to learn to look at the tags and not just the question - i can see you tagged this as sqlserver.</p>
| 3,403
|
<p>when a System.Web.HttpResponse.End() is called a System.Thread.Abort is being fired, which i'm guessing is (or fires) an exception? I've got some logging and this is being listed in the log file...</p>
<p>A first chance </p>
<pre><code>exception of type 'System.Threading.ThreadAbortException' occurred in mscorlib.dll
12/14/2008 01:09:31::
Error in Path :/authenticate
Raw Url :/authenticate
Message :Thread was being aborted.
Source :mscorlib
Stack Trace : at System.Threading.Thread.AbortInternal()
at System.Threading.Thread.Abort(Object stateInfo)
at System.Web.HttpResponse.End()
at DotNetOpenId.Response.Send()
at DotNetOpenId.RelyingParty.AuthenticationRequest.RedirectToProvider()
at MyProject.Services.Authentication.OpenIdAuthenticationService.GetOpenIdPersonaDetails(Uri serviceUri) in C:\Users\Pure Krome\Documents\Visual Studio 2008\Projects\MyProject\Projects\Services\Authentication\OpenIdAuthenticationService.cs:line 108
at MyProject.Mvc.Controllers.AuthenticationController.Authenticate() in C:\Users\Pure Krome\Documents\Visual Studio 2008\Projects\MyProject\Projects\MVC Application\Controllers\AuthenticationController.cs:line 69
TargetSite :Void AbortInternal()
A first chance exception of type 'System.Threading.ThreadAbortException' occurred in Ackbar.Mvc.DLL
An exception of type 'System.Threading.ThreadAbortException' occurred in Ackbar.Mvc.DLL but was not handled in user code
</code></pre>
<p>Is this normal behavior and is it possible to gracefully abort instead of (what looks like) a sudden abrupt abort?</p>
<h2>Update</h2>
<p>So far it the common census that it's <a href="http://msdn.microsoft.com/en-us/library/system.web.httpresponse.end.aspx" rel="noreferrer">by design</a>. So i'm wondering if it's possible we could take this question and see if we could tweak the code to make it not feel like we're ending the thread <em>prematurely</em> and gracefully exit ... Possible? Code examples?</p>
|
<p>There is no such thing as a "graceful" abort. You could simply Flush() the response, though, instead of ending it and let the framework take care of closing the connection for you. I'm assuming in this case that you want the response sent to the client, i.e., the typical case.</p>
<p>According to <a href="http://msdn.microsoft.com/en-us/library/system.web.httpresponse.end.aspx" rel="noreferrer">MSDN</a>, calling Response.End() throws the ThreadAbortException when the response ends prematurely. You really should only call Response.End() when you want the exception raised.</p>
|
<p>Don't use Response.End() method because it uses Application.End() and stop the application. Further use HTTP request or response violating Page Life Cycle. Use HttpContext.Current.Response.Close() or HttpContext.Current.ApplicationInstance.CompleteRequest(); </p>
| 47,682
|
<p>I am not able to access localhost https pages in firefox3. It gave the error </p>
<blockquote>
<p>'Can't connect securely because the SSL protocol has been disabled.
(Error code: ssl_error_ssl_disabled)'</p>
</blockquote>
<p>I enabled all the SSL2 related preferences through about:config and the error changed to </p>
<blockquote>
<p>'Data Transfer Error
The browser connected successfully, but the connection was interrupted while transferring information. Please try again.'</p>
</blockquote>
<p>The first error seems most likely due to a invalid certificate but can't figure out the second...</p>
|
<p>I think that it's better to use simply <a href="http://www.php.net/str_replace" rel="noreferrer">str_replace</a>, like the manual says:</p>
<blockquote>
<p>If you don't need fancy replacing
rules (like regular expressions), you
should always use this function
instead of ereg_replace() or
preg_replace().</p>
</blockquote>
<pre><code><?
$badUrl = "http://www.site.com/backend.php?/c=crud&m=index&t=care";
$goodUrl = str_replace('?/', '?', $badUrl);
</code></pre>
|
<p>While a regexp would suit here just fine, I'll present you with an alternative method. It <em>might</em> be a tad faster than the equivalent regexp, but life's all about choices (...or something).</p>
<pre><code>$length = strlen($urlString);
for ($i=0; $i<$length; i++) {
if ($urlString[$i] === '?') {
$urlString[$i+1] = '';
break;
}
}
</code></pre>
<p>Weird, I know.</p>
| 33,130
|
<p>To sketch the background of this question : at work we use Dell Precision workstations. My current one has got an NVidia Quadro FX1700.
My team is developing the graphics components for a real time data acquisition system.
So we are always looking out to see if the graphics operations don't use up too much CPU time. For quick checks, we have a couple of test programs that we run, which draw scenes at a specified rate ( e.g. 10 fps ) and we use plain old Task Manager to see where CPU usage is at.
One of these programs is heavy on GDI DrawRectangle calls ( which are filled ). This program always used to consume about 40% CPU user-time, but since about a year or so ( just guessing here ) it only uses about 2-3 % kernel-time. So clearly some hardware acceleration is going on here. And indeed, if I turn HW-accell off, we're back to the original 40% user-time.
All of this is of course good news, because we were already thinking about going to OpenGL. Year after year GDI never got the benefit of hardware acceleration. Until some time ago that is.</p>
<p>Does anyone know anything more about this? Did Microsoft do this? Or is it gfx-card vendor specific?</p>
<p><strong>Edit</strong></p>
<p>Thnx for the answers already ( Ferrucio, Torlack and Rob Walker ) but my question has not been answered yet. We are talking about a filled rectangle here. Probably the most trivial function to optimize : just send a couple of coordinates to the GPU and let it rip. Yet it was always implemented on the CPU side.
So far the answers lead me to believe that NVidia finally saw the light ( after more than 10 years ) and accelerated GDI. And no announcement about this? There's no information to be found on this at all.
My internal customers ask me about the speedup of the graphics, and all I can say is "well, we got lucky".</p>
<p><strong>Edit2</strong></p>
<p>It does seem like it is driver related according to the different answers. So, then NVidia has made crappy GDI drivers for its workstation cards for years. It really was an accepted fact within this company that GDI was not accelerated and all the tests confirmed this.</p>
|
<p>GDI works by calling various functions in the graphics device driver. There are a core set of functions that every driver <em>must</em> implement. Other functions may be implemented by the driver. If they are not, GDI will perform those functions itself.</p>
<p>If a particular function is not implemented in hardware then there is no point in the driver doing a software implementation of that function since GDI can probably do a better job. GDI is extremely well optimized for performance.</p>
<p>As more functions are implemented in hardware, not only do those functions perform much better, but there is also less work for GDI to do, resulting in less CPU time spent on graphics.</p>
<p>It may also be the case that the graphics card vendor, in an effort to get a card out to market quickly, may not have implemented all possible hardware functions that the card could perform. Later versions of that driver may then implement that functionality, resulting in improved performance.</p>
|
<p>Vista has a new <a href="http://msdn.microsoft.com/en-us/library/aa480220.aspx" rel="nofollow noreferrer">display driver architecture</a> which would provide an opportunity for a dramatic increase in performance. Are you comparing like hardware/OS combinations?</p>
| 17,135
|
<p>During development (and for debugging) it is very useful to run a Java class' <em>public static void main(String[] argv)</em> method directly from inside Eclipse (using the Run As context menu).</p>
<p>Is there a similarily quick way to specify command line parameters for the run?
What I do now is go to the "Run Dialog", click through the various settings to the tab where I can specify VM and program arguments and enter them there.
Too many steps, plus I do not want to mix the more permanent runtime configuration settings with the one-off invokation parameters.
What I want instead is to check a box somewhere (or have a separate menu item "Run as Java application with command line") and then be prompted for the commandline every time (with a nice history).</p>
|
<p>This answer is based on Eclipse 3.4, but should work in older versions of Eclipse.</p>
<p>When selecting Run As..., go into the run configurations.</p>
<p>On the Arguments tab of your Java run configuration, configure the variable ${string_prompt} to appear (you can click variables to get it, or copy that to set it directly).</p>
<p>Every time you use that run configuration (name it well so you have it for later), you will be prompted for the command line arguments.</p>
|
<p>Another idea:</p>
<p>Place all your parameters in a properties file (one parameter = one property in this file), then in your main method, load this file (using <code>Properties.load(*fileInputStream*)</code>).
So if you want to modify one argument, you will just need to edit your args.properties file, and launch your application without more steps to do...</p>
<p>Of course, this is only for development purposes, but can be really helpfull if you have to change your arguments often...</p>
| 48,823
|
<p>I am using CCNET on a sample project with SVN as my source control. CCNET is configured to create a build on every check in. CCNET uses MSBuild to build the source code.</p>
<p>I would like to use the latest revision number to generate <code>AssemblyInfo.cs</code> while compiling.
How can I retrieve the latest revision from subversion and use the value in CCNET?</p>
<p>Edit: I'm not using NAnt - only MSBuild.</p>
|
<p>CruiseControl.Net 1.4.4 has now an <a href="http://confluence.public.thoughtworks.org/display/CCNET/Assembly+Version+Labeller" rel="noreferrer">Assembly Version Labeller</a>, which generates version numbers compatible with .Net assembly properties.</p>
<p>In my project I have it configured as:</p>
<pre><code><labeller type="assemblyVersionLabeller" incrementOnFailure="true" major="1" minor="2"/>
</code></pre>
<p>(Caveat: <code>assemblyVersionLabeller</code> won't start generating svn revision based labels until an actual commit-triggered build occurs.)</p>
<p>and then consume this from my MSBuild projects with <a href="http://msbuildtasks.tigris.org/" rel="noreferrer">MSBuildCommunityTasks.AssemblyInfo</a> :</p>
<pre><code><Import Project="$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets"/>
<Target Name="BeforeBuild">
<AssemblyInfo Condition="'$(CCNetLabel)' != ''" CodeLanguage="CS" OutputFile="Properties\AssemblyInfo.cs"
AssemblyTitle="MyTitle" AssemblyCompany="MyCompany" AssemblyProduct="MyProduct"
AssemblyCopyright="Copyright © 2009" ComVisible="false" Guid="some-random-guid"
AssemblyVersion="$(CCNetLabel)" AssemblyFileVersion="$(CCNetLabel)"/>
</Target>
</code></pre>
<p>For sake of completness, it's just as easy for projects using NAnt instead of MSBuild:</p>
<pre><code><target name="setversion" description="Sets the version number to CruiseControl.Net label.">
<script language="C#">
<references>
<include name="System.dll" />
</references>
<imports>
<import namespace="System.Text.RegularExpressions" />
</imports>
<code><![CDATA[
[TaskName("setversion-task")]
public class SetVersionTask : Task
{
protected override void ExecuteTask()
{
StreamReader reader = new StreamReader(Project.Properties["filename"]);
string contents = reader.ReadToEnd();
reader.Close();
string replacement = "[assembly: AssemblyVersion(\"" + Project.Properties["CCNetLabel"] + "\")]";
string newText = Regex.Replace(contents, @"\[assembly: AssemblyVersion\("".*""\)\]", replacement);
StreamWriter writer = new StreamWriter(Project.Properties["filename"], false);
writer.Write(newText);
writer.Close();
}
}
]]>
</code>
</script>
<foreach item="File" property="filename">
<in>
<items basedir="..">
<include name="**\AssemblyInfo.cs"></include>
</items>
</in>
<do>
<setversion-task />
</do>
</foreach>
</target>
</code></pre>
|
<p>Be careful. The structure used for build numbers is only a short so you have a ceiling on how high your revision can go.</p>
<p>In our case, we've already exceeded the limit.</p>
<p>If you attempt to put in the build number 99.99.99.599999, the file version property will actually come out as 99.99.99.10175.</p>
| 2,358
|
<p>I'm quite familiar with the reasons for wanting to copy a property vs. retain. (Essentially the value vs. relationship argument. You almost always want to copy strings, for example.)</p>
<p>What about NSColor and NSGradient? </p>
<p>They both conform to NSCopying, but as currently implemented, are immutable.</p>
<p>Thoughts?</p>
|
<p>Subclasses of NSColor and NSGradient that are assigned to your properties may not be immutable or referentially transparent, so you should still use the same logic for determining retain vs copy that you would for any object that has commonly used mutable subclasses, even though in practice it is unlikely to matter most of the time.</p>
|
<p>Subclasses of NSColor and NSGradient that are assigned to your properties may not be immutable or referentially transparent, so you should still use the same logic for determining retain vs copy that you would for any object that has commonly used mutable subclasses, even though in practice it is unlikely to matter most of the time.</p>
| 33,061
|
<p>I'm using:</p>
<pre><code>FileInfo(
System.Environment.GetFolderPath(
System.Environment.SpecialFolder.ProgramFiles)
+ @"\MyInstalledApp"
</code></pre>
<p>In order to determine if a program is detected on a users machine (it's not ideal, but the program I'm looking for is a right old kludge of a MS-DOS application, and I couldn't think of another method).</p>
<p>On Windows XP and 32-bit versions of Windows Vista this works fine. However, on x64 Windows Vista the code returns the x64 Program Files folder, whereas the application is installed in Program Files x86. Is there a way to programatically return the path to Program Files x86 without hard wiring "C:\Program Files (x86)"?</p>
|
<p>The function below will return the x86 <code>Program Files</code> directory in all of these three Windows configurations:</p>
<ul>
<li>32 bit Windows</li>
<li>32 bit program running on 64 bit Windows</li>
<li>64 bit program running on 64 bit windows</li>
</ul>
<p> </p>
<pre><code>static string ProgramFilesx86()
{
if( 8 == IntPtr.Size
|| (!String.IsNullOrEmpty(Environment.GetEnvironmentVariable("PROCESSOR_ARCHITEW6432"))))
{
return Environment.GetEnvironmentVariable("ProgramFiles(x86)");
}
return Environment.GetEnvironmentVariable("ProgramFiles");
}
</code></pre>
|
<p>One-liner using the new method in .NET. Will always return x86 Program Files folder.</p>
<p><code>Environment.Is64BitOperatingSystem ? Environment.GetEnvironmentVariable("ProgramFiles(x86)") : Environment.GetEnvironmentVariable("ProgramFiles"))</code></p>
| 23,591
|
<p>I am writing a client-side <strong>Swing</strong> application (graphical font designer) on <strong>Java 5</strong>. Recently, I am running into <code>java.lang.OutOfMemoryError: Java heap space</code> error because I am not being conservative on memory usage. The user can open unlimited number of files, and the program keeps the opened objects in the memory. After a quick research I found <a href="http://java.sun.com/docs/hotspot/gc5.0/ergo5.html" rel="noreferrer">Ergonomics in the 5.0 Java Virtual Machine</a> and others saying on Windows machine the JVM defaults max heap size as <code>64MB</code>.</p>
<p>Given this situation, how should I deal with this constraint?</p>
<p>I could increase the <strong>max heap size</strong> using <strong>command line</strong> option to java, but that would require figuring out available RAM and writing some launching program or script. Besides, increasing to some <strong>finite</strong> max does not <strong>ultimately</strong> get rid of the issue.</p>
<p>I could rewrite some of my code to persist objects to file system frequently (using database is the same thing) to free up the memory. It could work, but it's probably a lot work too.</p>
<p>If you could point me to details of above ideas or some alternatives like <strong>automatic virtual memory, extending heap size dynamically</strong>, that will be great.</p>
|
<p>Ultimately you always have a finite max of heap to use no matter what platform you are running on. In Windows 32 bit this is around <code>2GB</code> (not specifically heap but total amount of memory per process). It just happens that Java chooses to make the default smaller (presumably so that the programmer can't create programs that have runaway memory allocation without running into this problem and having to examine exactly what they are doing).</p>
<p>So this given there are several approaches you could take to either determine what amount of memory you need or to reduce the amount of memory you are using. One common mistake with garbage collected languages such as Java or C# is to keep around references to objects that you <strong>no longer</strong> are using, or allocating many objects when you could <strong>reuse</strong> them instead. As long as objects have a reference to them they will continue to use heap space as the garbage collector will not delete them.</p>
<p>In this case you can use a Java memory profiler to determine what methods in your program are allocating large number of objects and then determine if there is a way to make sure they are no longer referenced, or to not allocate them in the first place. One option which I have used in the past is "JMP" <a href="http://www.khelekore.org/jmp/" rel="noreferrer">http://www.khelekore.org/jmp/</a>.</p>
<p>If you determine that you are allocating these objects for a reason and you need to keep around references (depending on what you are doing this might be the case), you will just need to increase the max heap size when you start the program. However, once you do the memory profiling and understand how your objects are getting allocated you should have a better idea about how much memory you need. </p>
<p>In general if you can't guarantee that your program will run in some finite amount of memory (perhaps depending on input size) you will always run into this problem. Only after exhausting all of this will you need to look into caching objects out to disk etc. At this point you should have a very good reason to say "I need Xgb of memory" for something and you can't work around it by improving your algorithms or memory allocation patterns. Generally this will only usually be the case for algorithms operating on large datasets (like a database or some scientific analysis program) and then techniques like caching and memory mapped IO become useful.</p>
|
<p>If everything else fails, in addition to increasing the max heap size try also increasing the swap size. For Linux, as of now, relevant instructions can be found in <a href="https://linuxize.com/post/create-a-linux-swap-file/" rel="nofollow noreferrer">https://linuxize.com/post/create-a-linux-swap-file/</a>.</p>
<p>This can help if you're e.g. compiling something big in an embedded platform.</p>
| 5,799
|
<p>How do I make icons for my exe file when compiling my Python program?</p>
|
<p>I was searching for this a while ago, and found this: <a href="http://www.mail-archive.com/pygame-users@seul.org/msg05619.html" rel="nofollow noreferrer">http://www.mail-archive.com/pygame-users@seul.org/msg05619.html</a></p>
<p>Quote from above link:</p>
<blockquote>
<p>The setup.py File: PY_PROG =</p>
<p>'trek10.py' APP_NAME = 'Trek_Game'</p>
<p>cfg = {</p>
<pre><code>'name':APP_NAME,
'version':'1.0',
'description':'',
'author':'',
'author_email':'',
'url':'',
'py2exe.target':'',
'py2exe.icon':'icon.ico', #64x64
'py2exe.binary':APP_NAME, #leave off the .exe, it will be added
'py2app.target':'',
'py2app.icon':'icon.icns', #128x128
'cx_freeze.cmd':'~/src/cx_Freeze-3.0.3/FreezePython',
'cx_freeze.target':'',
'cx_freeze.binary':APP_NAME,
}
</code></pre>
<p>--snip--</p>
</blockquote>
|
<p>I have no experience with py2exe but a quick <a href="http://www.google.com/search?q=py2exe+embed+icon" rel="nofollow noreferrer">google search</a> found <a href="http://www.py2exe.org/index.cgi/CustomIcons" rel="nofollow noreferrer">this</a>, if <em>embedding</em> icons in exe files was what you asked for. </p>
<p>If you want to <em>create</em> .ico files, I'd really suggest you search for a icon designer or finished icons. Sure you <em>can</em> create a Win 3.x style icon fairly easy by creating a 16x16, 32x32, or 64x64 px image in paint, and rename it to .ico. But to create modern multi resolution icons for windows is a lot more complicated.</p>
<p>(I was about to ask what OS you was compiling for, when I realized "exe" sounds very windows, and sure enough...)</p>
| 36,874
|
<p>How do you draw a custom button next to the minimize, maximize and close buttons within the Titlebar of the Form?</p>
<p>I know you need to use Win32 API calls and override the WndProc procedure, but I haven't been able to figure out a solution that works right.</p>
<p>Does anyone know how to do this? More specifically, does anyone know a way to do this that works in Vista?</p>
|
<p>The following will work in XP, I have no Vista machine handy to test it, but I think your issues are steming from an incorrect hWnd somehow. Anyway, on with the poorly commented code.</p>
<pre><code>// The state of our little button
ButtonState _buttState = ButtonState.Normal;
Rectangle _buttPosition = new Rectangle();
[DllImport("user32.dll")]
private static extern IntPtr GetWindowDC(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern int GetWindowRect(IntPtr hWnd,
ref Rectangle lpRect);
[DllImport("user32.dll")]
private static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
protected override void WndProc(ref Message m)
{
int x, y;
Rectangle windowRect = new Rectangle();
GetWindowRect(m.HWnd, ref windowRect);
switch (m.Msg)
{
// WM_NCPAINT
case 0x85:
// WM_PAINT
case 0x0A:
base.WndProc(ref m);
DrawButton(m.HWnd);
m.Result = IntPtr.Zero;
break;
// WM_ACTIVATE
case 0x86:
base.WndProc(ref m);
DrawButton(m.HWnd);
break;
// WM_NCMOUSEMOVE
case 0xA0:
// Extract the least significant 16 bits
x = ((int)m.LParam << 16) >> 16;
// Extract the most significant 16 bits
y = (int)m.LParam >> 16;
x -= windowRect.Left;
y -= windowRect.Top;
base.WndProc(ref m);
if (!_buttPosition.Contains(new Point(x, y)) &&
_buttState == ButtonState.Pushed)
{
_buttState = ButtonState.Normal;
DrawButton(m.HWnd);
}
break;
// WM_NCLBUTTONDOWN
case 0xA1:
// Extract the least significant 16 bits
x = ((int)m.LParam << 16) >> 16;
// Extract the most significant 16 bits
y = (int)m.LParam >> 16;
x -= windowRect.Left;
y -= windowRect.Top;
if (_buttPosition.Contains(new Point(x, y)))
{
_buttState = ButtonState.Pushed;
DrawButton(m.HWnd);
}
else
base.WndProc(ref m);
break;
// WM_NCLBUTTONUP
case 0xA2:
// Extract the least significant 16 bits
x = ((int)m.LParam << 16) >> 16;
// Extract the most significant 16 bits
y = (int)m.LParam >> 16;
x -= windowRect.Left;
y -= windowRect.Top;
if (_buttPosition.Contains(new Point(x, y)) &&
_buttState == ButtonState.Pushed)
{
_buttState = ButtonState.Normal;
// [[TODO]]: Fire a click event for your button
// however you want to do it.
DrawButton(m.HWnd);
}
else
base.WndProc(ref m);
break;
// WM_NCHITTEST
case 0x84:
// Extract the least significant 16 bits
x = ((int)m.LParam << 16) >> 16;
// Extract the most significant 16 bits
y = (int)m.LParam >> 16;
x -= windowRect.Left;
y -= windowRect.Top;
if (_buttPosition.Contains(new Point(x, y)))
m.Result = (IntPtr)18; // HTBORDER
else
base.WndProc(ref m);
break;
default:
base.WndProc(ref m);
break;
}
}
private void DrawButton(IntPtr hwnd)
{
IntPtr hDC = GetWindowDC(hwnd);
int x, y;
using (Graphics g = Graphics.FromHdc(hDC))
{
// Work out size and positioning
int CaptionHeight = Bounds.Height - ClientRectangle.Height;
Size ButtonSize = SystemInformation.CaptionButtonSize;
x = Bounds.Width - 4 * ButtonSize.Width;
y = (CaptionHeight - ButtonSize.Height) / 2;
_buttPosition.Location = new Point(x, y);
// Work out color
Brush color;
if (_buttState == ButtonState.Pushed)
color = Brushes.LightGreen;
else
color = Brushes.Red;
// Draw our "button"
g.FillRectangle(color, x, y, ButtonSize.Width, ButtonSize.Height);
}
ReleaseDC(hwnd, hDC);
}
private void Form1_Load(object sender, EventArgs e)
{
_buttPosition.Size = SystemInformation.CaptionButtonSize;
}
</code></pre>
|
<p>Drawing seems to be the easy part, the following will do that:</p>
<p>[Edit: Code removed, see my other answer]</p>
<p>The real problem is changing the state and detecting clicks on the button... for that you'll need to hook into the global message handler for the program, .NET seems to hide the mouse events for a form while not in the actual container areas (ie. mouse moves and clicks on the title bar). I'm looking for info on that, found it now, I'm working on it, shouldn't be too hard... If we can figure out what these messages are actually passing.</p>
| 13,249
|
<p>We are using Linq To SQL with our own data context logic that executes the one linq query across multiple databases. When we get the results back, we need the database for each of the rows. So...</p>
<p>I want to have a property on my class that will return the database name (SQL Server, so DB_NAME()). How can I do this in Linq To Sql?</p>
<hr>
<p>Dave, thanks for the answer, but we have hundreds of databases and don't want to have to add views if possible.</p>
|
<p>I tried to do that recently and couldn't get it to work. What I ended up doing is sending a variable at startup. So say you have an environment variable called $LOG_LEVEL:</p>
<pre><code><level value="${log_level}" />
</code></pre>
<p>and at startup...</p>
<pre><code>java -Dlog_level=$LOG_LEVEL your_app
</code></pre>
|
<p>Create a system variable. I prefer to use setenv.bat for such variables.</p>
<pre><code>@echo off
rem app specific log dir
set "APP_LOG_ROOTDIR=../app/app-log"
exit /b 0
</code></pre>
<p>Add reference in log4j.xml file</p>
<pre><code><appender name="fileAppender" class="org.apache.log4j.RollingFileAppender">
<param name="Threshold" value="DEBUG" />
<param name="MaxFileSize" value="512KB" />
<param name="MaxBackupIndex" value="10" />
<param name="File" value="${APP_LOG_ROOTDIR}/app.log"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %-5p %c{1} %m %n" />
</layout>
</appender>
</code></pre>
| 24,564
|
<p>I have implemented a python webserver. Each http request spawns a new thread.
I have a requirement of caching objects in memory and since its a webserver, I want the cache to be thread safe. Is there a standard implementatin of a thread safe object cache in python? I found the following </p>
<p><a href="http://freshmeat.net/projects/lrucache/" rel="noreferrer">http://freshmeat.net/projects/lrucache/</a></p>
<p>This does not look to be thread safe. Can anybody point me to a good implementation of thread safe cache in python?</p>
<p>Thanks!</p>
|
<p>Well a lot of operations in Python are thread-safe by default, so a standard dictionary should be ok (at least in certain respects). This is mostly due to the GIL, which will help avoid some of the more serious threading issues.</p>
<p>There's a list here: <a href="http://coreygoldberg.blogspot.com/2008/09/python-thread-synchronization-and.html" rel="noreferrer">http://coreygoldberg.blogspot.com/2008/09/python-thread-synchronization-and.html</a> that might be useful.</p>
<p>Though atomic nature of those operation just means that you won't have an entirely inconsistent state if you have two threads accessing a dictionary at the same time. So you wouldn't have a corrupted value. However you would (as with most multi-threading programming) not be able to rely on the specific order of those atomic operations.</p>
<p>So to cut a long story short...</p>
<p>If you have fairly simple requirements and aren't to bothered about the ordering of what get written into the cache then you can use a dictionary and know that you'll always get a consistent/not-corrupted value (it just might be out of date).</p>
<p>If you want to ensure that things are a bit more consistent with regard to reading and writing then you might want to look at Django's local memory cache:</p>
<p><a href="http://code.djangoproject.com/browser/django/trunk/django/core/cache/backends/locmem.py" rel="noreferrer">http://code.djangoproject.com/browser/django/trunk/django/core/cache/backends/locmem.py</a></p>
<p>Which uses a read/write lock for locking.</p>
|
<p>For a thread safe object you want threading.local:</p>
<pre><code>from threading import local
safe = local()
safe.cache = {}
</code></pre>
<p>You can then put and retrieve objects in <code>safe.cache</code> with thread safety.</p>
| 26,239
|
<p>Is it possible to change the font size used in a ContextMenu using the .NET Framework 3.5 and C# for a desktop application? It seems it's a system-wide setting, but I would like to change it only within my application.</p>
|
<p>If you are defining your own context menu via a <code>ContextMenuStrip</code> in Windows Forms, use the <em>Font</em> property.</p>
<p>If you are defining your own context menu via a <code>ContextMenu</code> in WPF, use the various <em>Fontxxx</em> properties such as <em>FontFamily</em> and <em>FontSize</em>.</p>
<p>You cannot change the default context menus that come with controls; those are determined by system settings. So if you want the "Copy/Cut/Paste/etc." menu with a custom font size for a WinForms <code>TextBox</code>, you'll have to create a <code>ContextMenuStrip</code> with the appropriate font size and assign it to the <code>TextBox</code>'s <em>ContextMenuStrip</em> property.</p>
|
<p>You mention .NET 3.5 - are you writing in WPF? If so, you can specify font size for the TextBlock.FontSize attached property</p>
<pre><code><Whatever.ContextMenu TextBlock.FontSize="12">
<MenuItem ... /> <!-- Will get the font size from parent -->
</Whatever.ContextMenu>
</code></pre>
<p>Or, you could specify it in a style that affects all menu items</p>
<pre><code><Style TargetType="MenuItem">
<Setter Property="TextBlock.FontSize" Value="12" />
</Style>
</code></pre>
<p>Of course, it's always better to let the system setting determine the font size. Some people may have changed it to better fit their physical condition (like poor eye sight) or hardware (big/small screen). Whatever you force in your code will be the wrong choice for some people, while you give them no way to change it.</p>
| 12,211
|
<p>I have a couple of tables in a SQL 2008 server that I need to generate unique ID's for. I have looked at the "identity" column but the ID's really need to be unique and shared between all the tables. </p>
<p>So if I have say (5) five tables of the flavour "asset infrastructure" and I want to run with a unique ID between them as a combined group, I need some sort of generator that looks at all (5) five tables and issues the next ID which is not duplicated in any of those (5) five tales. </p>
<p>I know this could be done with some sort of stored procedure but I'm not sure how to go about it. Any ideas?</p>
|
<p>Why not use a GUID?</p>
|
<p>I found this when searching on google. I am facing a simillar problem for the first time. I had the idea to have a dedicated ID table specifically to generate the IDs but I was unsure if it was something that was considered OK design. So I just wanted to say THANKS for confirmation.. it looks like it is an adequate sollution although not ideal. </p>
| 37,660
|
<p>This is something I've always wondered, and I can't find any mention of it anywhere online. When a shop from, say Japan, writes code, would I be able to read it in English? Or do languages, like C, PHP, anything, have Japanese translations that they write?</p>
<p>I guess what I'm asking is does every single coder in the world know enough English to use the exact same reserved words I do?</p>
<p>Would this code:</p>
<pre><code>If (i < size){
switch
case 1:
print "hi there"
default:
print "no, thank you"
} else {
print "yes, thank you"
}
</code></pre>
<p>display the exact same as I'm seeing it right now in English, or would some other non-English-speaking person see the words "if", "switch", "case", "default", "print", and "else" in their native language?</p>
<p>EDIT - yes, this is serious. I didn't know if different localizations of a language have different keywords. or if there are even different localizations at all.</p>
|
<p>If I understood well the question actually is: "does every single coder in the world know enough English to use the exact same reserved words as I do?"</p>
<p>Well.. English is not the subject here but programming language reserved words. I mean, when I started about 10 yrs ago, I didn't have any clue of English, and still I was able to program simple things by learning the programming language, even when I did not know what they meant ( in English ). As a matter of fact this helped me to learn English.</p>
<p>For example. I know to do an "iteración" ( iteration of course ) I had to write:</p>
<pre><code> for( i = 0 ; i < 100 ; i++ ) {}
</code></pre>
<p>To me, the "for", the ";" and the "++" were simple foreign words or symbols. Later I learned that "for" meant "para", "while" meant "mientras", etc. But, in the meantime, I did not need to know English, what I needed was to know was "C".</p>
<p>Of course when I needed to learn more things, I had to learn English, for the documentation is written in that language.</p>
<p>So the answer is: No, I don't see if, while, for etc. in my native language. I see them in English, but they didn't mean to me any other thing that they meant for the programming language in turn.</p>
<p>Is like switch statement in bash: case .. esac. What Is "esac"... for me the end of the switch statement in bash.</p>
<p>I guess that's what we call "abstraction"</p>
|
<p>I think WordBasic was localized. WordBasic was used to write macro's for in Word before VBA was used.</p>
<p>If I remember it correctly, only WordBasic written in the English version would execute on all localized version. If you would write a Dutch version, you could only execute it on a Dutch Word.</p>
| 24,797
|
<p>Calling all PHP gurus!</p>
<p>I understand that you can use getimagesize() to get the actual pixel height and width of an image in PHP. However, if you open an image in photoshop and look at the image size dialog, you notice that there is a resolution value that determines the print size of the image.</p>
<p>Given an arbitrary jpg image file, I need to use PHP to determine this resolution number. It appears that this information is stored in the jpg file somewhere, so how do I get to it?</p>
<p>One other requirement - I only have gdlib available to me. I need to do this without the use of other php libraries (imagemagick, etc.)</p>
<p>Thanks for the help!</p>
|
<p>You could just read the JPEG file directly, bytes 14-18 specify:</p>
<ul>
<li>byte 14: 01, X and Y density unit specifier (00: none, pixel ratios, 01: DPI,02: DPC)</li>
<li>bytes 15-16: horizontal pixel density,</li>
<li>byte 16-18: vertical pixel densit</li>
</ul>
<p>Also see: <a href="http://www.obrador.com/essentialjpeg/headerinfo.htm" rel="noreferrer">http://www.obrador.com/essentialjpeg/headerinfo.htm</a></p>
|
<p>Depending on how the image is saved, EXIF contains a metric crapload of information - Read more about it in the <a href="http://php.net/exif" rel="nofollow noreferrer">PHP manual</a>. You may need to parse/process the results a bit, however (e.g. the flash info is, or at least has been, just a byte, expressing various states).</p>
| 32,785
|
<p>That's basically the question, is there a "right" way to implement <code>operator<<</code> ?
Reading <a href="http://bytes.com/forum/thread170304.html" rel="noreferrer">this</a> I can see that something like:</p>
<pre><code>friend bool operator<<(obj const& lhs, obj const& rhs);
</code></pre>
<p>is preferred to something like </p>
<pre><code>ostream& operator<<(obj const& rhs);
</code></pre>
<p>But I can't quite see why should I use one or the other.</p>
<p>My personal case is:</p>
<pre><code>friend ostream & operator<<(ostream &os, const Paragraph& p) {
return os << p.to_str();
}
</code></pre>
<p>But I could probably do:</p>
<pre><code>ostream & operator<<(ostream &os) {
return os << paragraph;
}
</code></pre>
<p>What rationale should I base this decision on?</p>
<p><em>Note</em>:</p>
<pre><code> Paragraph::to_str = (return paragraph)
</code></pre>
<p>where paragraph's a string.</p>
|
<p>The problem here is in your interpretation of the article you <a href="http://bytes.com/forum/thread170304.html" rel="noreferrer">link</a>.</p>
<h3>Equality</h3>
<p>This article is about somebody that is having problems correctly defining the bool relationship operators.</p>
<p>The operator:</p>
<ul>
<li>Equality == and !=</li>
<li>Relationship < > <= >=</li>
</ul>
<p>These operators should return a bool as they are comparing two objects of the same type. It is usually easiest to define these operators as part of the class. This is because a class is automatically a friend of itself so objects of type Paragraph can examine each other (even each others private members).</p>
<p>There is an argument for making these free standing functions as this lets auto conversion convert both sides if they are not the same type, while member functions only allow the rhs to be auto converted. I find this a paper man argument as you don't really want auto conversion happening in the first place (usually). But if this is something you want (I don't recommend it) then making the comparators free standing can be advantageous.</p>
<h3>Streaming</h3>
<p>The stream operators:</p>
<ul>
<li>operator << output</li>
<li>operator >> input</li>
</ul>
<p>When you use these as stream operators (rather than binary shift) the first parameter is a stream. Since you do not have access to the stream object (its not yours to modify) these can not be member operators they have to be external to the class. Thus they must either be friends of the class or have access to a public method that will do the streaming for you.</p>
<p>It is also traditional for these objects to return a reference to a stream object so you can chain stream operations together.</p>
<pre><code>#include <iostream>
class Paragraph
{
public:
explicit Paragraph(std::string const& init)
:m_para(init)
{}
std::string const& to_str() const
{
return m_para;
}
bool operator==(Paragraph const& rhs) const
{
return m_para == rhs.m_para;
}
bool operator!=(Paragraph const& rhs) const
{
// Define != operator in terms of the == operator
return !(this->operator==(rhs));
}
bool operator<(Paragraph const& rhs) const
{
return m_para < rhs.m_para;
}
private:
friend std::ostream & operator<<(std::ostream &os, const Paragraph& p);
std::string m_para;
};
std::ostream & operator<<(std::ostream &os, const Paragraph& p)
{
return os << p.to_str();
}
int main()
{
Paragraph p("Plop");
Paragraph q(p);
std::cout << p << std::endl << (p == q) << std::endl;
}
</code></pre>
|
<p><code>operator<<</code> implemented as a friend function:</p>
<pre><code>#include <iostream>
#include <string>
using namespace std;
class Samp
{
public:
int ID;
string strName;
friend std::ostream& operator<<(std::ostream &os, const Samp& obj);
};
std::ostream& operator<<(std::ostream &os, const Samp& obj)
{
os << obj.ID<< “ ” << obj.strName;
return os;
}
int main()
{
Samp obj, obj1;
obj.ID = 100;
obj.strName = "Hello";
obj1=obj;
cout << obj <<endl<< obj1;
}
</code></pre>
<blockquote>
<p>OUTPUT:<br>
100 Hello<br>
100 Hello</p>
</blockquote>
<p>This can be a friend function only because the object is on the right hand side of <code>operator<<</code> and argument <code>cout</code> is on the left hand side. So this can't be a member function to the class, it can only be a friend function.</p>
| 29,302
|
<p>I was trying to solve my <a href="https://stackoverflow.com/questions/254718/how-do-you-use-fonts-after-installing-xna">XNA Font problem</a>, when I found this <a href="http://www.xnaresources.com/pages.asp?pageid=33" rel="nofollow noreferrer">here</a>:</p>
<blockquote>
<p>Visual Studio doesn’t recognize any
fonts you add after it is up and
running.</p>
</blockquote>
<p>Is there a way to use fonts installed after Visual Studio?</p>
<p>After finding out that is was the Font file why would the tutorial mention something like that ?</p>
|
<p>I have successfully installed a <a href="http://www.proggyfonts.com/index.php?menu=download" rel="noreferrer">PROGGY</a> font. It was usable after I restarted VC6.</p>
<p>I suspect they are talking about restarting your visual studio, instead of reinstalling your visual studio.</p>
|
<p>I'd imagine this is only true until you restart the IDE. Easy enough to test, isn't it?</p>
| 31,925
|
<p>I am working on an application which draws a simple dot grid. I would like the mouse to snap between the points on the grid, eventually to draw lines on the grid.</p>
<p>I have a method which takes in the current mouse location (X,Y) and calculates the nearest grid coordinate.</p>
<p>When I create an event and attempt to move the mouse to the new coordinate the whole system becomes jerky. The mouse doesn't snap smoothly between grid points.</p>
<p>I have copied a code sample below to illustrate what I am attempting to do. Does anyone have any advice they could offer me as to how I can eliminate the jumpiness within the mouse movement?</p>
<hr>
<pre><code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace GridTest
{
public partial class Form1 : Form
{
Graphics g;
const int gridsize = 20;
public Form1()
{
InitializeComponent();
g = splitContainer1.Panel2.CreateGraphics();
splitContainer1.Panel2.Invalidate();
}
private void splitContainer1_Panel2_Paint(object sender, PaintEventArgs e)
{
Drawgrid();
}
private void Drawgrid()
{
for (int x = 0; x < splitContainer1.Panel2.ClientSize.Width; x += gridsize)
{
for (int y = 0; y < splitContainer1.Panel2.ClientSize.Height; y += gridsize)
{ g.DrawLine(Pens.Black, new Point(x, y), new Point(x + 1, y)); }
}
}
private void splitContainer1_Panel2_MouseMove(object sender, MouseEventArgs e)
{
Point newPosition = new Point();
newPosition = RoundToNearest(gridsize, e.Location);
Cursor.Position = splitContainer1.Panel2.PointToScreen(newPosition);
}
private Point RoundToNearest(int nearestRoundValue, Point currentPoint)
{
Point newPoint = new Point();
int lastDigit;
lastDigit = currentPoint.X % nearestRoundValue;
if (lastDigit >= (nearestRoundValue/2))
{ newPoint.X = currentPoint.X - lastDigit + nearestRoundValue; }
else
{ newPoint.X = currentPoint.X - lastDigit; }
lastDigit = currentPoint.Y % nearestRoundValue;
if (lastDigit >= (nearestRoundValue / 2))
{ newPoint.Y = currentPoint.Y - lastDigit + nearestRoundValue; }
else
{ newPoint.Y = currentPoint.Y - lastDigit; }
return newPoint;
}
}
}
</code></pre>
|
<p>Don't modify the cursor position. You don't need to.</p>
<p>Instead, <em>draw</em> as if it was snapped to the grid. When the user clicks somewhere, just draw the line from the nearest grid points.</p>
<p>For instance, if the user clicks on (197,198), but you know that the nearest point actually is (200,200), just draw a line to (200,200) instead of (197,198).</p>
<p>And please, don't mess with the <em>actual</em> cursor position.</p>
<hr>
<p>I don't know if there's some way to hide the mouse cursor. If there is, you can hide it and draw it yourself, <em>without modifying the real position</em>.</p>
|
<p>I agree with ruijoel, do not mess with the cursor position.
It is better to have a cross or a ring that is drawn at the snap point to show the user which point is the one that will be snapped to at a click event.</p>
<p>For this to work well you may want to look at xor-drawing so that item is erased once you move to a new snap point.</p>
| 46,849
|
<p>A few years ago we started playing around with <a href="http://www.w3.org/MarkUp/Forms/" rel="noreferrer">XForms</a> from the W3C for a web app which required hundreds of custom forms.</p>
<p>As they aren't currently supported natively by the major browsers, what parsers/tools are you using on your projects today?</p>
<p>I'm not really interested in plugins - this needs to be something server side that emulates XForms.</p>
|
<p>We use XForms for creating user interfaces for SOAP-based web services. Currently we settled with <strong>Chiba</strong> XForms engine (<a href="http://chiba.sourceforge.net/" rel="nofollow noreferrer">http://chiba.sourceforge.net/</a>), but <strong>Orbeon</strong> (<a href="http://www.orbeon.com" rel="nofollow noreferrer">http://www.orbeon.com/</a>) actually seems more mature. Both are server-side engines, which convert XForms into HTML on the fly. The validation is performed on server side with the help of AJAX. This puts quite high demands on the server, so I wouldn't bet on those engines when creating sites with heavy traffic. Alternatives are well documented on XForms Wikipedia page: <a href="http://en.wikipedia.org/wiki/XForms" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/XForms</a>.</p>
|
<p>I do not use them and as they are not supported by any major browsers I doubt that anybody else will use them very often either.</p>
| 10,652
|
<p>Currently we have mutiple projects sharing a JIRA instances. We want to make it such that the users only view the projects that they are doing testing.</p>
<p>But however we are currently groupging these users to the standard grouping jira-users.</p>
<p>What is the best way to filter out JIRA project that only certain users can see and access</p>
|
<p>Personally I'm all for project roles. I have a general permission scheme that allows all users/groups defined in project roles to browse the project, which leaves the project administrator/manager to define which groups can view their project. So by removing or adding jira-users (default group that a user would have to be a part of to even log into JIRA) to thier project's "users" project role, the project manager can control if all users can view their project or not.</p>
|
<p>The best and dynamic way of solving this problem is with the help of security levels and setting the security levels based on the issue at run time using a post function.</p>
| 30,619
|
<p>I'm working on a localized application which I develop in SharpDevelop. Based on a <a href="http://www.devhood.com/tutorials/tutorial_details.aspx?tutorial_id=211" rel="nofollow noreferrer">tutorial</a> I ran into an error:</p>
<blockquote>
<p>Could not find any resources appropriate for the specified culture (or the neutral culture) on disk. baseName: </p>
</blockquote>
<p>I created the ressource file using Project | Add | New item respective "Empty ressource file" (I couldn't find "Assembly Resource file"). Furthermore I've set the "Build action" to "EmbeddedResource".</p>
<p>Within the program I have a class which does the following</p>
<pre><code>// load the resource file once
resourceManager = ResourceManager.CreateFileBasedResourceManager(file, filePath, null);
// depending on user selection, I set the CultureInfo in the code behind the form, i.e.
Thread.CurrentThread.CurrentUICulture = locales[0]; // which contains "en"
// and that's the method of the same class used to lookup the values
public string getValue ( string key )
{
return resourceManager.GetString(key);
}
</code></pre>
<p>SharpDevelop 3.0.0.3437
.NET Version 2.0.50727.3053</p>
<p>Even after carefully going through the comments and googling for a long while, I couldn't find an example or a solution. Hence the questions:</p>
<ul>
<li>How can I add the culture to the ressource file itself? </li>
<li>Can you provide an example or link?</li>
</ul>
<p>Many thanks!</p>
|
<p>CreateFileBasedResourceManager will only deal with binary .resources files (not .resx files).</p>
<p>If you insist on loading resources from external file rather than embed the resources into the assembly,
you will need to run the resgen command line utility to generate a .resources file.
So if you haven't done that, generate one for each supported culture.</p>
<p>Otherwise it looks OK.</p>
<p>But if you would rather embed resources into assembly, in the properties window, set the Build Action to Embedded Resource.</p>
<p>If you want also want a strongly typed class generated taking care of all the dirty work,
set the Custom Tool on the <em>base file only</em> (the invariant one) to ResXFileCodeGenerator,
or PublicResXFileCodeGenerator if you need that (good when creating satellite assemblies).</p>
<p>Then you don't need to take care of loading the localized resources yourself.
The generated class does all this for you.</p>
<p>For each key in the resource, a static property is generated in the generated class, and you'll just invoke this property,
it is very clean and by far the easiest way.</p>
<p>Unless there are special reasons for loading resources from .resources files,
i would always recommend embedding them into the (an) assembly.</p>
|
<p>I'm not sure what version of .NET you are using but this MSDN article on <a href="http://msdn.microsoft.com/en-us/library/yx7xezcf.aspx" rel="nofollow noreferrer">how the runtime locates assemblies</a> may be of service to you.</p>
| 39,362
|
<p>What is the easiest way, preferably using recursion, to find the shortest root-to-leaf path in a BST (Binary Search Tree). Java prefered, pseudocode okay.</p>
<p>Thanks!</p>
|
<p><strong>General description:</strong></p>
<p>Use a <a href="http://en.wikipedia.org/wiki/Breadth-first_search" rel="noreferrer">Breadth-first search (BFS)</a> as opposed to a <a href="http://en.wikipedia.org/wiki/Depth-first_search" rel="noreferrer">Depth-first search (DFS)</a>. Find the first node with no children. </p>
<p>Using a DFS you might get lucky on some input trees (but there is no way to know you got lucky so you still need to search the whole tree), but using the BFS method is much faster and you can find a solution without touching all nodes.</p>
<p>To find the root to leaf path, you could follow the first found childless node all the way back up to the root using the parent reference. If you have no parent reference stored in each node, you can keep track of the parent nodes as you recurse down. If you have your list in reverse order you could push it all on a stack and then pop it off.</p>
<p><strong>Pseudo-code:</strong></p>
<p>The problem is very simple; here is pseudo code to find the smallest length:</p>
<ol>
<li>Put the root node on the queue.</li>
</ol>
<p>Repeat while the queue is not empty, and no result was found:</p>
<ol start="2">
<li>Pull a node from the beginning of the queue and check if it has no children. If it has no children you
are done you found the shortest path.</li>
<li>Otherwise push all the children (left, right) onto the queue.</li>
</ol>
<p><strong>Finding all shortest paths:</strong></p>
<p>To find all shortest paths you can store the depth of the node along with node inside the queue. Then you would continue the algorithm for all nodes in the queue with the same depth.</p>
<p><strong>Alternative:</strong></p>
<p>If instead you decided to use a DFS, you would have to search the entire tree to find the shortest path. But this could be optimized by keeping a value for the shortest so far, and only checking the depth of future nodes up until you find a new shortest, or until you reach the shortest so far. The BFS is a much better solution though.</p>
|
<p>Breadth first search is exactly optimal in terms of the number of vertices visited. You have to visit every one of the vertices you'd visit in a breadth first search just in order to prove you have the closest leaf!</p>
<p>However, if you have a mandate to use recursion, Mike Thompson's approach is <em>almost</em> the right one to use -- and is slightly simpler.</p>
<pre><code>TD(p) is
0 if p is NULL (empty tree special case)
1 if p is a leaf (p->left == NULL and p->right == NULL)
min(TD(p->left), TD(p->right)) if p is not a leaf
</code></pre>
| 13,780
|
<p>I want to close a System.Windows.Forms.Form if the user clicks anywhere outside it. I've tried using IMessageFilter, but even then none of the messages are passed to PreFilterMessage. How do I receive clicks outside a form's window?</p>
|
<p>With thanks to <a href="https://stackoverflow.com/users/36388/p-daddy">p-daddy</a> in <a href="https://stackoverflow.com/questions/298626/what-do-these-wndproc-codes-mean">this question</a>, I've found this solution which allows me to use ShowDialog:</p>
<pre><code>protected override void OnShown(EventArgs e)
{
base.OnShown(e);
this.Capture = true;
}
protected override void OnCaptureChanged(EventArgs e)
{
if (!this.Capture)
{
if (!this.RectangleToScreen(this.DisplayRectangle).Contains(Cursor.Position))
{
this.Close();
}
else
{
this.Capture = true;
}
}
base.OnCaptureChanged(e);
}
</code></pre>
|
<p>If it is a child form in an MDI application, you could trap the click in the parent form, otherwise the solution will be messy.</p>
<p>I am not convinced what you suggest represents intuitive UI behaviour anyway. Are you sure that is the best design?</p>
| 38,210
|
<p>I've got a new varchar(10) field in a database with 1000+ records. I'd like to update the table so I can have random data in the field. I'm looking for a SQL solution.</p>
<p>I know I can use a cursor, but that seems inelegant.</p>
<p>MS-SQL 2000,BTW</p>
|
<pre><code>update MyTable Set RandomFld = CONVERT(varchar(10), NEWID())
</code></pre>
|
<p>If this is a one time thing just to get data into the system I really see no issue with using a cursor as much as I hate cursors they do have their place. </p>
| 10,945
|
<p>I'm wondering if the need to alter the indentation of code to adjust the nesting has any adverse effects on merging changes in a system like SVN.</p>
|
<p>I've used python with SVN and Mercurial, and have no hassles merging.</p>
<p>It all depends on how the diffing is done - and I suspect that it is character-by-character, which would notice the difference between one level of indent and another.</p>
|
<p>Generally source control systems merge on a line-by-line basis by default. I have found that merging Python code is no different from merging any other source code that is reasonably indented. If one programmer wraps a block of code in an <code>if</code> statement (indenting the whole block), and another programmer modifies something inside the block, then there will be a merge conflict. Fortunately, the conflict in this case is super easy to resolve.</p>
<p>If you use an external merge tool, then your tool may support more detailed textual merging algorithms that take the above scenario into account automatically.</p>
| 14,522
|
<p>What I want to do is something like this: I have enums with combined flagged values.</p>
<pre><code>public static class EnumExtension
{
public static bool IsSet<T>( this T input, T matchTo )
where T:enum //the constraint I want that doesn't exist in C#3
{
return (input & matchTo) != 0;
}
}
</code></pre>
<p>So then I could do:</p>
<pre><code>MyEnum tester = MyEnum.FlagA | MyEnum.FlagB
if( tester.IsSet( MyEnum.FlagA ) )
//act on flag a
</code></pre>
<p>Unfortunately, C#'s generic where constraints have no enum restriction, only class and struct. C# doesn't see enums as structs (even though they are value types) so I can't add extension types like this.</p>
<p>Does anyone know a workaround?</p>
|
<p><strong>EDIT: This is now live in version 0.0.0.2 of UnconstrainedMelody.</strong></p>
<p>(As requested on my <a href="http://codeblog.jonskeet.uk/2009/09/10/generic-constraints-for-enums-and-delegates/" rel="noreferrer">blog post about enum constraints</a>. I've included the basic facts below for the sake of a standalone answer.)</p>
<p>The best solution is to wait for me to include it in <a href="https://github.com/jskeet/unconstrained-melody" rel="noreferrer">UnconstrainedMelody</a><sup>1</sup>. This is a library which takes C# code with "fake" constraints such as</p>
<pre><code>where T : struct, IEnumConstraint
</code></pre>
<p>and turns it into</p>
<pre><code>where T : struct, System.Enum
</code></pre>
<p>via a postbuild step.</p>
<p>It shouldn't be too hard to write <code>IsSet</code>... although catering for both <code>Int64</code>-based and <code>UInt64</code>-based flags could be the tricky part. (I smell some helper methods coming on, basically allowing me to treat any flags enum as if it had a base type of <code>UInt64</code>.)</p>
<p>What would you want the behaviour to be if you called</p>
<pre><code>tester.IsSet(MyFlags.A | MyFlags.C)
</code></pre>
<p>? Should it check that <em>all</em> the specified flags are set? That would be my expectation.</p>
<p>I'll try to do this on the way home tonight... I'm hoping to have a quick blitz on useful enum methods to get the library up to a usable standard quickly, then relax a bit.</p>
<p>EDIT: I'm not sure about <code>IsSet</code> as a name, by the way. Options:</p>
<ul>
<li>Includes</li>
<li>Contains</li>
<li>HasFlag (or HasFlags)</li>
<li>IsSet (it's certainly an option)</li>
</ul>
<p>Thoughts welcome. I'm sure it'll be a while before anything's set in stone anyway...</p>
<hr>
<p><sup>1</sup> or submit it as a patch, of course...</p>
|
<p>I just wanted to add Enum as a generic constraint.</p>
<p>While this is just for a tiny helper method using <a href="https://www.github.com/Fody/ExtraConstraints" rel="nofollow noreferrer"><code>ExtraConstraints</code></a> is a bit too much overhead for me.</p>
<p>I decided to just just create a <code>struct</code> constraint and add a runtime check for <code>IsEnum</code>. For converting a variable from T to Enum I cast it to object first.</p>
<pre><code> public static Converter<T, string> CreateConverter<T>() where T : struct
{
if (!typeof(T).IsEnum) throw new ArgumentException("Given Type is not an Enum");
return new Converter<T, string>(x => ((Enum)(object)x).GetEnumDescription());
}
</code></pre>
| 2,886
|
<p>I recently got an Ender 3 Pro and had a blast with it for the first few days, but then I got greedy for a better print and threw off my calibration with some "upgrades" and ended up with some really nasty elephant's foot. The first 3 mm are all bubbly and uneven as if someone heated it up and squished it slightly.</p>
<p>I've read the other forums and have made sure my belts are tight, my bed is perfectly level, and my filament is just fine. I've tried using rafts to take the blow from the deformity and that usually helps but even with my initial layer horizontal expansion setting turned to -1, I'm still getting a little bit for flaring on the base layer on the raft.</p>
<p>The upgrades I got were an aluminum extruder housing (single drive) and Capricorn tubing.</p>
<p><a href="https://i.stack.imgur.com/8TQ6d.png" rel="nofollow noreferrer" title="3D printed calibration cube with elephant's foot"><img src="https://i.stack.imgur.com/8TQ6d.png" alt="3D printed calibration cube with elephant's foot" title="3D printed calibration cube with elephant's foot" /></a></p>
<hr />
<p>After addressing the comments, now my corners on bigger prints come up and commonly fail even bed level tests... and the prints that do work (that I do print on a raft) are incredibly weak and break when I pull it off.</p>
<p>Furthermore, I’ve been fixing several things like suggested in comments and nothings worked, now for the most part every part I’ve printed that’s longer then 2 hours has failed.</p>
<p><a href="https://i.stack.imgur.com/PJQul.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PJQul.jpg" alt="enter image description here" /></a></p>
<p>Yes that is brand new capricorn tubing... the old fittings dug through my old tube and caused the filament to melt in the tube and ruin it.</p>
|
<p>The following is from the article "<a href="https://all3dp.com/2/elephant-s-foot-3d-printing-problem-easy-fixes/" rel="nofollow noreferrer">Elephant's Foot - Easy Fixes</a>" on All3DP.com</p>
<blockquote>
<p>As we’ve explained, elephant’s foot most often occurs as the result of an uncooled first layer. If the <a href="https://all3dp.com/2/the-best-printing-temperature-for-different-filaments/" rel="nofollow noreferrer">temperature</a> of the print bed is too high, or if there’s insufficient <a href="https://all3dp.com/2/3d-printer-fans-do-i-really-need-one/" rel="nofollow noreferrer">cooling</a>, the first layer may not cool properly, causing elephant’s foot.</p>
<p>Here are a few things to try to reduce or even completely resolve elephant’s foot on your prints:</p>
<ul>
<li><strong>Level the print bed and adjust your nozzle:</strong> Before trying anything else, make sure your printing conditions are ideal. Sometimes elephant’s foot is simply the result of an unleveled build plate or an incorrect nozzle height. These issues both cause the first layer to be squished too far down, forcing it to bulge out. Fortunately, they’re easy to fix, as both <a href="https://all3dp.com/2/3d-printer-bed-leveling-step-by-step-tutorial/" rel="nofollow noreferrer">leveling the build plate</a> and slightly increasing the nozzle height (in your <a href="https://all3dp.com/topic/3d-slicer/" rel="nofollow noreferrer">slicer</a>) are simple and quick.</li>
<li><strong>Lower bed temperature:</strong> Incrementally lower the temperature of your bed by 5 °C until it successfully prints without any bulging. If you lower it by more than 20 °C outside the recommended temperature and the problem isn’t getting better, the elephant’s foot is likely to be caused by something else.</li>
<li><strong>Print with a raft:</strong> Because the problem exists between the first layer and the bed, a <a href="https://all3dp.com/2/3d-printing-raft-when-should-you-use-it/" rel="nofollow noreferrer">raft</a> can take the hit for you. This is less of a solution and more of a workaround, but it can be very helpful if, for example, you really need one piece to slot into another.</li>
<li><strong>Add chamfers to your model:</strong> In some rare cases, elephant’s foot can be extremely difficult to get rid of. Instead of tweaking your printer, it may be easier to simply alter the model. By putting a small 45° chamfer on the bottom edge of the print, the effects of the elephant’s foot can be mitigated.</li>
</ul>
</blockquote>
<p>There is also a great YouTube video "Smooth Top Surface and No Elephants Foot Using Cura 4.7.1" from CHEP:</p>
<p><div class="youtube-embed"><div>
<iframe width="640px" height="395px" src="https://www.youtube.com/embed/FH1wUWy7Hjw?start=0"></iframe>
</div></div></p>
<p>I had a similar problem on my Ender 3 V2 and followed the above information and cured my issues.</p>
|
<p>I have 2 Ender 3 Max printers. Both suffered elephant's foot after the initial setup. After trying virtually every suggestion available on the internet I eventually was able to fix them. Assuming the bed is properly leveled, I feel the most common causes are:</p>
<ol>
<li>Too much tension on the X-axis guide wheels on the right side of the printer</li>
<li>Too little tension on the X-axis belt (it should be quite tight)</li>
<li>Over extrusion. If your initial layers still look rough (bumpy) along the edges it may be from the excess filament. Even after careful calibration, I had to back off the E-steps by -3 (to 95). The change was dramatic!</li>
</ol>
<p>Both printers now print the XYZ calibration cube within 0.1 mm (0.003").</p>
<p>Hope this helps.</p>
| 2,036
|
<p>I'm running into a perplexing problem with an ActiveX control I'm writing - sometimes, Internet Explorer appears to fail to properly unload the control on process shutdown. This results in the control instance's destructor not being called.</p>
<p>The control is written in C++, uses ATL and it's compiled using Visual Studio 2005. The control instance's destructor is always called when the user browses away from the page the control is embedded in - the problem only occurs when the browser is closed. </p>
<p>When I run IE under a debugger, I don't see anything unusual - the debugger doesn't catch any exceptions, access violations or assertion failures, but the problem is still there - I can set a breakpoint in the control's destructor and it's never hit when I close the broswer.</p>
<p>In addition, when I load a simple HTML page that embeds multiple instances of the control I don't see the problem. The problem only appears to happen when the control is instantiated from our web application, which inserts tags dynamically into the web page - of course, not knowing what causes this problem, I don't know whether this bit of information is relevant or not, but it does seem to indicate that this might be an IE problem, since it's data dependent. </p>
<p>When I run the simple test case under the debugger, I can set a breakpoint in the control's destructor and it's hit every time. I believe this rules out a problem with the control itself (say, an error that would prevent the destructor from ever being called, like an interface leak.)</p>
<p>I do most of my testing with IE 6, but I've seen the problem occur on IE 7, as well. I haven't tested IE 8.</p>
<p>My working hypothesis right now is that there's something in the dynamic HTML code that causes the browser to leak an interface on the ActiveX control. So far, I haven't been able to produce a good test case that reproduces this outside of the application, and the application is a bit too large to make a good test case.</p>
<p>I was hoping that someone might be able to provide insight into possible IE bugs that are known to cause this kind of behavior. The answer provided below, by the way, is too general - I'm looking for a specific set of circumstances that is known to cause this. Surely someone out there has seen this before.</p>
|
<p>To debug a problem in COM with C++ where an object's (C++) destructor is not being called, the best approach is to focus on how the COM object's refcounts are being incremented or decremented. What is probably happening is that somebody is incrementing the refcount one too many times, and then not decrementing it the same number of times. This leads to the object not being freed.</p>
<p>It is possible that your dynamic HTML is simply showing up a bug in IE, which doesn't happen if you use a static page.</p>
<p>If there is a bug in IE, the trick would be to figure out what causes the bug to appear, and what you can do to trick IE into releasing your COM object properly (like, making the HTML go away).</p>
|
<p>Another approach - add cleanup code to your <a href="http://msdn.microsoft.com/en-us/library/ms682583.aspx" rel="nofollow noreferrer">DllMain</a> function (adding that function if it doesn't already exist). Then regardless of reference counts (and reference count errors), when your DLL is unloaded you can clean yourself up:</p>
<pre><code>BOOL WINAPI DllMain(HINSTANCE, DWORD dwReason, LPVOID) {
if (dwReason == DLL_PROCESS_DETACH) {
CleanUpAnyObjectsStillAlive();
}
}
</code></pre>
<p>Oh, and a word of warning - don't take too long doing your cleanup - if you do, I can't promise the process shutdown won't kill you anyway.</p>
| 9,090
|
<p>I am trying to iterate over all the elements of a static array of strings in the best possible way. I want to be able to declare it on one line and easily add/remove elements from it without having to keep track of the number. Sounds really simple, doesn't it?</p>
<p>Possible non-solutions:</p>
<pre><code>vector<string> v;
v.push_back("abc");
b.push_back("xyz");
for(int i = 0; i < v.size(); i++)
cout << v[i] << endl;
</code></pre>
<p>Problems - no way to create the vector on one line with a list of strings</p>
<p>Possible non-solution 2:</p>
<pre><code>string list[] = {"abc", "xyz"};
</code></pre>
<p>Problems - no way to get the number of strings automatically (that I know of).</p>
<p>There must be an easy way of doing this.</p>
|
<p>C++ 11 added initialization lists to allow the following syntax:</p>
<pre><code>std::vector<std::string> v = {"Hello", "World"};
</code></pre>
<p>Support for this C++ 11 feature was added in at least <a href="http://gcc.gnu.org/projects/cxx0x.html" rel="noreferrer">GCC 4.4</a> and only in <a href="https://msdn.microsoft.com/en-us/library/hh567368.aspx#corelanguagetable" rel="noreferrer">Visual Studio 2013</a>.</p>
|
<pre><code>#include <iostream>
#include <string>
#include <vector>
#include <boost/assign/list_of.hpp>
int main()
{
const std::vector< std::string > v = boost::assign::list_of( "abc" )( "xyz" );
std::copy(
v.begin(),
v.end(),
std::ostream_iterator< std::string >( std::cout, "\n" ) );
}
</code></pre>
| 5,540
|
<p>I'm printing with opaque grey PETG on glass. The intention is to produce a house number plate, so a shiny, production quality finish on the bottom. For this reason, extruding at 245 °C with a bed at 95 °C, to give a perfect glass finish with no filament lines showing. Smaller test versions have been very promising; this seems to be the maximum temperatures before warping or a severe elephant's foot arises.</p>
<p>However when printing the full-scale version, areas of the first layer of filament seem to go completely "transparent"; there seems to be filament there - you can feel the filament "comb" when you run your finger over it, and it feels a similar thickness to its neighbours.</p>
<p>On the attached photo you might think that those gaps are simply not printed yet, however you can see on the top right corner that it's actually started on the next layer.</p>
<p><a href="https://i.stack.imgur.com/JYOVA.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JYOVA.jpg" alt="print"></a></p>
<p>What could be causing this? Is it a blockage which is interrupting flow, and maybe insufficient filament is being "stretched out"? Or maybe it could be something to do with temperature? Could it be insufficient layer height (I'm using 0.2 mm, but 0.24 mm on first layer, increasing further reveals filament lines, but tested higher and lower on smaller scale with success).</p>
<p>I've tested a range of extrude and temperatures and chosen the temps with the best results; but when I "go large" this always seems to happen. I've also calibrated the bed height using the 3 point adjustment screws on this printer (Qidi X-Plus). (The transparent areas are actually occuring in the center where the smaller test prints where working perfectly, so don't know how it could be to do with this). </p>
|
<p>Are you using Z-hop? Is there any play in the Z-axis direction? It appears that parts of the first layer are printed much thinner than other parts.</p>
<p>What can happen if there is a little play in the Z-axis direction that the nozzle doesn't return to the same level after a Z-hop movement (e.g. backlash in the leadscrew nuts).</p>
<p>The "transparent" printed part appears thinner, this must indicate that the Z positioning is not up to par.</p>
|
<p>PETG becomes transparent when the layers completely fuse. Translucency is from incomplete adhesion or voids left. Try small increases to flow or print width to get slightly better fill - or slow the speed (but speed might not affect how much material is output).</p>
<p>Also, I see the top surface has a pattern on it. My FDM printer always does a similar thing and it will take tuning to get it smooth. If you see the pattern repeating consistently, it is possible the extruder stepper (or its driver) is starting to fail. I've had that too.</p>
| 1,581
|
<p>My question is how do I configure an EJB 3.0 style message driven bean to use a configured JMS datasource in jboss. </p>
<p>For example, my MDB looks something like:</p>
<pre><code>@MessageDriven(mappedName = "ExampleMDB", activationConfig = {
@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Topic"),
@ActivationConfigProperty(propertyName = "destination", propertyValue = "MyTopic"),
@ActivationConfigProperty(propertyName = "channel", propertyValue = "MyChannel"),
})
@ResourceAdapter(value = "wmq.jmsra.rar")
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
@TransactionManagement(TransactionManagementType.BEAN)
public class MyMDB implements MessageListener {
.....
}
</code></pre>
<p>But I would like the bean to attached to a given JMS datasource ( in the case of jboss 4.2.2 this is in deploy/jms/jms-ds.xml). Perhaps this is not even possible but is worth asking.</p>
|
<p>bdfoy has the best large scale solution, but if you just want to install a few modules you can ask the CPAN shell to install a specific distribution by referencing a path to a tarball (relative to the top of the CPAN tree).</p>
<pre><code>cpan> install MSCHWERN/Test-Simple-0.62.tar.gz
</code></pre>
<p>Throw a URL to BackPAN into your URL list and you can install any older version.</p>
<pre><code>cpan> o conf urllist push http://backpan.perl.org/
</code></pre>
<p>This is in the <a href="https://metacpan.org/pod/CPAN#pod12" rel="noreferrer">CPAN.pm FAQ</a> under "how do I install a 'DEVELOPER RELEASE' of a module?"</p>
|
<p><a href="https://stratopan.com" rel="nofollow noreferrer">Stratopan.com</a> is another alternative. Stratopan provides private CPANs in the cloud. You can fill your Stratopan repository with specific versions of modules (and their dependencies) and then install them using the standard Perl tool chain. The repository changes only when <em>you</em> decide to change it, so you'll get always get the versions of the modules that you want.</p>
<p><em>Disclaimer: I operate Stratopan.</em></p>
| 32,580
|
<p>I need to create and copy to the clipboard some RichText with standard "formatting" like bold/italics, indents and the like. The way I'm doing it now seems kind of inelegant... I'm creating a RichTextBox item and applying my formatting through that like so:</p>
<pre><code>RichTextBox rtb = new RichTextBox();
Font boldfont = new Font("Times New Roman", 10, FontStyle.Bold);
rtb.Text = "sometext";
rtb.SelectAll()
rtb.SelectionFont = boldfont;
rtb.SelectionIndent = 12;
</code></pre>
<p>There has got to be a better way, but after a few hours of searching I was unable to come up with anything better. Any ideas?</p>
<p>Edit:
The RichTextBox (rtb) is not displayed/drawn anywhere on a form. I'm just using the object to format my RichText.</p>
|
<p>You may want to suspend the layout of the richtextbox before you do all of that, to avoid unecessary flicker. That's one of the common mistakes I used to make which made it seem "inelegant"</p>
|
<p>I know it's been a while, but check out this stackoverflow post on converting rtf to html. It would probably be way easier to get your stuff into html, manipulate it, then either display it using html or convert it back to rtf.</p>
<p><a href="https://stackoverflow.com/questions/439301/convert-rtf-to-html">Convert Rtf to HTML</a></p>
| 16,478
|
<p>I'm trying to determine the best way to truncate or drop extra decimal places in SQL without rounding. For example:</p>
<pre><code>declare @value decimal(18,2)
set @value = 123.456
</code></pre>
<p>This will automatically round <code>@value</code> to be <code>123.46</code>, which is good in most cases. However, for this project, I don't need that. Is there a simple way to truncate the decimals I don't need? I know I can use the <code>left()</code> function and convert back to a decimal. Are there any other ways?</p>
|
<pre><code>select round(123.456, 2, 1)
</code></pre>
|
<pre><code>select convert(int,@value)
</code></pre>
| 6,567
|
<p>How can I make a Property "ReadOnly" outside the Assembly (DLL) for people using the DLL but still be able to populate that property from within the assembly for them to read?</p>
<p>For example, if I have a <strong>Transaction</strong> object that needs to populate a property in a <strong>Document</strong> object (which is a child class of the <strong>Transaction</strong> class) when something happens in the <strong>Transaction</strong> object, but I just want to developer using my DLL to only be able to read that property and not change it (it should only be changed from within the DLL itself).</p>
|
<p>C#</p>
<pre><code>public object MyProp {
get { return val; }
internal set { val = value; }
}
</code></pre>
<p>VB</p>
<pre><code>Public Property MyProp As Object
Get
Return StoredVal
End Get
Friend Set(ByVal value As Object)
StoredVal = value
End Set
End Property
</code></pre>
|
<p>What language? In VB you mark the setter as Friend, in C# you use internal.</p>
| 49,580
|
<p>Currently I use the <a href="http://www.onepageprojectmanager.com/oppm/resource.html" rel="nofollow noreferrer">"One Page Project Manager" Excel Template</a> for project status reports. It contains a summary of last week's work and a forecast for the next week. For all important tasks we track, if they are comleted or not. Everything on one page. I send this report every week to all participants/stakeholders. (hint: I do not work in an agile environment)</p>
<p>How do you report your project status?</p>
|
<p>Status reporting should be brief (nobody likes to sit there for ages while every member of the team goes on and on about their status) so I'm a big fan of SOFT reports:</p>
<ul>
<li><strong>Successes</strong> - what have you achieved since the last status meeting: tasks directly off the project schedule. If possible I tried to avoid reporting x% done -- it's either done, or it's not. Reporting by % means that tasks will sit at 95% for <em>weeks</em>. This also encourages the project manager/tech lead to break down the work breakdown structure into tasks that are no longer than a few days.</li>
<li><strong>Opportunities</strong> - have you identified any opportunities: things that will help the project that aren't being considered yet (e.g.: found a better way to script something, a library that will save the project from implementing something themselves, etc)</li>
<li><strong>Future Work</strong> - what are you working on between now and the next status meeting: again, directly off the project schedule.</li>
<li><strong>Threats</strong> - have you identified anything that will impact your ability to get your scheduled work done? e.g.: a previously-unidentified hole in the requirements, support calls are taking a big chunk of your time, implementing something turns out to be harder than expected, etc.</li>
</ul>
<p>Ideally I would try and avoid doing this stuff in a big project meeting since 90% of the material is irrelevant to half the people in the room. I like to collect SOFT reports before the meeting, spend some time looking at them before the meeting and then discuss specific issues that are probably relevant to everybody during the actual meeting.</p>
|
<p>Even if you're not using Agile you would still win from tracking your progress in functionality rather than in tasks.</p>
<p>Your stakeholders most likely have no idea what '<em>refactor the t_sec_name table to add auto-increment to the identity column</em>' means and most likely would not care if it is completed or not.</p>
<p>However if you would report the progress on 'Increasing performance of adding new users to the application' you would be able to convey the information on the progress to your readers.</p>
<p>So I would report:</p>
<ul>
<li>the progress of your changes/fixes/enhancements on the functional level,
<ul>
<li>work completed</li>
<li>work in progress</li>
<li>work planned</li>
</ul></li>
<li>decisions/issues for the business/customers to address</li>
<li>risks (creating a report is a good time to update your risk register)</li>
<li>team issues (holidays, sick leaves, trainings)</li>
</ul>
| 30,080
|
<p>I want to add my own member to the StringBuilder class, but when I go to create it IntelliSense doesn't bring it up.</p>
<pre><code>public class myStringBuilder()
Inherits System.Text.[StringBuilder should be here]
....
end class
</code></pre>
<p>Is it even possible? thanks</p>
|
<p><code>StringBuilder</code> is <code>NotInheritable</code> (aka <code>sealed</code> in C#) so you cannot derive from it. You could try wrapping <code>StringBuilder</code> in your own class or consider using <a href="http://msdn.microsoft.com/en-us/library/bb384936.aspx" rel="nofollow noreferrer">extension methods</a> instead.</p>
|
<p>StringBuilder is a sealed class... so inheritance is not allowed.</p>
| 21,610
|
<p>Sorry the title isn't more help. I have a database of media-file URLs that came from two sources: </p>
<p>(1) RSS feeds and (2) manual entries. </p>
<p>I want to find the ten most-recently added URLs, but a maximum of one from any feed. To simplify, table '<code>urls</code>' has columns <code>'url, feed_id, timestamp'</code>. </p>
<p><code>feed_id=''</code> for any URL that was entered manually.</p>
<p>How would I write the query? Remember, I want the ten most-recent urls, but only one from any single <code>feed_id</code>.</p>
|
<p>Assuming feed_id = 0 is the manually entered stuff this does the trick: </p>
<pre><code>select p.* from programs p
left join
(
select max(id) id1 from programs
where feed_id <> 0
group by feed_id
order by max(id) desc
limit 10
) t on id1 = id
where id1 is not null or feed_id = 0
order by id desc
limit 10;
</code></pre>
<p>It works cause the id column is constantly increasing, its also pretty speedy. t is a table alias. </p>
<p>This was my original answer:</p>
<pre><code>(
select
feed_id, url, dt
from feeds
where feed_id = ''
order by dt desc
limit 10
)
union
(
select feed_id, min(url), max(dt)
from feeds
where feed_id <> ''
group by feed_id
order by dt desc
limit 10
)
order by dt desc
limit 10
</code></pre>
|
<p>You probably want a <a href="http://dev.mysql.com/doc/refman/5.0/en/union.html" rel="nofollow noreferrer">union</a>. Something like this should work:</p>
<pre><code> (SELECT
url, feed_id, timestamp
FROM rss_items
GROUP BY feed_id
ORDER BY timestamp DESC
LIMIT 10)
UNION
(SELECT
url, feed_id, timestamp
FROM manual_items
GROUP BY feed_id
ORDER BY timestamp DESC
LIMIT 10)
ORDER BY timestamp DESC
LIMIT 10
</code></pre>
| 14,421
|
<p>Developing websites are time-consuming. To improve productivity, I would code a prototype to show to our clients. I don't worry about making the prototype comform to the standard. Most of the time, our clients would approve the prototype and give an unreasonable deadline. I usually end up using the prototype in production (hey, the prototype works. No need to make my job harder.)</p>
<p>I could refactor the code to output valid HTML. But is it worth the effort to output valid HTML?</p>
|
<p>It is only worth the effort if it gives you a practical benefit. Sticking to standards might make it easier to build a website that works across most browsers. Then again, if you're happy with how a website displays on the browsers you care about (maybe one, maybe all), then going through hoops to make it pass validation is a waste of time.</p>
<p>Also, the difference in SEO between an all-valid html website and a mostly-valid html website is negligible. </p>
<p>So always look for the practical benefit, there are some in some situations, but don't do it just for the sake of it.</p>
|
<p>There are two rules for writing websites:</p>
<ol>
<li>The site must work for your users.</li>
<li>The site must work for your users.</li>
</ol>
<p>To meet the first rule, you have to code such that your site renders correctly when using Internet Explorer. Unless you have the freedom to alter your site design to use only those features that IE renders correctly, this means writing invalid HTML.</p>
<p>To meet the second rule, you have to code such that your site renders correctly when using screen-readers and braille screens. Although some newer screen readers can work with IE-targeted sites, in general this means writing valid HTML.</p>
<p>If you're working on a small project, or you're part of a large team, you can code a site that outputs IE-targeted HTML for IE, and valid HTML otherwise. But if you're taking on a medium-to-large project on your own, you have to decide which rule you're going to follow and which one you're going to ignore.</p>
<p>UPDATE:</p>
<p>This is getting voted down by users who think you can always get away with valid HTML in IE. That may be true if you have the flexibility to change your design to get around IE's shortcomings, but if a client has given you a design and you have to get it working, you may have to resort to invalid HTML. It's sad, but it's true, whatever they might think.</p>
| 14,556
|
<p>Are there common machines or OSs that will have problems connecting on a network where unicast ARP requests or broadcast ARP responses are not supported? I am providing a public Wi-Fi service, and considering blocking these types of ARP packet. Will this cause connectivity issues for contemporary clients?</p>
|
<p>The ARP specification has recently been updated with <a href="http://tools.ietf.org/rfcmarkup/5227" rel="nofollow noreferrer">RFC 5227</a> which talks about the use of gratuitous ARP packets for "address conflict detection".</p>
<p>If you block ARP response broadcasts this ACD is not possible.</p>
|
<p>Broadcast ARP is used by some High-Availability IP-Takeover schemes to announce the new MAC-address on switch-over.</p>
| 49,705
|
<p>We are currently using BizTalk 2006 R2 to build Enterprise Integration solutions. We use BizTalk maps extensively, but when you build a solution in Visual Studio 2005, it produces the following warning against maps:</p>
<blockquote>
<p>Warning Double-click here to show/hide compiler links.</p>
</blockquote>
<p>In my opinion, these are not real warnings and can be ignored, but I don't like that strategy because ignoring warnings is a bad habit to get into.</p>
<p>Using a \nowarn property does not seem to be an option because the message does not have an associated number.</p>
<p>Also, when the project is built using a build script the warning disappears, suggesting that this is a feature of Visual Studio rather than a real compiler warning.</p>
<p>So I was wondering if there is a way to suppress this type of warning in Visual Studio.</p>
|
<p>I don't believe there's a way to suppress these for BizTalk projects. BizTalk gurus just learn to ignore them.</p>
|
<p>You can use the /nowarn option to suppress warnings.</p>
<p>See <a href="http://msdn.microsoft.com/en-us/library/7f28x9z3(VS.80).aspx" rel="nofollow noreferrer">MSDN: /nowarn (Suppress Specified Warnings) (C# Compiler Options)</a>.</p>
| 22,152
|
<p>I learned something simple about SQL the other day:</p>
<pre><code>SELECT c FROM myTbl GROUP BY C
</code></pre>
<p>Has the same result as:</p>
<pre><code>SELECT DISTINCT C FROM myTbl
</code></pre>
<p>What I am curious of, is there anything different in the way an SQL engine processes the command, or are they truly the same thing? </p>
<p>I personally prefer the distinct syntax, but I am sure it's more out of habit than anything else.</p>
<p>EDIT: This is not a question about aggregates. The use of <code>GROUP BY</code> with aggregate functions is understood.</p>
|
<p><a href="https://stackoverflow.com/questions/164319/is-there-any-difference-between-group-by-and-distinct#164485">MusiGenesis</a>' response is functionally the correct one with regard to your question as stated; the SQL Server is smart enough to realize that if you are using "Group By" and not using any aggregate functions, then what you actually mean is "Distinct" - and therefore it generates an execution plan as if you'd simply used "Distinct."</p>
<p>However, I think it's important to note <a href="https://stackoverflow.com/questions/164319/is-there-any-difference-between-group-by-and-distinct#164323">Hank</a>'s response as well - cavalier treatment of "Group By" and "Distinct" could lead to some pernicious gotchas down the line if you're not careful. It's not entirely correct to say that this is "not a question about aggregates" because you're asking about the functional difference between two SQL query keywords, one of which is <strong>meant to be used with aggregates</strong> and one of which is not.</p>
<p>A hammer can work to drive in a screw sometimes, but if you've got a screwdriver handy, why bother?</p>
<p>(for the purposes of this analogy, <code>Hammer : Screwdriver :: GroupBy : Distinct</code> and <code>screw => get list of unique values in a table column</code>)</p>
|
<p>There is no significantly difference between group by and distinct clause except the usage of aggregate functions.
Both can be used to distinguish the values but if in performance point of view group by is better.
When distinct keyword is used , internally it used sort operation which can be view in execution plan.</p>
<p>Try simple example</p>
<pre><code>Declare @tmpresult table
(
Id tinyint
)
Insert into @tmpresult
Select 5
Union all
Select 2
Union all
Select 3
Union all
Select 4
Select distinct
Id
From @tmpresult
</code></pre>
| 19,861
|
<p>This question comes up occasionally, but I haven't seen a satisfactory answer.</p>
<p>A typical pattern is (row is a <strong>DataRow</strong>):</p>
<pre><code> if (row["value"] != DBNull.Value)
{
someObject.Member = row["value"];
}
</code></pre>
<p>My first question is which is more efficient (I've flipped the condition):</p>
<pre><code> row["value"] == DBNull.Value; // Or
row["value"] is DBNull; // Or
row["value"].GetType() == typeof(DBNull) // Or... any suggestions?
</code></pre>
<p><a href="https://stackoverflow.com/questions/184681/is-vs-typeof">This</a> indicates that .GetType() should be faster, but maybe the compiler knows a few tricks I don't?</p>
<p>Second question, is it worth caching the value of row["value"] or does the compiler optimize the indexer away anyway?</p>
<p>For example:</p>
<pre><code> object valueHolder;
if (DBNull.Value == (valueHolder = row["value"])) {}
</code></pre>
<p>Notes:</p>
<ol>
<li>row["value"] exists.</li>
<li>I don't know the column index of the column (hence the column name lookup).</li>
<li>I'm asking specifically about checking for DBNull and then assignment (not about premature optimization, etc.).</li>
</ol>
<p>I benchmarked a few scenarios (time in seconds, 10,000,000 trials):</p>
<pre><code>row["value"] == DBNull.Value: 00:00:01.5478995
row["value"] is DBNull: 00:00:01.6306578
row["value"].GetType() == typeof(DBNull): 00:00:02.0138757
</code></pre>
<p>Object.ReferenceEquals has the same performance as "=="</p>
<p>The most interesting result? If you mismatch the name of the column by case (for example, "Value" instead of "value", it takes roughly ten times longer (for a string):</p>
<pre><code>row["Value"] == DBNull.Value: 00:00:12.2792374
</code></pre>
<p>The moral of the story seems to be that if you can't look up a column by its index, then ensure that the column name you feed to the indexer matches the DataColumn's name exactly.</p>
<p>Caching the value also appears to be nearly <strong>twice</strong> as fast:</p>
<pre><code>No Caching: 00:00:03.0996622
With Caching: 00:00:01.5659920
</code></pre>
<p>So the most efficient method <em>seems</em> to be:</p>
<pre><code> object temp;
string variable;
if (DBNull.Value != (temp = row["value"]))
{
variable = temp.ToString();
}
</code></pre>
|
<p>I must be missing something. Isn't checking for <code>DBNull</code> exactly what the <a href="http://msdn.microsoft.com/en-us/library/3fwatee0.aspx" rel="noreferrer"><code>DataRow.IsNull</code></a> method does?</p>
<p>I've been using the following two extension methods:</p>
<pre class="lang-cs prettyprint-override"><code>public static T? GetValue<T>(this DataRow row, string columnName) where T : struct
{
if (row.IsNull(columnName))
return null;
return row[columnName] as T?;
}
public static string GetText(this DataRow row, string columnName)
{
if (row.IsNull(columnName))
return string.Empty;
return row[columnName] as string ?? string.Empty;
}
</code></pre>
<p>Usage:</p>
<pre class="lang-cs prettyprint-override"><code>int? id = row.GetValue<int>("Id");
string name = row.GetText("Name");
double? price = row.GetValue<double>("Price");
</code></pre>
<p>If you didn't want <code>Nullable<T></code> return values for <code>GetValue<T></code>, you could easily return <code>default(T)</code> or some other option instead.</p>
<hr>
<p>On an unrelated note, here's a VB.NET alternative to Stevo3000's suggestion:</p>
<pre class="lang-vb prettyprint-override"><code>oSomeObject.IntMember = If(TryConvert(Of Integer)(oRow("Value")), iDefault)
oSomeObject.StringMember = If(TryCast(oRow("Name"), String), sDefault)
Function TryConvert(Of T As Structure)(ByVal obj As Object) As T?
If TypeOf obj Is T Then
Return New T?(DirectCast(obj, T))
Else
Return Nothing
End If
End Function
</code></pre>
|
<p>I always use :</p>
<pre><code>if (row["value"] != DBNull.Value)
someObject.Member = row["value"];
</code></pre>
<p>Found it short and comprehensive.</p>
| 27,318
|
<p>I have a HTML with the following content:</p>
<pre><code>... some text ...
<a href="file.aspx?userId=123&section=2">link</a> ... some text ...
... some text ...
<a href="file.aspx?section=5&user=678">link</a> ... some text ...
... some text ...
</code></pre>
<p>I would like to parse that and get a match with named groups:</p>
<p><strong>match 1</strong></p>
<p>group["user"]=123</p>
<p>group["section"]=2</p>
<p><strong>match 2</strong></p>
<p>group["user"]=678</p>
<p>group["section"]=5</p>
<p>I can do it if parameters always go in order, first User and then Section, but I don't know how to do it if the order is different.</p>
<p>Thank you!</p>
|
<p>Why use regex to split it out?</p>
<p>You could first extrct the query string. Split the result on & and then create a map by splitting the result from that on =</p>
|
<p>Using regex to first find the key value pairs and then doing splits... doesn't seem right.</p>
<p>I'm interested in a complete regex solution.</p>
<p>Anyone?</p>
| 40,341
|
<p>In asp.net is there any benefit to including or not including an id property? Assume for this question that there is no programtic reason why we need an ID. (We are not manipulating the control in code behind, nor on the client).</p>
<p>My personal preference is only to include an Id property when I have a reason to manipulate the control and need to be able to refer to it. So I find myself always removing Image1 Label1 etc etc... </p>
<h1>Answers so far:</h1>
<ol>
<li>Keeping them can help assisted technologies.</li>
<li>Keeping them can help with test suites</li>
<li>Removing them can have an impact on bandwidth</li>
<li>Removing them keeps your intellisense cleaner (just added this one)</li>
</ol>
|
<p>Having ID properties are useful for testing your page with a tool like Quick Test Pro, etc. They're also useful for blind users who browse with a screen reading tool.</p>
<p>There's a good Hanselminutes podcast where this is discussed:
<a href="http://www.hanselminutes.com/default.aspx?showID=143" rel="nofollow noreferrer">http://www.hanselminutes.com/default.aspx?showID=143</a></p>
|
<p>True, the only reason the ID exists is to get a handle on an individual object, but there is definitely no benefit to deleting the auto-assigned ID that VisualStudio creates for you. </p>
<p>You never know when you may an ID, so I would at least recommend leaving the default if nothing else.</p>
| 46,136
|
<p>I've got a data object with a component in it that is an System.Collections.Generic.IList, and I'd like to reflect changes to that list into a Gtk# NodeView, so that when an item is added to the list, the NodeView will get a new item added to it. </p>
<p>How would I listen for changes to an IList? I have considered wrapping the IList with a class that implements IList, delegates the requisite methods, and broadcasts an event when changing it's contents, but that seems like a lot of work for something that has probably already been solved by someone else.</p>
|
<p>1) Concentrate on a properly normalized database design. I would say that when you are forced to make design tradeoffs in your code vs. database design, if performance is your goal, make tradeoffs in your object design instead of your database design. Understand that you aren't going to be able to do a proper supertype/subtype database design which will work with Linq to SQL (I'm told you need to use the EF instead). </p>
<p>2) Depends what you mean here. If you're asking how you would serialize anonymous classes across the wire, the easy answer is: "you can't, so don't try". If you want to put lists of objects across the wire, just use the ToArray() extension method on your IEnumerable collections to ship arrays of your business objects over the wire.</p>
|
<p>Linq to SQL is very slow unless you compile queries. Otherwise your application will be CPU bound as most of the time will be spend converting Expression trees into SQL. </p>
<p>We are talking about 10x performance gain if you use compiled queries. Try it :)</p>
| 20,691
|
<p>How do I print debug messages in the Google Chrome JavaScript Console?</p>
<p>Please note that the JavaScript Console is not the same as the JavaScript Debugger; they have different syntaxes AFAIK, so the <strong>print</strong> command in JavaScript Debugger will not work here. In the JavaScript Console, <code>print()</code> will send the parameter to the printer.</p>
|
<p>Executing following code from the browser address bar:</p>
<pre>
javascript: console.log(2);
</pre>
<p>successfully prints message to the "JavaScript Console" in Google Chrome.</p>
|
<p>Even though this question is old, and has good answers, I want to provide an update on other logging capabilities.</p>
<p>You can also print with groups:</p>
<pre><code>console.group("Main");
console.group("Feature 1");
console.log("Enabled:", true);
console.log("Public:", true);
console.groupEnd();
console.group("Feature 2");
console.log("Enabled:", false);
console.warn("Error: Requires auth");
console.groupEnd();
</code></pre>
<p>Which prints:</p>
<p><a href="https://i.stack.imgur.com/5TqdF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5TqdF.png" alt="enter image description here" /></a></p>
<p>This is supported by all major browsers according to <a href="https://developer.mozilla.org/en-US/docs/Web/API/Console/group" rel="nofollow noreferrer">this page</a>:
<a href="https://i.stack.imgur.com/eOjxc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eOjxc.png" alt="enter image description here" /></a></p>
| 26,801
|
<p>Despite the rather clear <a href="http://www.adobe.com/support/flash/action_scripts/actionscript_dictionary/actionscript_dictionary620.html" rel="noreferrer">documentation</a> which says that <a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/package.html#parseFloat()" rel="noreferrer">parseFloat()</a> can return NaN as a value, when I write a block like:</p>
<pre><code>if ( NaN == parseFloat(input.text) ) {
errorMessage.text = "Please enter a number."
}
</code></pre>
<p>I am warned that the comparison will always be false. And testing shows the warning to be correct.</p>
<p>Where is the corrected documentation, and how can I write this to work with AS3?</p>
|
<p>Because comparing anything to NaN is always false. Use isNaN() instead.</p>
|
<p>Documentation can be found in the Adobe Flex Language Reference <a href="http://livedocs.adobe.com/flex/2/langref/package.html#isNaN()" rel="nofollow noreferrer">Here</a> as well as other globally available functions.</p>
| 18,149
|
<p>I'm making a game and one of the methods calculates a character's base hit numbers based on skill values. The method currently calculates each value individually, since each skill can be used at short, medium, and long range.</p>
<p>I originally thought I could combine the skills into a tuple and iterate over it, dynamically creating each hit number. But I don't know if it's actually possible, since I currently have each hit number assigned to it's own variable.</p>
<p>I also thought about creating a method for each range, and passing the tuple as an argument. I could create a new tuple or list with the resulting values and then assign them to the individual variables, but I don't see how it would be any better than do it this way, except that it won't look so copy & pasted.</p>
<p>Here's what I currently have:</p>
<pre><code> def calcBaseHitNumbers(self, dict):
"""Calculate character's base hit numbers depending on skill level."""
self.skill_dict = dict
self.rifle = self.skill_dict.get('CRM', 0)
self.pistol = self.skill_dict.get('PST', 0)
self.big_gun = self.skill_dict.get('LCG', 0)
self.heavy_weapon = self.skill_dict.get('HW', 0)
self.bow = self.skill_dict.get('LB', 0)
#self.skill_tuple = (self.rifle, self.pistol, self.big_gun, self.heavy_weapon,
# self.bow)
#---Short range
## for skill in self.skill_tuple:
## self.base_hit_short = skill * 0.6
self.charAttribs.bhCRM_short = self.rifle * 0.6
self.charAttribs.bhPST_short = self.pistol * 0.6
self.charAttribs.bhHW_short = self.heavy_weapon * 0.6
self.charAttribs.bhLCG_short = self.big_gun * 0.6
self.charAttribs.bhLB_short = self.bow * 0.6
#---Med range
self.charAttribs.bhCRM_med = self.rifle * 0.3
self.charAttribs.bhPST_med = self.pistol * 0.3
self.charAttribs.bhHW_med = self.heavy_weapon * 0.3
self.charAttribs.bhLCG_med = self.big_gun * 0.3
self.charAttribs.bhLB_med = self.bow * 0.3
#---Long range
self.charAttribs.bhCRM_long = self.rifle * 0.1
self.charAttribs.bhPST_long = self.pistol * 0.1
self.charAttribs.bhHW_long = self.heavy_weapon * 0.1
self.charAttribs.bhLCG_long = self.big_gun * 0.1
self.charAttribs.bhLB_long = self.bow * 0.1
</code></pre>
<p>How would you refactor this so it's more dynamic?</p>
<hr>
<p><strong>Edit:</strong> I guess what I want to do is something like this:
Have a tuple (like the one I commented out) and iterate over it 3 times, each time making a new value (for each skill) based on the modifier for each particular range. The resulting value is then automatically assigned to it's respective variable.</p>
<p>In my head, it makes sense. But when I actually try to code it, I get lost. The problem, I think, is that this is the first "real" program I've written; all I've done before are small scripts.</p>
<p>This is only the 0.1 version of my program, so it's not critical to refactor it now. However, it seems very un-Pythonic to do this manually and I also want to "future-proof" this in case things change down the road.</p>
|
<p>It feels like what you really want is a class representing the weapon, with attributes to handle the base values and calculate hit values with various modifiers. Here's a simple example:</p>
<pre><code>SHORT_RANGE = 'S'
MEDIUM_RANGE = 'M'
LONG_RANGE = 'L'
SHORT_RANGE_MODIFIER = 0.6
MEDIUM_RANGE_MODIFIER = 0.3
LONG_RANGE_MODIFIER = 0.1
class Weapon(object):
def __init__(self, code_name, full_name, base_hit_value,
short_range_modifier=None, medium_range_modifier=None,
long_range_modifier=None):
self.code_name, self.full_name = code_name, full_name
self.base_hit_value = base_hit_value
self.range_modifiers = {
SHORT_RANGE: short_range_modifier or SHORT_RANGE_MODIFIER,
MEDIUM_RANGE: medium_range_modifier or MEDIUM_RANGE_MODIFIER,
LONG_RANGE: long_range_modifier or LONG_RANGE_MODIFIER,
}
def hit_value(self, range, modifier=1):
return self.base_hit_value * self.range_modifiers[range] * modifier
</code></pre>
<p>From there, you might create instances of Weapon inside your Character object like so:</p>
<pre><code> self.rifle = Weapon('CRM', 'rifle', 5)
self.pistol = Weapon('PST', 'pistol', 10)
</code></pre>
<p>And then if, say, the character fires the pistol at short range:</p>
<pre><code> hit_value = self.pistol.hit_value(SHORT_RANGE)
</code></pre>
<p>The extra argument to the hit_value() method can be used to pass in character- or situation-specific modifications.</p>
<p>Of course, the next step beyond this would be to directly model the weapons as subclasses of Weapon (perhaps breaking down into specific types of weapons, like guns, bows, grenades, etc., each with their own base values) and add an Inventory class to represent the weapons a character is carrying.</p>
<p>All of this is pretty standard, boring object-oriented design procedure, but for plenty of situations this type of thinking will get you off the ground quickly and provide at least a little bit of basic flexibility.</p>
|
<p>@Vinko: perhaps make calcBaseHitNumbers, do the "if not self.calculatedBase:" check internally, and just no-op if it's been done before. That said, I can't see the pressing need for precalculating this information. But I'm no Python performance expert.</p>
| 29,428
|
<p>Is there any way of doing parallel assignment in C++? Currently, the below compiles (with warnings)</p>
<pre><code>#include <iostream>
int main() {
int a = 4;
int b = 5;
a, b = b, a;
std::cout << "a: " << a << endl
<< "b: " << b << endl;
return 0;
}
</code></pre>
<p>and prints:</p>
<pre><code>a: 4
b: 5
</code></pre>
<p>What I'd like it to print ... if it weren't obvious, is:</p>
<pre><code>a: 5
b: 4
</code></pre>
<p>As in, say, ruby, or python.</p>
|
<p>That's not possible. Your code example</p>
<pre><code>a, b = b, a;
</code></pre>
<p>is interpreted in the following way:</p>
<pre><code>a, (b = b), a
</code></pre>
<p>It does nothing. The comma operator makes it return the value of a (the right most operand). Because assignment binds tighter, b = b is in parens. </p>
<p>The proper way doing this is just </p>
<pre><code>std::swap(a, b);
</code></pre>
<p>Boost includes a tuple class with which you can do</p>
<pre><code>tie(a, b) = make_tuple(b, a);
</code></pre>
<p>It internally creates a tuple of references to a and b, and then assigned to them a tuple of b and a.</p>
|
<p>Or Lua...<br>
There are tricks with C/C++, like using xor or operations, but with risk of overflow and such. Just do it the painful way, with three assignments. Not a big deal.</p>
| 34,671
|
<p>Given a small set of entities (say, 10 or fewer) to insert, delete, or update in an application, what is the best way to perform the necessary database operations? Should multiple queries be issued, one for each entity to be affected? Or should some sort of XML construct that can be parsed by the database engine be used, so that only one command needs to be issued?</p>
<p>I ask this because a common pattern at my current shop seems to be to format up an XML document containing all the changes, then send that string to the database to be processed by the database engine's XML functionality. However, using XML in this way seems rather cumbersome given the simple nature of the task to be performed.</p>
|
<p>It depends on how many you need to do, and how fast the operations need to run. If it's only a few, then doing them one at a time with whatever mechanism you have for doing single operations will work fine.</p>
<p>If you need to do thousands or more, and it needs to run quickly, you should re-use the connection and command, changing the arguments for the parameters to the query during each iteration. This will minimize resource usage. You don't want to re-create the connection and command for each operation.</p>
|
<p>Most databases support BULK UPDATE or BULK DELETE operations. </p>
| 6,622
|
<p>can anybody please explain the following c# behaviour? I have written a small console application just to learn about CAS, but I can not seem to understand why the following lines of code work like they do:</p>
<pre><code>string[] myRoles = new string[] { "role1", "role2", "role3" };
GenericIdentity myIdentity = new GenericIdentity("myUsername", "customAuthType");
GenericPrincipal myPrincipal = new GenericPrincipal(myIdentity, myRoles);
System.Threading.Thread.CurrentPrincipal = myPrincipal;
Console.WriteLine(SecurityManager.IsGranted(new PrincipalPermission(null, "role1")));
Console.WriteLine(SecurityManager.IsGranted(new PrincipalPermission(null, "roleX")));
</code></pre>
<p>The output is "true" for both SecurityManager.IsGranted() calls.</p>
<p>If I then add the following lines:</p>
<pre><code> new PrincipalPermission(null, "role1").Demand();
new PrincipalPermission(null, "roleX").Demand();
</code></pre>
<p>the first demand call passes, but the second one (as expected) causes a SecurityException. </p>
<p>Why does not the SecurityManager.IsGranted()-call return false for the "roleX" permission?</p>
|
<p>In .NET 4.0 SecurityManager.IsGranted has been made obsolete. </p>
<p>This is what it was and if you compile in .NET 4.0 compatibility it will complain.</p>
<pre><code>bool isGranted = SecurityManager.IsGranted(new SecurityPermission(SecurityPermissionFlag.Infrastructure))
</code></pre>
<p>To fix it:</p>
<pre><code>var permissionSet = new PermissionSet(PermissionState.None);
permissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode));
bool isGranted = permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet);
</code></pre>
<p>Reference:<br>
<a href="http://www.stringbuilder.net/post/2009/07/31/In-NET-40-SecurityManagerIsGranted-is-obsolete.aspx" rel="nofollow">http://www.stringbuilder.net/post/2009/07/31/In-NET-40-SecurityManagerIsGranted-is-obsolete.aspx</a></p>
|
<p>I believe <code>SecurityManager.IsGranted</code> is mainly looking at code demands (the assembly etc) - not specific demands such as principal permissions.</p>
<p>To do what you want:</p>
<pre><code> static bool HasAccess(string role)
{
IPrincipal principal = System.Threading.Thread.CurrentPrincipal;
return principal == null ? false : principal.IsInRole(role);
}
</code></pre>
| 40,166
|
<p>I have the following query:</p>
<pre><code>select column_name, count(column_name)
from table
group by column_name
having count(column_name) > 1;
</code></pre>
<p>What would be the difference if I replaced all calls to <code>count(column_name)</code> to <code>count(*)</code>?</p>
<p>This question was inspired by <a href="https://stackoverflow.com/questions/59232/how-do-i-find-duplicate-values-in-a-table-in-oracle">How do I find duplicate values in a table in Oracle?</a>.</p>
<hr>
<p>To clarify the accepted answer (and maybe my question), replacing <code>count(column_name)</code> with <code>count(*)</code> would return an extra row in the result that contains a <code>null</code> and the count of <code>null</code> values in the column.</p>
|
<p><code>count(*)</code> counts NULLs and <code>count(column)</code> does not</p>
<p>[edit] added this code so that people can run it</p>
<pre><code>create table #bla(id int,id2 int)
insert #bla values(null,null)
insert #bla values(1,null)
insert #bla values(null,1)
insert #bla values(1,null)
insert #bla values(null,1)
insert #bla values(1,null)
insert #bla values(null,null)
select count(*),count(id),count(id2)
from #bla
</code></pre>
<p>results
7 3 2</p>
|
<p>It is best to use</p>
<pre><code>Count(1) in place of column name or *
</code></pre>
<p>to count the number of rows in a table, it is faster than any format because it never go to check the column name into table exists or not</p>
| 8,383
|
<p>I wanted to edit a log comment in the repository browser and received an error message that no pre-revprop-change hook exists for the repository. Besides having a scary name, what is a pre-revprop-change hook, and how do I create it?</p>
|
<p>For Windows, here's a link to an example batch file that only allows changes to the log message (not other properties):</p>
<p><a href="http://ayria.livejournal.com/33438.html" rel="noreferrer">http://ayria.livejournal.com/33438.html</a></p>
<p>Basically copy the code below into a text file and name it <code>pre-revprop-change.bat</code> and save it in the <code>\hooks</code> subdirectory for your repository.</p>
<pre><code>@ECHO OFF
:: Set all parameters. Even though most are not used, in case you want to add
:: changes that allow, for example, editing of the author or addition of log messages.
set repository=%1
set revision=%2
set userName=%3
set propertyName=%4
set action=%5
:: Only allow the log message to be changed, but not author, etc.
if /I not "%propertyName%" == "svn:log" goto ERROR_PROPNAME
:: Only allow modification of a log message, not addition or deletion.
if /I not "%action%" == "M" goto ERROR_ACTION
:: Make sure that the new svn:log message is not empty.
set bIsEmpty=true
for /f "tokens=*" %%g in ('find /V ""') do (
set bIsEmpty=false
)
if "%bIsEmpty%" == "true" goto ERROR_EMPTY
goto :eof
:ERROR_EMPTY
echo Empty svn:log messages are not allowed. >&2
goto ERROR_EXIT
:ERROR_PROPNAME
echo Only changes to svn:log messages are allowed. >&2
goto ERROR_EXIT
:ERROR_ACTION
echo Only modifications to svn:log revision properties are allowed. >&2
goto ERROR_EXIT
:ERROR_EXIT
exit /b 1
</code></pre>
|
<ol>
<li>Go to SVN repo directory into the subfolder "hooks", e.g. "D:\SVN\hooks\" </li>
<li>create the empty file "pre-revprop-change.bat" there</li>
<li>in the file write "exit 0" (without "") and save it</li>
<li>enjoy :)</li>
</ol>
<p>(This solution surely has drawbacks, as nothing is checked/prohibited. But for my case - a local repo that only I am using - it seems to work.)</p>
| 23,989
|
<p>I have created a common library at work, and it is installed in the GAC on our test server. I've recently updated it and I want all of our applications to be using the update. I created a publisher policy assembly and installed it in the GAC along with the update, but when a web app loads Leggett.Common, 1.0.0.0, it isn't redirected to Leggett.Common, 1.1.0.0.</p>
<p>I have the common assembly (there are actually five, but lets keep it simple) on a network drive, I created the publisher policy xml file there next to it and then used al.exe to create the publisher policy assembly in the same folder. After that I put the updated assembly in the GAC and then put the publisher policy assembly in the GAC.</p>
<p>The common assembly is 'Leggett.Common.dll', the publisher policy file is '1.1.Leggett.Common.policy', and the publisher policy assembly is 'policy.1.1.Leggett.Common.dll'. </p>
<p>The XML for the publisher policy file looks like the following:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Leggett.Common"
publicKeyToken="32cd8f1a53a4c744"
culture="neutral" />
<bindingRedirect oldVersion="1.0.0.0"
newVersion="1.1.0.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
</code></pre>
<p>What am I doing wrong?</p>
<p><strong>Clarification</strong><br />
I'm testing this on my local dev machine since developers don't have access to the test server.</p>
|
<p>You're talking about code that would be shared library stuff. Static methods do have a place in shared libs. Check out System.Linq.Enumerable</p>
<p>I'd follow these guidelines:</p>
<ul>
<li>These aren't static methods by default. They should only be static methods because they are naturally stateless (behavior only depend on parameters). If they aren't naturally stateless, then you should be making a proper class to manage that state.</li>
<li>Cover these with Unit Tests. If you don't Unit Test anything else, Unit Test these. This should be very very easy to do. If this isn't easy, this isn't right.</li>
</ul>
<p>If dependency injection is something you like, you can still have it. Code that relies on a static method could instead be calling a Func(T, U) or an Action that references that static method.</p>
|
<p>Absolutely not. Utility modules over time turn into large collections of cruddy code.</p>
| 22,393
|
<p>I'd like to show/hide a column at runtime based on a particular condition. I'm using "Print when expression" to conditionally show/hide this column (and it's header) in my report. When the column is hidden, the space it would have occupied is left blank, which is not particularly attractive.</p>
<p>I would prefer if the extra space was used in a more effective manner, possibilities include:</p>
<ul>
<li>the width of the report is reduced by the width of the hidden column</li>
<li>the extra space is distributed among the remaining columns</li>
</ul>
<p>In theory, I could achieve the first by setting the width of the column (and header) to 0, but also indicate that the column should resize to fit its contents. But JasperReports does not provide a "resize width to fit contents" option.</p>
<p>Another possibility is to generate reports using the Jasper API instead of defining the report template in XML. But that seems like a lot of effort for such a simple requirement.</p>
|
<p>In later version (v5 or above) of jasper reports you can use the <code>jr:table</code> component and <strong>truly</strong> achieve this (without the use of java code as using dynamic-jasper or dynamic-reports).</p>
<p>The method is using a <code><printWhenExpression/></code> under the <code><jr:column/></code></p>
<h1>Example</h1>
<p><strong>Sample Data</strong></p>
<pre><code>+----------------+--------+
| User | Rep |
+----------------+--------+
| Jon Skeet | 854503 |
| Darin Dimitrov | 652133 |
| BalusC | 639753 |
| Hans Passant | 616871 |
| Me | 6487 |
+----------------+--------+
</code></pre>
<p><strong>Sample jrxml</strong></p>
<p><strong>Note</strong>: the parameter <code>$P{displayRecordNumber}</code> and the <code><printWhenExpression></code> under first <code>jr:column</code></p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="reputation" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="a88bd694-4f90-41fc-84d0-002b90b2d73e">
<style name="table">
<box>
<pen lineWidth="1.0" lineColor="#000000"/>
</box>
</style>
<style name="table_TH" mode="Opaque" backcolor="#F0F8FF">
<box>
<pen lineWidth="0.5" lineColor="#000000"/>
</box>
</style>
<style name="table_CH" mode="Opaque" backcolor="#BFE1FF">
<box>
<pen lineWidth="0.5" lineColor="#000000"/>
</box>
</style>
<style name="table_TD" mode="Opaque" backcolor="#FFFFFF">
<box>
<pen lineWidth="0.5" lineColor="#000000"/>
</box>
</style>
<subDataset name="tableDataset" uuid="7a53770f-0350-4a73-bfc1-48a5f6386594">
<field name="User" class="java.lang.String"/>
<field name="Rep" class="java.math.BigDecimal"/>
</subDataset>
<parameter name="displayRecordNumber" class="java.lang.Boolean">
<defaultValueExpression><![CDATA[true]]></defaultValueExpression>
</parameter>
<queryString>
<![CDATA[]]>
</queryString>
<title>
<band height="50">
<componentElement>
<reportElement key="table" style="table" x="0" y="0" width="555" height="47" uuid="76ab08c6-e757-4785-a43d-b65ad4ab1dd5"/>
<jr:table xmlns:jr="http://jasperreports.sourceforge.net/jasperreports/components" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/components http://jasperreports.sourceforge.net/xsd/components.xsd">
<datasetRun subDataset="tableDataset" uuid="07e5f1c2-af7f-4373-b653-c127c47c9fa4">
<dataSourceExpression><![CDATA[$P{REPORT_DATA_SOURCE}]]></dataSourceExpression>
</datasetRun>
<jr:column width="90" uuid="918270fe-25c8-4a9b-a872-91299cddbc31">
<printWhenExpression><![CDATA[$P{displayRecordNumber}]]></printWhenExpression>
<jr:columnHeader style="table_CH" height="30" rowSpan="1">
<staticText>
<reportElement x="0" y="0" width="90" height="30" uuid="5cd6da41-01d5-4f74-99c2-06784f891d1e"/>
<textElement textAlignment="Center" verticalAlignment="Middle"/>
<text><![CDATA[Record number]]></text>
</staticText>
</jr:columnHeader>
<jr:detailCell style="table_TD" height="30" rowSpan="1">
<textField>
<reportElement x="0" y="0" width="90" height="30" uuid="5fe48359-0e7e-44b2-93ac-f55404189832"/>
<textElement textAlignment="Center" verticalAlignment="Middle"/>
<textFieldExpression><![CDATA[$V{REPORT_COUNT}]]></textFieldExpression>
</textField>
</jr:detailCell>
</jr:column>
<jr:column width="90" uuid="7979d8a2-4e3c-42a7-9ff9-86f8e0b164bc">
<jr:columnHeader style="table_CH" height="30" rowSpan="1">
<staticText>
<reportElement x="0" y="0" width="90" height="30" uuid="61d5f1b6-7677-4511-a10c-1fb8a56a4b2a"/>
<textElement textAlignment="Center" verticalAlignment="Middle"/>
<text><![CDATA[Username]]></text>
</staticText>
</jr:columnHeader>
<jr:detailCell style="table_TD" height="30" rowSpan="1">
<textField>
<reportElement x="0" y="0" width="90" height="30" uuid="a3cdb99d-3bf6-4c66-b50c-259b9aabfaef"/>
<box leftPadding="3" rightPadding="3"/>
<textElement verticalAlignment="Middle"/>
<textFieldExpression><![CDATA[$F{User}]]></textFieldExpression>
</textField>
</jr:detailCell>
</jr:column>
<jr:column width="90" uuid="625e4e5e-5057-4eab-b4a9-c5b22844d25c">
<jr:columnHeader style="table_CH" height="30" rowSpan="1">
<staticText>
<reportElement x="0" y="0" width="90" height="30" uuid="e1c07cb8-a44c-4a8d-8566-5c86d6671282"/>
<textElement textAlignment="Center" verticalAlignment="Middle"/>
<text><![CDATA[Reputation]]></text>
</staticText>
</jr:columnHeader>
<jr:detailCell style="table_TD" height="30" rowSpan="1">
<textField pattern="#,##0">
<reportElement x="0" y="0" width="90" height="30" uuid="6be2d79f-be82-4c7b-afd9-0039fb8b3189"/>
<box leftPadding="3" rightPadding="3"/>
<textElement textAlignment="Right" verticalAlignment="Middle"/>
<textFieldExpression><![CDATA[$F{Rep}]]></textFieldExpression>
</textField>
</jr:detailCell>
</jr:column>
</jr:table>
</componentElement>
</band>
</title>
</jasperReport>
</code></pre>
<p><strong>Output with $P{displayRecordNumber}=true</strong></p>
<p><a href="https://i.stack.imgur.com/B4Lwv.png" rel="noreferrer"><img src="https://i.stack.imgur.com/B4Lwv.png" alt="true"></a></p>
<p><strong>Output with $P{displayRecordNumber}=false</strong></p>
<p><a href="https://i.stack.imgur.com/UsUo9.png" rel="noreferrer"><img src="https://i.stack.imgur.com/UsUo9.png" alt="false"></a></p>
<p><em>As you can see the columns adapts nicely on the basis of which are displayed.</em></p>
|
<p>If it is just one column, is it possible to place this column to the far right, and then use the print when expression. That way there is not a hole in the middle. I know this is not ideal, as I had tried to do what you are currently trying to accomplish in the past, and could not find what I call a good solution.</p>
<p>A second idea would to be create a second report based on the first with out the column, and then when calling the report check the condition, to decide which one to call. Again not ideal, but would work.</p>
<p>I know this is not really the answer you were looking for, but one of these suggestions may work for you.</p>
| 14,146
|
<p>I have an exe with an <code>App.Config</code> file. Now I want to create a wrapper dll around the exe in order to consume some of the functionalities.</p>
<p>The question is how can I access the app.config property in the exe from the wrapper dll?</p>
<p>Maybe I should be a little bit more in my questions, I have the following app.config content with the exe:</p>
<pre><code><?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="myKey" value="myValue"/>
</appSettings>
</configuration>
</code></pre>
<p>The question is how to how to get "myValue" out from the wrapper dll?</p>
<hr>
<p>thanks for your solution.</p>
<p>Actually my initial concept was to avoid XML file reading method or LINQ or whatever. My preferred solution was to use the <a href="http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx" rel="noreferrer">configuration manager libraries and the like</a>.</p>
<p>I'll appreciate any help that uses the classes that are normally associated with accessing app.config properties. </p>
|
<p>The <a href="http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.openmappedexeconfiguration(VS.80).aspx" rel="noreferrer">ConfigurationManager.OpenMappedExeConfiguration Method</a> will allow you to do this.</p>
<p>Sample from the MSDN page:</p>
<pre><code>static void GetMappedExeConfigurationSections()
{
// Get the machine.config file.
ExeConfigurationFileMap fileMap =
new ExeConfigurationFileMap();
// You may want to map to your own exe.comfig file here.
fileMap.ExeConfigFilename =
@"C:\test\ConfigurationManager.exe.config";
System.Configuration.Configuration config =
ConfigurationManager.OpenMappedExeConfiguration(fileMap,
ConfigurationUserLevel.None);
// Loop to get the sections. Display basic information.
Console.WriteLine("Name, Allow Definition");
int i = 0;
foreach (ConfigurationSection section in config.Sections)
{
Console.WriteLine(
section.SectionInformation.Name + "\t" +
section.SectionInformation.AllowExeDefinition);
i += 1;
}
Console.WriteLine("[Total number of sections: {0}]", i);
// Display machine.config path.
Console.WriteLine("[File path: {0}]", config.FilePath);
}
</code></pre>
<hr>
<p>EDIT: This should output the "myKey" value:</p>
<pre><code>ExeConfigurationFileMap fileMap =
new ExeConfigurationFileMap();
fileMap.ExeConfigFilename =
@"C:\test\ConfigurationManager.exe.config";
System.Configuration.Configuration config =
ConfigurationManager.OpenMappedExeConfiguration(fileMap,
ConfigurationUserLevel.None);
Console.WriteLine(config.AppSettings.Settings["MyKey"].Value);
</code></pre>
|
<p>It's an xml file, you can use Linq-XML or DOM based approaches to parse out the relevant information.<br>
(that said I'd question if there isn't a better design for whatever it is.. you're trying to achieve.)</p>
| 7,706
|
<p>I just wanted to compare different solutions used when implementing ACLs in Rails.</p>
|
<p>I use the authorization plugin (Created by <a href="http://www.billkatz.com/" rel="nofollow noreferrer">Bill Katz</a>):</p>
<blockquote>
<p>Roles can be authorized for the entire application, a model class, or a specific object. The plugin provides a way of checking authorization at the class or instance method level using permit and permit? methods. It also provides english-like dynamic methods like "user.is_manager_of project" (where "user" acts as authorized, "manager" is a role, and "project" is an authorizable model). You can specify how control is redirected if authorization is denied. (<a href="http://www.vaporbase.com/postings/Authorization_in_Rails" rel="nofollow noreferrer">quote source</a>)</p>
</blockquote>
<p>Homepage:
<a href="http://www.writertopia.com/developers/authorization" rel="nofollow noreferrer">http://www.writertopia.com/developers/authorization</a></p>
<p>Docs:
<a href="http://github.com/DocSavage/rails-authorization-plugin/tree/master/authorization/README.rdoc" rel="nofollow noreferrer">http://github.com/DocSavage/rails-authorization-plugin/tree/master/authorization/README.rdoc</a></p>
<hr>
<p>You might also be interested in reading this comparison (from last year but still somewhat useful; it's where I got the above quote from):
<a href="http://www.vaporbase.com/postings/Authorization_in_Rails" rel="nofollow noreferrer">http://www.vaporbase.com/postings/Authorization_in_Rails</a></p>
<p>And a more recent comparison:
<a href="http://steffenbartsch.com/blog/2008/08/rails-authorization-plugins/" rel="nofollow noreferrer">http://steffenbartsch.com/blog/2008/08/rails-authorization-plugins/</a></p>
|
<p>There's a plugin called acl_system2 which operates by having a users table and a roles table. There's a lot more useful information in the <a href="http://github.com/ezmobius/acl_system2/tree/master/README" rel="nofollow noreferrer">README</a> and the project is on github too.</p>
| 14,393
|
<p>Is there any easy way to create an acronym from a string?</p>
<pre><code>First_name Middle_name Last_name => FML
first_name middle_name last_name => FML
First_name-Middle_name Last_name => F-ML
first_name-middle_name last_name => F-ML
</code></pre>
|
<pre><code>Tokenize the string on whitespace.
For each token1,
Tokenize on dash.
For each token2
Take token2[0] and capitalize
if not first token2, prepend with dash
Concatenate to result2
Concatenate to result
</code></pre>
|
<p>I don't know about language agnostic, but I would make a function that accepts an args[] parameter to bring in all of your strings then loop through those and concatenate the first char of each onto another string which is returned.</p>
<p>Edit: Strike that. Didn't realize it was a single string. You would have to loop through all characters looking for special character types. Any letters after the first would be ignored until you get to a space or special character.</p>
| 28,653
|
<p>Greetings,</p>
<p>I need a way (either via C# or in a .bat file) to get a list of all the computers on a given network. Normally, I use "net view", but this tends to work (from my understanding) only within your domain. I need the names (or at least the IP Addresses) of all computers available on my network. </p>
<p>Being able to get all computers on a domain that isn't mine (in which case I'd use WORKGROUP, or whatever the default is) would also work.</p>
|
<p><a href="http://nmap.org/" rel="noreferrer">Nmap</a> is good for this - use the -O option for OS fingerprinting and -oX "filename.xml" for <a href="http://nmap.org/book/man-output.html" rel="noreferrer">output</a> as xml that you can then parse from c#.</p>
<p>A suitable commandline would be (where 192.168.0.0/24 is the subnet to scan):</p>
<pre><code>nmap -O -oX "filename.xml" 192.168.0.0/24
</code></pre>
<p>leave out the -O if you aren't interested in guessing the OS - if you just want a ping sweep use -sP, or read the docs for the myriad other options.</p>
|
<p>Ping everything in the rage, then you can get netbios info from the systems that respond to identify it's name.</p>
| 13,118
|
<p>Ok so I am trying to print a new fusion 360 file that I converted into an STL and then into gcode using cura and I got the gcode loaded onto the SD card and mounted into my Monoprice 3D printer, Maker Select 3D Printer v2, and tried to do a print. Now here is the strange part. When I choose "print file" and then select a gcode to print it takes me back to the main screen and from there the 3D printers screen displays "Printing...0%" for a few seconds. After this it just goes back to displaying "Stepper Disabled." And if it is not stepper disabled it is just a blank screen. I tried to mount and print multiple gcodes just to make sure that it was not the softwares fault and low and behold I was running into the same issue. </p>
<p>Now before using today all of the gcode was printing just fine, however for some reason today it decided to give me this issue. </p>
|
<p>Wash-away filament used for support in PLA printing is typically PVA, which is completely water soluble and may serve your purpose. It is easily 3D printed as the primary filament and attaches well to the build plate.</p>
<p>Many 3D printer filament suppliers will carry this type of support material. It is important to keep it in a sealed bag with desiccant as it will absorb moisture from the air, rendering it useless for printing.</p>
<p>One such resource is <a href="https://www.matterhackers.com/store/l/175mm-pva-filament-half-kg/sk/M4MJTECR" rel="nofollow noreferrer">MatterHackers</a> which prices a half-kilogram at US$45. The link provides suitably appropriate information:</p>
<blockquote>
<p>PVA (Polyvinyl Alcohol) is a water-soluble material that is often used
as a support material, but can also be used to print independently.
PVA supports are useful for complex designs where removing support
material manually is difficult or impossible, but leaving the part in
a water bath overnight will completely dissolve this material.</p>
</blockquote>
<p><a href="https://i.stack.imgur.com/2ytSy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2ytSy.png" alt="PVA filament"></a></p>
|
<p>ABS dissolves in acetone. Indeed actone can be used to clean up 3D prints, see <a href="https://3dprinting.stackexchange.com/questions/4235/whats-smoother-acetone-treated-pla-or-abs/">What's smoother? Acetone treated PLA or ABS</a>. PLA maybe not somuch as ABS, see the same post.</p>
<p>PLA dissolves in any chlorinated or fluorinated solvent, such as THF or Chloroform - both of which are significantly more hazardous than acetone.</p>
<p>Hence, as always <strong>take care</strong> when using solvents, see <a href="https://3dprinting.stackexchange.com/questions/81/safety-precautions-when-using-acetone/278#278">Safety precautions when using acetone</a></p>
<p>Also, as filaments are often not pure ABS or PLA, due to additives and dyes, etc., then the solvent may not dissolve the 3D printed part <em>completely</em>, and you may be left with a deformed, rubbery residue.</p>
| 911
|
<p>I have a windows application that I want to run as a windows service - how can I do this ?</p>
|
<p>Quick-n-dirty way, use the INSTSRV and SRVANY tools in the Windows Resource Kit:
<a href="http://support.microsoft.com/kb/137890" rel="nofollow noreferrer">How To Create a User-Defined Service</a></p>
|
<p>In addition to XYNTService and SRVANY already recommended, you should consider <a href="http://www.CoreTechnologies.com/products/AlwaysUp" rel="nofollow noreferrer">AlwaysUp, a commercial product designed to run any application as a Windows Service</a>. You can try it free for 30 days to ensure that it will do the job for you.</p>
<p>Good luck!</p>
| 46,932
|
<p>In Microsoft Oslo SDK CTP 2008 (using Intellipad) the following code compiles fine:</p>
<pre><code>module M {
type T {
Text : Text;
}
}
</code></pre>
<p>while compiling the below code leads to the error "M0197: 'Text' cannot be used in a Type context"</p>
<pre><code>module M {
type T {
Text : Text;
Value : Text; // error
}
}
</code></pre>
<p>I do not see the difference between the examples, as in the first case Text is also used in a Type context.</p>
<p>UPDATE:</p>
<p>To add to the confusion, consider the following example, which also compiles fine:</p>
<pre><code>module M {
type X;
type T {
X : X;
Y : X;
}
}
</code></pre>
<p>The M Language Specification states that:</p>
<blockquote>
<p>Field declarations override lexical scoping to prevent the type of a declaration binding to the declaration itself. The ascribed type of a field declaration must not be the declaration itself; however, the declaration may be used in a constraint. Consider the following example:</p>
<p>type A;
type B {
A : A;
}</p>
<p>The lexically enclosing scope for the type ascription of the field declaration A is the entity declaration B. With no exception, the type ascription A would bind to the field declaration in a circular reference which is an error. The exception allows lexical lookup to skip the field declaration in this case. </p>
</blockquote>
<p>It seems that user defined types and built-in (intrinsic) types are not treated equal.</p>
<p>UPDATE2:</p>
<p>Note that <em>Value</em> in the above example is not a reserved keyword. The same error results if you rename <em>Value</em> to <em>Y</em>.</p>
<p>Any ideas?</p>
<p>Regards, tamberg</p>
|
<p>The primary benefits of a CHUI (that is something with forms and fields, not necessarily command line interfaces) is the keyboard for navigation and consistent layout. That is key.</p>
<p>If your GUI can be completely, and efficiently, keyboard navigated, then your CHUI user base should be happy. This is because in time, the users simply "type" their commands in to the system without "seeing the interface". They don't need to "discover" the interface, which is a primary feature of the GUI.</p>
<p>While CHUIs appear to be dinosaurs, they are still functional and usable. Most folks once they're trained (notably POS/Counter workers, but even back office scenarios like factory or warehouse floor, etc) have no problem using a CHUI.</p>
<p>But the key is the keyboard support so the user don't have to wait for the screen to catch up with them. Seeing a skilled operator with a mastery of the keyboard can make an application fly. You barely have a chance to see popup windows and what not.</p>
|
<p>As soon as you present some data, someone's going to want to query against it. You can integrate that with a gui, no problem. If you think some of your customers are going to want to script certain tasks. set it up. Anything to do with automation is better done from the command line(y harlo thar cron job!)</p>
<p>I love guis. I'm a mac user. But there is a time and a place for a CLI.</p>
| 31,619
|
<p>Java requires that you catch all possible exceptions or declare them as thrown in the method signature. This isn't the case with C# but I still feel that it is a good practice to catch all exceptions. Does anybody know of a tool which can process a C# project and point out places where an exception is thrown but not caught? </p>
|
<p>Check out the ExceptionFinder plug-in by Jason Bock for the .NET Reflector. It does just what you are looking for. Here's a screeny:</p>
<p>Check it out on <a href="http://www.codeplex.com/ExFinderReflector" rel="nofollow noreferrer">CodePlex</a></p>
|
<p>If you are using C# for a web application then you can use ELMAH which shows a list of all the handled and unhandled exceptions. </p>
<p>Just download ELMAH and plug it in. It is FREE!</p>
| 28,752
|
<p>I am using the <a href="http://ui.jquery.com/repository/latest/demos/functional/#ui.datepicker" rel="nofollow noreferrer">date picker provided by jQuery UI</a> to select a date range that ends up in a single text input with something like 11/11/2008 - 12/05/2008. What would you recommend as far a validation (jQuery/JavaScript) on the client side as well as code for validation on the server side (ASP.NET/C#) to make sure the user enters valid dates?</p>
<p>Note I <a href="https://stackoverflow.com/questions/311576/parsing-a-date-range-in-c-aspnet">asked a question on Stack Overflow</a> the other day about how to parse out the two dates using C# if your interested.</p>
|
<p>There has maybe been a lot of hype in the early 2000's, and what happened is the following: there has been a lot of attempts to create aspect-oriented frameworks, and these attempts have merged into two significant projects in the Java sphere: AspectJ and Spring AOP. AspectJ is complete, complex, academic, somewhat overengineered. Spring AOP covers 80% of use cases with 20% of complexity. </p>
<p>If you look at Google Trends for terms <a href="http://www.google.com/trends?q=aspectj%2C+spring+aop&ctab=0&geo=all&date=all&sort=0" rel="noreferrer">"AspectJ, Spring AOP"</a>, then compare to the popularity of Java itself, you will see that the relative popularity of AspectJ is somewhat constant, but Spring AOP is raising. That means that people use AOP, but don't want the complexity of AspectJ. I think that the creators of AspectJ made a lot of tactical mistakes; AspectJ has always been a research project and has not been designed "for the masses".</p>
<p>In the .NET sphere, we have seen a similar interest for AOP in the early 2000's. In 2003, when I started AOP researches, there were half a dozen of AOP weavers for .NET; all were following the path of AspectJ, and all were in infant stage. None of these projects survived. Based on this analysis, I built PostSharp, who was designed to cover 80% of use cases with 20% of complexity, and yet was much more convenient to use than Spring AOP. PostSharp is now considered the leading aspect weaver for .NET. PostSharp 2.0 builds on 5 years of feedback and from industry experience of AspectJ and brings "enterprise-ready" AOP (future will judge if this claim is deserved). Besides PostSharp, other significant players are Spring Framework for .NET and Windsor Castle, two DI-centric application frameworks providing 'also' aspects (aspects are considered as dependencies injected into constructed objects). Since these technologies use runtime weaving, they have severe technical limitations, so practically they can be used only in service objects (that's what these application frameworks have been designed for). Another starting project in .NET is LinFu, which can do 'also' aspects.</p>
<p>To be short, the AOP landscape has undergone some consolidation last years, and probably enters the phase of productivity: customers will use it because it really saves money, not because it is cool. Even if it is very cool :).</p>
<p>Oh, and I forgot: most application servers have built-in support for AOP. Thinking of JBoss, WebSphere, and, to some extent, WCF.</p>
|
<p>I'm going to suggest that it wasn't big enough. It sounds very appealing, but does it really make coding any easier? I've been wanting to try it out and find what benefits it really holds, but I don't think I do enough coding where I need the relationships that it provides. I don't think it is as beneficial as it sounds.</p>
<p>Also at this point, making it easier to do multicore programming easier is a big thing and I don't think aspect-oriented programming will assist with that.</p>
<p>You can also find lots of content on <a href="http://en.wikipedia.org/wiki/Aspect-oriented_programming#Adoption_risks" rel="nofollow noreferrer" title="Adoption Risks">Adoption Risks</a>.</p>
| 40,816
|
<p>I asked before about pixel-pushing, and have now managed to get far enough to get noise to show up on the screen. Here's how I init:</p>
<pre><code>CGDataProviderRef provider;
bitmap = malloc(320*480*4);
provider = CGDataProviderCreateWithData(NULL, bitmap, 320*480*4, NULL);
CGColorSpaceRef colorSpaceRef;
colorSpaceRef = CGColorSpaceCreateDeviceRGB();
ir = CGImageCreate(
320,
480,
8,
32,
4 * 320,
colorSpaceRef,
kCGImageAlphaNoneSkipLast,
provider,
NULL,
NO,
kCGRenderingIntentDefault
);
</code></pre>
<p>Here's how I render each frame:</p>
<pre><code>for (int i=0; i<320*480*4; i++) {
bitmap[i] = rand()%256;
}
CGRect rect = CGRectMake(0, 0, 320, 480);
CGContextDrawImage(context, rect, ir);
</code></pre>
<p>Problem is this is awfully awfully slow, around 5fps. I think my path to publish the buffer must be wrong. Is it even possible to do full-screen pixel-based graphics that I could update at 30fps, without using the 3D chip?</p>
|
<p>The slowness is almost certainly in the noise generation. If you run this in Instruments you'll probably see that a ton of time is spent sitting in your loop.</p>
<p>Another smaller issue is your colorspace. If you use the screen's colorspace, you'll avoid a colorspace conversion which is potentially expensive. </p>
<p>If you can use CoreGraphics routines for your drawing, you'd be better served by creating a CGLayer for the drawing context instead of creating a new object each time. </p>
<p>The bytesPerRow component is also important for performance. It should be a factor of 32 IIRC. There's some code available <a href="http://www.geekspiff.com/content/view/61/" rel="nofollow noreferrer" title="here">link text</a> that shows how to compute it.</p>
<p>And yeah, for raw performance, OpenGL.</p>
|
<p>I suspect doing 614400 (<code>320*480*4</code>) memory writes, random number generation and making a new object each frame is slowing you down. </p>
<p>Have you tried just writing a static bitmap to screen and seeing how fast that is? Have you perhaps tried profiling the code? Do you also need to make a new CGRect each time? </p>
<p>If you just want to give the effect of randomness, there is probably no need to regenerate the entire bitmap each time.</p>
| 23,593
|
<p>what is the best way to put a container class or a some other class inside a class as private or a public member?</p>
<p>Requirements:</p>
<p>1.Vector< someclass> inside my class</p>
<p>2.Add and count of vector is needed interface</p>
|
<p>If the container's state is part of the class's invariant, then it should, if possible, be private.</p>
<p>For example, if the container represents a three dimensional vector then part of the invariant might be that it always contains exactly 3 numbers. Exposing it as a public member would allow code external to the class to change the containers size, which in turn could cause problems for any routine which requires the container's size to be constant. Keeping the container private limits the places in your software where the container's size can be modified to the class's member functions.</p>
|
<p>Make all members private and use accessor methods, this allows you to change the implementation later. Only in very unusual circumstances would I make any data member public.</p>
<p>Remember that chaning the implementation happens more often than you may imagine, its not just a case of changing the type of the container but maybe you want to change the mechanism. Say you were storing names in a list, after a while you may chose to index this list with a hash and would like to have the hash updated every time you add a new name. If your implementation is suitably encapsulated doing this is easy, if you have just exposed the vector you would need to make changes that will adjust the interface (and so the change will ripple out).</p>
<p>If this is new to new you have a read of: <a href="http://en.wikipedia.org/wiki/Encapsulation_(classes_-_computers)" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Encapsulation_(classes_-_computers)</a></p>
| 23,985
|
<p>I've been seeing that expression for over 10 years now. I've been trying to think what it's good for. Since I see it mostly in #defines, I assume it's good for inner scope variable declaration and for using breaks (instead of gotos.)</p>
<p>Is it good for anything else? Do you use it?</p>
|
<p>It's the only construct in C that you can use to <code>#define</code> a multistatement operation, put a semicolon after, and still use within an <code>if</code> statement. An example might help:</p>
<pre><code>#define FOO(x) foo(x); bar(x)
if (condition)
FOO(x);
else // syntax error here
...;
</code></pre>
<p>Even using braces doesn't help:</p>
<pre><code>#define FOO(x) { foo(x); bar(x); }
</code></pre>
<p>Using this in an <code>if</code> statement would require that you omit the semicolon, which is counterintuitive:</p>
<pre><code>if (condition)
FOO(x)
else
...
</code></pre>
<p>If you define FOO like this:</p>
<pre><code>#define FOO(x) do { foo(x); bar(x); } while (0)
</code></pre>
<p>then the following is syntactically correct:</p>
<pre><code>if (condition)
FOO(x);
else
....
</code></pre>
|
<p>Generically, <code>do</code>/<code>while</code> is good for any sort of loop construct where one must execute the loop <em>at least</em> once. It is possible to emulate this sort of looping through either a straight <code>while</code> or even a <code>for</code> loop, but often the result is a little less elegant. I'll admit that specific applications of this pattern are fairly rare, but they do exist. One which springs to mind is a menu-based console application:</p>
<pre><code>do {
char c = read_input();
process_input(c);
} while (c != 'Q');
</code></pre>
| 32,122
|
<p>I'm trying to get an expect script to work, and when I use the -re flag (to invoke regular expression parsing), the 'timeout' keyword seems to no longer work. When the following script is run, I get the message 'timed out at step 1', then 'starting step 2' and then it times out but does NOT print the 'timed out at step 2' I just get a new prompt.</p>
<p>Ideas?</p>
<pre><code>#!/usr/bin/expect --
spawn $env(SHELL)
match_max 100000
set timeout 2
send "echo This will print timed out\r"
expect {
timeout { puts "timed out at step 1" }
"foo " { puts "it said foo at step 1"}
}
puts "Starting test two\r"
send "echo This will not print timed out\r"
expect -re {
timeout { puts "timed out at step 2" ; exit }
"foo " { puts "it said foo at step 2"}
}
</code></pre>
|
<p>The important thing is that a declaration in C++ is not an expression.</p>
<pre><code>bool a = (CThing* pThing = GetThing()); // not legit!!
</code></pre>
<p>You can't do both a declaration and boolean logic in an if statement, C++ language spec specifically allows either an expression or a declaration.</p>
<pre><code>if(A *a = new A)
{
// this is legit and a is scoped here
}
</code></pre>
<p>How can we know whether a is defined between one term and another in an expression?</p>
<pre><code>if((A *a = new A) && a->test())
{
// was a really declared before a->test?
}
</code></pre>
<p>Bite the bullet and use an internal if. The scope rules are useful and your logic is explicit:</p>
<pre><code>if (CThing* pThing = GetThing())
{
if(pThing->IsReallySomeThing())
{
}
}
</code></pre>
|
<p>You can also enclose the assignment in an extra set of ( ) to prevent the warning message.</p>
| 16,526
|
<p><strong>Sorry answer found while typing</strong> </p>
<p>I am trying to connect to an external webservice that requires username/password authentication through a proxy. I am using Visual Studio Express 2008 to generate a service reference</p>
<ul>
<li>I have connected to the same
webservice using a web reference.We
only had to set a larger timeout
because it takes a long time to
finish. </li>
<li>I have connected to another
webservice that does not require
username/password authentication
with a generated service reference
and some settings to get it through
the proxy. </li>
</ul>
<p>So my thought would be to
take this reference, point it to the
correct webservice and add
authentication.</p>
<p>The config I am using without security:</p>
<pre><code> <?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.net>
<defaultProxy useDefaultCredentials="true">
<proxy bypassonlocal="False" proxyaddress="http://***.***.****:80" />
</defaultProxy>
</system.net>
<system.serviceModel>
<bindings>
<customBinding>
<binding name="AreaWebServiceSoap12">
<textMessageEncoding maxReadPoolSize="64" maxWritePoolSize="16"
messageVersion="Soap12" writeEncoding="utf-8">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
</textMessageEncoding>
<httpTransport manualAddressing="false" maxBufferPoolSize="524288"
maxReceivedMessageSize="65536" allowCookies="false" authenticationScheme="Anonymous"
bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
keepAliveEnabled="true" maxBufferSize="65536" proxyAuthenticationScheme="Anonymous"
realm="" transferMode="Buffered" unsafeConnectionNtlmAuthentication="false"
useDefaultWebProxy="true" />
</binding>
</customBinding>
</bindings>
<client>
<endpoint address="http://www.****.*****.****.com/samplewebservice/service.asmx"
binding="customBinding" bindingConfiguration="AreaWebServiceSoap12"
contract="ServiceReference1.ServiceSoap" name="ServiceSoap" />
</client>
</system.serviceModel>
</configuration>
</code></pre>
<p>I have added te following code to my call for authentication:</p>
<pre><code>static void Main(string[] args)
{
ServiceSoapClient s = new ServiceSoapClient();
s.ClientCredentials.UserName.UserName = @"username";
s.ClientCredentials.UserName.Password = @"password";
Service.RawGpsData[] result = s.GetRawGpsData(0);
Console.WriteLine(String.Format("done:{0}",result.Length));
Console.ReadLine();
}
</code></pre>
<p>Just using this setup gives an error as expected:</p>
<p><em>The HTTP request is not authorized with client authentication scheme Anonymous. The authentication header from the server is received, is NTLM.</em></p>
<p>Now I get lost and start trying silly things because I am just starting to use WCF.</p>
<p>When I add the following section to the config</p>
<pre><code> <security authenticationMode="UserNameOverTransport"></security>
</code></pre>
<p>I get the following error:</p>
<p><em>The binding CustomBinding.http: / / tempuri.org / for the contract AreaWebServiceSoap.AreaWebServices is configured with a verification mode for which a transport level with integrity and confidentiality is required. The transport can not provide integrity and confidentiality.</em></p>
<p>Sorry, while typing this question I stumbled upon the answer myself. I still think people might be interested in this and all comments and thoughts are still welcome. So I will leave the question here and make it community and post the answer myself.</p>
|
<p>Change the binding to :</p>
<pre><code><?xml version="1.0" encoding="utf-8" ?>
<customBinding>
<binding name="AreaWebServiceSoap12" closeTimeout="00:01:00" openTimeout="00:10:00"
receiveTimeout="00:20:00" sendTimeout="00:05:00">
<textMessageEncoding maxReadPoolSize="64" maxWritePoolSize="16"
messageVersion="Soap12" writeEncoding="utf-8">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
</textMessageEncoding>
<httpTransport manualAddressing="false" maxBufferPoolSize="524288"
maxReceivedMessageSize="65536" allowCookies="false" authenticationScheme="Ntlm"
bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
keepAliveEnabled="true" maxBufferSize="65536" proxyAuthenticationScheme="Anonymous"
realm="" transferMode="Buffered" unsafeConnectionNtlmAuthentication="false"
useDefaultWebProxy="true" />
</binding>
</customBinding>
</code></pre>
<p>So set authenticationScheme="Ntlm"</p>
|
<p>And here is how you can connect without proxy:</p>
<p><a href="http://blog.bodurov.com/Create-a-WCF-client-for-asmx-web-service-without-using-web-proxy" rel="nofollow noreferrer">http://blog.bodurov.com/Create-a-WCF-client-for-asmx-web-service-without-using-web-proxy</a></p>
| 36,886
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.