instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>I've just inherited a java application that needs to be installed as a service on XP and vista. It's been about 8 years since I've used windows in any form and I've never had to create a service, let alone from something like a java app (I've got a jar for the app and a single dependency jar - log4j). What is the magic necessary to make this run as a service? I've got the source, so code modifications, though preferably avoided, are possible.</p>
<p>I've had some luck with <a href="http://wrapper.tanukisoftware.org/doc/english/introduction.html" rel="noreferrer">the Java Service Wrapper</a></p>
<p>It's possible to implement a Windows service in 100% Java code by combining the use of <a href="https://jdk.java.net/panama/" rel="nofollow noreferrer">Foreign Memory and Linker API</a> (previewing from JDK16 upwards) with <a href="https://github.com/openjdk/jextract" rel="nofollow noreferrer">OpenJDK jextract project</a> to handle the Windows Service callbacks, and then use <a href="https://docs.oracle.com/en/java/javase/18/jpackage/packaging-overview.html" rel="nofollow noreferrer">jpackage</a> to produce a Windows EXE which can then be registered as a Windows Service.</p> <p>See this example which outlines the work needed to implement a <a href="https://learn.microsoft.com/en-gb/windows/win32/services/svc-cpp" rel="nofollow noreferrer">Windows service</a>. All Windows service EXE must provide callbacks for the main entrypoint <a href="https://learn.microsoft.com/en-gb/windows/win32/api/winsvc/nc-winsvc-lpservice_main_functionw" rel="nofollow noreferrer">ServiceMain</a> and <a href="https://learn.microsoft.com/en-us/windows/win32/api/winsvc/nc-winsvc-lphandler_function" rel="nofollow noreferrer">Service Control Handler</a>, and use API calls <a href="https://learn.microsoft.com/en-us/windows/win32/api/winsvc/nf-winsvc-startservicectrldispatcherw" rel="nofollow noreferrer">StartServiceCtrlDispatcherW</a>, <a href="https://learn.microsoft.com/en-us/windows/win32/api/winsvc/nf-winsvc-registerservicectrlhandlerw" rel="nofollow noreferrer">RegisterServiceCtrlHandlerExW</a> and <a href="https://learn.microsoft.com/en-us/windows/win32/api/winsvc/nf-winsvc-setservicestatus" rel="nofollow noreferrer">SetServiceStatus</a> in <code>Advapi.DLL</code>.</p> <p>The flow of above callbacks in Java with Foreign Memory structures are:</p> <pre><code>main() Must register ServiceMain using StartServiceCtrlDispatcherW Above call blocks until ServiceMain exits void ServiceMain(int dwNumServicesArgs, MemoryAddress lpServiceArgVectors) Must register SvcCtrlHandler using RegisterServiceCtrlHandlerExW Use SetServiceStatus(SERVICE_START_PENDING) Initialise app Use SetServiceStatus(SERVICE_RUNNING) wait for app shutdown notification Use SetServiceStatus(SERVICE_STOPPED) int SvcCtrlHandler(int dwControl, int dwEventType, MemoryAddress lpEventData, MemoryAddress lpContext) Must respond to service control events and report back using SetServiceStatus On receiving SERVICE_CONTROL_STOP reports SetServiceStatus(SERVICE_STOP_PENDING) then set app shutdown notification </code></pre> <p>Once finished the Java application, jpackage can create runtime+EXE which can then be installed and registered as a Windows Service. Run as Adminstrator (spaces after = are important):</p> <pre><code> sc create YourJavaServiceName type= own binpath= &quot;c:\Program Files\Your Release Dir\yourjavaservice.exe&quot; </code></pre>
9,362
<p>I have an app that run on many computers and connect to sql server I want to log the machine names of that computers in a table every time they connect how can I do that</p> <p>I want to know if there is a command like that</p> <p>"Select @@MachineName"</p>
<p>It's up to you how you want to log this information, but <a href="http://msdn.microsoft.com/en-us/library/ms178598(SQL.90).aspx" rel="nofollow noreferrer">HOST_NAME()</a> returns the name of the workstation connecting to the server.</p>
<p>Create linked server : (allowing access to distributed, heterogeneous queries against OLE DB data sources.) using following command :</p> <blockquote> <p>sp_addlinkedserver [ @server= ] 'server' [ , [ @srvproduct= ] 'product_name' ] [ , [ @provider= ] 'provider_name' ]</p> <pre><code> [ , [ @datasrc= ] 'data_source' ] [ , [ @location= ] 'location' ] [ , [ @provstr= ] 'provider_string' ] [ , [ @catalog= ] 'catalog' ] </code></pre> </blockquote> <p>Then access is like :</p> <p>Select * from [server-name].[db-name].dbo.[tablename]</p> <p>Also, make sure security login you are using on both the servers is same (or atleast exists on other server too).</p>
45,414
<p>Or are they two distinct applications that are not related?</p>
<p>They are very different, although some people push the list of source control commits or latest files (head) to their team wiki (which could be SharePoint)</p>
<p>I believe they are unrelated but both use SQL Server as their backend.</p>
21,169
<p>You can have different naming convention for class members, static objects, global objects, and structs. Some of the examples of them are as below.</p> <pre><code>_member m_member </code></pre> <p>or in Java case, the usage of <code>this.member</code>.</p> <p>But is there any good technique or naming convention for function variables scope that conveys when a single variable has complete function scope or a short lifespan scope?</p> <pre><code>void MyFunction() { int functionScopeVariable; if(true) { //no need for function variable scope naming convention } } </code></pre>
<p>I actually encourage delegating this task to the IDE/editor you use.</p> <p>No, I'm not actually talking about naming variables, that is still best done by a human. But the underlying task of such naming strategies is to show you which type of variable any one name represents.</p> <p>Pretty much every IDE worth its salt can define different styles (colors, fonts, font types, ...) to different variable types (instance member, static member, argument, local variable, ...) so letting the IDE tell you what type of variable it is actually frees you from having to type those (otherwise useless) pre- or suffixes every time.</p> <p>So my suggestion: use meaningful names without any prefix or suffix.</p>
<p>It really all comes down to whatever the style guidelines for the language suggest if there are any.</p>
18,268
<p>I made a custom printer with RAMPS. I used Y-MIN endstop at beginning. After few prints I discovered that Y-axis was inverted (mirrored).</p> <p>I fixed Marlin firmware and now I have:</p> <pre><code>#define Y_MAX_ENDSTOP_INVERTING true #define INVERT_Y_DIR false #define Y_HOME_DIR 1 #define USE_YMAX_PLUG </code></pre> <p>I also connected the Y-endstop to Y-max pin on RAMPS.</p> <p>Now the printer homing in the same direction than before (in front) and the y-endstop works as expected.</p> <p>If I try to start printing or if I try to press the "center" button in Pronterface, the Y-axis moves in the wrong direction.</p> <p>Can someone help me?</p>
<p>This <a href="https://www.everybitelectronics.co.uk/blog/3d-printer-error-prints-reversed/" rel="nofollow noreferrer">blog post</a> shows 3 main solutions:</p> <ol> <li>Flipping the motor cables (As suggested in the other answer)</li> <li>Switching the x and y-axis: This may switch the direction of your y-axis depending on the way your printer is setup)</li> <li>Change the direction of the axis in firmware which you can see below how to do:</li> </ol> <blockquote> <p>"When the solution opens up, you will see many different files open. You need to navigate to the Configuration.h file. Within this file scroll down to the following lines of code:"</p> </blockquote> <pre><code>// Invert the stepper direction. Change (or reverse the motor connector) if an axis goes the wrong way. define INVERT_X_DIR true define INVERT_Y_DIR true define INVERT_Z_DIR true </code></pre> <blockquote> <p>"This is where you need to switch the values around. If they are currently true, change them to false and if they are false, change them to true. Due to the fact I was having issues with my x-Axis, I have changed the above to the following:"</p> </blockquote> <pre><code>// Invert the stepper direction. Change (or reverse the motor connector) if an axis goes the wrong way. define INVERT_X_DIR false define INVERT_Y_DIR true define INVERT_Z_DIR true </code></pre>
<p>Usually I just flip the connector around on the board. This causes the stepper to reverse without fiddling around with firmware.</p>
1,601
<p>I have a plugin for OpenFire that creates and delivers a message to a user using</p> <pre><code>XMPPServer.getInstance().getMessageRouter().route(message) </code></pre> <p>What I would like to know is what happens to that message if the user is not online. </p> <p>My goal is to only have the message delivered if the user is online, and fail or be routed to the bit bucket otherwise.</p>
<p>It's all down to Openfire config. In the Openfire admin console, go to Server -> Server Settings -> Offline Messages. There are options for store, bounce and drop. </p> <ul> <li>Store: deliver the message when the user comes back online.</li> <li>Drop: Just discard the message.</li> <li>Bounce: Discard and notify the sender with a return message.</li> </ul>
<p>Another approach, if you just want these messages to not go offline without affecting the delivery of other messages, is to use type='headline'. Headlines are not terribly well-specified, but <a href="http://xmpp.org/internet-drafts/draft-saintandre-rfc3921bis-07.html#message-syntax-type" rel="nofollow noreferrer">RFC 3921bis Section 5.2.2</a> says:</p> <blockquote> <p>headline -- The message provides an alert, a notification, or other information to which no reply is expected (e.g., news headlines, sports updates, near-real-time market data, and syndicated content). Because no reply to the message is expected, typically a receiving client will present a message of type "headline" in an interface that appropriately differentiates the message from standalone messages, chat messages, or groupchat messages (e.g., by not providing the recipient with the ability to reply). <strong>The receiving server SHOULD deliver the message to all of the recipient's available resources.</strong></p> </blockquote> <p>Most servers of today will just silently drop headlines to offline users, and deliver to the highest priority resource if the user is online.</p>
30,761
<p>Here is a VB.NET code snippet</p> <pre><code>Public Class OOPDemo Private _strtString as String Public Function Func(obj as OOPDemo) as boolean obj._strString = "I can set value to private member using a object" End Function End Class </code></pre> <p>I thought we cannot access the private members using the object, but perhaps CLR allows us to do that. So that means that access modifiers are based on the type and not on the instance of that type. I have also heard that c++ also allows that..</p> <p>Any guesses what could be the reason for this?</p> <p>Edit:</p> <p>I think this line from the msdn link given by RoBorg explains this behaviour "Code in the type that declares a private element, including code within contained types, can access the element "</p>
<pre><code>Image imgControl = new Image(); Grid.SetColumn(imgControl, 1); gridContainer.Children.Add(imgControl); </code></pre> <p>Objects contained in a grid are positioned based on the attached dependency properties Column Row ColumnSpan and RowSpan which are set as shown above.</p>
<p>The row/column index on an element in WPF is an attached property. You set it using a static method on Grid, like this:</p> <pre><code>Grid.SetColumn(img, 1); </code></pre> <p>More info <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.grid.setcolumn.aspx" rel="noreferrer">here</a>, and more about attached properties <a href="http://msdn.microsoft.com/en-us/library/ms749011.aspx" rel="noreferrer">here</a>.</p>
45,041
<p>I'm looking at the source code for the .net membership provider, and it sqlmembershipprovider.cs there are calls to EncryptPassword and DecryptPassword but I don't see the method anywhere in the source.</p> <p>What algorithm are they using? Isn't the source for that released also?</p>
<p>SqlMembershipProvider derives from MembershipProvider from which it inherits EncryptPassword() and DecryptPassword().</p> <p>Looking though the code with Reflector, it looks like the algorithm is DES if the key is 8 bytes long and AES (Rijndael) otherwise.</p>
<p>SqlMembershipProvider uses System.Web.Security.MembershipProvider as its base class. The EncryptPassword and DecryptPassword methods are being called on the base class.</p> <p>Fire up .NET Reflector and point it at System.Web.Security.MembershipProvider and you'll see how they do it.</p>
35,558
<p>How do I open multiple pages in Internet Explorer 7 with a single DOS command? Is a batch file the only way to do this?</p> <p>Thanks!</p>
<p>A batch file will work as a quick and dirty solution.</p> <pre><code>@echo off @setlocal :openurl set url=%~1 if "%url:~0,4%" == "http" ( start "%ProgramFiles%\Internet Explorer\iexplore.exe" "%url%" ) if NOT "%url:~0,4%" == "http" ( start "%ProgramFiles%\Internet Explorer\iexplore.exe" "http://%url%" ) shift if "%~1" == "" goto :end goto :openurl :end </code></pre> <p>Edit: added support for domain names without http handler prefix.</p>
<p>Unfortunately, there is no way to include multiple URLs as command-line parameters. Here is a a <a href="http://blogs.msdn.com/tonyschr/archive/2007/01/19/ie-automation-amp-tabs.aspx" rel="nofollow noreferrer">blog post</a> which details another (fairly convoluted) way to do it via Javascript.</p>
14,459
<p>I recently read a nice <a href="http://macdevelopertips.com/ruby/using-a-string-as-a-file-in-ruby.html" rel="noreferrer">post</a> on using <code>StringIO</code> in Ruby. What the author doesn't mention, though, is that <code>StringIO</code> is just an "I." There's no "O." You <em>can't</em> do this, for example:</p> <pre><code>s = StringIO.new s &lt;&lt; 'foo' s &lt;&lt; 'bar' s.to_s # =&gt; should be "foo\nbar" # =&gt; really is ''` </code></pre> <p>Ruby really needs a StringBuffer just like the one Java has. StringBuffers serve two important purposes. First, they let you test the output half of what Ruby's StringIO does. Second, they are useful for building up long strings from small parts -- something that Joel reminds us over and over again is otherwise very very slow.</p> <p>Is there a good replacement?</p> <p>It's true that Strings in Ruby are mutable, but that doesn't mean we should always rely on that functionality. If <code>stuff</code> is large, the performance and memory requirements of this, for example, is really bad.</p> <pre><code>result = stuff.map(&amp;:to_s).join(' ') </code></pre> <p>The "correct" way to do this in Java is:</p> <pre><code>result = StringBuffer.new("") for(String s : stuff) { result.append(s); } </code></pre> <p>Though my Java is a bit rusty.</p>
<p>I looked at the ruby documentation for <code>StringIO</code>, and it looks like what you want is <a href="http://ruby-doc.org/stdlib/libdoc/stringio/rdoc/classes/StringIO.html#method-i-string" rel="noreferrer"><code>StringIO#string</code></a>, not <code>StringIO#to_s</code></p> <p>Thus, change your code to:</p> <pre><code>s = StringIO.new s &lt;&lt; 'foo' s &lt;&lt; 'bar' s.string </code></pre>
<p>Well, a StringBuffer is not quite as necessary in Ruby, mainly because Strings in Ruby are mutable... thus you can build up a string by modifying the existing string instead of constructing new strings with each concat.</p> <p>As a note, you can also use special string syntax where you can build a string which references other variables within the string, which makes for very readable string construction. Consider:</p> <pre><code>first = "Mike" last = "Stone" name = "#{first} #{last}" </code></pre> <p>These strings can also contain expressions, not just variables... such as:</p> <pre><code>str = "The count will be: #{count + 1}" count = count + 1 </code></pre>
3,156
<p>In Matlab, how can I find value of K, in a system that has oscillation?</p> <blockquote> <p>(system's tf, if needed: (K * (s + 25))/(s^3 + 24 s^2 + 100 s) )</p> </blockquote> <p>PS. I'm using root locus.</p>
<p>I assume this is the plant for a closed-loop system with gain compensation only (that would be K). In that case I would express it as a transfer function and then use the root-locus command to see where it hits on the x-axis:</p> <pre><code>num = [1 25]; den = [1 24 100 0]; sys=tf(num,den) rlocus(sys) </code></pre> <p>Unfortunately your system appears to be stable for all values of K! Doh!</p>
<p>Does the <code>dcgain</code> function do what you need?</p>
47,909
<p>I need to make sure that user can run only one instance of my program at a time.<br> Which means, that I have to check programatically, whether the same program is already running, and quit in such case.</p> <p>The first thing that came to my mind was to create a file somewhere, when the program starts. Then, each other instance of the program would check for this file and exit if it found it.<br> The trouble is, that the program must always exit gracefully and be able to delete the file it created, for this to work. In case of, say, power outage, the lock file remains in place and the program can't be started again.</p> <p>To solve this, I decided to store the first program's process ID into the lock file and when another instance starts, it checks if the PID from the file is attached to some running process.<br> If the file doesn't exist, is empty, or the PID doesn't correspond to any existing process, the program continues to run and writes its own PID to the file.</p> <p>This seems to work quite fine - even after an unexpected shutdown, the chance that the (now obsolete) process ID will be associated with some other program, seems to be quite low.</p> <p>But it still doesn't feel right (there <em>is</em> a chance of getting locked by some unrelated process) and working with process IDs seems to go beyond the standard C++ and probably isn't very portable either.</p> <p>So, is there another (more clean and secure) way of doing this? Ideally one that would work with the ISO 98 C++ standard and on Windows and *nix alike.<br> If it cannot be done platform-independently, Linux/Unix is a priority for me.</p>
<p>There are several methods you can use to accomplish only allowing one instance of your application:</p> <p><strong>Method 1: Global synchronization object or memory</strong></p> <p>It's usually done by creating a named global mutex or event. If it is already created, then you know the program is already running.</p> <p>For example in windows you could do:</p> <pre><code> #define APPLICATION_INSTANCE_MUTEX_NAME "{BA49C45E-B29A-4359-A07C-51B65B5571AD}" //Make sure at most one instance of the tool is running HANDLE hMutexOneInstance(::CreateMutex( NULL, TRUE, APPLICATION_INSTANCE_MUTEX_NAME)); bool bAlreadyRunning((::GetLastError() == ERROR_ALREADY_EXISTS)); if (hMutexOneInstance == NULL || bAlreadyRunning) { if(hMutexOneInstance) { ::ReleaseMutex(hMutexOneInstance); ::CloseHandle(hMutexOneInstance); } throw std::exception("The application is already running"); } </code></pre> <p><strong>Method 2: Locking a file, second program can't open the file, so it's open</strong></p> <p>You could also exclusively open a file by locking it on application open. If the file is already exclusively opened, and your application cannot receive a file handle, then that means the program is already running. On windows you'd simply not specify sharing flags <code>FILE_SHARE_WRITE</code> on the file you're opening with <code>CreateFile</code> API. On linux you'd use <code>flock</code>.</p> <p><strong>Method 3: Search for process name:</strong></p> <p>You could enumerate the active processes and search for one with your process name. </p>
<p>I don't have a good solution, but two thoughts:</p> <ol> <li><p>You could add a ping capability to query the other process and make sure it's not an unrelated process. Firefox does something similar on Linux and doesn't start a new instance when one is already running.</p></li> <li><p>If you use a signal handler, you can ensure the pid file is deleted on all but a <code>kill -9</code></p></li> </ol>
20,644
<p>I'm new to both ASP.Net MVC and jQuery and what I'm trying to do is make a form that either adds a new RockBand or updates an existing RockBand based on if the rockbandid is an empty guid or not. I figured now is a good time to get rolling with jQuery. So the first step is to make a list of bands and put an edit link next to it. If the user clicks on the edit link I want to alter the value of the input box and the hidden field. The code below is the first step, trying to set the value of the input box (with a fixed string for the moment but eventually would be whatever the band name is). However I get an Object Required Error when I do so. (The jQuery include is on the Site.Master)</p> <pre><code>&lt;asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server"&gt; &lt;script type="text/javascript"&gt; function fillinbandname(thebandname) { $('#bandname').val(thebandname); } &lt;/script&gt; &lt;ul&gt; &lt;%foreach (DomainModel.RockBand rockband in ViewData.Model) %&gt; &lt;%{ %&gt; &lt;li&gt;&lt;%=rockband.BandName %&gt; &lt;a href='javascript:fillinbandname("somesamplevalue");'&gt;edit&lt;/a&gt;&lt;/li&gt; &lt;%} %&gt;&lt;/ul&gt; &lt;%Html.BeginForm("MakeOrUpdateRockBand", "Bands", FormMethod.Post); %&gt; &lt;input type="text" id="bandname" name="bandname" maxlength="30" /&gt; &lt;input type="hidden" id="bandid" name="bandid" value="00000000-0000-0000-0000-000000000000" /&gt; &lt;input type="submit" value="Add New Band" /&gt; &lt;%Html.EndForm(); %&gt; &lt;/asp:Content&gt; </code></pre> <p>It feels like I'm soooo close...but am missing something fundamental.</p>
<p>Just to elaborate a little further to what Frans has said...Even though the ListBox owns the ContextMenuStrip, you can still customize the items in the menu strip at the time it's opening. Thus customizing it's contents based on the mouse position within the listbox.</p> <p>The example below selects the item in the listbox based on a right mouse click and then customizes a context menu strip based on the item the user right-clicked on. This is a simple example but should get you going: Add a listbox to a form and add this code:</p> <pre><code>#region Private Members private ContextMenuStrip listboxContextMenu; #endregion private void Form1_Load( object sender, EventArgs e ) { //assign a contextmenustrip listboxContextMenu = new ContextMenuStrip(); listboxContextMenu.Opening +=new CancelEventHandler(listboxContextMenu_Opening); listBox1.ContextMenuStrip = listboxContextMenu; //load a listbox for ( int i = 0; i &lt; 100; i++ ) { listBox1.Items.Add( &quot;Item: &quot; + i ); } } private void listBox1_MouseDown( object sender, MouseEventArgs e ) { if ( e.Button == MouseButtons.Right ) { //select the item under the mouse pointer listBox1.SelectedIndex = listBox1.IndexFromPoint( e.Location ); if ( listBox1.SelectedIndex != -1) { listboxContextMenu.Show(); } } } private void listboxContextMenu_Opening( object sender, CancelEventArgs e ) { //clear the menu and add custom items listboxContextMenu.Items.Clear(); listboxContextMenu.Items.Add( string.Format( &quot;Edit - {0}&quot;, listBox1.SelectedItem.ToString() ) ); } </code></pre> <p>Hope that help.</p>
<pre><code>//Create and Initialize the contextMenuStrip component contextMenuStrip_ListaAulas = new ContextMenuStrip(); //Adding an Item contextMenuStrip_ListaAulas.Items.Add("Modificar"); //Binding the contextMenuStrip with the ListBox listBox_Aulas.ContextMenuStrip = contextMenuStrip_ListaAulas; //The solution below if (e.Button == System.Windows.Forms.MouseButtons.Right) { //select the item under the mouse pointer listBox_Aulas.SelectedIndex = listBox_Aulas.IndexFromPoint(e.Location); //if the selected index is an item, binding the context MenuStrip with the listBox if (listBox_Aulas.SelectedIndex != -1) { listBox_Aulas.ContextMenuStrip = contextMenuStrip_ListaAulas; } //else, untie the contextMenuStrip to the listBox else { listBox_Aulas.ContextMenuStrip = null; } } </code></pre>
49,342
<p>This question regards unit testing in Visual Studio using MSTest (this is important, because of MSTest's <a href="http://blogs.msdn.com/nnaderi/archive/2007/02/17/explaining-execution-order.aspx" rel="noreferrer">execution order</a>). Both the method marked [TestInitialize] and the test class constructor will run before each test method.</p> <p>So, the question is, what do you tend to do in each of these areas? Do you avoid performing certain activities in either? What is your reason: style, technical, superstition?</p>
<p>The constructor is just a structure provided by the language. Every test framework seems has its own controlled lifecycle "initialize". You'll probably only get into trouble using the constructor to mutate your locals.</p> <p><strong>MSTest:</strong> You get an entire new instance of the test class for every <code>TestMethod</code>. This might be the only case where it's ok to mutate your locals in the constructor, initializer, or test method and not affect the other test methods.</p> <pre><code>public class TestsForWhatever { public TestsForWhatever() { // You get one of these per test method, yay! } [TestInitialize] public void Initialize() { // and one of these too! } [TestMethod] public void AssertItDoesSomething() { } [TestMethod] public void AssertItDoesSomethingElse() { } } </code></pre> <p><strong>MSpec:</strong> You only get one <code>Establish</code> and <code>Because</code> for all your assertions (<code>It</code>). So, don't mutate your locals in your assertions. And don't depend on mutations of locals in base contexts (if you use them).</p> <pre><code>[Subject(typeof(Whatever))] public class When_doing_whatever { Establish context = () =&gt; { // one of these for all your Its }; Because of = () =&gt; _subject.DoWhatever(); It should_do_something; It should_do_something_else; } </code></pre>
<p>It depends on the scenario. If you have a test class, and for some weird reason if you need to create instance of it on another test class, you will need to use constructor.</p> <p>Otherwise test initialize more fits in the concept. Firstly, same reasons written above, second MS can introduce more features on that attribute and you will benefit them, with constructor you will stuck into it.</p>
43,375
<p>Inside my page, I have the following:</p> <pre><code>&lt;aspe:UpdatePanel runat="server" ID="updatePanel"&gt; &lt;ContentTemplate&gt; &lt;local:KeywordSelector runat="server" ID="ksKeywords" /&gt; &lt;/ContentTemplate&gt; &lt;/aspe:UpdatePanel&gt; </code></pre> <p>The <code>KeywordSelector</code> control is a control I define in the same assembly and <code>local</code> is mapped to its namespace.</p> <p>The control is made up of several other controls and is defined as such:</p> <pre><code>&lt;%@ Control Language="C#" AutoEventWireup="true" CodeBehind="KeywordSelector.ascx.cs" Inherits="Keywords.KeywordSelector" %&gt; </code></pre> <p>and has quite a few server controls of its own, all defined as members in the <code>.designer.cs</code> file.</p> <p>However, <strong>during no part of the control's lifecycle does it have any child control objects nor does it produce HTML</strong>:</p> <ol> <li>All of the members defined in the <code>.designer.cs</code> file are <code>null</code>.</li> <li>Calls to <code>HasControls</code> return <code>false</code>.</li> <li>Calls to <code>EnsureChildControls</code> do nothing.</li> <li>The <code>Controls</code> collection is empty.</li> </ol> <p>Removing the <code>UpdatePanel</code> did no good. I tried to reproduce it in a clean page with a new <code>UserControl</code> and the same thing happens.</p> <p>I am using ASP.NET over .NET Framework 3.5 SP1 with the integrated web server.</p> <p>What am I missing here?</p> <p><strong>Update #1:</strong> Following Rob's comment, I looked into <code>OnInit</code> and found that the <code>UserControl</code> does not detect that it has any child controls. Moreover, <code>CreateControlCollection</code> is never called!</p>
<p>Well, I've found the problem(s):</p> <ol> <li><p><em>User Controls</em>, as opposed to <em>Custom Controls</em> must be registered one-by-one in the <em>web.config</em> file. Do this:</p> <p><code>&lt;add tagPrefix="local" tagName="KeywordSelector" src="~/KeywordSelector.ascx" /&gt;</code></p> <p>instead of:</p> <p><code>&lt;add tagPrefix="local" namespace="Keywords" assembly="Keywords" /&gt;</code></p></li> <li><p>You should never place a <code>WebControl</code> in the same directory as the <code>Control</code> that is using it. This is downright silly. <a href="http://www.mertner.com/morten/?p=31" rel="noreferrer">Read about it here</a>.</p></li> </ol> <p>Thanks for the help. Now if only I could mark my own answer as <strong>the</strong> answer...</p>
<p>In my case the reason was the Resharper 7.1 added incorrect @Register directive at the top of aspx - instead of this desired row:</p> <pre><code>&lt;%@ Register Src="~/Controls/Hello/Hello.ascx" TagName="Hello" TagPrefix="p" %&gt; </code></pre> <p>i got wrong one:</p> <pre><code>&lt;%@ Register TagPrefix="p" Namespace="MyNamespace.WebApp.Controls" Assembly="MyApp.Web" %&gt; </code></pre>
30,130
<p>I'm looking for a good ocaml parsing library that isn't a derivative of flex/bison. Ideally, I'd like a monadic combinator library along the lines of parsec, but I can't find anything.</p> <p>I would use haskell, but making llvm bindings for haskell is proving more tiresome than I originally thought.</p> <p>Cheers,</p> <p>Duane</p>
<p><a href="http://ocaml-batteries-team.github.com/batteries-included/hdoc/BatParserCo.html" rel="noreferrer">Here's one library</a>, via Google. (Which also brought up <a href="http://osp.janestreet.com/files/pcl.pdf" rel="noreferrer">this</a> and <a href="http://caml.inria.fr/cgi-bin/hump.en.cgi?sort=0&amp;browse=96" rel="noreferrer">this</a>, which lists several more relevant-sounding libraries.)</p> <p>When I wrote a combinator parser in ML, it turned out rather cumbersome to use because of the value restriction and eager evaluation, which forced you to eta-expand your grammar rules. Ocaml is said to be more relaxed about the value restriction, though -- maybe you'll be spared some of that pain.</p>
<p>In the OCaml world, <a href="http://www.ffconsultancy.com/ocaml/benefits/parsing.html" rel="nofollow noreferrer">stream-based parsers</a> and <a href="http://brion.inria.fr/gallium/index.php/Full_parser_tutorial" rel="nofollow noreferrer">Camlp4</a> are the next two most common alternatives. Both have been described in detail in previous <a href="http://www.ffconsultancy.com/products/ocaml_journal/?so" rel="nofollow noreferrer">OCaml Journal</a> articles.</p> <p>Monadic parser combinators are comparatively rare in OCaml, largely because there are several higher-level and vastly more efficient libraries available.</p>
39,577
<p>I've written a small service (plain Win32) and I'd like to know if it's possible to run multiple instances of it when multiple users are logged on.</p> <p>Basically, let's say we've got UserA and UserB for UserA the service would log on as "domain\UserA" and for UserB the service would log on as "domain\UserB" - this is from the same executable of course. I can change the logon dynamically using the ChangeServiceConfig() function, but it changes it system-wide it seems, while I'd like each user to have his own copy of the service running only for him.</p> <p>Thank you in advance for any pointers.</p>
<p>Win32 services are designed to be system-wide, and start running before any user is logged in. If you want something to run on a per-user basis, it's probably better to design it as a regular application and run it from the user's Startup group.</p>
<p>The whole concept of a service is that it is started before any user is even logged on. so even if this was possible, you wouldn't be able to choose between userA and userB when the service starts because none of them is logged on yet.</p> <hr> <p>A possible direction would be for the service to run as SYSTEM And every few minutes check if there is a user logged in, if there is- impersonate that user and do this stuff.</p>
13,838
<p>I noticed in another post, someone had done something like:</p> <pre><code>double d = 3.1415; int i = Convert.ToInt32(Math.Floor(d)); </code></pre> <p>Why did they use the convert function, rather than:</p> <pre><code>double d = 3.1415; int i = (int)d; </code></pre> <p>which has an implicit floor and convert.</p> <p>Also, more concerning, I noticed in some production code I was reading:</p> <pre><code>double d = 3.1415; float f = Convert.ToSingle(d); </code></pre> <p>Is that the same as:</p> <pre><code>float f = (float)d; </code></pre> <p>Are all those otherwise implicit conversions just in the Convert class for completeness, or do they serve a purpose? I can understand a need for .ToString(), but not the rest.</p>
<p>Casting to int is implicit truncation, not implicit flooring:</p> <pre><code>double d = -3.14; int i = (int)d; // i == -3 </code></pre> <p>I choose Math.Floor or Math.Round to make my intentions more explicit.</p>
<p>You can use Convert when you have a string that you want to convert to an int </p> <pre><code>int i = Convert.ToInt32("1234"); </code></pre> <p>Convert and casting will both throw an exception if they fail.</p> <p>i.e, this will still throw an exception, it will not return 0:</p> <pre><code>Convert.ToInt32("1234NonNumber"); </code></pre> <p>In many cases Convert and casting will have the same result, but a cast is often times easier to read.</p>
12,961
<p>I'm trying to import some data from Excel to SQL Server, I have a TEXT column with some numbers in it, some of the numbers go over just fine, and some turn into scientific form.</p> <p>Column in Excel is "text" type, column in the target sql table is varchar(255)</p> <p>Here are some examples: </p> <p>Excel [text] -> SQL Server [varchar(255)]<br> 0313852230 -> 0313852230<br> 1024869004 -> 1024869004<br> 1022868890 -> 1.02287e+009<br> 1022868899 -> 1.02287e+009<br> 1022868907 -> 1022868907<br> 1030869319 -> 1030869319<br> 1106869726 -> 1106869726<br> SomeText -> SomeText </p> <p>Please help!</p> <p><strong>SOLUTION: Formatting the column as [Number] with 10 leading zeros worked for me, since all my numbers are 10-digit numbers</strong></p>
<p>There's not really a better way than that, though I tend to put the looping part into a <code>CopyTo</code> extension method, e.g.</p> <pre><code>public static void CopyTo(this Stream source, Stream destination) { var buffer = new byte[0x1000]; int bytesInBuffer; while ((bytesInBuffer = source.Read(buffer, 0, buffer.Length)) &gt; 0) { destination.Write(buffer, 0, bytesInBuffer); } } </code></pre> <p>Which you could then call as:</p> <pre><code>fsin.CopyTo(ds); </code></pre>
<p>Now that I think about it, I haven't ever seen any built-in support for piping the results of an input stream directly into an output stream as you're describing. <a href="http://msdn.microsoft.com/en-us/magazine/cc163290.aspx" rel="nofollow noreferrer">This article on MSDN</a> has some code for a "StreamPipeline" class that does the sort of thing you're describing.</p>
40,803
<p>Im using delphi's ttreeview as an 'options' menu. how would i go upon selecting the next node at runtime like a previous and next button? i tried the getprev and getnext methods but no luck.</p>
<p>Here you have the 'Next' behavior. For 'Previous' I leave as exercise for you: :-)</p> <pre><code>procedure TForm8.btn1Click(Sender: TObject); var crt: TTreeNode; begin with tv1 do //this is our tree begin if Selected=nil then crt:=Items[0] //the first one else crt:=Selected.GetNext; //for previous you'll have 'GetPrev' if crt&lt;&gt;nil then //can be 'nil' if we reached to the end Selected:=crt; end; end; </code></pre> <p>HTH</p>
<p>here is another way to do this:</p> <pre><code>type TfrmMain = class(TForm) ... public DLLHandle : THandle; function GetNodePath(node: TTreeNode; delimiter: string = '\') : String; ... function TfrmMain.GetNodePath(node: TTreeNode; delimiter: string = '\') : String; begin Result:=''; while Assigned(node) do begin Result:=delimiter+node.Text+Result; node:=node.Parent; end; if Result &lt;&gt; '' then Delete(Result, 1, 1); end; ... </code></pre> <p>here is how to use it: on your treeview's click or doubleclick event do this</p> <pre><code>... var path : String; begin path:=GetNodePath(yourTreeView.Selected); ShowMessage(path); ... </code></pre> <p>if you have a 'Item 1' and a subitem called 'Item 1' and click on Item 2 than the message should be 'Item 1\Item 2'. By doing this you can have a better control...</p> <p>hope this gives you another idea to enhance your code</p>
20,684
<p>In particular, I'm editing the AutoCompletion.plist file for CSSEdit (if that even matters).</p> <p>My question is, are there any characters withing the STRING elements that need to be escaped? spaces? quotes?</p> <p>EDIT: Just to be clear, I'm not using CSSEdit to edit the file - rather the file is part of the CSSEdit package. I'm using TextMate to edit the file (although "Property List Editor.app" is another option) and it is in XML format. Here's a snippet from the AutoCompletion.plist file:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"&gt; &lt;plist version="1.0"&gt; &lt;dict&gt; &lt;key&gt;font-family&lt;/key&gt; &lt;array&gt; &lt;string&gt;Arial&lt;/string&gt; &lt;string&gt;Helvetica&lt;/string&gt; &lt;string&gt;Georgia&lt;/string&gt; &lt;string&gt;serif&lt;/string&gt; &lt;string&gt;sans-serif&lt;/string&gt; &lt;string&gt;cursive&lt;/string&gt; etc... </code></pre> <p>I'd like to add STRINGs with spaces and single quotes such as:</p> <pre><code>&lt;string&gt;Georgia, Times, 'Times New Roman', serif&lt;/string&gt; </code></pre> <p>But CSSEdit goes haywire when I edit the file as such</p>
<p>If you're editing an XML plist using a text editor of some sort, you'll need to escape characters just like in any XML. The basic characters to watch out for are:</p> <p>&lt; (less than), escaped as &amp;lt;</p> <p>&gt; (greater than), escaped as &amp;gt;</p> <p>&amp; (ampersand), escaped as &amp;amp;</p> <p>' (apostrophe), escaped as &amp;apos;</p> <p>&quot; (quote mark), escaped as &amp;quot;</p> <p>So in your example, you would want</p> <p><code>&lt;string&gt;Georgia, Times, &amp;apos;Times New Roman&amp;apos;, serif&lt;/string&gt;</code></p> <p>You can also use a tool such as Apple's Property List Editor, which is included with their free <a href="http://developer.apple.com/technology/tools.html" rel="nofollow noreferrer">Xcode developer tools</a>, or a third party product like <a href="http://www.fatcatsoftware.com/plisteditpro" rel="nofollow noreferrer">PlistEdit Pro</a>, both of which will take care of all the character escaping for you.</p>
<p>There are 3 types of plists, and the escaping rules depend on type you are working with. The most common form are XML plists, which do require certain things to be escaped. In general you can use XML escaping rules within the string elements. If you are working with older NextStep style plists I believe much less needs to be escaped, but I would need to look up the details to be certain of what the rules are. The third type are binary, I am pretty confident you are not editing those with CSSEdit.</p>
32,015
<p>I have a csv file of the format:</p> <pre><code>270291014011 ED HARDY - TRUE TO MY LOVE - Cap NEU 2008 NEU 0,00 € 0,00 € 0 1 0 22.10.2008 03:37:10 21.11.2008 02:37:10 21.11.2008 02:42:10 50 0 0 0 39,99 € http://i7.ebayimg.com/02/i/001/16/0d/68af_1.JPG?set_id=800005007 0 2 8.10.2008 13:40:20 8.10.2008 13:40:20 80587 0 &lt;table bordercolordark="#999900" bordercolorlight="#666666" bgcolor="#ffffff" border="10" bordercolor="#666666" width="100%"&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;&lt;b&gt;&lt;font color="#990000" face="arial" size="5"&gt;&lt;br&gt; &lt;/font&gt;&lt;/b&gt;&lt;blockquote&gt; &lt;div align="center"&gt;&lt;b&gt;&lt;font color="#990000" face="arial" size="5"&gt;&lt;font color="#ff0000"&gt; &lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;h1&gt;&lt;font size="6"&gt;&lt;b&gt;&lt;font color="#990000" face="arial"&gt;&lt;font color="#ff0000"&gt;100% ORGINAL MARKENWARE AUS DEN USA&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/h1&gt; &lt;p style="color: rgb(0, 0, 0);"&gt;&lt;font size="6"&gt;&lt;b&gt;&lt;font face="arial"&gt;ED HARDY&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/p&gt;&lt;p style="color: rgb(0, 0, 0);"&gt;&lt;b&gt;&lt;font face="arial" size="5"&gt;CAP&lt;br&gt;&lt;/font&gt;&lt;/b&gt;&lt;/p&gt;&lt;/div&gt;&lt;div style="text-align: center;"&gt;&lt;font size="5"&gt;&lt;br&gt;&lt;b&gt;&lt;font color="#990000" face="arial"&gt;&lt;font color="#ff0000"&gt;&lt;b&gt;&lt;font color="black" face="arial"&gt;Style: TRUE ROSE&lt;br&gt;&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;b&gt;&lt;font color="#990000" face="arial"&gt;&lt;font color="#ff0000"&gt;&lt;b&gt;&lt;font color="black" face="arial"&gt;&lt;br&gt;&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;font size="5"&gt;&lt;b&gt;&lt;font color="#990000" face="arial"&gt;&lt;font color="#ff0000"&gt;&lt;b&gt;&lt;font color="black" face="arial"&gt;Die Kollektion von der trend Marke Ed Hardy kreiert sportlich, hipe Mode die bei den Stars in Hollywood der absolute Renner ist. In diesem super Trucker Cap fallen Sie auf !!&amp;nbsp; &lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;font size="5"&gt;&lt;b&gt;&lt;font color="#990000" face="arial"&gt;&lt;font color="#ff0000"&gt;&lt;b&gt;&lt;font color="black" face="arial"&gt;Dieses Cap ist nagelneu mit Etikett und&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;font size="5"&gt;&lt;b&gt;&lt;font color="#990000" face="arial"&gt;&lt;font color="#ff0000"&gt;&lt;b&gt;&lt;font color="black" face="arial"&gt; 100% orginal.&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;font size="5"&gt;&lt;br&gt;&lt;b&gt;&lt;font color="#990000" face="arial"&gt;&lt;font color="#ff0000"&gt;&lt;b&gt;&lt;font color="black" face="arial"&gt;&lt;br&gt;&lt;br&gt;&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;br&gt;&lt;b&gt;&lt;font color="#990000" face="arial"&gt;&lt;font color="#ff0000"&gt;&lt;b&gt;&lt;font color="black" face="arial"&gt;Wir tragen die ebay Kosten und der Kaeufer die Versandkosten.&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;br&gt;&lt;b&gt;&lt;font color="#990000" face="arial"&gt;&lt;font color="#ff0000"&gt;&lt;b&gt;&lt;font color="black" face="arial"&gt;Versandkosten nach Europa sind folgend:&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;br&gt;&lt;b&gt;&lt;font color="#990000" face="arial"&gt;&lt;font color="#ff0000"&gt;&lt;b&gt;&lt;font color="black" face="arial"&gt;fuer unversicherten Versand 6,00 Euro&lt;br&gt;&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;font size="5"&gt;&lt;b&gt;&lt;font color="#990000" face="arial"&gt;&lt;font color="#ff0000"&gt;&lt;b&gt;&lt;font color="black" face="arial"&gt;fuer versicherten Versand 12,00 Euro&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;br&gt; &lt;font size="5"&gt;&lt;span style="font-family: arial;"&gt;&lt;span style="font-weight: bold;"&gt;Bei paypal Bezahlungen akzeptieren wir nur noch versicherten Versand!&lt;/span&gt;&lt;/span&gt;&lt;/font&gt;&lt;br&gt;&lt;font size="5"&gt;&lt;b&gt;&lt;font color="#990000" face="arial"&gt;&lt;font color="#ff0000"&gt;&lt;b&gt;&lt;font color="black" face="arial"&gt;Auf Ihren Wunsch versenden wir die Ware auch versichert. Ansonsten trägt das Risiko beim Versand der Käufer. &lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;br&gt;&lt;b&gt;&lt;font color="#990000" face="arial"&gt;&lt;font color="#ff0000"&gt;&lt;b&gt;&lt;font color="black" face="arial"&gt;Wir bitten um Ihre Zahlung innerhalb 10 Tage nach Auktionsende.&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;br&gt;&lt;/font&gt;&lt;/div&gt;&lt;b&gt;&lt;font color="#990000" face="arial" size="5"&gt;&lt;font color="#ff0000"&gt;&lt;b&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;br&gt; &lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;div align="center"&gt;&lt;b&gt;&lt;font color="#990000" face="arial" size="5"&gt;&lt;font color="#ff0000"&gt;&lt;b&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;font color="#ff0000"&gt; &lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;marquee width="70%" bgcolor="#ffffff"&gt; &lt;h2&gt;&lt;b&gt;&lt;font color="#990000" face="arial" size="5"&gt;&lt;font color="#ff0000"&gt;&lt;b&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;font color="#ff0000"&gt;Schauen Sie unbedingt bei unserem Shop "cheap-and-hip" vorbei!!!&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;/h2&gt;&lt;/marquee&gt;&lt;b&gt;&lt;font color="#990000" face="arial" size="5"&gt;&lt;font color="#ff0000"&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;br&gt;&lt;b&gt;&lt;font color="black" face="arial" size="5"&gt;&lt;br&gt; &lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;blockquote&gt; &lt;div align="center"&gt; &lt;center&gt; &lt;h1&gt;&lt;b&gt;&lt;font color="#990000" face="arial" size="5"&gt;&lt;font color="#ff0000"&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;b&gt;&lt;font color="black" face="arial" size="5"&gt;Abwicklung Ihres Einkaufs bei uns&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;/h1&gt;&lt;b&gt;&lt;font color="#990000" face="arial" size="5"&gt;&lt;font color="#ff0000"&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;b&gt;&lt;font color="black" face="arial" size="5"&gt;&lt;br&gt;&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;/center&gt;&lt;b&gt;&lt;font color="#990000" face="arial" size="5"&gt;&lt;font color="#ff0000"&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;br&gt;&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;/div&gt;&lt;b&gt;&lt;font color="#990000" face="arial" size="5"&gt;&lt;font color="#ff0000"&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;font color="black" face="arial" size="3"&gt;Jeder Käufer erhält innerhalb von 24 Stunden nach Auktionsende eine e-mail mit allen für die Kaufabwicklung relevanten Informationen. Sollten Sie nach 24 Stunden noch keine e-mail erhalten haben, setzen Sie sich bitte mit uns per e-mail in Verbindung. &lt;br&gt;&lt;br&gt; &lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;h2&gt;&lt;b&gt;&lt;font color="#990000" face="arial" size="5"&gt;&lt;font color="#ff0000"&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;font color="black" face="arial" size="3"&gt;Kauf von mehreren Artikeln&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;/h2&gt;&lt;b&gt;&lt;font color="#990000" face="arial" size="5"&gt;&lt;font color="#ff0000"&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;font color="black" face="arial" size="3"&gt;Da das Porto aus den USA nach Gewicht berechnet wird, werden die Versandkosten beim Einkauf von mehreren Artikeln neu berechnet. Bitte teilen Sie uns per e-mail mit, wenn Sie mehrere Artikel ersteigert/gekauft haben, bzw. noch ersteigern/kaufen moechten, Sie erhalten von uns dann die kompletten Versandkosten. Die Kosten fuer den Versand werden von dem Kaeufer getragen. Die Versanddauer betraegt bei Luftversand zirka 5-10 Tage.&lt;br&gt;&lt;br&gt; &lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;h2&gt;&lt;b&gt;&lt;font color="#990000" face="arial" size="5"&gt;&lt;font color="#ff0000"&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;font color="black" face="arial" size="3"&gt;Versand&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;/h2&gt;&lt;b&gt;&lt;font color="#990000" face="arial" size="5"&gt;&lt;font color="#ff0000"&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;font color="black" face="arial" size="3"&gt;Der Versand erfolgt innerhalb von 2-3 Werktagen nach Zahlungseingang (Gutschrift der Überweisung auf unserem Konto bei der Postbank oder bei paypal). Bitte beachten Sie, dass es je nach Kreditinstitut 2-4 Werktage dauern kann, bis Ihre Überweisung auf unserem Konto gutgeschrieben wird. Kreditkarten Gutbuchung ueber paypal erfolgt noch am gleichen Tag.&lt;br&gt;Als Betreff einer Ueberweisung muß unbedingt die eBay-Artikelnummer der Auktion angegeben werden. Ohne diese Information ist eine Zuordnung der Überweisung leider fast nicht möglich! &lt;br&gt;ZOLL: Bitte beachten Sie das Zollgebuehren anfallen koennen auch wenn es nur selten vorkommt sollten Sie sich mit den Einfuhrbestimmungen Ihres Landes vertraut machen. &lt;br&gt;&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;br&gt;&lt;b&gt;&lt;font color="#990000" face="arial" size="5"&gt;&lt;font color="#ff0000"&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;br&gt; &lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;h2&gt;&lt;b&gt;&lt;font color="#990000" face="arial" size="5"&gt;&lt;font color="#ff0000"&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;font color="black" face="arial" size="3"&gt;Umtausch&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;/h2&gt;&lt;b&gt;&lt;font color="#990000" face="arial" size="5"&gt;&lt;font color="#ff0000"&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;font color="black" face="arial" size="3"&gt;Wir tauschen gerne Ihren Artikel um sofern Sie die Ware innerhalb von 14 Tagen nach erhalt den Artikel uns wieder zuschicken. Wir nehmen nur ungetragene Ware zurueck und alle Etiketten muessen noch an dem Artikel befestigt sein&lt;br&gt;&lt;br&gt; &lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;h2&gt;&lt;b&gt;&lt;font color="#990000" face="arial" size="5"&gt;&lt;font color="#ff0000"&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;font color="black" face="arial" size="3"&gt;Falls Sie Reklamationen haben&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;/h2&gt;&lt;b&gt;&lt;font color="#990000" face="arial" size="5"&gt;&lt;font color="#ff0000"&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;font color="black" face="arial" size="3"&gt;Wir bitten bei Beanstandungen der Ware sich erst mit uns in Verbindung zu setzten. Wir pruefen unsere Ware immer auf Defekte aber es kann vorkommen das uns etwas entgeht und bevor Sie eine "negative Bewertung" abgeben moechten wir die Chance bekommen Sie zufrieden zustellen. &lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;p&gt;&lt;b&gt;&lt;font color="#990000" face="arial" size="5"&gt;&lt;font color="#ff0000"&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;b&gt;&lt;font color="#ff0000" face="arial" size="5"&gt; &lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;/p&gt;&lt;center&gt;&lt;b&gt;&lt;font color="#990000" face="arial" size="5"&gt;&lt;font color="#ff0000"&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;b&gt;&lt;font color="#ff0000" face="arial" size="5"&gt;Vielen Dank fuer Ihr Intresse!&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;/center&gt;&lt;p&gt;&lt;b&gt;&lt;font color="#990000" face="arial" size="5"&gt;&lt;font color="#ff0000"&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;b&gt;&lt;font color="#ff0000" face="arial" size="5"&gt;&lt;br&gt;&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;/p&gt;&lt;/blockquote&gt;&lt;/div&gt;&lt;/blockquote&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;br&gt;&lt;br&gt; 1 Baltimore 1 0 1 0 0 0,10 € 0,00 € 0,00 € 0 0 1 77 </code></pre> <p>I would like to know if there is an easy way with sed or awk to remove the HTML tags except for <code>&lt;p&gt;</code> tags. I would also like to know if it is possible for any link html embedding a Flash SWF file, to change the HTML automatically to link to this file.</p> <p>So, in essence, to replace any code such as</p> <pre><code>&lt;embed src="http://backend.supremeauction.com/app/gallery/loader.swf"&gt; </code></pre> <p>with something like <code>&lt;a href="http://backend.supremeauction.com/app/gallery/loader.swf"&gt;Click here for external description&lt;/a&gt;</code> and then remove all other HTML tags except for <code>&lt;p&gt;</code></p> <p>Is this even possible?</p>
<p>Here's the Perl for removing the non-p tags--it won't work across lines though</p> <pre><code>perl -pe 's/&lt;\/?(?&gt;[^p]|p\w+)[^&gt;]*&gt;//ig' </code></pre> <p>That will print it out to standard out and you can redirect it from there. </p> <p>If you have only one link, you could do this:</p> <pre><code>perl -pe 's/&lt;embed\s+src="(.*?\.swf)"\/?&gt;/&lt;a href="$1"&gt;Click here for external description&lt;\/a&gt;/i;s/&lt;\/?(?&gt;[^ap]|[ap]\w+)[^&gt;]*&gt;//ig' </code></pre>
<p>Use <A HREF="http://xmlstar.sf.net/" rel="nofollow noreferrer">xmlstarlet</A> to filter out the tags you want; as it knows XML syntax (which is considerably more complex than can be correctly captured in a regex), it isn't prone to failure in corner cases like nested tags, and can decode <code>&amp;amp;</code> and kin within elements correctly. The <code>select</code> subcommand will take XPath, so a trivial expression to find <code>A</code> elements will do what you want.</p> <p>The <code>format</code> subcommand has an option to take HTML as input, so you'll want to do an initial processing stage with that if your content isn't valid XHTML.</p>
34,243
<p>I have some javascript menu code that works just fine from a separate directory. But, when I try to call the same .js files from within the same directory, it won't see the files.</p> <p>The following works from another directory:</p> <p>script type="text/javascript"> var <strong>vbImgPath="../00-Menu-Files/"</strong></p> <p>But, if I do this from within the same folder, how would I do it?</p> <p><strong>THE SOLUTION (edited this in after much experimentation):</strong></p> <p>I experimented A LOT!!! There is only ONE solution that ultimately worked:</p> <p>"../00-Menu-Files/"</p> <p>The SAME thing as from the other directory! Pretty strange that there is no other way to call this from within its own directory. But I cannot find another alternative that actually works.</p>
<p>Usually directories are like this:</p> <p>../ one up</p> <p>/ root directory</p> <p>./ The current directory. However not adding anything to the front should mean the same.</p>
<p>Maybe you'd use:</p> <pre><code>script type="text/javascript"&gt; var vbImgPath="00-Menu-Files/" </code></pre> <p>You may want to make this work anywhere by using absolute urls with a / at the beginning and the full path afterwards, ie.</p> <pre><code>script type="text/javascript"&gt; var vbImgPath="/00-Menu-Files/" </code></pre> <p>Whether this works or not depends on your site's directory structure.</p>
41,425
<p>I've use Moq to mock my <a href="http://martinfowler.com/eaaCatalog/repository.html" rel="nofollow noreferrer">repositories</a>. However, someone recently said that they prefer to create hard-coded test implementations of their repository interfaces.</p> <p>What are the pros and cons of each approach?</p> <p><strong>Edit:</strong> clarified meaning of repository with link to Fowler.</p>
<p>I generally see two scenarios with repositories. I ask for something, and I get it, or I ask for something, and it isn't there.</p> <p>If you are mocking your repository, that means you system under test (SUT) is something that is using your repository. So you generally want to test that your SUT behaves correctly when it is given an object from the repository. And you also want to test that it handles the situation properly when you expect to get something back and don't, or aren't sure if you are going to get something back.</p> <p>Hard-coded test doubles are ok if you are doing integration testing. Say, you want to save an object, and then get it back. But this is testing the interaction of two objects together, not just the behavior of the SUT. They are two different things. If you start coding fake repositories, you need unit tests for those as well, otherwise you end up basing the success and failure of your code on untested code.</p> <p>That's my opinion on Mocking vs. Test Doubles.</p>
<p>I assume that by "repository" you mean a <a href="http://en.wikipedia.org/wiki/Data_Access_Object" rel="nofollow noreferrer">DAO</a>; if not then this answer won't apply.</p> <p>Lately I've been making "in memory" "mock" (or test) implementations of my DAO, that basically operate off of data (a List, Map, etc.) passed into the mock's constructor. This way the unit test class is free to throw in whatever data it needs for the test, can change it, etc., without forcing all unit tests operating on the "in memory" DAO to be coded to use the same test data. </p> <p>One plus that I see in this approach is that if I have a dozen unit tests that need to use the same DAO for their test (to inject into the class under test, for example), I don't need to remember all of the details of the test data each time (as you would if the "mock" was hardcoded) - the unit test creates the test data itself. On the downside, this means each unit test has to spend a few lines creating and wiring up it's test data; but that's a small downside to me.</p> <p>A code example:</p> <pre><code>public interface UserDao { User getUser(int userid); User getUser(String login); } public class InMemoryUserDao implements UserDao { private List users; public InMemoryUserDao(List users) { this.users = users; } public User getUser(int userid) { for (Iterator it = users.iterator(); it.hasNext();) { User user = (User) it.next(); if (userid == user.getId()) { return user; } } return null; } public User getUser(String login) { for (Iterator it = users.iterator(); it.hasNext();) { User user = (User) it.next(); if (login.equals(user.getLogin())) { return user; } } return null; } } </code></pre>
46,916
<p>I just installed the SharePoint SDK on my machine, but I can't seem to find the location of Microsoft.Sharepoint.dll so I can add a reference to it.</p> <p>It's not in the GAC or C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\ISAPI\ and a search comes up with nothing.</p> <p>Any suggestions?</p>
<p>Just FYI, I found it on the server where SharePoint was installed at:</p> <p>E:\Program Files\Common Files\Microsoft Shared\web server extensions\12\ISAPI</p>
<p>It might show up in the "add reference" dialog anyway - 99% of the time you don't reed to know the physical location. Look in the ".Net" list, which is sorted alphabetically.</p> <p>I assume the SDK installer would assert this, but Sharepoint development also requires a server OS.</p>
43,146
<p>How is possible to set some special column values when update/insert entities via NHibernate without extending domain classes with special properties?</p> <p>E.g. every table contains audit columns like CreatedBy, CreatedDate, UpdatedBy, UpdatedDate. But I dont want to add these poperties to the domain classes. I want to keep domain modedl Percistence Ignorance factor as high as possible.</p>
<p>You might want to try looking into NHibernate's IUserType.</p> <p>At the bottom of the following page is an example where ayende removes some encryption logic out of the entity and allows NHibernate to just take care of it.</p> <p><a href="http://ayende.com/Blog/archive/2008/07/31/Entities-dependencies-best-practices.aspx" rel="nofollow noreferrer">http://ayende.com/Blog/archive/2008/07/31/Entities-dependencies-best-practices.aspx</a></p>
<p>It's not the same as "not adding these properties", but the last time I saw this, the engineer addressed it by implementing concrete NHibernate classes and deriving them from a common abstract base class (e.g. MyAuditable) that implemented the properties you dislike. This way you only have to solve the problem once.</p>
12,302
<p>I am in the start up of a project using ASP.NET MVC and have started creating my models. Since I know <em>some</em> Ruby On Rails and would like to use a system as similar to Rails <strong>Active Record</strong> as possible.</p> <p>Have anyone used <strong>Castle Projects Active Record</strong> in a ASP.NET MVC application (or any application that is relevant) and have some experience to share?</p> <p>Are MVC and Castle Active Record the right way to go or do you suggest I use LinqToSql instead.</p> <p>Please share any thoughts and experiences you might have gain.</p> <p>Edit: To clarify; I come from a long ASP.NET and C# background but have looked a little at Rails and love how easy you can create the ORM </p>
<p>I have used Castle Active Record with ASP.NET MVC. I highly encourage this model, as ActiveRecord/NHibernate are much more mature that LINQ to SQL or the Entity Framework.</p> <p>I think that ASP.NET MVC has a bright future and would recommend it over Monorail for new projects. However, as I said, ActiveRecord is (in my view) a superior ORM to LinqToSQL.</p>
<p>MVC doesn't know what ORM you are using, or is there even some ORM tool behind. Controller/Action must send object references to View, so that object can be simple int, string array, DataSet, Linq object, ActiveRecord object, whatever, it doesn't matter for View how some object is filled with data!</p>
21,705
<p>Ok so I've spent a couple hours trying to resolve this issue and have had no leads so far, keep getting the same 404 error. What happens is the website picks up the Default.aspx page and displays it like it should. But the Home page has a clickable image where it routes to another view page. The image code is like so:</p> <pre><code>&lt;a href="&lt;%= Url.Action("SelectPage", "Home") %&gt;" onmouseover="lightup('pic1')" onmouseout="turnoff('pic1') "&gt; &lt;img class="imageMain" src="&lt;%= Url.Content("~/Content/Images/image.gif")%&gt;" name="pic1" alt="Image 1" /&gt;&lt;/a&gt; </code></pre> <p>When clicked I receive a 404 error. </p> <p>My Controller View is setup like so:</p> <pre><code>public ActionResult SelectPage() { // Add action logic here ViewData["Title"] = "Select an option"; ViewData["Header"] = "NoHeader"; return View(); } </code></pre> <p>in my global file i have the routing setup like so:</p> <pre><code>routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}.aspx/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = "" } // Parameter defaults ); </code></pre> <p>I have tried the wildcard trick, but no luck I have also tried this tutorial <a href="http://www.asp.net/learn/mvc/tutorial-08-cs.aspx" rel="nofollow noreferrer">http://www.asp.net/learn/mvc/tutorial-08-cs.aspx</a> still no luck.</p> <p>I have no idea where to go with this any help would be greatly appreciated.</p>
<p>I noticed something odd in that tutorial link you posted. Verify File Exists should be unchecked.</p>
<p>Check out this post:</p> <p><a href="http://www.ee99ee.com/blog/2009/02/08/how-to-get-aspnet-mvc-working-under-iis-51-on-windows-xp/" rel="nofollow noreferrer">http://www.ee99ee.com/blog/2009/02/08/how-to-get-aspnet-mvc-working-under-iis-51-on-windows-xp/</a></p>
49,139
<p>In PHP, the HEREDOC string declarations are really useful for outputting a block of html. You can have it parse in variables just by prefixing them with $, but for more complicated syntax (like $var[2][3]), you have to put your expression inside {} braces.</p> <p>In PHP 5, it <em>is</em> possible to actually make function calls within {} braces inside a HEREDOC string, but you have to go through a bit of work. The function name itself has to be stored in a variable, and you have to call it like it is a dynamically-named function. For example:</p> <pre><code>$fn = 'testfunction'; function testfunction() { return 'ok'; } $string = &lt;&lt;&lt; heredoc plain text and now a function: {$fn()} heredoc; </code></pre> <p>As you can see, this is a bit more messy than just:</p> <pre><code>$string = &lt;&lt;&lt; heredoc plain text and now a function: {testfunction()} heredoc; </code></pre> <p>There are other ways besides the first code example, such as breaking out of the HEREDOC to call the function, or reversing the issue and doing something like:</p> <pre><code>?&gt; &lt;!-- directly output html and only breaking into php for the function --&gt; plain text and now a function: &lt;?PHP print testfunction(); ?&gt; </code></pre> <p>The latter has the disadvantage that the output is directly put into the output stream (unless I'm using output buffering), which might not be what I want.</p> <p>So, the essence of my question is: is there a more elegant way to approach this?</p> <p><b>Edit based on responses:</b> It certainly does seem like some kind of template engine would make my life much easier, but it would require me basically invert my usual PHP style. Not that that's a bad thing, but it explains my inertia.. I'm up for figuring out ways to make life easier though, so I'm looking into templates now.</p>
<p>I would not use HEREDOC at all for this, personally. It just doesn't make for a good "template building" system. All your HTML is locked down in a string which has several disadvantages</p> <ul> <li>No option for WYSIWYG</li> <li>No code completion for HTML from IDEs</li> <li>Output (HTML) locked to logic files</li> <li>You end up having to use hacks like what you're trying to do now to achieve more complex templating, such as looping</li> </ul> <p>Get a basic template engine, or just use PHP with includes - it's why the language has the <code>&lt;?php</code> and <code>?&gt;</code> delimiters.</p> <p><strong>template_file.php</strong></p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;&lt;?php echo $page_title; ?&gt;&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;?php echo getPageContent(); ?&gt; &lt;/body&gt; </code></pre> <p><strong>index.php</strong></p> <pre><code>&lt;?php $page_title = "This is a simple demo"; function getPageContent() { return '&lt;p&gt;Hello World!&lt;/p&gt;'; } include('template_file.php'); </code></pre>
<pre><code>&lt;?php echo &lt;&lt;&lt;ETO &lt;h1&gt;Hellow ETO&lt;/h1&gt; ETO; </code></pre> <p>you should try it . after end the ETO; command you should give an enter.</p>
13,011
<p>How do I declare a private function in Fortran?</p>
<p>This will only work with a Fortran 90 module. In your module declaration, you can specify the access limits for a list of variables and routines using the "public" and "private" keywords. I usually find it helpful to use the private keyword by itself initially, which specifies that everything within the module is private unless explicitly marked public.</p> <p>In the code sample below, subroutine_1() and function_1() are accessible from outside the module via the requisite "use" statement, but any other variable/subroutine/function will be private.</p> <pre><code>module so_example implicit none private public :: subroutine_1 public :: function_1 contains ! Implementation of subroutines and functions goes here end module so_example </code></pre>
<pre><code>Private xxx, yyy, zzz real function xxx (v) ... end function xxx integer function yyy() ... end function yyy subroutine zzz ( a,b,c ) ... end subroutine zzz ... other stuff that calls them ... </code></pre>
27,249
<p>I'd like to stick a class down in my folder hierarchy. The scenario is too trivial to warrant it's own project or separate website. However, I hate to clutter my top-level App_Code with something that's used by a tiny corner of the site.</p> <p>Is there a way in web.config to include another file or folder in the compilation process?</p>
<pre><code>&lt;configuration&gt; &lt;system.web&gt; &lt;compilation&gt; &lt;assemblies&gt; &lt;add assembly="&lt;AssemblyName&gt;, Version=&lt;Version&gt;, Culture=&lt;Culture&gt;, PublicKeyToken=&lt;PublicKeyToken&gt;"/&gt; &lt;/assemblies&gt; &lt;/compilation&gt; &lt;/system.web&gt; &lt;/configuration&gt; </code></pre>
<pre><code>&lt;configuration&gt; &lt;system.web&gt; &lt;compilation&gt; &lt;assemblies&gt; &lt;add assembly="&lt;AssemblyName&gt;, Version=&lt;Version&gt;, Culture=&lt;Culture&gt;, PublicKeyToken=&lt;PublicKeyToken&gt;"/&gt; &lt;/assemblies&gt; &lt;/compilation&gt; &lt;/system.web&gt; &lt;/configuration&gt; </code></pre>
30,942
<p>I've read different things about PLA and heat-bed. Some say it is not needed, others recommend 60-70°C, but not for the first layers.</p> <p>For larger objects I often have the problem that the object does not stick to the blue-painters-tape-covered aluminium print plate. Instead the print "curls" up on one or more corners. To reduce this effect, I'm using a brim between 5 and 10mm. Depending on the size of the object the brim works quite well. Will heating the bed also improve the print quality by reducing the amount of heat warping / curling?</p>
<p>Heating the bed helps me, even with PLA. I print with a 60&nbsp;°C bed. The bed is 3/8" 6061 alloy aluminum, sanded with 600 grit sandpaper, coated with Elmer's purple glue stick, and dried.</p> <p>The brim will help. You might make the brim thicker than one layer (like 2-3 layers).</p> <p>If you look at the bottom of your print, are there large gaps where the PLA doesn't touch the bed? If so, you could zero the head closer to the bed, or increase the flow for the first layer.</p> <p>I haven't set up a cooling fan, although many praise the results. It is an experiment for a future day.</p>
<p>Heated bed definitely helps with PLA adhesion, it also helps depending the surface, for example PEI offers better adhesion than glass. Another option is to try to overextrude the first layer (125&nbsp;%) and make sure it is squeezed out, so basically you get a wavy effect on the first layer. This should help a bit even in the curly corners. Another thing I have noticed from experience is the PLA itself, not all PLAs are the same so you could try another manufacturer or try your PLA in a friend's printer to see if you get the same effect. Generally on PLA we do not expect any warping, but the reality is that some do have.</p>
455
<pre><code>string[] filesOfType1 = GetFileList1(); string[] filesOfType2 = GetFileList2(); var cookieMap = new Dictionary&lt;string, CookieContainer&gt;(); Action&lt;string, Func&lt;string, KeyValuePair&lt;string, CookieContainer&gt;&gt;&gt; addToMap = (filename, pairGetter) =&gt; { KeyValuePair&lt;string, CookieContainer&gt; cookiePair; try { cookiePair = pairGetter(filename); } catch { Console.WriteLine("An error was encountered while trying to read " + file + "."); return; } if (cookieMap.ContainsKey(cookiePair.Key)) { if (cookiePair.Value.Count &gt; cookieMap[cookiePair.Key].Count) { cookieMap[cookiePair.Key] = cookiePair.Value; } } else { cookieMap.Add(cookiePair.Key, cookiePair.Value); } }; foreach (string file in filesOfType1) { addToMap(file, GetType1FileCookiePair); } foreach (string file in filesOfType2) { addToMap(file, GetType2FileCookiePair); } </code></pre> <p>Salient features that must be preserved:</p> <ul> <li>Files of type 1 are more important than files of type 2; i.e. if a file of type 1 maps to a (key, value1) combination and a file of type 2 maps to a (key, value2) combination, then we add (key, value1) to cookieMap and <em>not</em> (key, value2). <strong>Edit: as pointed out by Bevan, this is not satisfied by my original procedural code.</strong></li> <li>Secondarily, <code>CookieContainer</code>s with a higher <code>Count</code> have higher priority, i.e. if there are two (key, value) combos for the same key and both from the same filetype, we choose the one with higher <code>value.Count</code>.</li> <li>Per-case exception handling is a must; screwing up a single file-reading should just allows us to note that and continue.</li> </ul> <p>My best attempt started like this:</p> <pre><code>var cookieMap = (filesOfType1.Select(file =&gt; GetType1FileCookiePair(file)) .Concat(filesOfType2.Select(file =&gt; GetType2FileCookiePair(file)))) .GroupBy(pair =&gt; pair.Key) .Select(/* some way of selecting per the above bullets */) .ToDictionary(pair =&gt; pair.Key, pair =&gt; pair.Value); </code></pre> <p>But it's inelegant and filling in that comment block seems like a bitch. Right now I'm happy to stay procedural, but I thought that it might be a fun challenge to see if people can come up with something really clever.</p>
<p>Here's my attempt - seemed simplest to split the task into three distinct statements.</p> <p>I'm using a helper function that returns null if the action throws an exception - for consistency with the answer from Omer van Kloeten, I've called this Swallow()</p> <p>Also, I'm not using the LINQ syntax, just the extension methods provided by System.Linq.Enumerable</p> <p>Lastly, note that this is uncompiled - so take it as intent.</p> <pre><code>// Handle all files of type 1 var pairsOfType1 = filesOfType1 .Select( file =&gt; Swallow( pairGetter(file))) .Where( pair =&gt; pair != null); // Handle files of type 2 and filter out those with keys already provided by type 1 var pairsOfType2 = filesOfType2 .Select( file =&gt; Swallow( pairGetter(file))) .Where( pair =&gt; pair != null); .Where( pair =&gt; !pairsOfType1.Contains(p =&gt; p.Key == pair.Key)); // Merge the two sets, keeping only the pairs with the highest count var cookies = pairsOfType1 .Union( pairsOfType2) .GroupBy( pair =&gt; pair.Key) .Select( group =&gt; group.OrderBy( pair =&gt; pair.Value.Count).Last()); .ToDictionary( pair =&gt; pair.Key); </code></pre>
<p>Excuse my not actually going ahead and compiling this, but this is the way I'd go around to doing it:</p> <pre><code>var cookieMap = (from pair in (from f1 in filesOfType1 select Swallow(() =&gt; GetType1FileCookiePair(f1))) .Concat(from f2 in filesOfType2 select Swallow(() =&gt; GetType2FileCookiePair(f2))) .SelectMany(dict =&gt; dict) group pair by pair.Key into g select g) .ToDictionary(g =&gt; g.Key, g =&gt; g.Select(pair =&gt; pair.Value) .OrderByDescending(value =&gt; value.Count) .First()); </code></pre> <p><code>Swallow</code> follows:</p> <pre><code>private static T Swallow&lt;T&gt;(Func&lt;T&gt; getT) { try { return getT(); } catch { } return default(T); } </code></pre> <p>Love me a good LINQ.</p> <ul> <li><strong>Edit:</strong> Added a <code>Swallow</code> method that will swallow all exceptions.</li> <li><strong>Edit 2:</strong> Compiled, altered, etc. Added <code>Swallow</code>. Now works as intended.</li> </ul>
29,520
<p>I need to call a <a href="http://en.wikipedia.org/wiki/VBScript" rel="noreferrer">VBScript</a> file (.vbs file extension) in my C# Windows application. How can I do this? </p> <p>There is an add-in to access a VBScript file in Visual Studio. But I need to access the script in code behind. How to do this?</p>
<p>The following code will execute a VBScript script with no prompts or errors and no shell logo.</p> <pre><code>System.Diagnostics.Process.Start(@"cscript //B //Nologo c:\scripts\vbscript.vbs"); </code></pre> <p>A more complex technique would be to use:</p> <pre><code>Process scriptProc = new Process(); scriptProc.StartInfo.FileName = @"cscript"; scriptProc.StartInfo.WorkingDirectory = @"c:\scripts\"; //&lt;---very important scriptProc.StartInfo.Arguments ="//B //Nologo vbscript.vbs"; scriptProc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; //prevent console window from popping up scriptProc.Start(); scriptProc.WaitForExit(); // &lt;-- Optional if you want program running until your script exit scriptProc.Close(); </code></pre> <p>Using the <code>StartInfo</code> properties will give you quite granular access to the process settings.</p> <p>You need to use <a href="http://en.wikipedia.org/wiki/Windows_Script_Host" rel="noreferrer">Windows Script Host</a> if you want windows, etc. to be displayed by the script program. You could also try just executing <code>cscript</code> directly but on some systems it will just launch the editor :)</p>
<p>For the benefit of searchers, I found this <a href="https://social.microsoft.com/Forums/en-US/9f5505d3-ab39-4f66-9ce5-95a7af432d22/passing-a-parameter-from-a-c-form-to-a-vbscript-and-executing-script?forum=Offtopic" rel="nofollow">post</a>, which gives a clear answer (esp if you have parameters). Have tested it - seems to work fine.</p> <pre><code>string scriptName = "myScript.vbs"; // full path to script int abc = 2; string name = "Serrgggio"; ProcessStartInfo ps = new ProcessStartInfo(); ps.FileName = "cscript.exe"; ps.Arguments = string.Format("\"{0}\" \"{1}\" \"{2}\"", scriptName, abc, name); //This will equate to running via the command line: // &gt; cscript.exe "myScript.vbs" "2" "Serrgggio" Process.Start(ps); </code></pre>
24,448
<h2>Note</h2> <p>The question below was asked in 2008 about some code from 2003. As the OP's <strong>update</strong> shows, this entire post has been obsoleted by vintage 2008 algorithms and persists here only as a historical curiosity.</p> <hr> <p>I need to do a fast case-insensitive substring search in C/C++. My requirements are as follows:</p> <ul> <li>Should behave like strstr() (i.e. return a pointer to the match point).</li> <li>Must be case-insensitive (doh).</li> <li>Must support the current locale.</li> <li>Must be available on Windows (MSVC++ 8.0) or easily portable to Windows (i.e. from an open source library).</li> </ul> <p>Here is the current implementation I am using (taken from the GNU C Library):</p> <pre><code>/* Return the offset of one string within another. Copyright (C) 1994,1996,1997,1998,1999,2000 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ /* * My personal strstr() implementation that beats most other algorithms. * Until someone tells me otherwise, I assume that this is the * fastest implementation of strstr() in C. * I deliberately chose not to comment it. You should have at least * as much fun trying to understand it, as I had to write it :-). * * Stephen R. van den Berg, berg@pool.informatik.rwth-aachen.de */ /* * Modified to use table lookup instead of tolower(), since tolower() isn't * worth s*** on Windows. * * -- Anders Sandvig (anders@wincue.org) */ #if HAVE_CONFIG_H # include &lt;config.h&gt; #endif #include &lt;ctype.h&gt; #include &lt;string.h&gt; typedef unsigned chartype; char char_table[256]; void init_stristr(void) { int i; char string[2]; string[1] = '\0'; for (i = 0; i &lt; 256; i++) { string[0] = i; _strlwr(string); char_table[i] = string[0]; } } #define my_tolower(a) ((chartype) char_table[a]) char * my_stristr (phaystack, pneedle) const char *phaystack; const char *pneedle; { register const unsigned char *haystack, *needle; register chartype b, c; haystack = (const unsigned char *) phaystack; needle = (const unsigned char *) pneedle; b = my_tolower (*needle); if (b != '\0') { haystack--; /* possible ANSI violation */ do { c = *++haystack; if (c == '\0') goto ret0; } while (my_tolower (c) != (int) b); c = my_tolower (*++needle); if (c == '\0') goto foundneedle; ++needle; goto jin; for (;;) { register chartype a; register const unsigned char *rhaystack, *rneedle; do { a = *++haystack; if (a == '\0') goto ret0; if (my_tolower (a) == (int) b) break; a = *++haystack; if (a == '\0') goto ret0; shloop: ; } while (my_tolower (a) != (int) b); jin: a = *++haystack; if (a == '\0') goto ret0; if (my_tolower (a) != (int) c) goto shloop; rhaystack = haystack-- + 1; rneedle = needle; a = my_tolower (*rneedle); if (my_tolower (*rhaystack) == (int) a) do { if (a == '\0') goto foundneedle; ++rhaystack; a = my_tolower (*++needle); if (my_tolower (*rhaystack) != (int) a) break; if (a == '\0') goto foundneedle; ++rhaystack; a = my_tolower (*++needle); } while (my_tolower (*rhaystack) == (int) a); needle = rneedle; /* took the register-poor approach */ if (a == '\0') break; } } foundneedle: return (char*) haystack; ret0: return 0; }</code></pre> <p>Can you make this code faster, or do you know of a better implementation?</p> <p><strong>Note:</strong> I noticed that the GNU C Library now has <a href="http://sources.redhat.com/cgi-bin/cvsweb.cgi/libc/string/strstr.c?rev=1.2&amp;content-type=text/x-cvsweb-markup&amp;cvsroot=glibc" rel="nofollow noreferrer">a new implementation of <code>strstr()</code></a>, but I am not sure how easily it can be modified to be case-insensitive, or if it is in fact faster than the old one (in my case). I also noticed that <a href="http://sources.redhat.com/cgi-bin/cvsweb.cgi/libc/wcsmbs/wcsstr.c?rev=1.4&amp;content-type=text/x-cvsweb-markup&amp;cvsroot=glibc" rel="nofollow noreferrer">the old implementation is still used for wide character strings</a>, so if anyone knows why, please share.</p> <p><strong>Update</strong></p> <p>Just to make things clear&mdash;in case it wasn't already&mdash;I didn't write this function, it's a part of the GNU C Library. I only modified it to be case-insensitive.</p> <p>Also, thanks for the tip about <code>strcasestr()</code> and checking out other implementations from other sources (like OpenBSD, FreeBSD, etc.). It seems to be the way to go. The code above is from 2003, which is why I posted it here in hope for a better version being available, which apparently it is. :)</p>
<p>The code you posted is about half as fast as <code>strcasestr</code>. </p> <pre class="lang-none prettyprint-override"><code>$ gcc -Wall -o my_stristr my_stristr.c steve@solaris:~/code/tmp $ gcc -Wall -o strcasestr strcasestr.c steve@solaris:~/code/tmp $ ./bench ./my_stristr &gt; my_stristr.result ; ./bench ./strcasestr &gt; strcasestr.result; steve@solaris:~/code/tmp $ cat my_stristr.result run 1... time = 6.32 run 2... time = 6.31 run 3... time = 6.31 run 4... time = 6.31 run 5... time = 6.32 run 6... time = 6.31 run 7... time = 6.31 run 8... time = 6.31 run 9... time = 6.31 run 10... time = 6.31 average user time over 10 runs = 6.3120 steve@solaris:~/code/tmp $ cat strcasestr.result run 1... time = 3.82 run 2... time = 3.82 run 3... time = 3.82 run 4... time = 3.82 run 5... time = 3.82 run 6... time = 3.82 run 7... time = 3.82 run 8... time = 3.82 run 9... time = 3.82 run 10... time = 3.82 average user time over 10 runs = 3.8200 steve@solaris:~/code/tmp </code></pre> <p>The <code>main</code> function was: </p> <pre class="lang-c prettyprint-override"><code>int main(void) { char * needle="hello"; char haystack[1024]; int i; for(i=0;i&lt;sizeof(haystack)-strlen(needle)-1;++i) { haystack[i]='A'+i%57; } memcpy(haystack+i,needle, strlen(needle)+1); /*printf("%s\n%d\n", haystack, haystack[strlen(haystack)]);*/ init_stristr(); for (i=0;i&lt;1000000;++i) { /*my_stristr(haystack, needle);*/ strcasestr(haystack,needle); } return 0; } </code></pre> <p>It was suitably modified to test both implementations. I notice as I am typing this up I left in the <code>init_stristr</code> call, but it shouldn't change things too much. <code>bench</code> is just a simple shell script:</p> <pre class="lang-c prettyprint-override"><code>#!/bin/bash function bc_calc() { echo $(echo "scale=4;$1" | bc) } time="/usr/bin/time -p" prog="$1" accum=0 runs=10 for a in $(jot $runs 1 $runs) do echo -n "run $a... " t=$($time $prog 2&gt;&amp;1| grep user | awk '{print $2}') echo "time = $t" accum=$(bc_calc "$accum+$t") done echo -n "average user time over $runs runs = " echo $(bc_calc "$accum/$runs") </code></pre>
<p>If you want to shed CPU cycles, you might consider this - let's assume that we're dealing with ASCII and not Unicode.</p> <p>Make a static table with 256 entries. Each entry in the table is 256 bits.</p> <p>To test whether or not two characters are equal, you do something like this:</p> <pre><code>if (BitLookup(table[char1], char2)) { /* match */ } </code></pre> <p>To build the table, you set a bit everywhere in table[char1] where you consider it a match for char2. So in building the table you would set the bits at the index for 'a' and 'A' in the 'a'th entry (and the 'A'th entry).</p> <p>Now this is going to be slowish to do the bit lookup (bit look up will be a shift, mask and add most likely), so you could use instead a table of bytes so you use 8 bits to represent 1 bit. This will take 32K - so hooray - you've hit a time/space trade-off! We might want to make the table more flexible, so let's say we do this instead - the table will define congruences instead.</p> <p>Two characters are considered congruent if and only if there is a function that defines them as equivalent. So 'A' and 'a' are congruent for case insensitivity. 'A', '&Agrave;', '&Aacute;' and '&#194;' are congruent for diacritical insensitivity.</p> <p>So you define bitfields that correspond to your congruencies</p> <pre><code>#define kCongruentCase (1 &lt;&lt; 0) #define kCongruentDiacritical (1 &lt;&lt; 1) #define kCongruentVowel (1 &lt;&lt; 2) #define kCongruentConsonant (1 &lt;&lt; 3) </code></pre> <p>Then your test is something like this:</p> <pre><code>inline bool CharsAreCongruent(char c1, char c2, unsigned char congruency) { return (_congruencyTable[c1][c2] &amp; congruency) != 0; } #define CaseInsensitiveCharEqual(c1, c2) CharsAreCongruent(c1, c2, kCongruentCase) </code></pre> <p>This kind of bit fiddling with ginormous tables is the heart of ctype, by the by.</p>
25,999
<p>We want to store our overridden build targets in an external file and include that targets file in the TFSBuild.proj. We have a core set steps that happens and would like to get those additional steps by simply adding the import line to the TFSBuild.proj created by the wizard. </p> <pre><code>&lt;Import Project="$(SolutionRoot)/libs/my.team.build/my.team.build.targets"/&gt; </code></pre> <p>We cannot have an import on any file in the <code>$(SolutionRoot)</code> because at the time the Import statement is validated, the source has not be fetched from the repository. It looks like TFS is pulling down the <code>TFSBuild.proj</code> first without any other files.</p> <p>Even if we add a conditional import, the version in source control will not be imported if present. The previous version, already present on disk will be imported. </p> <p>We can give up storing those build targets with our source, but it is the first dependency to move out of our source tree so we are reluctant to do it.</p> <p>Is there a way to either:</p> <ol> <li>Tell Team Build to pull down a few more files so those <code>Import</code> statements evaluate correctly?</li> <li>Override those Team Build targets like <code>AfterCompile</code> in a manner besides the <code>Import</code>?</li> <li>Ultimately run build targets in Team Build that are kept under the source it's trying to build?</li> </ol>
<p>The Team Build has a "bootstrap" phase where everything in the Team Build Configuration folder (the folder with TFSBuild.proj) is downloaded from version control. This is performed by the build agent before the build agent calls MSBuild.exe telling it to run TFSBuild.proj.</p> <p>If you move your targets file from under SolutionRoot and place it in your configuration folder alongside the TFSBuild.proj file you will then be able to import it in your TFSBuild.proj file using a relative import statement i.e.</p> <pre><code>&lt;Import Project="myTeamBuild.targets"/&gt; </code></pre> <p>If these targets rely on any additional custom MSBuild task assemblies then you can also have them in the same folder as your TFSBuild.proj file and you can reference them easily using a relative path.</p> <p>Note that in TFS2008, the build configuration folder defaults to being under $/TeamProject/TeamBuildTypes however, it does not have to be there. It can actually live in a folder that is inside your solution - and can even be a project in your solution dedicated to Team Build. This has several advantages including making branching of the build easier. Therefore I typically have my build located in a folder like this:</p> <pre><code>$/TeamProject/main/MySolution/TeamBuild </code></pre> <p>Also note that by default, during the bootstrap phase of the build, the build agent will only download files that are in the build configuration folder and will not recurse down into any subfolders. If you wanted it to include files in subfolders during the bootstrap phase then you can set the following property in the appSettings of the tfsbuildserver.exe.config file on the build agent machines (located in %ProgramFiles%\Visual Studio 9.0\Common7\IDE\PrivateAssemblies)</p> <pre><code>&lt;add key="ConfigurationFolderRecursionType" value="Full" /&gt; </code></pre> <p>Note that if you had multiple build agents you would have to remember to set this setting on all of the machines, and it would affect every build performed by that build agent - so really it is best just to keep the files in the root of the build configuration folder if you can.</p> <p>Good luck,</p> <p>Martin.</p>
<p>If you create an overrides target file to import and call it something like TeamBuildOverrides.targets and put it in the same folder in source control where TFSBuild.proj lives for your Build Type, it will be pulled first and be available for import into the TFSBuild.proj file. By default, the TFSBuild.proj file is added to the TeamBuildTypes folder in Source Control directly under the root folder of your project.</p> <p>use the following import statement in your TFSBuild.proj file:</p> <pre><code>&lt;Import Project="$(MSBuildProjectDirectory)\TeamBuildOverrides.targets" /&gt; </code></pre> <p>Make sure you don't have any duplicate overrides in your TFSBuild.proj file or the imported overrides will not get fired.</p>
12,282
<p>Is there a way in <em>Xcode</em> to sort my list of files under say the Classes folder Alphabetically?</p> <p>I know I can drag them around, but with tons of files that is a pain.</p> <p>I am surprised I can not right click on the folder and say to sort.</p>
<p>Click on the folder, and then click Edit > Sort > By Name</p>
<p>Czar there are advantages to having it the way you want, instead of automatically having it sort at all times.</p> <p>Some classes might be related in some way, but the names aren't right next to each other, I've used that for certain. :)</p>
29,585
<p>How can I convert a varchar field of the form YYYYMMDD to a datetime in T-SQL?</p> <p>Thank you.</p>
<pre><code>select convert(datetime, '20081030') </code></pre>
<p>Use the CONVERT() function?</p> <p><a href="http://msdn.microsoft.com/en-us/library/ms187928.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms187928.aspx</a></p>
31,249
<p>I have an application that I would like to embed inside our companies CMS. The only way to do that (I am told), is to load it in an <code>&lt;iframe&gt;</code>.</p> <p>Easy: just set <code>height</code> and <code>width</code> to <code>100%</code>! Except, it doesn't work.</p> <p>I did find out about setting <code>frameborder</code> to <code>0</code>, so it at least <em>looks</em> like part of the site, but I'd prefer not to have an ugly scrollbar <em>inside</em> a page that allready has one.</p> <p>Do you know of any tricks to do this?</p> <p><strong>EDIT:</strong> I think I need to clarify my question somewhat:</p> <ul> <li>the company CMS displays the fluff and stuff for our whole website</li> <li>most pages created through the CMS</li> <li>my application isn't, but they will let me embedd it in an <code>&lt;iframe&gt;</code></li> <li>I have no control over the <code>iframe</code>, so any solution must work from the referenced page (according to the <code>src</code> attribute of the <code>iframe</code> tag)</li> <li>the CMS displays a footer, so setting the height to 1 million pixels is not a good idea</li> </ul> <p>Can I access the parent pages DOM from the referenced page? This might help, but I can see some people might not want this to be possible...</p> <p>This technique seems to work (<a href="http://bytes.com/forum/thread91876.html" rel="noreferrer">gleaned</a> from several sources, but inspired by the <a href="http://brondsema.net/blog/index.php/2007/06/06/100_height_iframe" rel="noreferrer">link</a> from the accepted answer:</p> <p>In parent document:</p> <pre><code>&lt;iframe id="MyIFRAME" name="MyIFRAME" src="http://localhost/child.html" scrolling="auto" width="100%" frameborder="0"&gt; no iframes supported... &lt;/iframe&gt; </code></pre> <p>In child:</p> <pre><code>&lt;!-- ... --&gt; &lt;body&gt; &lt;script type="text/javascript"&gt; function resizeIframe() { var docHeight; if (typeof document.height != 'undefined') { docHeight = document.height; } else if (document.compatMode &amp;&amp; document.compatMode != 'BackCompat') { docHeight = document.documentElement.scrollHeight; } else if (document.body &amp;&amp; typeof document.body.scrollHeight != 'undefined') { docHeight = document.body.scrollHeight; } // magic number: suppress generation of scrollbars... docHeight += 20; parent.document.getElementById('MyIFRAME').style.height = docHeight + "px"; } parent.document.getElementById('MyIFRAME').onload = resizeIframe; parent.window.onresize = resizeIframe; &lt;/script&gt; &lt;/body&gt; </code></pre> <p><strong>BTW:</strong> This will only work if parent and child are in the same domain due to a restriction in JavaScript for security reasons...</p>
<p>You could either just use a scripting language to include the page into the parent page, other wise, you might want to try one of these javascript methods:</p> <p><a href="http://brondsema.net/blog/index.php/2007/06/06/100_height_iframe" rel="nofollow noreferrer">http://brondsema.net/blog/index.php/2007/06/06/100_height_iframe</a> <a href="http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_22840093.html" rel="nofollow noreferrer">http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_22840093.html</a></p>
<p>I might be missing something here, but adding <code>scrolling=no</code> as an attribute to the <code>iframe</code> tag normally gets rid of the scrollbars.</p>
8,291
<p>I am a <code>C/C++</code> programmer professionally, but I've created a couple of personal web sites using <code>PHP and MySQL</code>. </p> <p>They're pretty basic, and I'd like to jazz them up using <code>Ajax</code>, but I've never done any Ajax. I've done all the development so far manually, i.e. no IDE or anything like that.</p> <p><strong>Does anyone have suggestions on Ajax development environments that can help me?</strong></p> <p>Shareware or freeware would be preferable as I'd find it hard to justify spending more than a minimal amount of money on this...</p>
<p>As T.O. says, try Aptana. There's a very good free version, and they really push the AJAX. They even have Jaxer, an "AJAX Server" that they're working on. If nothing else, the plugins are great, and, other than a few quirks, I really like working in it.</p>
<p>First off, make sure you understand the basics of the HTTP protocol. Then learn how the javascript httpXmlRequest function works. Once you've covered those, pick an Ajax library - prototype is good.</p> <p>Then look at a few examples, and follow the API.</p> <p>Job done.</p> <p>I seriously have no idea how they manage to write entire books on this subject.</p> <p>Edit: Why vote me down? Learning the basics first, leads to a much better understanding of the way it works. And yes, I believe Jeff should learn C too ;-P</p>
4,316
<p>I have a form element that I want to address via javascript, but it doesn't like the syntax.</p> <pre><code>&lt;form name="mycache"&gt; &lt;input type="hidden" name="cache[m][2]"&gt; &lt;!-- ... --&gt; &lt;/form&gt; </code></pre> <p>I want to be able to say:</p> <pre><code>document.mycache.cache[m][2] </code></pre> <p>but obviously I need to indicate that <code>cache[m][2]</code> is the whole name, and not an array reference to <code>cache</code>. Can it be done?</p>
<p>UPDATE: Actually, I was wrong, you can use [ or ] characters as part of a form elements id and/or name attribute.</p> <p>Here's some code that proves it:</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;form id="form1"&gt; &lt;input type='test' id='field[m][2]' name='field[m][2]' value='Chris'/&gt; &lt;input type='button' value='Test' onclick='showtest();'/&gt; &lt;script type="text/javascript"&gt; function showtest() { var value = document.getElementById("field[m][2]").value; alert(value); } &lt;/script&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Update: You can also use the following to get the value from the form element:</p> <pre><code>var value = document.forms.form1["field[m][2]"].value; </code></pre>
<p>Is it possible to add an id reference to the form element and use document.getElementById?</p>
18,798
<p>What are the “normal” ways to do plug-ins in compiled languages (C#/C/C++/D)? I am specifically interested in language agnostic approaches but language specific is not unacceptable.</p> <p>For the time being, “compile time” plug in approaches (just include the code or not and everything works) are valid but things that can migrate to a more dynamic approach are preferred.</p> <p>Regarding the runtime type, I'm more interested in the mechanics of loading the plug-in and whatnot than designing the plug-in/app interface </p> <p>EDIT: BTW the plugin would be a slave not a master. The basic action of a plug-in would be to that under a given situation, it would be called on to "do its thing" and be given an environment object that it should use to get what it needs to operate.</p>
<p>For compiled languages (where compiled means the program runs as a native executable, without any sort of virtual machine), you pretty much need to use some sort of platform-specific shared library approach. In Windows, this means using DLLs.</p> <p>You define your plugin interface in terms of a set of functions (with specific names, arguments, and calling conventions). Then, you load the addresses of the functions within the shared library and go to town. In Windows, this means using <a href="http://msdn.microsoft.com/en-us/library/ms683212(VS.85).aspx" rel="nofollow noreferrer">GetProcAddress()</a>, and then casting the return value to a function pointer of the appropriate type in C, or whatever the equivalent is in the language you're using.</p> <p>Another option that may or may not be more desirable would be to run a virtual machine for another language from within your native application, and have plugins be code for that language. For example, you could run a Python VM using CPython and dynamically load Python modules.</p>
<p>Interfaces with a void Register(EventSource) seem to work well - see ASP.NET's <a href="http://msdn.microsoft.com/en-us/library/system.web.ihttpmodule.init.aspx" rel="nofollow noreferrer">IHttpModule.Init(HttpApplication</a>) for an example.</p> <p>This allows the app author (who controls EventSource) to add events as needed, without needing to extend the IPlugin interface (inevitably leading to IPluginEx, IPlugin2, IPlugin2Ex, etc.)</p>
26,692
<p>I've got the following example running in a simple Silverlight page:</p> <pre><code>public Page() { InitializeComponent(); InitializeOther(); } private DoubleCollection dashes; public DoubleCollection Dashes { get { //dashes = new DoubleCollection(); //works ok //dashes.Add(2.0); //dashes.Add(2.0); if (dashes == null) { dashes = new DoubleCollection(); //causes exception dashes.Add(2.0); dashes.Add(2.0); } return dashes; } set { dashes = value; } } private void InitializeOther() { Line line; for (int i = 0; i &lt; 10; i++) { line = new Line(); line.Stroke = new SolidColorBrush(Colors.Blue); line.StrokeDashArray = Dashes; //exception thrown here line.X1 = 10; line.Y2 = 10; line.X2 = 400; line.Y2 = 10 + (i * 40); canvas1.Children.Add(line); } } </code></pre> <p>The above code throws a System.ArgumentException on the line marked. One solution to the problem is also marked in the example.</p> <p>Does anybody know if this problem is related to the fact that the property System.Windows.Shapes.Shape.StrokeDashArray is a dependency property? </p>
<p>Thank you for your answers and comments.</p> <p>I can run exactly the same code in a WPF application and it does not fail. For me, this is a clear indication that it is a Silverlight bug. I don't now think it has anything to do with dependency properties.</p>
<p>The fact that StrokeDashArray is a dependency property shouldn't have anything to do with that code failing, since in XAML you are constantly setting dependency properties which are processed during parsing in InitializeComponent.</p> <p>I would say that the problem is that in your code you are reusing the same double collection for each line. Whenever you try to set a children to different parents SL fails with an argument exception, same when you reuse a resource that is not a style. Seems like each line needs its own DoubleCollection.</p>
22,588
<p>I am implementing a comment control that allows a person to select comments and have them sent to specified departments. The email needs to be formatted in a specific way, and I was wondering what the best way to do this would be.</p> <p>Should I just hard code all of the style information into one massive method, or should I try and create a separate file and read it in, and then replace certain tags with the relevant information?</p>
<p>Find and use some kind of template library, if possible. This will make each email a template which will then be much easier to maintain than the hardcoded form.</p>
<p>I would use a template approach. It wouldn't he hard to create a simple regex template system, replacing something like #somevar# with the value for 'somevar'. You could also use a premade template system, like Smarty for PHP. I think that would be the cleanest approach.</p> <p>Alex</p>
12,717
<pre><code> &lt;form action="/Villa/Add" method="post"&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt; Name: &lt;/td&gt; &lt;td&gt; &lt;%= Html.TextBox("name") %&gt; &lt;%= Html.ValidationMessage("Name") %&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;/td&gt; &lt;td&gt; &lt;input type="submit" value="Add" /&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/form&gt; </code></pre> <p>My form is above, how do I retrieve the values in my controller?</p> <p>Thanks a lot in advance! Hard to find the right material because of different Previews of MVC being released and being different.</p>
<p>This works for ASP.Net MVC Beta.</p> <pre><code> public ActionResult Add( string name ) { .... } or public ActionResult Add( FormCollection form ) { string name = form["Name"]; } or public ActionResult Add( [Bind(Prefix="")]Villa villa ) { villa.Name ... } </code></pre>
<p>It belongs to your url routes, you defined.</p> <p>In your case the form ist looking for an controller named "Villa" and the action inside of it named "Add".</p> <p>Maybe you should read ScottGu's blog post: <a href="http://weblogs.asp.net/scottgu/archive/2008/09/02/asp-net-mvc-preview-5-and-form-posting-scenarios.aspx" rel="nofollow noreferrer">http://weblogs.asp.net/scottgu/archive/2008/09/02/asp-net-mvc-preview-5-and-form-posting-scenarios.aspx</a></p>
40,972
<p>But here's an example:</p> <pre><code>Dim desiredType as Type if IsNumeric(desiredType) then ... </code></pre> <p><strong>EDIT:</strong> I only know the Type, not the Value as a string.</p> <p>Ok, so unfortunately I have to cycle through the TypeCode.</p> <p>But this is a nice way to do it:</p> <pre><code> if ((desiredType.IsArray)) return 0; switch (Type.GetTypeCode(desiredType)) { case 3: case 6: case 7: case 9: case 11: case 13: case 14: case 15: return 1; } ;return 0; </code></pre>
<p>A few years late here, but here's my solution (you can choose whether to include boolean). Solves for the Nullable case. XUnit test included</p> <pre><code>/// &lt;summary&gt; /// Determines if a type is numeric. Nullable numeric types are considered numeric. /// &lt;/summary&gt; /// &lt;remarks&gt; /// Boolean is not considered numeric. /// &lt;/remarks&gt; public static bool IsNumericType( Type type ) { if (type == null) { return false; } switch (Type.GetTypeCode(type)) { case TypeCode.Byte: case TypeCode.Decimal: case TypeCode.Double: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.SByte: case TypeCode.Single: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: return true; case TypeCode.Object: if ( type.IsGenericType &amp;&amp; type.GetGenericTypeDefinition() == typeof(Nullable&lt;&gt;)) { return IsNumericType(Nullable.GetUnderlyingType(type)); } return false; } return false; } /// &lt;summary&gt; /// Tests the IsNumericType method. /// &lt;/summary&gt; [Fact] public void IsNumericTypeTest() { // Non-numeric types Assert.False(TypeHelper.IsNumericType(null)); Assert.False(TypeHelper.IsNumericType(typeof(object))); Assert.False(TypeHelper.IsNumericType(typeof(DBNull))); Assert.False(TypeHelper.IsNumericType(typeof(bool))); Assert.False(TypeHelper.IsNumericType(typeof(char))); Assert.False(TypeHelper.IsNumericType(typeof(DateTime))); Assert.False(TypeHelper.IsNumericType(typeof(string))); // Arrays of numeric and non-numeric types Assert.False(TypeHelper.IsNumericType(typeof(object[]))); Assert.False(TypeHelper.IsNumericType(typeof(DBNull[]))); Assert.False(TypeHelper.IsNumericType(typeof(bool[]))); Assert.False(TypeHelper.IsNumericType(typeof(char[]))); Assert.False(TypeHelper.IsNumericType(typeof(DateTime[]))); Assert.False(TypeHelper.IsNumericType(typeof(string[]))); Assert.False(TypeHelper.IsNumericType(typeof(byte[]))); Assert.False(TypeHelper.IsNumericType(typeof(decimal[]))); Assert.False(TypeHelper.IsNumericType(typeof(double[]))); Assert.False(TypeHelper.IsNumericType(typeof(short[]))); Assert.False(TypeHelper.IsNumericType(typeof(int[]))); Assert.False(TypeHelper.IsNumericType(typeof(long[]))); Assert.False(TypeHelper.IsNumericType(typeof(sbyte[]))); Assert.False(TypeHelper.IsNumericType(typeof(float[]))); Assert.False(TypeHelper.IsNumericType(typeof(ushort[]))); Assert.False(TypeHelper.IsNumericType(typeof(uint[]))); Assert.False(TypeHelper.IsNumericType(typeof(ulong[]))); // numeric types Assert.True(TypeHelper.IsNumericType(typeof(byte))); Assert.True(TypeHelper.IsNumericType(typeof(decimal))); Assert.True(TypeHelper.IsNumericType(typeof(double))); Assert.True(TypeHelper.IsNumericType(typeof(short))); Assert.True(TypeHelper.IsNumericType(typeof(int))); Assert.True(TypeHelper.IsNumericType(typeof(long))); Assert.True(TypeHelper.IsNumericType(typeof(sbyte))); Assert.True(TypeHelper.IsNumericType(typeof(float))); Assert.True(TypeHelper.IsNumericType(typeof(ushort))); Assert.True(TypeHelper.IsNumericType(typeof(uint))); Assert.True(TypeHelper.IsNumericType(typeof(ulong))); // Nullable non-numeric types Assert.False(TypeHelper.IsNumericType(typeof(bool?))); Assert.False(TypeHelper.IsNumericType(typeof(char?))); Assert.False(TypeHelper.IsNumericType(typeof(DateTime?))); // Nullable numeric types Assert.True(TypeHelper.IsNumericType(typeof(byte?))); Assert.True(TypeHelper.IsNumericType(typeof(decimal?))); Assert.True(TypeHelper.IsNumericType(typeof(double?))); Assert.True(TypeHelper.IsNumericType(typeof(short?))); Assert.True(TypeHelper.IsNumericType(typeof(int?))); Assert.True(TypeHelper.IsNumericType(typeof(long?))); Assert.True(TypeHelper.IsNumericType(typeof(sbyte?))); Assert.True(TypeHelper.IsNumericType(typeof(float?))); Assert.True(TypeHelper.IsNumericType(typeof(ushort?))); Assert.True(TypeHelper.IsNumericType(typeof(uint?))); Assert.True(TypeHelper.IsNumericType(typeof(ulong?))); // Testing with GetType because of handling with non-numerics. See: // http://msdn.microsoft.com/en-us/library/ms366789.aspx // Using GetType - non-numeric Assert.False(TypeHelper.IsNumericType((new object()).GetType())); Assert.False(TypeHelper.IsNumericType(DBNull.Value.GetType())); Assert.False(TypeHelper.IsNumericType(true.GetType())); Assert.False(TypeHelper.IsNumericType('a'.GetType())); Assert.False(TypeHelper.IsNumericType((new DateTime(2009, 1, 1)).GetType())); Assert.False(TypeHelper.IsNumericType(string.Empty.GetType())); // Using GetType - numeric types // ReSharper disable RedundantCast Assert.True(TypeHelper.IsNumericType((new byte()).GetType())); Assert.True(TypeHelper.IsNumericType(43.2m.GetType())); Assert.True(TypeHelper.IsNumericType(43.2d.GetType())); Assert.True(TypeHelper.IsNumericType(((short)2).GetType())); Assert.True(TypeHelper.IsNumericType(((int)2).GetType())); Assert.True(TypeHelper.IsNumericType(((long)2).GetType())); Assert.True(TypeHelper.IsNumericType(((sbyte)2).GetType())); Assert.True(TypeHelper.IsNumericType(2f.GetType())); Assert.True(TypeHelper.IsNumericType(((ushort)2).GetType())); Assert.True(TypeHelper.IsNumericType(((uint)2).GetType())); Assert.True(TypeHelper.IsNumericType(((ulong)2).GetType())); // ReSharper restore RedundantCast // Using GetType - nullable non-numeric types bool? nullableBool = true; Assert.False(TypeHelper.IsNumericType(nullableBool.GetType())); char? nullableChar = ' '; Assert.False(TypeHelper.IsNumericType(nullableChar.GetType())); DateTime? nullableDateTime = new DateTime(2009, 1, 1); Assert.False(TypeHelper.IsNumericType(nullableDateTime.GetType())); // Using GetType - nullable numeric types byte? nullableByte = 12; Assert.True(TypeHelper.IsNumericType(nullableByte.GetType())); decimal? nullableDecimal = 12.2m; Assert.True(TypeHelper.IsNumericType(nullableDecimal.GetType())); double? nullableDouble = 12.32; Assert.True(TypeHelper.IsNumericType(nullableDouble.GetType())); short? nullableInt16 = 12; Assert.True(TypeHelper.IsNumericType(nullableInt16.GetType())); short? nullableInt32 = 12; Assert.True(TypeHelper.IsNumericType(nullableInt32.GetType())); short? nullableInt64 = 12; Assert.True(TypeHelper.IsNumericType(nullableInt64.GetType())); sbyte? nullableSByte = 12; Assert.True(TypeHelper.IsNumericType(nullableSByte.GetType())); float? nullableSingle = 3.2f; Assert.True(TypeHelper.IsNumericType(nullableSingle.GetType())); ushort? nullableUInt16 = 12; Assert.True(TypeHelper.IsNumericType(nullableUInt16.GetType())); ushort? nullableUInt32 = 12; Assert.True(TypeHelper.IsNumericType(nullableUInt32.GetType())); ushort? nullableUInt64 = 12; Assert.True(TypeHelper.IsNumericType(nullableUInt64.GetType())); } </code></pre>
<p>Use Type.IsValueType() and TryParse():</p> <pre><code>public bool IsInteger(Type t) { int i; return t.IsValueType &amp;&amp; int.TryParse(t.ToString(), out i); } </code></pre>
15,143
<p>Is there a way to change name of company to which the Visual Studio 2008 is registered without reinstalling it?</p>
<p>This should have the answer you are looking for : <a href="http://bytes.com/forum/thread635503.html" rel="noreferrer">http://bytes.com/forum/thread635503.html</a></p> <blockquote> <p>For the CompanyName in AssemblyInfo, it's $registeredorganization$ which uses value from registry key value from HKLM\Software\Microsoft\Windows NT\CurrentVersion\RegisteredOrganization.</p> </blockquote>
<p>A quick suggestion, bring up RegEdit and search for the existing company name string. Then attempt to change it.</p>
24,482
<p>My app keeps track of the state of about 1000 objects. Those objects are read from and written to a persistent store (serialized) in no particular order. </p> <p>Right now the app uses the registry to store each object's state. This is nice because:</p> <ul> <li><p>It is simple</p></li> <li><p>It is very fast</p></li> <li><p>Individual object's state can be read/written without needing to read some larger entity (like pulling out a snippet from a large XML file)</p></li> <li><p>There is a decent editor (RegEdit) which allow easily manipulating individual items</p></li> </ul> <p>Having said that, I'm wondering if there is a better way. SQLite seems like a possibility, but you don't have the same level of multiple-reader/multiple-writer that you get with the registry, and no simple way to edit existing entries.</p> <p>Any better suggestions? A bunch of flat files?</p>
<p>If what you mean by 'multiple-reader/multiple-writer' is that you keep a lot of threads writing to the store concurrently, SQLite is threadsafe (you can have concurrent SELECTs and concurrent writes are handled transparently). See the [FAQ [1]] and grep for 'threadsafe'</p> <p>[1]: <a href="http://www.sqlite.org/faq.html/" rel="nofollow noreferrer">http://www.sqlite.org/faq.html/</a> FAQ</p>
<p>Do you need to persist the objects on each change event or just in memory and store on shutdown? If so, just load them up and serialize them at the end, assuming your app runs for a long time (and you don't share that state with another program) then in memory is going to be a winner.</p> <p>If you've got fixed size structures then you could consider just using a memory mapped file and allocate memory from that? </p>
16,483
<p>From within my Java program I want to determine which .NET Framework is installed on the system. What is the best (and easiest) way to do this?</p> <p><strong>Answer</strong> Thanks scubabbl! It worked to check the directory <code>System.getenv( "WINDIR" ) + "\\Microsoft.NET\\Framework"</code> for its directories starting with the letter "v".</p>
<p>From what I understand, the actual file structure in c:\windows\Microsoft.Net\Framework has folders with versions of .Net installed. On my computer, I have folders up to v3.5, or c:\windows\Microsoft.Net\Framework\v3.5.</p> <p>There are lots of issues with this, including security issues though.</p> <p>The second, and probably better answer would be to check the windows registry.</p> <p>HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP</p> <p>The Version key will have the value you are looking for.</p> <p>Edit: stackoverflow question regarding reading the registry with java. <a href="https://stackoverflow.com/questions/62289/readwrite-to-windows-registry-using-java">read/write to Windows Registry using Java</a></p> <p>This library <a href="http://www.trustice.com/java/jnireg/" rel="nofollow noreferrer">http://www.trustice.com/java/jnireg/</a> will allow you to read the registry.</p>
<p>Checking the directory structure is not the best way to do this. Take a look at this <a href="https://stackoverflow.com/questions/199080/how-to-detect-what-net-framework-versions-and-service-packs-are-installed">thread</a> for the full details on the registry keys you need to evaluate.</p>
16,761
<p>This is my setting: I have written a .NET application for local client machines, which implements a feature that could also be used on a webpage. To keep this example simple, assume that the client installs a software into which he can enter some data and gets some data back. </p> <p>The idea is to create a webpage that holds a form into which the user enters the same data and gets the same results back as above. Due to the company's available web servers, the first idea was to create a mono webservice, but this was dismissed for reasons unknown. The "service" is not to be run as a webservice, but should be called by a PHP script. This is currently realized by calling the mono application via shell_exec from PHP.</p> <p>So now I am stuck with a mono port of my application, which works fine, but takes way too long to execute. I have already stripped out all unnecessary dlls, methods etc, but calling the application via the command line - submitting the desired data via commandline parameters - takes approximately 700ms. We expect about 10 hits per second, so this could only work when setting up a lot of servers for this task.</p> <p>I assume the 700m are related to the cost of starting the application every time, because it does not make much difference in terms of time if I handle the request only once or five hundred times (I take the original input, vary it slighty and do 500 iterations with "new" data every time. Starting from the second iteration, the processing time drops down to approximately 1ms per iteration)</p> <p>My next idea was to setup the mono application as a remoting server, so that it only has to be started once and can then handle incoming requests. I therefore wrote another mono application that serves as the client. Calling the client, letting the client pass the data to the server and retrieving the result now takes 344ms. This is better, but still way slower than I would expect and want it to be.</p> <p>I have then implemented a new project from scratch based on <a href="http://pubcrawler.org/2003/02/19/net-remoting-with-mono/" rel="nofollow noreferrer">this blog post</a> and get stuck with the same performance issues.</p> <p>The question is: am I missing something related to the mono-projects that could improve the speed of the client/server? Although the idea of creating a webservice for this task was dismissed, would a webservice perform better under these circumstances (as I would not need the client application to call the service), although it is said that remoting is faster than webservices?</p> <hr> <p>I could have made that clearer, but implementing a webservice is currently not an option (and please don't ask why, I didn't write the requirements ;))</p> <p>Meanwhile I have checked that it's indeed the startup of the client, which takes most of the time in the remoting scenario. </p> <p>I could imagine accessing the server via pipes from the command line, which would be perfectly suitable in my scenario. I guess this would be done using sockets?</p>
<p>You can try to use AOT to reduce the startup time. On .NET you would use ngen for that purpoise, on mono just do a mono --aot on all assemblies used by your application.</p> <p>AOT'ed code is slower than JIT'ed code, but has the advantage of reducing startup time.</p> <p>You can even try to AOT framework assemblies such as mscorlib and System.</p>
<p>I believe that remoting is not an ideal thing to use in this scenario. However your idea of having mono on server instead of starting it every time is indeed solid.</p> <p>Did you consider using SOAP webservices over HTTP? This would also help you with your 'web page' scenario.</p> <p>Even if it is a little to slow for you in my experience a custom RESTful services implementation would be easier to work with than remoting. </p>
14,608
<p>I'm a long-time ActionScript 2 user, now getting started with ActionScript 3. The one thing I'm missing is an easy way to duplicate the functionality of AS2's MovieClip.onReleaseOutside. It is almost always necessary to implement this event, otherwise you get funny bugs like flash thinks your mouse is down when really it's up. </p> <p>According to the <a href="http://livedocs.adobe.com/flex/2/langref/migration.html" rel="nofollow noreferrer">AS2 to AS3 Migration Guide</a>, I'm supposed to use <code>flash.display.InteractiveObject.setCapture()</code> for this, however it does not exist as far as I can tell. I guess this document is out of date or incorrect. I've found a few posts on the web about how to duplicate this functionality, but they either have their own problems:</p> <ul> <li><a href="http://www.arpitonline.com/blog/?p=33" rel="nofollow noreferrer">This one</a> triggers onReleaseOutside even if there was no corresponding onPress event. </li> <li><a href="http://www.kirupa.com/forum/showpost.php?p=1948182&amp;postcount=204" rel="nofollow noreferrer">This one</a> seems very inefficient, you'll add and remove an event listener every time the mouse is clicked anywhere inside your app.</li> </ul> <p>There has to be an easier way, don't tell me Adobe forgot about this when rewriting Actionscript?</p> <p>Example AS2 code:</p> <pre><code>// Assume myMC is a simple square or something on the stage myMC.onPress = function() { this._rotation = 45; } myMC.onRelease = myMC.onReleaseOutside = function() { this._rotation = 0; } </code></pre> <p>Without the onReleaseOutside handler, if you pressed down on the squre, dragged your mouse outside of it, and released the mouse, then the square would not un-rotate, and appear to be stuck.</p>
<p>Simple and foolproof:</p> <pre><code>button.addEventListener( MouseEvent.MOUSE_DOWN, mouseDownHandler ); button.addEventListener( MouseEvent.MOUSE_UP, buttonMouseUpHandler ); // * function mouseDownHandler( event : MouseEvent ) : void { trace( "onPress" ); // this will catch the event anywhere event.target.stage.addEventListener( MouseEvent.MOUSE_UP, mouseUpHandler ); } function buttonMouseUpHandler( event : MouseEvent ) : void { trace( "onRelease" ); // don't bubble up, which would trigger the mouse up on the stage event.stopImmediatePropagation( ); } function mouseUpHandler( event : MouseEvent ) : void { trace( "onReleaseOutside" ); event.target.removeEventListener( MouseEvent.MOUSE_UP, mouseUpHandler ); } </code></pre> <p>If you don't care about the difference between onRelease and onReleaseOutside (for example with draggable items) you an skip the mouse up listener on the button itself (commented here with an asterisk).</p>
<p>Have you looked at this event:</p> <pre><code>flash.events.Event.MOUSE_LEAVE </code></pre> <p><br /> <br /> From the documentation:</p> <p><strong>Dispatched by the Stage object when the mouse pointer moves out of the stage area. The Event.MOUSE_LEAVE constant defines the value of the type property of a mouseLeave event object.</strong> <br /> <br /></p> <p>It will solve your problem if you are only interested whether the user's mouse if off the stage instead of just outside that particular MovieClip.</p>
31,834
<p>I've been 3D printing as a hobby for a couple of years now, and have always heard how 3D printing is great for prototyping, but once you get beyond 10 or 20 pieces it's just not cost competitive with other technologies. I just accepted this to be truth, and have even told some of the customers I've gotten through 3DHubs and other marketplaces the same thing.</p> <p>Now I'm creating an item for resale and am 3D printing the case. As I'll need 40 - 50 cases at a time I thought I would shop around for other options. But I just received some quotes back on injection molding. The mold price (for half the case) was \$15k, plus \$10 per unit at a quantity of 50 and \$4 per unit at a quantity of 500. Even in the case of the latter, the cost of tooling plus production is \$34/piece. 3D printing the same part myself costs $7 in filament, and paying someone else to 3D print it cost \$28.</p> <p>Keeping in mind that 3D printing allows me to make changes to the design on the fly and print the exact number I need without having to worry about volume discounts, I now wonder if I've just been repeating a common misconception. Is 3D printing really noncompetitive for medium (10-500 pieces) production runs? If so, what makes it noncompetitive, given the extremely high up-front cost of IM?</p>
<h1>TL:DR</h1> <p>3D printing is great for low quantities of items, but terrible for large quantities of items. This is a continuous scale and as your quantity grows, the drawbacks of 3D printing become more pronounced. In your situation, you seem to be dancing in the nebulous zone where there isn't really a good answer as to which production method is better. It's more of a question of price vs speed. <hr/> There are several factors that limit additive manufacturing technologies (in this answer I'll just talk about FDM since you're asking about a plastic item) from being practical in large scale manufacturing. </p> <h1>Time</h1> <p>Compared to injection molding, 3D printing takes a very long time. An injection mold can make <a href="https://www.youtube.com/watch?v=WHwTHarf8Ck" rel="nofollow noreferrer">72 plastic caps in 3 seconds</a>. While I don't have a source, I would expect a similar item to take at least 5 minutes to be printed. In order to produce an average of 24 caps/second, you would need 7,200 3d printers working without down time. That doesn't take into consideration ...</p> <h1>Labor</h1> <p>Every 3d printed object needs to be removed from the print bed by hand. That requires a person to be there ready to remove the item. It's possible to have <a href="http://www.3ders.org/articles/20150419-automate-the-removal-and-3d-printing-of-multiple-objects-with-the-echodrive-add-on.html" rel="nofollow noreferrer">automated print removal</a>, but for now I've yet to see it as a standard option on any machine. An injection model machine can just pop the parts out into a box. Even with the capability to remove the parts extra labor is still required for 3d printing because ...</p> <h1>Quality</h1> <p>Injection molded parts are as smooth as the mold they were made in. While failures still exist even for molded items, their relatively cheap production cost and very quick production time ensure that an occasional failure won't be problematic. 3D printing on the other hand is still prone to <a href="https://all3dp.com/common-3d-printing-problems-3d-printer-troubleshooting-guide/" rel="nofollow noreferrer">variations</a> in the final product. For a few items, it's sensible to hand finish the parts with filing, sanding, or other reductive manufacturing techniques, but for many items this quickly become burdensome. Also, given the long production time compared to injection molding, even 1 discarded product will result in a long time required to produce a replacement.</p>
<p>Break even points have always been dependent on the part. If the goal is to make a rod or filament-like piece of your extrusion nozzle diameter, your extruder may be pretty competitive. Additive manufacture has come a long way already so the break even points may have shifted. Interestingly a great use for additive is to produce tooling.</p> <p>You could for example use the 3D printed part (with non-stick coating) to make a 600 deg F silicone mold from high temp RTV. Presuming you have the heating equipment, that mold can then be used to produce tens of the part at slightly lower quality. As silicone is flexible, it isnt good for high speed/pressure of injection molding.</p> <p>If you are willing to accept lower quality (3d printing with filament is pretty low so that's likely a yes) and your injection molder is willing to go for DMLS molds with minor smoothing/drilling post-operations, your tooling costs may be significantly lower than your original estimate. Chances are this isn't happening unless the injection molder is also an additive enthusiast, and often will have to be one and the same as the person who designed at least some of the 3d printed part.</p>
555
<p>In many symbolic math systems, such as Matlab or Mathematica, you can use a variable like <code>Ans</code> or <code>%</code> to retrieve the last computed value. Is there a similar facility in the Python shell?</p>
<p>Underscore.</p> <pre><code>&gt;&gt;&gt; 5+5 10 &gt;&gt;&gt; _ 10 &gt;&gt;&gt; _ + 5 15 &gt;&gt;&gt; _ 15 </code></pre>
<p>IPython allows you to go beyond the single underscore <code>_</code> with double (<code>__</code>) and triple underscore (<code>___</code>), returning results of the second- and third-to-last commands.</p> <p>Alternatively, you can also use <code>Out[n]</code>, where <code>n</code> is the number of the input that generated the output:</p> <pre><code>In [64]: 1+1 Out[64]: 2 ... In [155]: Out[64] + 3 Out[155]: 5 </code></pre> <p>For more info, see <a href="https://jakevdp.github.io/PythonDataScienceHandbook/01.04-input-output-history.html" rel="noreferrer">https://jakevdp.github.io/PythonDataScienceHandbook/01.04-input-output-history.html</a> .</p>
24,390
<p>I have to pass some parameter from an action to another action,for example to keep trace of an event. </p> <p>What is the best way to do that? </p> <p>I would not use session parameters. Thanks</p>
<p>Assuming you are serverside within one action and wishing to invoke another action with some parameters.</p> <p>You can use the s:action tag to invoke another action, possibly with additional/other parameters than the original action:</p> <pre><code> &lt;s:action name="myAction" ignoreContextParams="true" executeResult="true"&gt; &lt;s:param name="foo" value="bar"/&gt; &lt;/s:action&gt; </code></pre> <p>You can also use a standard struts-xml result type with a parameter:</p> <pre><code>&lt;result name="success" type="redirect" &gt; &lt;param name="location"&gt;foo.jsp?foo=${bar}&lt;/param&gt; &lt;param name="parse"&gt;true&lt;/param&gt; &lt;param name="encode"&gt;true&lt;/param&gt; &lt;/result&gt; </code></pre> <p>If you want a client side redirect you have to send an url back to the client with the proper parameters, and maybe use some javascript to go there.</p> <pre><code> &lt;s:url action="myAction" &gt; &lt;s:param name="foo" value="bar"/&gt; &lt;/s:url&gt; </code></pre>
<p>actually, the scope and servletConfig interceptor can be utilized in struts2, to automatic pop the action context parameters, (request/session, etc)</p>
48,923
<p>This is more a thought experiment than anything.</p> <p>I'm wondering what it would take to detect everything I legally can about the laptops in a hotspot. My first thought was to grab every MAC address I can and extract the maker from the first 24bit.</p> <p>The question is would this be illegal and what else could I legally scavenge, preferably passively?</p> <p>P.S. This constitutes a pattern-recognition problem so it IS programming... I think.</p>
<p>For the brain dead answer: <em>Quit typing and look around for a few minutes</em> :-D</p>
<p><a href="http://www.gfi.com/lannetscan/" rel="nofollow noreferrer">GFI Languard</a> gives a lot of info like this. Check it out.</p>
17,675
<p>In Linux When I invoke python from the shell it replicates its environment, and starts the python process. Therefore if I do something like the following:</p> <pre><code>import os os.environ["FOO"] = "A_Value" </code></pre> <p>When the python process returns, FOO, assuming it was undefined originally, will still be undefined. Is there a way for the python process (or any child process) to modify the environment of its parent process?</p> <p>I know you typically solve this problem using something like</p> <pre><code>source script_name.sh </code></pre> <p>But this conflicts with other requirements I have.</p>
<p>No process can change its parent process (or any other existing process' environment).</p> <p>You can, however, create a new environment by creating a new interactive shell with the modified environment.</p> <p>You have to spawn a new copy of the shell that uses the upgraded environment and has access to the existing stdin, stdout and stderr, and does its reinitialization dance.</p> <p>You need to do something like use subprocess.Popen to run <code>/bin/bash -i</code>.</p> <p>So the original shell runs Python, which runs a new shell. Yes, you have a lot of processes running. No it's not too bad because the original shell and Python aren't really doing anything except waiting for the subshell to finish so they can exit cleanly, also.</p>
<p>I needed something similar, I ended up creating a script <code>envtest.py</code> with:</p> <pre class="lang-py prettyprint-override"><code>import sys, os sys.stdout = open(os.devnull, 'w') # Python code with any number of prints (to stdout). print(&quot;This is some other logic, which shouldn't pollute stdout.&quot;) sys.stdout = sys.__stdout__ print(&quot;SomeValue&quot;) </code></pre> <p>Then in bash:</p> <pre class="lang-bash prettyprint-override"><code>export MYVAR=$(python3 envtest.py) echo &quot;MYVAR is $MYVAR&quot; </code></pre> <p>Which echos the expected: <code>MYVAR is SomeValue</code></p>
32,922
<p>I have a large script file (nearly 300MB, and feasibly bigger in the future) that I am trying to run. It has been suggested in the comments of Gulzar's answer to my <a href="https://stackoverflow.com/questions/222442/sql-server-running-large-script-files">question about it</a> that I should change the script timeout to 0 (no timeout).</p> <p>What is the best way to set this timeout from within the script? At the moment I have all of this at the top of the script file in the hopes that one of them does something:</p> <pre><code>sp_configure 'remote login timeout', 600 go sp_configure 'remote query timeout', 0 go sp_configure 'query wait', 0 go reconfigure with override go </code></pre> <p>However, I'm still getting the same result and I can't tell if I'm succeeding in setting the timeout because the response from sqlcmd.exe is the world's least helpful error message:</p> <blockquote> <p>Sqlcmd: Error: Scripting error.</p> </blockquote>
<pre><code>sqlcmd -t {n} </code></pre> <p>Where {n} must be a number between 0 and 65535.</p> <p>Note that your question is a bit misleading since <a href="http://blogs.msdn.com/khen1234/archive/2005/10/20/483015.aspx" rel="noreferrer">the server has no concept of a timeout</a> and therefore you cannot set the timeout within your script. </p> <p>In your context the timeout is enforced by <strong><a href="http://msdn.microsoft.com/en-us/library/ms170572.aspx" rel="noreferrer">sqlcmd</a></strong></p>
<p>I think there is <strong>no concept of timeout within a SQL script</strong> on SQL Server. You have to set the timeout in the calling layer / client.</p> <p>According to <a href="http://support.microsoft.com/?scid=kb%3Ben-us%3B314530&amp;x=14&amp;y=12" rel="nofollow noreferrer">this MSDN article</a> you could try to increase the timeout this way:</p> <pre><code>exec sp_configure 'remote query timeout', 0 go reconfigure with override go </code></pre> <p><em>"Use the remote query timeout option to specify how long, in seconds, a remote operation can take before Microsoft SQL Server times out. The default is 600, which allows a 10-minute wait. This value applies to an outgoing connection initiated by the Database Engine as a remote query. This value has no effect on queries received by the Database Engine."</em></p> <p><em>P.S.: By 300 MB you mean the resulting file is 300 MB? I don't hope that the script file itself is 300 MB. That would be a world record. ;-)</em></p>
27,793
<p>I'd like to have some of the ScriptManager features in the new Asp.net MVC model:</p> <p>1- Script combining<br> 2- Resolving different paths for external Javascript files<br> 3- Minify and Gzip Compression </p> <p><a href="http://www.codeproject.com/KB/aspnet/HttpCombine.aspx" rel="nofollow noreferrer">Here</a> is what I found, but I'm not sure is the best way for MVC approach. In general what is a good approach to deal with Javascript code in the MVC model?</p>
<p>Maybe you could just create a new 'Scripts' controller with different actions serving different combinations of compressed JS files. Since MVC is designed with a resource oriented approach, i.e. URLs are now at the center of your programming model, why not define simple URIs for your Javascripts too ?</p> <p>In your views, for example you could reference your files like this :</p> <pre><code>&lt;script src="http://your_domain/scripts/all"/&gt; </code></pre> <p>This would call your 'all' action, resulting in all your compressed script files being sent.</p> <p>Of course you would need to code the combining and compressing for now, or maybe reuse the Scriptmanager internally, I don't know if it's possible.</p> <p>This is just an idea though, currently I'm referencing individual javascript files directly in my master pages.</p>
<p>Found this researching much the same problem: <a href="http://pietschsoft.com/post/2009/08/13/Simple-ScriptManager-for-ASPNET-MVC.aspx" rel="nofollow noreferrer">A Simple ScriptManager for ASP.NET MVC</a> - written after this question was answered so added for reference.</p> <p>In the first instance I'm going with the brute force solution i.e. stick it all in the master page (especially as one can now pull jQuery from Microsoft's CDN) - then we're going to investigate options for more optimal solutions.</p>
41,436
<p>In E (specman) I want to declare variables that are lists, and I want to fix their lengths.</p> <p>It's easy to do for a member of a struct:</p> <pre><code>thread[2] : list of thread_t; </code></pre> <p>while for a "regular" variable in a function the above doesn't work, and I have to do something like:</p> <pre><code>var warned : list of bool; gen warned keeping { it.size() == 5; }; </code></pre> <p>Is there a better way to declare a list of fixed size?</p>
<p>A hard keep like you have is only going to fix the size at initialization but elements could still be added or dropped later, are you trying to guard against this condition? The only way I can think of to guarantee that elements aren't added or dropped later is emitting an event synced on the size != the predetermined amount:</p> <pre><code>event list_size_changed is true (wanted.size() != 5) @clk; </code></pre> <p>The only other thing that I can offer is a bit of syntactic sugar for the hard keep:</p> <pre><code>var warned : list of bool; keep warned.size() == 5; </code></pre>
<p>I know nothing of specman, but a fixed sized list is an array, so that might point you somewhere.</p>
4,102
<p>When using SubSonic, do you return the data as a dataset or do you put that in a strongly typed custom collection or a generic object?</p> <p>I ran through the subsonic project and for the four stored procs I have in my DB, it gave me a Sps.cs with 4 methods which return a StoredProcedure object.</p> <p>If you used a MVC, do you usually use the StoredProcedure object or wrap that around your business logic and return a dataset, list, collection or something else?</p> <p>Are datasets still the norm or is that replaced by something else?</p>
<p>If the results of the stored procedure has the same schema as one of your tables, you can build a collection using this code (SubSonic 2.1):</p> <pre><code>ProductCollection coll = new ProductCollection(); coll.LoadAndCloseReader(SPs.GetProducts(1).GetReader()); </code></pre>
<p>You can do data readers, but that's so 1999. Returning objects is a breeze with SubSonic, and easier to use than a data reader. You can retrieve objects like so:</p> <pre><code>Dim Charts As Generic.List(Of MusicDB.Billboard) = _ New SubSonic.Select(MusicDB.DB.Repository.Provider, New String() _ {"Prefix", "Artist", "Track", "ArtistNarrowToken", "TrackNarrowToken", "ArtistId", "TrackId", "TrackYear"}). _ From(MetadataTagger.MusicDB.Tables.Billboard). _ Where(MusicDB.Billboard.Columns.ArtistNarrowToken).IsLessThan(10). _ Or(MusicDB.Billboard.Columns.TrackId).IsNull(). _ OrderAsc(New String() {"TrackYear"}).ExecuteTypedList(Of MetadataTagger.MusicDB.Billboard)() </code></pre>
28,239
<p>What are the expert debugging hints for your favourite language, you think everyone should use?</p> <p>As an example, I'll provide my C++ debugging hints, that between them help me shake out most of the bugs I come across, in this often hard-to-debug language.</p> <p><B>C++</B></p> <ul> <li><p>Increase the warning level of your compiler to maximum, then stop those warnings which occur a lot and you've decided you don't care about (for me it's unused parameters). g++ doesn't warn about missing return statements in functions (a problem I find frequently) until the warning level is very high.</p></li> <li><p>Learn how to turn on your compiler's debugging standard library, and use it! ( -D_GLIBCXX_DEBUG for g++). This finds lots of errors, and also helps show exactly where the errors occurred.</p></li> <li><p>Always, always, always run your code through a really good memory checker, like <a href="http://valgrind.org/" rel="noreferrer">valgrind</a>, and fix all the problems it produces.</p></li> </ul>
<p>Learn what the different magic numbers means that VS memory handler writes when it handles memory.</p> <p>0xCDCDCDCD Allocated in heap, but not initialized. By malloc<br> 0xCCCCCCCC Allocated on stack, but not initialized.<br> 0xDDDDDDDD Released heap memory. By free<br> 0xFDFDFDFD "NoMansLand" fences automatically placed at boundary of heap memory. Should never be overwritten. If you do overwrite one, you're probably walking off the end of an array.<br> 0xFEEEFEEE Deleted memory by HeapFree<br> 0xBAADF00D Allocated in heap, but not initialized. By HeapAlloc<br> 0xABABABAB Dont know. If someone know what this means, please add that.</p>
<p>I have no references for this, but I was told the 0xABABABAB address means 'memory beyond the bounds of allocated memory'. Hope it helps.</p>
38,689
<p>I'm trying to figure out how to drop/discard a request, I'm basically trying to implement a blocked list of IPs in my app to block spammers and I don't want to return any response (just ignore the request), is this possible in ASP.NET?</p> <p>Edit: Some of the answers suggest that I could add them in the firewall, while this will certainly be better it's not suitable in my case. To make a long story short, I'm adding a moderation section to my website where moderators will check the posts awaiting moderation for spam (filtered by a spam fitler), I want the IP of the sender of some post to be added to the list of blocked IPs once a post is marked as spam by the moderator, this is why I wan to do it in the application.</p> <p>Edit: Calling Response.End() returns a response to the user (even though it's empty), the whole purpose of my question was how not to return any response. Is this possible (even out of curiosity)? There's also Response.Close() which closes the socket but it sends notification (in TCP/IP) when it does this, I just wan to ignore as it if was never received (i.e. send nothing to the user)</p> <p>Thanks</p>
<p>Maybe you could use </p> <pre><code>Response.Clear(); Response.End(); </code></pre>
<p>I would suggest the best solution is not to give a specific "no response" but to give a more discouraging standard http error message. Whenever I am attempting to discourage unauthorised users I issue a page/url not found message as follows:</p> <pre><code>throw new HttpException(404, "File not found - " + Request.AppRelativeCurrentExecutionFilePath);</code></pre> <p>I think that this is very effective at convincing the person at the other end to give up and go away.</p>
34,926
<p>I would like to change the database files location of MySQL administrator to another drive of my computer. (I run Windows XP SP2 and MySQL Administrator 1.2.8.)</p> <p>--Under the startup variable --> General Parameters --> I changed <code>Data directory:</code> from <code>C:/Program Files/MySQL/MySQL Server 5.0/data</code> to <code>D:/.....</code>, but after I stopped the service and restarted it, the following error appeared: </p> <pre><code>Could not re-connect to the MySQL Server. Server could not be started. Fatal error: Can't open and lock privilege tables: Table 'mysql.host' doesn't exist </code></pre> <p>Has anyone else had this problem? </p>
<p>Normally it works like this:</p> <ol> <li>shut down MySQL</li> <li>change the <code>[mysqld]</code> and <code>[mysqld_safe]</code> <code>datadir</code> variable in the MySQL configuration</li> <li>change the <code>basedir</code> variable in the same section.</li> <li>move the location over</li> <li>restart MySQL</li> </ol> <p>If that doesn't work I have no idea. On linux you can try to move the socket to a new location too, but that shouldn't affect windows. Alternatively you can use a symbolic link on *nix what most people do I guess.</p>
<p>You also have to manually modify mysql's configuration (usually my.conf)</p>
15,377
<p>I'm trying to make the switch from Emacs to Eclipse. One thing that seems to be missing is its buffer/window support.</p> <p>I know in Eclipse I can drag an editor's tab title over to split the view, creating the equivalent of a new Emacs window, which is a step in the right direction. </p> <p>I can't find any key bindings for this functionality, though. Ideally, I'd like to be able to set keys to split horizontal, split vertical, switch to next (there is a next editor, but I want the next window/whatever you call it), switch to previous, close this window split (not this editor), close all other editor window splits.</p> <p>As it is, the only way I've found to close a split pane is to drag all the files over one by one until none are left. Things like this make working with split screens tedious in Eclipse.</p> <p>Any help would be appreciated, hopefully there's something simple I'm missing.</p>
<p>Emacs+ has this exact behavior for Eclipse: <a href="http://www.mulgasoft.com/emacsplus" rel="nofollow noreferrer">http://www.mulgasoft.com/emacsplus</a></p>
<p>Try <kbd>Ctrl</kbd>-<kbd>Tab</kbd> and <kbd>Ctrl</kbd>-<kbd>Shift</kbd>-<kbd>Tab</kbd> for cycling through tabs (buffers) and <kbd>Ctrl</kbd>-<kbd>F4</kbd> for closing a tab. You can also look through the shortcut bindings in the eclipse configuration.</p>
24,109
<p>I'll soon be working on a large c# project and would like to build in multi-language support from the start. I've had a play around and can get it working using a separate resource file for each language, then use a resource manager to load up the strings.</p> <p>Are there any other good approaches that I could look into?</p>
<h1>Use a separate project with Resources</h1> <p>I can tell this from out experience, having a current solution with <strike>12</strike> <strong>24</strong> projects that includes API, MVC, Project Libraries (Core functionalities), WPF, UWP and Xamarin. It is worth reading this long post as I think it is the best way to do so. With the help of VS tools easily exportable and importable to sent to translation agencies or review by other people.</p> <p><strong>EDIT 02/2018:</strong> Still going strong, converting it to a .NET Standard library makes it possible to even use it across .NET Framework and NET Core. I added an extra section for converting it to JSON so for example angular can use it.</p> <p><strong>EDIT 2019:</strong> Going forward with Xamarin, this still works across all platforms. E.g. Xamarin.Forms advices to use resx files as well. (I did not develop an app in Xamarin.Forms yet, but the documentation, that is way to detailed to just get started, covers it: <a href="https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/localization/text?tabs=windows" rel="noreferrer">Xamarin.Forms Documentation</a>). Just like converting it to JSON we can also convert it to a .xml file for Xamarin.Android.</p> <p><strong>EDIT 2019 (2):</strong> While upgrading to UWP from WPF, I encountered that in UWP they prefer to use another filetype <code>.resw</code>, which is is in terms of content identical but the usage is different. I found a different way of doing this which, in my opinion, works better then <a href="https://learn.microsoft.com/en-us/windows/uwp/app-resources/localize-strings-ui-manifest" rel="noreferrer">the default solution</a>.</p> <p><strong>EDIT 2020:</strong> Updated some suggestions for larger (modulair) projects that might require multiple language projects.</p> <p>So, lets get to it.</p> <p><strong>Pro's</strong></p> <ul> <li>Strongly typed almost everywhere.</li> <li>In WPF you don't have to deal with <code>ResourceDirectories</code>.</li> <li>Supported for ASP.NET, Class Libraries, WPF, Xamarin, .NET Core, .NET Standard as far as I have tested.</li> <li>No extra third-party libraries needed.</li> <li>Supports culture fallback: en-US -&gt; en.</li> <li>Not only back-end, works also in XAML for WPF and Xamarin.Forms, in .cshtml for MVC.</li> <li>Easily manipulate the language by changing the <code>Thread.CurrentThread.CurrentCulture</code></li> <li>Search engines can Crawl in different languages and user can send or save language-specific urls.</li> </ul> <p><strong>Con's</strong></p> <ul> <li>WPF XAML is sometimes buggy, newly added strings don't show up directly. Rebuild is the temp fix (vs2015).</li> <li>UWP XAML does not show intellisense suggestions and does not show the text while designing.</li> <li>Tell me.</li> </ul> <p><strong>Setup</strong></p> <p>Create language project in your solution, give it a name like <em>MyProject.Language</em>. Add a folder to it called Resources, and in that folder, create two Resources files (.resx). One called <strong>Resources.resx</strong> and another called <strong>Resources.en.resx</strong> (or .en-GB.resx for specific). In my implementation, I have NL (Dutch) language as the default language, so that goes in my first file, and English goes in my second file.</p> <p>Setup should look like this:</p> <p><a href="https://i.stack.imgur.com/jqeVN.png" rel="noreferrer"><img src="https://i.stack.imgur.com/jqeVN.png" alt="language setup project" /></a></p> <p>The properties for Resources.resx must be: <a href="https://i.stack.imgur.com/Gl4IL.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Gl4IL.png" alt="properties" /></a></p> <p>Make sure that the custom tool namespace is set to your project namespace. Reason for this is that in WPF, you cannot reference to <code>Resources</code> inside XAML.</p> <p>And inside the resource file, set the access modifier to Public:</p> <p><a href="https://i.stack.imgur.com/uGOMH.png" rel="noreferrer"><img src="https://i.stack.imgur.com/uGOMH.png" alt="access modifier" /></a></p> <p>If you have such a large application (let's say different modules) you can consider creating multiple projects like above. In that case you could prefix your Keys and resource classes with the particular Module. Use the <a href="https://marketplace.visualstudio.com/items?itemName=TomEnglert.ResXManager" rel="noreferrer">best language editor</a> there is for Visual Studio to combine all files into a single overview.</p> <p><strong>Using in another project</strong></p> <p>Reference to your project: Right click on References -&gt; Add Reference -&gt; Prjects\Solutions.</p> <p>Use namespace in a file: <code>using MyProject.Language;</code></p> <p>Use it like so in back-end: <code>string someText = Resources.orderGeneralError;</code> If there is something else called Resources, then just put in the entire namespace.</p> <h3>Using in MVC</h3> <p>In MVC you can do however you like to set the language, but I used parameterized url's, which can be setup like so:</p> <p><strong>RouteConfig.cs</strong> Below the other mappings</p> <pre><code>routes.MapRoute( name: &quot;Locolized&quot;, url: &quot;{lang}/{controller}/{action}/{id}&quot;, constraints: new { lang = @&quot;(\w{2})|(\w{2}-\w{2})&quot; }, // en or en-US defaults: new { controller = &quot;shop&quot;, action = &quot;index&quot;, id = UrlParameter.Optional } ); </code></pre> <p><strong>FilterConfig.cs</strong> (might need to be added, if so, add <code>FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);</code> to the <code>Application_start()</code> method in <code>Global.asax</code></p> <pre><code>public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new ErrorHandler.AiHandleErrorAttribute()); //filters.Add(new HandleErrorAttribute()); filters.Add(new LocalizationAttribute(&quot;nl-NL&quot;), 0); } } </code></pre> <p><strong>LocalizationAttribute</strong></p> <pre><code>public class LocalizationAttribute : ActionFilterAttribute { private string _DefaultLanguage = &quot;nl-NL&quot;; private string[] allowedLanguages = { &quot;nl&quot;, &quot;en&quot; }; public LocalizationAttribute(string defaultLanguage) { _DefaultLanguage = defaultLanguage; } public override void OnActionExecuting(ActionExecutingContext filterContext) { string lang = (string) filterContext.RouteData.Values[&quot;lang&quot;] ?? _DefaultLanguage; LanguageHelper.SetLanguage(lang); } } </code></pre> <p><strong>LanguageHelper</strong> just sets the Culture info.</p> <pre><code>//fixed number and date format for now, this can be improved. public static void SetLanguage(LanguageEnum language) { string lang = &quot;&quot;; switch (language) { case LanguageEnum.NL: lang = &quot;nl-NL&quot;; break; case LanguageEnum.EN: lang = &quot;en-GB&quot;; break; case LanguageEnum.DE: lang = &quot;de-DE&quot;; break; } try { NumberFormatInfo numberInfo = CultureInfo.CreateSpecificCulture(&quot;nl-NL&quot;).NumberFormat; CultureInfo info = new CultureInfo(lang); info.NumberFormat = numberInfo; //later, we will if-else the language here info.DateTimeFormat.DateSeparator = &quot;/&quot;; info.DateTimeFormat.ShortDatePattern = &quot;dd/MM/yyyy&quot;; Thread.CurrentThread.CurrentUICulture = info; Thread.CurrentThread.CurrentCulture = info; } catch (Exception) { } } </code></pre> <p><strong>Usage in .cshtml</strong></p> <pre><code>@using MyProject.Language; &lt;h3&gt;@Resources.w_home_header&lt;/h3&gt; </code></pre> <p>or if you don't want to define usings then just fill in the entire namespace OR you can define the namespace under /Views/web.config:</p> <pre class="lang-xml prettyprint-override"><code>&lt;system.web.webPages.razor&gt; &lt;host factoryType=&quot;System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35&quot; /&gt; &lt;pages pageBaseType=&quot;System.Web.Mvc.WebViewPage&quot;&gt; &lt;namespaces&gt; ... &lt;add namespace=&quot;MyProject.Language&quot; /&gt; &lt;/namespaces&gt; &lt;/pages&gt; &lt;/system.web.webPages.razor&gt; </code></pre> <p>This mvc implementation source tutorial: <a href="http://www.ryadel.com/en/setup-a-multi-language-website-using-asp-net-mvc/" rel="noreferrer">Awesome tutorial blog</a></p> <p><strong>Using in class libraries for models</strong></p> <p>Back-end using is the same, but just an example for using in attributes</p> <pre><code>using MyProject.Language; namespace MyProject.Core.Models { public class RegisterViewModel { [Required(ErrorMessageResourceName = &quot;accountEmailRequired&quot;, ErrorMessageResourceType = typeof(Resources))] [EmailAddress] [Display(Name = &quot;Email&quot;)] public string Email { get; set; } } } </code></pre> <p>If you have reshaper it will automatically check if the given resource name exists. If you prefer type safety you can use <a href="https://stackoverflow.com/a/20419904/2901207">T4 templates to generate an enum</a></p> <h3>Using in WPF.</h3> <p>Ofcourse add a reference to your <em>MyProject.Language</em> namespace, we know how to use it in back-end.</p> <p>In XAML, inside the header of a Window or UserControl, add a namespace reference called <code>lang</code> like so:</p> <pre class="lang-xml prettyprint-override"><code>&lt;UserControl x:Class=&quot;Babywatcher.App.Windows.Views.LoginView&quot; xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot; xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot; xmlns:mc=&quot;http://schemas.openxmlformats.org/markup-compatibility/2006&quot; xmlns:d=&quot;http://schemas.microsoft.com/expression/blend/2008&quot; xmlns:local=&quot;clr-namespace:MyProject.App.Windows.Views&quot; xmlns:lang=&quot;clr-namespace:MyProject.Language;assembly=MyProject.Language&quot; &lt;!--this one--&gt; mc:Ignorable=&quot;d&quot; d:DesignHeight=&quot;210&quot; d:DesignWidth=&quot;300&quot;&gt; </code></pre> <p>Then, inside a label:</p> <pre><code> &lt;Label x:Name=&quot;lblHeader&quot; Content=&quot;{x:Static lang:Resources.w_home_header}&quot; TextBlock.FontSize=&quot;20&quot; HorizontalAlignment=&quot;Center&quot;/&gt; </code></pre> <p>Since it is strongly typed you are sure the resource string exists. You might need to recompile the project sometimes during setup, WPF is sometimes buggy with new namespaces.</p> <p>One more thing for WPF, set the language inside the <code>App.xaml.cs</code>. You can do your own implementation (choose during installation) or let the system decide.</p> <pre class="lang-c# prettyprint-override"><code>public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); SetLanguageDictionary(); } private void SetLanguageDictionary() { switch (Thread.CurrentThread.CurrentCulture.ToString()) { case &quot;nl-NL&quot;: MyProject.Language.Resources.Culture = new System.Globalization.CultureInfo(&quot;nl-NL&quot;); break; case &quot;en-GB&quot;: MyProject.Language.Resources.Culture = new System.Globalization.CultureInfo(&quot;en-GB&quot;); break; default://default english because there can be so many different system language, we rather fallback on english in this case. MyProject.Language.Resources.Culture = new System.Globalization.CultureInfo(&quot;en-GB&quot;); break; } } } </code></pre> <h3>Using in UWP</h3> <p>In UWP, Microsoft uses <a href="https://learn.microsoft.com/en-us/windows/uwp/app-resources/localize-strings-ui-manifest" rel="noreferrer">this solution</a>, meaning you will need to create new resource files. Plus you can not re-use the text either because they want you to set the <code>x:Uid</code> of your control in XAML to a key in your resources. And in your resources you have to do <code>Example.Text</code> to fill a <code>TextBlock</code>'s text. I didn't like that solution at all because I want to re-use my resource files. Eventually I came up with the following solution. I just found this out today (2019-09-26) so I might come back with something else if it turns out this doesn't work as desired.</p> <p>Add this to your project:</p> <pre><code>using Windows.UI.Xaml.Resources; public class MyXamlResourceLoader : CustomXamlResourceLoader { protected override object GetResource(string resourceId, string objectType, string propertyName, string propertyType) { return MyProject.Language.Resources.ResourceManager.GetString(resourceId); } } </code></pre> <p>Add this to <code>App.xaml.cs</code> in the constructor:</p> <pre><code>CustomXamlResourceLoader.Current = new MyXamlResourceLoader(); </code></pre> <p>Where ever you want to in your app, use this to change the language:</p> <pre><code>ApplicationLanguages.PrimaryLanguageOverride = &quot;nl&quot;; Frame.Navigate(this.GetType()); </code></pre> <p>The last line is needed to refresh the UI. While I am still working on this project I noticed that I needed to do this 2 times. I might end up with a language selection at the first time the user is starting. But since this will be distributed via Windows Store, the language is usually equal to the system language.</p> <p>Then use in XAML:</p> <pre><code>&lt;TextBlock Text=&quot;{CustomResource ExampleResourceKey}&quot;&gt;&lt;/TextBlock&gt; </code></pre> <h3>Using it in Angular (convert to JSON)</h3> <p>Now days it is more common to have a framework like Angular in combination with components, so without cshtml. Translations are stored in json files, I am not going to cover how that works, I would just highly recommend <a href="https://github.com/ngx-translate/core" rel="noreferrer">ngx-translate</a> instead of the angular multi-translation. So if you want to convert translations to a JSON file, it is pretty easy, I use a T4 template script that converts the Resources file to a json file. I recommend installing <a href="http://t4-editor.tangible-engineering.com/T4-Editor-Visual-T4-Editing.html" rel="noreferrer">T4 editor</a> to read the syntax and use it correctly because you need to do some modifications.</p> <p>Only 1 thing to note: It is not possible to generate the data, copy it, clean the data and generate it for another language. So you have to copy below code as many times as languages you have and change the entry before '//choose language here'. Currently no time to fix this but probably will update later (if interested).</p> <p><em>Path: MyProject.Language/T4/CreateLocalizationEN.tt</em></p> <pre><code>&lt;#@ template debug=&quot;false&quot; hostspecific=&quot;true&quot; language=&quot;C#&quot; #&gt; &lt;#@ assembly name=&quot;System.Core&quot; #&gt; &lt;#@ assembly name=&quot;System.Windows.Forms&quot; #&gt; &lt;#@ import namespace=&quot;System.Linq&quot; #&gt; &lt;#@ import namespace=&quot;System.Text&quot; #&gt; &lt;#@ import namespace=&quot;System.Collections.Generic&quot; #&gt; &lt;#@ import namespace=&quot;System.Resources&quot; #&gt; &lt;#@ import namespace=&quot;System.Collections&quot; #&gt; &lt;#@ import namespace=&quot;System.IO&quot; #&gt; &lt;#@ import namespace=&quot;System.ComponentModel.Design&quot; #&gt; &lt;#@ output extension=&quot;.json&quot; #&gt; &lt;# var fileNameNl = &quot;../Resources/Resources.resx&quot;; var fileNameEn = &quot;../Resources/Resources.en.resx&quot;; var fileNameDe = &quot;../Resources/Resources.de.resx&quot;; var fileNameTr = &quot;../Resources/Resources.tr.resx&quot;; var fileResultName = &quot;../T4/CreateLocalizationEN.json&quot;;//choose language here var fileResultPath = Path.Combine(Path.GetDirectoryName(this.Host.ResolvePath(&quot;&quot;)), &quot;MyProject.Language&quot;, fileResultName); //var fileDestinationPath = &quot;../../MyProject.Web/ClientApp/app/i18n/&quot;; var fileNameDestNl = &quot;nl.json&quot;; var fileNameDestEn = &quot;en.json&quot;; var fileNameDestDe = &quot;de.json&quot;; var fileNameDestTr = &quot;tr.json&quot;; var pathBaseDestination = Directory.GetParent(Directory.GetParent(this.Host.ResolvePath(&quot;&quot;)).ToString()).ToString(); string[] fileNamesResx = new string[] {fileNameEn }; //choose language here string[] fileNamesDest = new string[] {fileNameDestEn }; //choose language here for(int x = 0; x &lt; fileNamesResx.Length; x++) { var currentFileNameResx = fileNamesResx[x]; var currentFileNameDest = fileNamesDest[x]; var currentPathResx = Path.Combine(Path.GetDirectoryName(this.Host.ResolvePath(&quot;&quot;)), &quot;MyProject.Language&quot;, currentFileNameResx); var currentPathDest =pathBaseDestination + &quot;/MyProject.Web/ClientApp/app/i18n/&quot; + currentFileNameDest; using(var reader = new ResXResourceReader(currentPathResx)) { reader.UseResXDataNodes = true; #&gt; { &lt;# foreach(DictionaryEntry entry in reader) { var name = entry.Key; var node = (ResXDataNode)entry.Value; var value = node.GetValue((ITypeResolutionService) null); if (!String.IsNullOrEmpty(value.ToString())) value = value.ToString().Replace(&quot;\n&quot;, &quot;&quot;); if (!String.IsNullOrEmpty(value.ToString())) value = value.ToString().Replace(&quot;\r&quot;, &quot;&quot;); #&gt; &quot;&lt;#=name#&gt;&quot;: &quot;&lt;#=value#&gt;&quot;, &lt;# } #&gt; &quot;WEBSHOP_LASTELEMENT&quot;: &quot;just ignore this, for testing purpose&quot; } &lt;# } File.Copy(fileResultPath, currentPathDest, true); } #&gt; </code></pre> <p>If you have a modulair application and you followed my suggestion to create multiple language projects, then you will have to create a T4 file for each of them. Make sure the json files are logically defined, it doesn't have to be <code>en.json</code>, it can also be <code>example-en.json</code>. To combine multiple json files for using with <a href="https://github.com/ngx-translate/core" rel="noreferrer">ngx-translate</a>, follow the instructions <a href="https://github.com/ngx-translate/core/issues/199#issuecomment-339084987" rel="noreferrer">here</a></p> <h3>Use in Xamarin.Android</h3> <p>As explained above in the updates, I use the same method as I have done with Angular/JSON. But Android uses XML files, so I wrote a T4 file that generates those XML files.</p> <p><em>Path: MyProject.Language/T4/CreateAppLocalizationEN.tt</em></p> <pre><code>#@ template debug=&quot;false&quot; hostspecific=&quot;true&quot; language=&quot;C#&quot; #&gt; &lt;#@ assembly name=&quot;System.Core&quot; #&gt; &lt;#@ assembly name=&quot;System.Windows.Forms&quot; #&gt; &lt;#@ import namespace=&quot;System.Linq&quot; #&gt; &lt;#@ import namespace=&quot;System.Text&quot; #&gt; &lt;#@ import namespace=&quot;System.Collections.Generic&quot; #&gt; &lt;#@ import namespace=&quot;System.Resources&quot; #&gt; &lt;#@ import namespace=&quot;System.Collections&quot; #&gt; &lt;#@ import namespace=&quot;System.IO&quot; #&gt; &lt;#@ import namespace=&quot;System.ComponentModel.Design&quot; #&gt; &lt;#@ output extension=&quot;.xml&quot; #&gt; &lt;# var fileName = &quot;../Resources/Resources.en.resx&quot;; var fileResultName = &quot;../T4/CreateAppLocalizationEN.xml&quot;; var fileResultRexPath = Path.Combine(Path.GetDirectoryName(this.Host.ResolvePath(&quot;&quot;)), &quot;MyProject.Language&quot;, fileName); var fileResultPath = Path.Combine(Path.GetDirectoryName(this.Host.ResolvePath(&quot;&quot;)), &quot;MyProject.Language&quot;, fileResultName); var fileNameDest = &quot;strings.xml&quot;; var pathBaseDestination = Directory.GetParent(Directory.GetParent(this.Host.ResolvePath(&quot;&quot;)).ToString()).ToString(); var currentPathDest =pathBaseDestination + &quot;/MyProject.App.AndroidApp/Resources/values-en/&quot; + fileNameDest; using(var reader = new ResXResourceReader(fileResultRexPath)) { reader.UseResXDataNodes = true; #&gt; &lt;resources&gt; &lt;# foreach(DictionaryEntry entry in reader) { var name = entry.Key; //if(!name.ToString().Contains(&quot;WEBSHOP_&quot;) &amp;&amp; !name.ToString().Contains(&quot;DASHBOARD_&quot;))//only include keys with these prefixes, or the country ones. //{ // if(name.ToString().Length != 2) // { // continue; // } //} var node = (ResXDataNode)entry.Value; var value = node.GetValue((ITypeResolutionService) null); if (!String.IsNullOrEmpty(value.ToString())) value = value.ToString().Replace(&quot;\n&quot;, &quot;&quot;); if (!String.IsNullOrEmpty(value.ToString())) value = value.ToString().Replace(&quot;\r&quot;, &quot;&quot;); if (!String.IsNullOrEmpty(value.ToString())) value = value.ToString().Replace(&quot;&amp;&quot;, &quot;&amp;amp;&quot;); if (!String.IsNullOrEmpty(value.ToString())) value = value.ToString().Replace(&quot;&lt;&lt;&quot;, &quot;&quot;); //if (!String.IsNullOrEmpty(value.ToString())) value = value.ToString().Replace(&quot;'&quot;, &quot;\'&quot;); #&gt; &lt;string name=&quot;&lt;#=name#&gt;&quot;&gt;&quot;&lt;#=value#&gt;&quot;&lt;/string&gt; &lt;# } #&gt; &lt;string name=&quot;WEBSHOP_LASTELEMENT&quot;&gt;just ignore this&lt;/string&gt; &lt;# #&gt; &lt;/resources&gt; &lt;# File.Copy(fileResultPath, currentPathDest, true); } #&gt; </code></pre> <p>Android works with <code>values-xx</code> folders, so above is for English for in the <code>values-en</code> folder. But you also have to generate a default which goes into the <code>values</code> folder. Just copy above T4 template and change the folder in the above code.</p> <p>There you go, you can now use one single resource file for all your projects. This makes it very easy exporting everything to an excl document and let someone translate it and import it again.</p> <p>Special thanks to <a href="https://github.com/tom-englert/ResXResourceManager" rel="noreferrer">this amazing VS extension</a> which works awesome with <code>resx</code> files. Consider <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&amp;hosted_button_id=TQQR8AKGNHELQ" rel="noreferrer">donating</a> to him for his awesome work (I have nothing to do with that, I just love the extension).</p>
<p>Most opensource projects use <a href="http://gnuwin32.sourceforge.net/packages/gettext.htm" rel="nofollow noreferrer">GetText</a> for this purpose. I don't know how and if it's ever been used on a .Net project before.</p>
48,837
<p>My application deals with e-mails coming from different sources, e.g. Outlook and IMAP mailboxes. Before parsing them, I write them to the temporary directory (keeping them in memory is not an option). While parsing, I might be writing attachments to the temp directory (for example, if they are too large to keep in memory or for full-text extraction).</p> <p>But in the wild, two things happen that seemed very strange in the first place but could all be traced back to virus scanner behaviour:</p> <ul> <li><p>I'm sometimes unable to open files which I've written myself a few milliseconds ago. They are obviously locked by virus scanners to ensure that they are clean. I get an Exception.</p></li> <li><p>If files are considered dangerous by the virus scanner, it deletes them at some point of time.</p></li> </ul> <p>To cope with this behaviour, I've written a few methods that try again if open fails or do some checks if files exist, but I'm unable to use them in every part of the application (3rd party code, for example filters), so things got better, but not 100% perfect and my source code looks ugly in parts because of this.</p> <p>How do you cope with virus scanners?</p>
<p>If changing Virus scanner configuration is not the ideal option for you. Could you keep the file open from it's creation up to the end of your process? If you got an handle on the file, it will not be available for the Virus scanner.</p>
<p>Virus scanner have exclude folders. Just look in the documentation and add your temp folder to this list.</p>
26,409
<p>The code that I want to write is like this:</p> <pre><code>void MethodOnThreadA() { for (;;) { // Do stuff if (ErrorConditionMet) ThrowOnThread(threadB, new MyException(...)); } } void MethodOnThreadB() { try { for (;;) { // Do stuff } } catch (MyException ex) { // Do the right thing for this exception. } } </code></pre> <p>I know I can have thread B periodically check, in thread safe way, to see if a flag has been set by thread A, but that makes the code more complicated. Is there a better mechanism that I can use?</p> <p>Here is a more fleshed out example of periodically checking:</p> <pre><code>Dictionary&lt;Thread, Exception&gt; exceptionDictionary = new Dictionary&lt;Thread, Exception&gt;(); void ThrowOnThread(Thread thread, Exception ex) { // the exception passed in is going to be handed off to another thread, // so it needs to be thread safe. lock (exceptionDictionary) { exceptionDictionary[thread] = ex; } } void ExceptionCheck() { lock (exceptionDictionary) { Exception ex; if (exceptionDictionary.TryGetValue(Thread.CurrentThread, out ex)) throw ex; } } void MethodOnThreadA() { for (;;) { // Do stuff if (ErrorConditionMet) ThrowOnThread(threadB, new MyException(...)); } } void MethodOnThreadB() { try { for (;;) { // Do stuff ExceptionCheck(); } } catch (MyException ex) { // Do the right thing for this exception. } } </code></pre>
<p>This is NOT a good idea</p> <p><a href="http://blog.headius.com/2008/02/rubys-threadraise-threadkill-timeoutrb.html" rel="noreferrer">This article talks about ruby's timeout library.</a> which throws exceptions across threads.</p> <p>It explains how doing such a thing is fundamentally broken. It's not just broken in ruby, it's broken anywhere that throws exceptions across threads.</p> <p>In a nutshell, what can (and does) happen is this:</p> <p>ThreadA: </p> <pre><code>At some random time, throw an exception on thread B: </code></pre> <p>ThreadB:</p> <pre><code>try { //do stuff } finally { CloseResourceOne(); // ThreadA's exception gets thrown NOW, in the middle // of our finally block and resource two NEVER gets closed. // Obviously this is BAD, and the only way to stop is to NOT throw // exceptions across threads CloseResourceTwo(); } </code></pre> <p>Your 'periodic checking' example is fine, as you're not actually throwing exceptions across threads.<br> You're just setting a flag which says "throw an exception the next time you look at this flag", which is fine as it doesn't suffer from the "can be thrown in the middle of your catch or finally block" problem.<br> However, if you're going to do that, you may as well just be setting an "exitnow" flag, and using that and save yourself the hassle of creating the exception object. A volatile bool will work just fine for that.</p>
<p>I'm interested to know why you would want to do this. There's not an easy way to do it, because it's not a good practice. You should probably go back to your design and figure out a cleaner way to accomplish the end goal.</p>
6,642
<p>Whats the best way to bind variable column names to a report field in Access when using a crosstab query? </p>
<p>I think because it's not needed very often. However, there is an easy way to do this in C++:</p> <pre><code>#include &lt;algorithm&gt; swap_ranges(ptr1, ptr1 + nbytes, ptr2) </code></pre> <p>It's it may not be quite as optimized as a compiler built in, but it has the potential of being faster than a loop you write for yourself, since it may have platform specific optimization that you would not implement.</p> <p>You do need to be careful with the above, because it assumes that ptr1 and ptr2 are char pointers. The more canonical way to do this is:</p> <pre><code>#include &lt;algorithm&gt; swap_ranges(ptr1, ptr1 + num_items, ptr2) </code></pre>
<p>Probably because it's not needed very often - I memset and memcpy reasonably often, but I don't know that I'd ever have used memswap if it was available.</p>
13,452
<p>As every Haxe developer knows, you could use <code>haxe.Timer.delayed()</code> to delay function call for some time. But this function doesn't exist for Neko at all. Is there a way to achieve the same results?</p>
<p>Have to check it first but </p> <pre><code>function delayed(f, time) { neko.vm.Thread.create(function() { neko.Sys.sleep(time); f(); }); } </code></pre> <p>might be the closest thing possible. The only cons is that application becomes multi threaded which could lead to serious problems.</p>
<p>Yes I don't know anything except for what you mention in your first answer. On Linux you can use SIGALARM - but this doesn't look trivial, 100% pure C code, and needs to be handled with great care to avoid crashing the VM.</p>
28,002
<p>I've created a windows forms control, which is hosted in a web page viewable with Internet Explorer.</p> <p>My control reads from a com port and it writes to the event log. Both of these operations by default fail when the framework requests proper permissions. This web application will always be running in the intranet zone, how do I enable these operations?</p> <p>Serial port code bits &amp; error:</p> <pre><code>private System.IO.Ports.SerialPort portCardReader_m = new System.IO.Ports.SerialPort(); portCardReader_m.PortName = value; portCardReader_m.Open(); //Exception here </code></pre> <blockquote> <p>Request for the permission of type 'System.Security.Permissions.SecurityPermission,mscorlib, Version=2.0.0.0, Culture=neutral,PublicKeyToken=b77a5c561934e089 failed.</p> </blockquote> <p>Event Log code bits &amp; error:</p> <pre><code>System.Diagnostics.EventLog pEventLog = new System.Diagnostics.EventLog("Application", ".", this.GetType().FullName); pEventLog.WriteEntry(this.Text, System.Diagnostics.EventLogEntryType.Error); //Exception Here </code></pre> <blockquote> <p>Request for the permission of type 'System.Diagnostics.EventLogPermission,System, Version=2.0.0.0, Culture=neutral,PublicKeyToken=b77a5c561934e089 failed.</p> </blockquote> <p>Code to embed my control in the browser:</p> <pre><code>&lt;object width="600px" height="300px" id="objCardReader" classid="cardreader.dll#CardReader"&gt; &lt;param name="Text" value="Testing" /&gt; &lt;param name="PortName" value="COM5" /&gt; &lt;/object&gt; </code></pre>
<p>You would need to create an installer or have your users grant a higher trust level for your website. These settings are editable under Microsoft .NET Framework configuration. under Administrative Tools. You can also take a look at <a href="http://www.sellsbrothers.com/wahoo/" rel="nofollow noreferrer">Chris Sells Wahoo</a> which uses an installer to grant these permissions</p>
<p>I've struggled with this in the past and tried to elevate permissions using caspol and it was a real pain. I ended up converting it to a click once app in 30 minutes and never had a problem with it since.</p>
37,211
<p>I'd like to have revision number of source code to Delphi's source code and exe version. What is the best way to do this automatically?</p> <p>I'd like to display the revision number in "About" screen and in the version info of the project.</p> <p>I'm using currently Delphi IDE (2006/2007) and Tortoise SVN.</p>
<p>There is a program called SubWCRev.exe that comes with TortoiseSVN that will do token replacement for you. So somewhere in your source, you insert the token, and pass the input and output filenames to SubWCRev.exe, and it will replace the token with various SVN info, e.g., revision number. Note, this is a standalone program you can use with your build script, you do not need to use TortoiseSVN with it.</p>
<p>Suggestion: modify your build scripts to change some version file that gets compiled in afterwards. It's difficult to suggest anything more specific without knowing the build environment you're using.</p>
47,520
<p>I need something in between a full text search and an index search:<br> I want to search for text in one column of my table (probably there will be an index on the column, too, if that matters).</p> <p>Problem is, I want to search for words in the column, but I don't want to match parts. </p> <p>For example, my column might contain business names:<br> <em>Mighty Muck Miller and Partners Inc.<br> Boy &amp; Butter Breakfast company</em> </p> <p>Now if I search for "<em>Miller</em>" I want to find the first line. But if I search for "<em>iller</em>" I don't want to find it, because there is no word starting with "iller". Searching for "<em>Break</em>" should find "<em>Boy &amp; Butter Breakfast company</em>", though, since one word is starting with "<em>Break</em>".</p> <p>So if I try and use </p> <pre><code>WHERE BusinessName LIKE %Break% </code></pre> <p>it will find too many hits.</p> <p>Is there any way to Search for Words separated by whitespace <strong>or other delimiters</strong>? </p> <p>(LINQ would be best, plain SQL would do, too)</p> <p><strong>Important:</strong> Spaces are by far not the only delimiters! Slashes, colons, dots, all non-alphanumerical characters should be considered for this to work!</p>
<p>Your word delimiters are going to be many: space, tab, beginning of line, parentheses, periods, commas, exclamation/question marks etc. So, a pretty simple solution is to use a regex in your WHERE clause. (And it's going to be a lot more efficient than just ORing every possible delimiter you can think of.)</p> <p>Since you mentioned LINQ, here's an article that describes how to do <a href="http://msdn.microsoft.com/en-us/magazine/cc163473.aspx" rel="nofollow noreferrer">efficient regex querying with SQL Server</a>.</p> <p>Complicated WHERE clauses like this always raise a red flag with me as far as performance is concerned, so I definitely suggest benchmarking whatever you end up with, you may decide to build a search index for the column after all.</p> <p><strong>EDIT:</strong> Saw you edited your question. When <a href="http://regexlib.com/CheatSheet.aspx" rel="nofollow noreferrer">writing your regex</a>, it's easy to just have it use any non-alphanum character as a delimiter, i.e. [^0-9a-zA-Z], or \W for any non-word character, \b for any word boundary and \B for any non-word boundary. Or, instead of matching delimiters, just match any word, i.e. \w+. Here's <a href="http://www.sqlteam.com/article/regular-expressions-in-t-sql" rel="nofollow noreferrer">another example</a> of someone doing regex searches with SQL Server (more complicated than what you'd need). </p>
<p>Try this:</p> <pre><code>declare @vSearch nvarchar(100) set @vSearch = 'About' select * from btTab where ' ' + vText + ' ' LIKE '%[^A-z^0-9]' + @vSearch + '[^A-z^0-9]%' </code></pre>
18,996
<p>With my multiproject pom I get an error while running release:prepare. There is nothing fancy about the project setup and every release-step before runs fine. The error I get is:</p> <pre> [INFO] ------------------------------------------------------------------------ [ERROR] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Unable to tag SCM Provider message: The svn tag command failed. Command output: svn: Commit failed (details follow): svn: File '/repos/june/tags/foo-1.0.2/foo.bar.org/pom.xml' already exists </pre> <p>Any idea where it comes from and how to get around it?</p> <p>(sorry for duplicate post - first was closed because I didn't formulate it as a question that can be answered. I hope it's ok now.)</p> <p><b>EDIT</b><br> The maven release plugin takes care of the version handling itself. So when I check the path in the subversion repository the path does not yet exist.</p> <p><b>EDIT 2</b><br> @Ben: I don't know the server version, however the client is 1.5.2, too.</p>
<p>This issue is addressed in the latest version of the <a href="http://maven.apache.org/plugins/maven-release-plugin/" rel="noreferrer">maven-release-plugin</a>. Add this to your POM to pull it in.</p> <pre><code>&lt;build&gt; &lt;pluginManagement&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;artifactId&gt;maven-release-plugin&lt;/artifactId&gt; &lt;version&gt;2.0-beta-9&lt;/version&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/pluginManagement&gt; &lt;/build&gt; </code></pre> <p>The issue that was fixed is <a href="http://jira.codehaus.org/browse/MRELEASE-375" rel="noreferrer">MRELEASE-375</a>.</p>
<p>As far as I know it is a bug in Subversion 1.5 and not directly related with maven. However a workaround the fixed it for me is to update the local svn repository and run the release:prepare goal again.</p>
11,770
<p>Every time I do an <code>hg diff file.ext</code> I end up using a console diff application. I would like to use Kdiff3 or WinMerge (I'm using Windows).</p> <p>Is there a way to change that? I can't find a reference in Mercurial documentation (<strong>I'm not talking about merge!</strong>). </p>
<p>I've solved this using a Mercurial built-in extension... I just have to add the following lines to Mercurial.ini (on Mercurial folder):</p> <pre><code>[extensions] hgext.extdiff= [extdiff] cmd.vdiff = kdiff3 </code></pre> <p>When I want to use kdiff3 instead of diff I only have to use:</p> <pre><code>hg vdiff file.ext </code></pre>
<p>I just had this problem a few minutes ago; I just installed it and added its path (default is at c:\program files\kdiff3) to my system PATH e.v. Restarted my window to pick up the new path, and "hg kdiff3" just worked. As it turns out the following is in my base "mercurial.ini" file, this allows the kdiff3 to work for all hg repos on the system.</p> <pre><code>[extensions] hgext.extdiff = [extdiff] cmd.kdiff3 = [merge-tools] kdiff3.args = $base $local $other -o $output </code></pre>
29,461
<p>We've noticed that IE7 has an odd behavor with code blocks posted on Stack Overflow. For example, this little code block:</p> <pre><code>public PageSizer(string href, int index) { HRef = href; PageIndex = index; } </code></pre> <p>Copy and pasted from IE7, ends up like this:</p> <pre> public PageSizer(string href, int index){ HRef = href; PageIndex = index; } </pre> <p>Not exactly what we had in mind.. the underlying HTML source actually looks fine; if you View Source, you'll see this:</p> <pre><code>&lt;pre&gt;&lt;code&gt;public PageSizer(string href, int index) { HRef = href; PageIndex = index; } &lt;/code&gt;&lt;/pre&gt; </code></pre> <p>So what are we doing wrong? Why can't IE7 copy and paste this HTML in a rational way?</p> <blockquote> <p>Update: <strong>this specifically has to do with <code>&lt;pre&gt;</code> <code>&lt;code&gt;</code> blocks that are being modified at runtime via JavaScript.</strong> The native HTML does render and copy correctly; it's the JavaScript modified version of that HTML which doesn't behave as expected. Note that copying and pasting into WordPad or Word works because IE is putting different content in the rich text clipboard compared to the plain text clipboard that Notepad gets its data from.</p> </blockquote>
<p>It seems that this is a known bug for IE6 and prettify.js has a workaround for it. Specifically it replaces the BR tags with '\r\n'.</p> <p>By modifying the check to allow for IE6 or 7 then the cut-and-paste will work correctly from IE7, but it will render with a <em>newline</em> followed by a <em>space</em>. By checking for IE7 and providing just a '\r' instead of a '\r\n' it will continue to cut-and-paste and render correctly.</p> <p>Add this code to prettify.js:</p> <pre><code>function _pr_isIE7() { var isIE7 = navigator &amp;&amp; navigator.userAgent &amp;&amp; /\bMSIE 7\./.test(navigator.userAgent); _pr_isIE7 = function () { return isIE7; }; return isIE7; } </code></pre> <p>and then modify the prettyPrint function as follows:</p> <pre><code> function prettyPrint(opt_whenDone) { var isIE6 = _pr_isIE6(); + var isIE7 = _pr_isIE7(); </code></pre> <p>...</p> <pre><code>- if (isIE6 &amp;&amp; cs.tagName === 'PRE') { + if ((isIE6 || isIE7) &amp;&amp; cs.tagName === 'PRE') { var lineBreaks = cs.getElementsByTagName('br'); + var newline; + if (isIE6) { + newline = '\r\n'; + } else { + newline = '\r'; + } for (var j = lineBreaks.length; --j &gt;= 0;) { var lineBreak = lineBreaks[j]; lineBreak.parentNode.replaceChild( - document.createTextNode('\r\n'), lineBreak); + document.createTextNode(newline), lineBreak); } </code></pre> <p>You can see a <a href="http://andrjohn.myzen.co.uk/soTest/136443.html" rel="noreferrer">working example here</a>.</p> <p><strong>Note:</strong> I haven't tested the original workaround in IE6, so I'm guessing it renders without the space caused by the '\n' that is seen in IE7, otherwise the fix is simpler.</p>
<p>Remove the inner <code>&lt;code&gt;</code>. IE's copy/paste behavior could see that as an inline tag and forget about the visible whitespace.</p>
16,511
<p>It's the weekend, so I relax from spending all week programming by writing a hobby project.</p> <p>I wrote the framework of a MOS 6502 CPU emulator yesterday, the registers, stack, memory and all the opcodes are implemented. (Link to source below)</p> <p>I can manually run a series of operations in the debugger I wrote, but I'd like to load a NES rom and just point the program counter at its instructions, I figured that this would be the fastest way to find flawed opcodes.</p> <p>I wrote a quick NES rom loader and loaded the ROM banks into the CPU memory.</p> <p>The problem is that I don't know how the opcodes are encoded. I know that the opcodes themselves follow a pattern of one byte per opcode that uniquely identifies the opcode, </p> <pre><code>0 - BRK 1 - ORA (D,X) 2 - COP b </code></pre> <p>etc</p> <p>However I'm not sure where I'm supposed to find the opcode argument. Is it the the byte directly following? In absolute memory, I suppose it might not be a byte but a short. </p> <p>Is anyone familiar with this CPU's memory model?</p> <p>EDIT: I realize that this is probably shot in the dark, but I was hoping there were some oldschool Apple and Commodore hackers lurking here.</p> <p><strong>EDIT:</strong> Thanks for your help everyone. After I implemented the proper changes to align each operation the CPU can load and run Mario Brothers. It doesn't do anything but loop waiting for Start, but its a good sign :)</p> <p>I uploaded the source:</p> <p><a href="https://archive.codeplex.com/?p=cpu6502" rel="nofollow noreferrer">https://archive.codeplex.com/?p=cpu6502</a></p> <p>If anyone has ever wondered how an emulator works, its pretty easy to follow. Not optimized in the least, but then again, I'm emulating a CPU that runs at 2mhz on a 2.4ghz machine :)</p>
<p>The opcode takes one byte, and the operands are in the following bytes. Check out the byte size column <a href="http://www.atariarchives.org/2bml/chapter_10.php" rel="noreferrer">here</a>, for instance.</p>
<p>The apple II roms included a dissassembler, I think that's what it was called, and it would show you in a nice format the hex opcodes and the 3 character opcode and the operands.</p> <p>So given how little memory was available, they managed to shove in the operand byte count (always 0, 1 or 2) the 3 character opcode for the entire 6502 instruction set into a really small space, because there's really not that much of it.</p> <p>If you can dig up an apple II rom, you can just cut and paste from there...</p>
13,694
<p>I'm reading in a lot of data from ldap which needs to be compared to the respective records in the database. To minimize the number of SQL queries, I want to batch multiple ldap records into a single query.</p> <p>All this is pretty simple: A thread to produce ldap results, and a thread to consume those results and run the SQL query.</p> <pre> ldap_results = Queue.Queue(10) def producer(): for result in ldap_results(): ldap_results.put(result) def consumer(): buffer = [] buffer_size = 5 while True: record = ldap_results.get() buffer.append(record) if len(buffer) >= buffer_size: do_sql(buffer) buffer = [] </pre> <p>The problem is: If ldap only returns, say, 3 results and <code>buffer_size</code> is 5, it'll end up blocking forever. I realize I could put some special token into the buffer, like <code>None</code>, or <code>"EOF"</code>, but that seems like bad design: "iterate until you're done, oh, unless you see this special value, that means you're done, too".</p> <p>I came up with two alternative ideas. The first is to have a shared <code>eof</code> variable, but I don't know how to properly synchronize it.</p> <pre> def producer(): while data: buffer.put() eof = True def consumer(): while not eof: buffer.get() </pre> <p>The second is to have a <code>ProduceChunks(chunk_size)</code> method for the producer, and it'll handle the batching up of results, but I don't like that because it assumes the producer will know how best to buffer up results, when, really, I think that is the responsibility of the consumer.</p> <p>Does anyone have any guidance?</p>
<p>I would follow the "Make it Run, Make it Right, Make it Fast, Make it Simple" pattern.</p> <p>Can you implement this correctly without an special "EOF" token? If not, then you just have to use the EOF token, do not sweat it. Yes, the termination condition is more complex, but now it is "Right."</p>
<p>The "EOF" approach is perfectly respectable. Let's look at the microcosm of an ANSI string. The null is the EOF. What's bad about that?</p> <p>Alternatively, let's look at the microcosm of the BSTR. Instead of a trailing null, the first bytes tell you how bytes are coming.</p> <p>Either way is fine.</p> <p>Doesn't matter.</p>
35,842
<p>How can I limit my post-build events to running only for one type of build?</p> <p>I'm using the events to copy DLL files to a local IIS virtual directory, but I don't want this happening on the build server in release mode.</p>
<p>Pre- and Post-Build Events run as a batch script. You can do a conditional statement on <code>$(ConfigurationName)</code>.</p> <p>For instance</p> <pre><code>if $(ConfigurationName) == Debug xcopy something somewhere </code></pre>
<p>Like any project setting, the buildevents can be configured per Configuration. Just select the configuration you want to change in the dropdown of the Property Pages dialog and edit the post build step.</p>
18,083
<p>I have a load of user-submitted content. It is HTML, and may contain URLs. Some of them will be <code>&lt;a&gt;</code>'s already (if the user is good) but sometimes users are lazy and just type www.something.com or at best <a href="http://www.something.com" rel="noreferrer">http://www.something.com</a>.</p> <p>I can't find a decent regex to capture URLs but ignore ones that are immediately to the right of either a double quote or '>'. Anyone got one?</p>
<p>Jan Goyvaerts, creator of <a href="http://www.regexbuddy.com" rel="noreferrer">RegexBuddy</a>, has <a href="http://www.regexguru.com/2008/11/detecting-urls-in-a-block-of-text/" rel="noreferrer">written a response</a> to Jeff Atwood's blog that addresses the issues Jeff had and provides a nice solution. </p> <pre><code>\b(?:(?:https?|ftp|file)://|www\.|ftp\.)[-A-Z0-9+&amp;@#/%=~_|$?!:,.]*[A-Z0-9+&amp;@#/%=~_|$] </code></pre> <p>In order to ignore matches that occur right next to a " or >, you could add <code>(?&lt;!["&gt;])</code> to the start of the regex, so you get</p> <pre><code>(?&lt;!["&gt;])\b(?:(?:https?|ftp|file)://|www\.|ftp\.)[-A-Z0-9+&amp;@#/%=~_|$?!:,.]*[A-Z0-9+&amp;@#/%=~_|$] </code></pre> <p>This will match full addresses (<a href="http://.." rel="noreferrer">http://..</a>.) and addresses that start with www. or ftp. - you're out of luck with addresses like ars.userfriendly.org...</p>
<p>Shameless plug: You can look here (<a href="https://stackoverflow.com/questions/276029/#276109">regular expression replace a word by a link</a>) for inspiration. </p> <p>The question asked to replace some word with a certain link, unless there already was a link. So the problem you have is more or less the same thing.</p> <p>All you need is a regex that matches a URL (in place of the word). The simplest assumption would be like this: An URL (optionally) starts with <code>"http://"</code>, <code>"ftp://"</code> or <code>"mailto:"</code> and lasts as long as there are no white-space characters, line breaks, tag brackets or quotes). </p> <p>Beware, long regex ahead. Apply case-insensitively.</p> <pre><code>(href\s*=\s*['"]?)?((?:http://|ftp://|mailto:)?[^.,&lt;&gt;"'\s\r\n\t]+(?:\.(?![.&lt;&gt;"'\s\r\n])[^.,!&lt;&gt;"'\s\r\n\t]+)+) </code></pre> <p>Be warned - this will also match URLs that are <em>technically</em> invalid, and it will recognize things.formatted.like.this as an URL. It depends on your data if it is too insensitive. I can fine-tune the regex if you have examples where it returns false positives.</p> <p>The regex will produce two match groups. Group 2 will contain the matched thing, which is most likely an URL. Group 1 will either contain an empty string or an <code>'href="'</code>. You can use it as an indicator that this match occurred <em>inside</em> a href parameter of an existing link and you don't have to do touch that one.</p> <p>Once you confirm that this does the right thing for you <em>most of the time</em> (with user supplied data, you can never be sure), you can do the rest in two steps, as I proposed it in the other question:</p> <ol> <li>Make a link around every URL there is (<strong>unless</strong> there is something in match group 1!) This <em>will</em> produce double nested <code>&lt;a&gt;</code> tags for things that have a link already.</li> <li>Scan for incorrectly nested <code>&lt;a&gt;</code> tags, removing the innermost one</li> </ol>
36,525
<p>How do I check if an object has a specific property in JavaScript?</p> <p>Consider:</p> <pre><code>x = {'key': 1}; if ( x.hasOwnProperty('key') ) { //Do this } </code></pre> <p>Is that the best way to do it?</p>
<h2>2022 UPDATE</h2> <h2><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn" rel="noreferrer"><code>Object.hasOwn()</code></a></h2> <blockquote> <p><code>Object.hasOwn()</code> is recommended over <code>Object.hasOwnProperty()</code> because it works for objects created using <code>Object.create(null)</code> and with objects that have overridden the inherited <code>hasOwnProperty()</code> method. While it is possible to workaround these problems by calling <code>Object.prototype.hasOwnProperty()</code> on an external object, <code>Object.hasOwn()</code> is more intuitive.</p> </blockquote> <h4>Example</h4> <pre class="lang-js prettyprint-override"><code>const object1 = { prop: 'exists' }; console.log(Object.hasOwn(object1, 'prop')); // expected output: true </code></pre> <hr /> <h2>Original answer</h2> <p>I'm really confused by the answers that have been given - most of them are just outright incorrect. Of course you can have object properties that have undefined, null, or false values. So simply reducing the property check to <code>typeof this[property]</code> or, even worse, <code>x.key</code> will give you completely misleading results.</p> <p>It depends on what you're looking for. If you want to know if an object physically contains a property (and it is not coming from somewhere up on the prototype chain) then <code>object.hasOwnProperty</code> is the way to go. All modern browsers support it. (It was missing in older versions of Safari - 2.0.1 and older - but those versions of the browser are rarely used any more.)</p> <p>If what you're looking for is if an object has a property on it that is iterable (when you iterate over the properties of the object, it will appear) then doing: <code>prop in object</code> will give you your desired effect.</p> <p>Since using <code>hasOwnProperty</code> is probably what you want, and considering that you may want a fallback method, I present to you the following solution:</p> <pre><code>var obj = { a: undefined, b: null, c: false }; // a, b, c all found for ( var prop in obj ) { document.writeln( &quot;Object1: &quot; + prop ); } function Class(){ this.a = undefined; this.b = null; this.c = false; } Class.prototype = { a: undefined, b: true, c: true, d: true, e: true }; var obj2 = new Class(); // a, b, c, d, e found for ( var prop in obj2 ) { document.writeln( &quot;Object2: &quot; + prop ); } function hasOwnProperty(obj, prop) { var proto = obj.__proto__ || obj.constructor.prototype; return (prop in obj) &amp;&amp; (!(prop in proto) || proto[prop] !== obj[prop]); } if ( Object.prototype.hasOwnProperty ) { var hasOwnProperty = function(obj, prop) { return obj.hasOwnProperty(prop); } } // a, b, c found in modern browsers // b, c found in Safari 2.0.1 and older for ( var prop in obj2 ) { if ( hasOwnProperty(obj2, prop) ) { document.writeln( &quot;Object2 w/ hasOwn: &quot; + prop ); } } </code></pre> <p>The above is a working, cross-browser, solution to <code>hasOwnProperty()</code>, with one caveat: It is unable to distinguish between cases where an identical property is on the prototype and on the instance - it just assumes that it's coming from the prototype. You could shift it to be more lenient or strict, based upon your situation, but at the very least this should be more helpful.</p>
<p>Don't over-complicate things when you can do:</p> <pre><code>var isProperty = (objectname.keyname || &quot;&quot;) ? true : false; </code></pre> <p>It Is simple and clear for most cases...</p>
16,405
<p>I have a report in SQL Server Reporting Services (SSRS) that I'd like to schedule to run automatically as an email. I'd like the report to be attached as Excel file.<br> According to the <a href="http://www.microsoft.com/Sqlserver/2005/en/us/reporting-services.aspx" rel="noreferrer">Microsoft overview</a> this should be possible.</p> <blockquote> <p><strong>Report delivery</strong>. SQL Server Reporting Services supports both on-demand (pull) and event-based (push) delivery of reports. Users can view reports in a Web-based format or in e-mail.</p> </blockquote> <p>However I can't find any information on how to actually do this. Does anyone know what tools should be used or where there is a good tutorial?</p> <p>Thanks!</p>
<p>When you browse to the report in your reporting services site you should see a tab for Subscriptions. That's where you'd specify the recipients and delivery methods for automated delivery.</p> <p>Here's a <a href="http://msdn.microsoft.com/en-us/library/ms160334.aspx" rel="noreferrer">page</a> that describes the process.</p>
<p>You can use SQL- RD Application for Dynamic schedules</p>
35,141
<p>After installing a third-party SDK, it very discourteously makes one if its templates the default item in "Add New Item..." dialog in Visual Studio 2005. This is also the case for all other similar dialogs - "Add Class...", "Add User Control..." etc.</p> <p>Is there a way to change this behavior?</p>
<p>You may have to manually modify the SortOrder on the Item templates yourself. You can do this by following these directions:</p> <p>1) Find the Item Template(s)</p> <p>Item Templates for VS2005 are stored in the following locations:</p> <p><code></p> <pre><code> (Installed Templates) &lt;VisualStudioInstallDir&gt;\Common7\IDE\ItemTemplates\Language\Locale\ (Custom Templates) My Documents\Visual Studio 2005\Templates\ItemTemplates\Language\ </code></pre> <p></code></p> <p>2) Open the template zip file to modify the .vstemplate file.</p> <p>Each Item Template is stored in a .zip file, so you will need to open the zip file that pertains to the template you want to modify.</p> <p>Open the template's .vstemplate file and find the SortOrder property under the TemplateData section. The following is a sample file:</p> <p><code></p> <p>&lt;TemplateData&gt;<br/> &lt;Name&gt;SomeITem&lt;/Name&gt;<br/> &lt;Description&gt;Description&lt;/Description&gt;<br/> &lt;ProjectType&gt;&gt;CSharp&lt;/ProjectType&gt;<br/> <strong>&lt;SortOrder&gt;1000&lt;/SortOrder&gt;</strong><br/> &lt;DefaultName&gt;&lt;/DefaultName&gt;<br/> &lt;ProvideDefaultName&gt;true&lt;/ProvideDefaultName&gt;<br/> &lt;/TemplateData&gt;<br/></p> <p></code></p> <p>Modify the SortOrder value using the following rules:</p> <ul> <li>The default value is 100, and all values must be multiples of 10.</li> <li>The SortOrder element is ignored for user-created templates. All user-created templates are sorted alphabetically.</li> <li>Templates that have low sort order values appear in either the New Project or New Add Item dialog box before templates that have high sort order values.</li> </ul> <p>Once you've made edits to the template definitions you'll need to open a command prompt and navigate to the directory that contains devenv.exe, and type "devenv /setup". This presumably rebuilds some internal settings and until you do this you won't see any difference.</p>
<p>Try looking at the registry under </p> <pre><code>HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\ </code></pre> <p>I see some relevant entries on my machine under</p> <pre><code>HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0 </code></pre> <p>for VS2008.</p>
14,866
<p>Is there a compression API available for use on the iPhone? We're building some RESTful web services for our iPhone app to talk to, but we want to compress at least some of the conversations for efficiency.</p> <p>I don't care what the format (ZIP, LHA, whatever) is, and it does not need to be secure.</p> <p>Some respondents have pointed out that the server can compress its output, and the iPhone can consume that. The scenario we have is exactly the reverse. We'll be POSTing compressed content <strong>to</strong> the web service. We're not concerned with compression going the other way.</p>
<p>If you store the data for the conversations in an NSData object, the folks at the CocoaDev wiki have posted an <a href="http://www.cocoadev.com/index.pl?NSDataCategory" rel="noreferrer">NSData category</a> that adds gzip and zlib compression / decompression as simple methods. These have worked well for me in <a href="http://www.sunsetlakesoftware.com/2008/10/02/molecules-source-code-now-available" rel="noreferrer">my iPhone application</a>.</p> <p>As the above link has gone dead while the CocoaDev wiki is being moved to a new host, I've reproduced this category in its entirety below.</p> <p>Interface:</p> <pre><code>@interface NSData (NSDataExtension) // Returns range [start, null byte), or (NSNotFound, 0). - (NSRange) rangeOfNullTerminatedBytesFrom:(int)start; // Canonical Base32 encoding/decoding. + (NSData *) dataWithBase32String:(NSString *)base32; - (NSString *) base32String; // COBS is an encoding that eliminates 0x00. - (NSData *) encodeCOBS; - (NSData *) decodeCOBS; // ZLIB - (NSData *) zlibInflate; - (NSData *) zlibDeflate; // GZIP - (NSData *) gzipInflate; - (NSData *) gzipDeflate; //CRC32 - (unsigned int)crc32; // Hash - (NSData*) md5Digest; - (NSString*) md5DigestString; - (NSData*) sha1Digest; - (NSString*) sha1DigestString; - (NSData*) ripemd160Digest; - (NSString*) ripemd160DigestString; @end </code></pre> <p>Implementation:</p> <pre><code>#import "NSData+CocoaDevUsersAdditions.h" #include &lt;zlib.h&gt; #include &lt;openssl/md5.h&gt; #include &lt;openssl/sha.h&gt; #include &lt;openssl/ripemd.h&gt; @implementation NSData (NSDataExtension) // Returns range [start, null byte), or (NSNotFound, 0). - (NSRange) rangeOfNullTerminatedBytesFrom:(int)start { const Byte *pdata = [self bytes]; int len = [self length]; if (start &lt; len) { const Byte *end = memchr (pdata + start, 0x00, len - start); if (end != NULL) return NSMakeRange (start, end - (pdata + start)); } return NSMakeRange (NSNotFound, 0); } + (NSData *) dataWithBase32String:(NSString *)encoded { /* First valid character that can be indexed in decode lookup table */ static int charDigitsBase = '2'; /* Lookup table used to decode() characters in encoded strings */ static int charDigits[] = { 26,27,28,29,30,31,-1,-1,-1,-1,-1,-1,-1,-1 // 23456789:;&lt;=&gt;? ,-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14 // @ABCDEFGHIJKLMNO ,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1 // PQRSTUVWXYZ[\]^_ ,-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14 // `abcdefghijklmno ,15,16,17,18,19,20,21,22,23,24,25 // pqrstuvwxyz }; if (! [encoded canBeConvertedToEncoding:NSASCIIStringEncoding]) return nil; const char *chars = [encoded cStringUsingEncoding:NSASCIIStringEncoding]; // avoids using characterAtIndex. int charsLen = [encoded lengthOfBytesUsingEncoding:NSASCIIStringEncoding]; // Note that the code below could detect non canonical Base32 length within the loop. However canonical Base32 length can be tested before entering the loop. // A canonical Base32 length modulo 8 cannot be: // 1 (aborts discarding 5 bits at STEP n=0 which produces no byte), // 3 (aborts discarding 7 bits at STEP n=2 which produces no byte), // 6 (aborts discarding 6 bits at STEP n=1 which produces no byte). switch (charsLen &amp; 7) { // test the length of last subblock case 1: // 5 bits in subblock: 0 useful bits but 5 discarded case 3: // 15 bits in subblock: 8 useful bits but 7 discarded case 6: // 30 bits in subblock: 24 useful bits but 6 discarded return nil; // non-canonical length } int charDigitsLen = sizeof(charDigits); int bytesLen = (charsLen * 5) &gt;&gt; 3; Byte bytes[bytesLen]; int bytesOffset = 0, charsOffset = 0; // Also the code below does test that other discarded bits // (1 to 4 bits at end) are effectively 0. while (charsLen &gt; 0) { int digit, lastDigit; // STEP n = 0: Read the 1st Char in a 8-Chars subblock // Leave 5 bits, asserting there's another encoding Char if ((digit = (int)chars[charsOffset] - charDigitsBase) &lt; 0 || digit &gt;= charDigitsLen || (digit = charDigits[digit]) == -1) return nil; // invalid character lastDigit = digit &lt;&lt; 3; // STEP n = 5: Read the 2nd Char in a 8-Chars subblock // Insert 3 bits, leave 2 bits, possibly trailing if no more Char if ((digit = (int)chars[charsOffset + 1] - charDigitsBase) &lt; 0 || digit &gt;= charDigitsLen || (digit = charDigits[digit]) == -1) return nil; // invalid character bytes[bytesOffset] = (Byte)((digit &gt;&gt; 2) | lastDigit); lastDigit = (digit &amp; 3) &lt;&lt; 6; if (charsLen == 2) { if (lastDigit != 0) return nil; // non-canonical end break; // discard the 2 trailing null bits } // STEP n = 2: Read the 3rd Char in a 8-Chars subblock // Leave 7 bits, asserting there's another encoding Char if ((digit = (int)chars[charsOffset + 2] - charDigitsBase) &lt; 0 || digit &gt;= charDigitsLen || (digit = charDigits[digit]) == -1) return nil; // invalid character lastDigit |= (Byte)(digit &lt;&lt; 1); // STEP n = 7: Read the 4th Char in a 8-chars Subblock // Insert 1 bit, leave 4 bits, possibly trailing if no more Char if ((digit = (int)chars[charsOffset + 3] - charDigitsBase) &lt; 0 || digit &gt;= charDigitsLen || (digit = charDigits[digit]) == -1) return nil; // invalid character bytes[bytesOffset + 1] = (Byte)((digit &gt;&gt; 4) | lastDigit); lastDigit = (Byte)((digit &amp; 15) &lt;&lt; 4); if (charsLen == 4) { if (lastDigit != 0) return nil; // non-canonical end break; // discard the 4 trailing null bits } // STEP n = 4: Read the 5th Char in a 8-Chars subblock // Insert 4 bits, leave 1 bit, possibly trailing if no more Char if ((digit = (int)chars[charsOffset + 4] - charDigitsBase) &lt; 0 || digit &gt;= charDigitsLen || (digit = charDigits[digit]) == -1) return nil; // invalid character bytes[bytesOffset + 2] = (Byte)((digit &gt;&gt; 1) | lastDigit); lastDigit = (Byte)((digit &amp; 1) &lt;&lt; 7); if (charsLen == 5) { if (lastDigit != 0) return nil; // non-canonical end break; // discard the 1 trailing null bit } // STEP n = 1: Read the 6th Char in a 8-Chars subblock // Leave 6 bits, asserting there's another encoding Char if ((digit = (int)chars[charsOffset + 5] - charDigitsBase) &lt; 0 || digit &gt;= charDigitsLen || (digit = charDigits[digit]) == -1) return nil; // invalid character lastDigit |= (Byte)(digit &lt;&lt; 2); // STEP n = 6: Read the 7th Char in a 8-Chars subblock // Insert 2 bits, leave 3 bits, possibly trailing if no more Char if ((digit = (int)chars[charsOffset + 6] - charDigitsBase) &lt; 0 || digit &gt;= charDigitsLen || (digit = charDigits[digit]) == -1) return nil; // invalid character bytes[bytesOffset + 3] = (Byte)((digit &gt;&gt; 3) | lastDigit); lastDigit = (Byte)((digit &amp; 7) &lt;&lt; 5); if (charsLen == 7) { if (lastDigit != 0) return nil; // non-canonical end break; // discard the 3 trailing null bits } // STEP n = 3: Read the 8th Char in a 8-Chars subblock // Insert 5 bits, leave 0 bit, next encoding Char may not exist if ((digit = (int)chars[charsOffset + 7] - charDigitsBase) &lt; 0 || digit &gt;= charDigitsLen || (digit = charDigits[digit]) == -1) return nil; // invalid character bytes[bytesOffset + 4] = (Byte)(digit | lastDigit); //// This point is always reached for chars.length multiple of 8 charsOffset += 8; bytesOffset += 5; charsLen -= 8; } // On loop exit, discard the n trailing null bits return [NSData dataWithBytes:bytes length:sizeof(bytes)]; } - (NSString *) base32String { /* Lookup table used to canonically encode() groups of data bits */ static char canonicalChars[] = { 'A','B','C','D','E','F','G','H','I','J','K','L','M' // 00..12 ,'N','O','P','Q','R','S','T','U','V','W','X','Y','Z' // 13..25 ,'2','3','4','5','6','7' // 26..31 }; const Byte *bytes = [self bytes]; int bytesOffset = 0, bytesLen = [self length]; int charsOffset = 0, charsLen = ((bytesLen &lt;&lt; 3) + 4) / 5; char chars[charsLen]; while (bytesLen != 0) { int digit, lastDigit; // INVARIANTS FOR EACH STEP n in [0..5[; digit in [0..31[; // The remaining n bits are already aligned on top positions // of the 5 least bits of digit, the other bits are 0. ////// STEP n = 0: insert new 5 bits, leave 3 bits digit = bytes[bytesOffset] &amp; 255; chars[charsOffset] = canonicalChars[digit &gt;&gt; 3]; lastDigit = (digit &amp; 7) &lt;&lt; 2; if (bytesLen == 1) { // put the last 3 bits chars[charsOffset + 1] = canonicalChars[lastDigit]; break; } ////// STEP n = 3: insert 2 new bits, then 5 bits, leave 1 bit digit = bytes[bytesOffset + 1] &amp; 255; chars[charsOffset + 1] = canonicalChars[(digit &gt;&gt; 6) | lastDigit]; chars[charsOffset + 2] = canonicalChars[(digit &gt;&gt; 1) &amp; 31]; lastDigit = (digit &amp; 1) &lt;&lt; 4; if (bytesLen == 2) { // put the last 1 bit chars[charsOffset + 3] = canonicalChars[lastDigit]; break; } ////// STEP n = 1: insert 4 new bits, leave 4 bit digit = bytes[bytesOffset + 2] &amp; 255; chars[charsOffset + 3] = canonicalChars[(digit &gt;&gt; 4) | lastDigit]; lastDigit = (digit &amp; 15) &lt;&lt; 1; if (bytesLen == 3) { // put the last 1 bits chars[charsOffset + 4] = canonicalChars[lastDigit]; break; } ////// STEP n = 4: insert 1 new bit, then 5 bits, leave 2 bits digit = bytes[bytesOffset + 3] &amp; 255; chars[charsOffset + 4] = canonicalChars[(digit &gt;&gt; 7) | lastDigit]; chars[charsOffset + 5] = canonicalChars[(digit &gt;&gt; 2) &amp; 31]; lastDigit = (digit &amp; 3) &lt;&lt; 3; if (bytesLen == 4) { // put the last 2 bits chars[charsOffset + 6] = canonicalChars[lastDigit]; break; } ////// STEP n = 2: insert 3 new bits, then 5 bits, leave 0 bit digit = bytes[bytesOffset + 4] &amp; 255; chars[charsOffset + 6] = canonicalChars[(digit &gt;&gt; 5) | lastDigit]; chars[charsOffset + 7] = canonicalChars[digit &amp; 31]; //// This point is always reached for bytes.length multiple of 5 bytesOffset += 5; charsOffset += 8; bytesLen -= 5; } return [NSString stringWithCString:chars length:sizeof(chars)]; } #define FinishBlock(X) \ (*code_ptr = (X), \ code_ptr = dst++, \ code = 0x01) - (NSData *) encodeCOBS { if ([self length] == 0) return self; NSMutableData *encoded = [NSMutableData dataWithLength:([self length] + [self length] / 254 + 1)]; unsigned char *dst = [encoded mutableBytes]; const unsigned char *ptr = [self bytes]; unsigned long length = [self length]; const unsigned char *end = ptr + length; unsigned char *code_ptr = dst++; unsigned char code = 0x01; while (ptr &lt; end) { if (*ptr == 0) FinishBlock(code); else { *dst++ = *ptr; code++; if (code == 0xFF) FinishBlock(code); } ptr++; } FinishBlock(code); [encoded setLength:((Byte *)dst - (Byte *)[encoded mutableBytes])]; return [NSData dataWithData:encoded]; } - (NSData *) decodeCOBS { if ([self length] == 0) return self; const Byte *ptr = [self bytes]; unsigned length = [self length]; NSMutableData *decoded = [NSMutableData dataWithLength:length]; Byte *dst = [decoded mutableBytes]; Byte *basedst = dst; const unsigned char *end = ptr + length; while (ptr &lt; end) { int i, code = *ptr++; for (i=1; i&lt;code; i++) *dst++ = *ptr++; if (code &lt; 0xFF) *dst++ = 0; } [decoded setLength:(dst - basedst)]; return [NSData dataWithData:decoded]; } - (NSData *)zlibInflate { if ([self length] == 0) return self; unsigned full_length = [self length]; unsigned half_length = [self length] / 2; NSMutableData *decompressed = [NSMutableData dataWithLength: full_length + half_length]; BOOL done = NO; int status; z_stream strm; strm.next_in = (Bytef *)[self bytes]; strm.avail_in = [self length]; strm.total_out = 0; strm.zalloc = Z_NULL; strm.zfree = Z_NULL; if (inflateInit (&amp;strm) != Z_OK) return nil; while (!done) { // Make sure we have enough room and reset the lengths. if (strm.total_out &gt;= [decompressed length]) [decompressed increaseLengthBy: half_length]; strm.next_out = [decompressed mutableBytes] + strm.total_out; strm.avail_out = [decompressed length] - strm.total_out; // Inflate another chunk. status = inflate (&amp;strm, Z_SYNC_FLUSH); if (status == Z_STREAM_END) done = YES; else if (status != Z_OK) break; } if (inflateEnd (&amp;strm) != Z_OK) return nil; // Set real length. if (done) { [decompressed setLength: strm.total_out]; return [NSData dataWithData: decompressed]; } else return nil; } - (NSData *)zlibDeflate { if ([self length] == 0) return self; z_stream strm; strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; strm.total_out = 0; strm.next_in=(Bytef *)[self bytes]; strm.avail_in = [self length]; // Compresssion Levels: // Z_NO_COMPRESSION // Z_BEST_SPEED // Z_BEST_COMPRESSION // Z_DEFAULT_COMPRESSION if (deflateInit(&amp;strm, Z_DEFAULT_COMPRESSION) != Z_OK) return nil; NSMutableData *compressed = [NSMutableData dataWithLength:16384]; // 16K chuncks for expansion do { if (strm.total_out &gt;= [compressed length]) [compressed increaseLengthBy: 16384]; strm.next_out = [compressed mutableBytes] + strm.total_out; strm.avail_out = [compressed length] - strm.total_out; deflate(&amp;strm, Z_FINISH); } while (strm.avail_out == 0); deflateEnd(&amp;strm); [compressed setLength: strm.total_out]; return [NSData dataWithData: compressed]; } - (NSData *)gzipInflate { if ([self length] == 0) return self; unsigned full_length = [self length]; unsigned half_length = [self length] / 2; NSMutableData *decompressed = [NSMutableData dataWithLength: full_length + half_length]; BOOL done = NO; int status; z_stream strm; strm.next_in = (Bytef *)[self bytes]; strm.avail_in = [self length]; strm.total_out = 0; strm.zalloc = Z_NULL; strm.zfree = Z_NULL; if (inflateInit2(&amp;strm, (15+32)) != Z_OK) return nil; while (!done) { // Make sure we have enough room and reset the lengths. if (strm.total_out &gt;= [decompressed length]) [decompressed increaseLengthBy: half_length]; strm.next_out = [decompressed mutableBytes] + strm.total_out; strm.avail_out = [decompressed length] - strm.total_out; // Inflate another chunk. status = inflate (&amp;strm, Z_SYNC_FLUSH); if (status == Z_STREAM_END) done = YES; else if (status != Z_OK) break; } if (inflateEnd (&amp;strm) != Z_OK) return nil; // Set real length. if (done) { [decompressed setLength: strm.total_out]; return [NSData dataWithData: decompressed]; } else return nil; } - (NSData *)gzipDeflate { if ([self length] == 0) return self; z_stream strm; strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; strm.total_out = 0; strm.next_in=(Bytef *)[self bytes]; strm.avail_in = [self length]; // Compresssion Levels: // Z_NO_COMPRESSION // Z_BEST_SPEED // Z_BEST_COMPRESSION // Z_DEFAULT_COMPRESSION if (deflateInit2(&amp;strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, (15+16), 8, Z_DEFAULT_STRATEGY) != Z_OK) return nil; NSMutableData *compressed = [NSMutableData dataWithLength:16384]; // 16K chunks for expansion do { if (strm.total_out &gt;= [compressed length]) [compressed increaseLengthBy: 16384]; strm.next_out = [compressed mutableBytes] + strm.total_out; strm.avail_out = [compressed length] - strm.total_out; deflate(&amp;strm, Z_FINISH); } while (strm.avail_out == 0); deflateEnd(&amp;strm); [compressed setLength: strm.total_out]; return [NSData dataWithData:compressed]; } // --------------------------------CRC32------------------------------- static const unsigned long crc32table[] = { 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d }; - (unsigned int)crc32 { unsigned int crcval; unsigned int x, y; const void *bytes; unsigned int max; bytes = [self bytes]; max = [self length]; crcval = 0xffffffff; for (x = 0, y = max; x &lt; y; x++) { crcval = ((crcval &gt;&gt; 8) &amp; 0x00ffffff) ^ crc32table[(crcval ^ (*((unsigned char *)bytes + x))) &amp; 0xff]; } return crcval ^ 0xffffffff; } // Hash function, by [[DamienBob]] #define HEComputeDigest(method) \ method##_CTX ctx; \ unsigned char digest[method##_DIGEST_LENGTH]; \ method##_Init(&amp;ctx); \ method##_Update(&amp;ctx, [self bytes], [self length]); \ method##_Final(digest, &amp;ctx); #define HEComputeDigestNSData(method) \ HEComputeDigest(method) \ return [NSData dataWithBytes:digest length:method##_DIGEST_LENGTH]; #define HEComputeDigestNSString(method) \ static char __HEHexDigits[] = "0123456789abcdef"; \ unsigned char digestString[2*method##_DIGEST_LENGTH];\ unsigned int i; \ HEComputeDigest(method) \ for(i=0; i&lt;method##_DIGEST_LENGTH; i++) { \ digestString[2*i] = __HEHexDigits[digest[i] &gt;&gt; 4]; \ digestString[2*i+1] = __HEHexDigits[digest[i] &amp; 0x0f];\ } \ return [NSString stringWithCString:(char *)digestString length:2*method##_DIGEST_LENGTH]; #define SHA1_CTX SHA_CTX #define SHA1_DIGEST_LENGTH SHA_DIGEST_LENGTH - (NSData*) md5Digest { HEComputeDigestNSData(MD5); } - (NSString*) md5DigestString { HEComputeDigestNSString(MD5); } - (NSData*) sha1Digest { HEComputeDigestNSData(SHA1); } - (NSString*) sha1DigestString { HEComputeDigestNSString(SHA1); } - (NSData*) ripemd160Digest { HEComputeDigestNSData(RIPEMD160); } - (NSString*) ripemd160DigestString { HEComputeDigestNSString(RIPEMD160); } @end </code></pre>
<p>NSURL says it supports the gzip encoding so you shouldn't have to do anything more than have your RESTful web service return gzip encoded content when appropriate. All the decoding will be done under the covers.</p>
28,588
<p>How do I escape the underscore character?</p> <p>I am writing something like the following where clause and want to be able to find actual entries with _d at the end.</p> <pre><code>Where Username Like '%_d' </code></pre>
<p><a href="https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql?view=sql-server-ver15#using-wildcard-characters-as-literals" rel="noreferrer">T-SQL Reference for LIKE</a>:</p> <blockquote> <p>You can use the wildcard pattern matching characters as literal characters. To use a wildcard character as a literal character, enclose the wildcard character in brackets. The following table shows several examples of using the LIKE keyword and the [ ] wildcard characters.</p> </blockquote> <p>For your case:</p> <pre><code>... LIKE '%[_]d' </code></pre>
<p>Adding to <a href="https://stackoverflow.com/a/10415670/12221876">Gerardo Lima's answer</a>, I was having problems when trying to use backslash as my escape character for the ESCAPE clause. This caused issues:</p> <pre><code>SELECT * FROM table WHERE email LIKE '%@%\_%' ESCAPE '\' </code></pre> <p>It was resolved by switching to an exclamation point. This worked:</p> <pre><code>SELECT * FROM table WHERE email LIKE '%@%!_%' ESCAPE '!' </code></pre>
2,765
<p>Is there anyway to configure a WCF service with a failover endpoint if the primary endpoint dies? Kind of like being able to specify a failover server in a SQL cluster.</p> <p>Specifically I am using the TCP/IP binding for speed, but on the rare occurrence that the machine is not available I would like to redirect traffic to the failover server. Not too bothered about losing messages. I'd just prefer not to write the code to handle re-routing.</p>
<p>You need to use a layer 4 <a href="http://en.wikipedia.org/wiki/Load_balancing_%28computing%29#Relationship_with_failover" rel="nofollow noreferrer">load balancer</a> in front of the two endpoints. Prob best to stick with a dedicated piece of hardware.</p>
<p>We've had good luck with BigIP as a solution, though it's not cheap or easy to set up. </p> <p>One nice feature is it allows you to set up your SSL certificate (and backdoor to the CA) at the load balancer's common endpoint. Then you can use protocols to transfer the requests back to the WCF servers so the entire transmission is encrypted. </p>
2,635
<p>I'm working on an ASP.net 3.5 website with MooTools as the AJAX framework. I want to disable ASP.net's AJAX framework so it behaves more like ASP.net 2.0. This is to decrease page loading times and to reduce incompatibilities. Is this possible and if so how do I go about it?</p>
<p>I was able to remove the System.Web.Extensions assembly from the references, and then I found and removed all instances of the ScriptManager control. </p> <p>Once I did this, none of the AJAX framework stuff is rendered to the pages.</p> <p>I wanted to keep 3.5 for LINQ and other jazz, so just targeting the 2.0 framework wouldn't work.</p> <p>Thanks for the tips.</p>
<p>I've seen some articles on how to improve the performance of asp.net ajax in the .net 3.5 framework. Just can't find the link. But there are some changes you can do in the web.config which will improve performance wise. But, if you want to use MooTools, i guess you can just remove the Assemblies and the remove all references in the web.config.</p>
43,855
<p>Boost is a great set of libraries and it really <em>boosts</em> productivity. But debugging code that uses it is a total nightmare. Sure, stepping through twenty thousand header files can be a valuable intellectual exercise, but what if you need to do it over and over again?</p> <p>Is there a developer-friendly way of just skipping the boost portion and having the debugger go straight to my code?</p> <p>Visual Studio has a <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerstepthroughattribute.aspx" rel="noreferrer">DebuggerStepThroughAttribute</a> for .NET framework. Is there anything similar for native C++?</p>
<p>You can skip the boost namespace entirely by using the techniques described <a href="http://through-the-interface.typepad.com/through_the_interface/2006/07/advanced_visual_1.html" rel="noreferrer">here</a>. Just use something like:</p> <p><code>boost\:\:.*=NoStepInto</code></p> <p>... in the relevant registry entry.</p> <p>However if your code gets called from within boost (e.g. through a <code>boost::function</code> or similar) then your code will be skipped as well! I'll be interested if someone can come up with a good solution for <em>that</em> problem...</p>
<p>You can skip the boost namespace entirely by using the techniques described <a href="http://through-the-interface.typepad.com/through_the_interface/2006/07/advanced_visual_1.html" rel="noreferrer">here</a>. Just use something like:</p> <p><code>boost\:\:.*=NoStepInto</code></p> <p>... in the relevant registry entry.</p> <p>However if your code gets called from within boost (e.g. through a <code>boost::function</code> or similar) then your code will be skipped as well! I'll be interested if someone can come up with a good solution for <em>that</em> problem...</p>
38,142
<pre><code>cmd /C "myshortcut1.lnk" cmd /C "myshortcut2.lnk" </code></pre> <p>Works, but gives me a pop-up DOS window which, when closed, kills my two loaded programs. Same is true for this:</p> <pre><code>start /B cmd /C "1.lnk" start /B cmd /C "2.lnk" start /B cmd /C "3.lnk" start /B cmd /C "4.lnk" </code></pre>
<p>The MySQL JDBC driver times out after 8 hours of inactivity and drops the connection.</p> <p>You can set <code>autoReconnect=true</code> in your JDBC URL, and this causes the driver to reconnect if you try to query after it has disconnected. But this has side effects; for instance session state and transactions cannot be maintained over a new connection.</p> <p>If you use <code>autoReconnect</code>, the JDBC connection is reestablished, but it doesn't automatically re-execute your query that got the exception. So you do need to catch <code>SQLException</code> in your application and retry queries.</p> <p>Read <a href="http://dev.mysql.com/doc/refman/5.0/en/connector-j-reference-configuration-properties.html" rel="noreferrer">http://dev.mysql.com/doc/refman/5.0/en/connector-j-reference-configuration-properties.html</a> for more details.</p>
<p>I would suggest that, in almost any client/server set-up, it's a bad idea to leave connections open when they're not needed.</p> <p>I'm thinking specifically about DB2/z connections but it applies equally to all servers (database and otherwise). These connections consume resources at the server that could be best utilized elsewhere.</p> <p>If you were to hold connections open in a corporate environment where tens of thousand of clients connect to the database, you would probably even bring a mainframe to its knees.</p> <p>I'm all for the idea of connection pooling but not so much for the idea of trying to hold individual sessions open for ever.</p> <p>My advice would be as follows:</p> <p>1/ Have three sorts of connections in your connection pool:</p> <ul> <li>closed (so not actually <strong>in</strong> your pool).</li> <li>ready, meaning open but not in use by a client.</li> <li>active, meaning in use by a client.</li> </ul> <p>2/ Have your connection pooling maintain a small number of ready connections, minimum of N and maximum of M. N can be adjusted depending on the peak speed at which your clients request connections. If the number of ready connections ever drops to zero, you need a bigger N.</p> <p>3/ When a client wants a connection, give them one of the ready ones (making it active), then immediately open a new one if there's now less than N ready (but don't make the client wait for this to complete, or you'll lose the advantage of pooling). This ensures there will always be at least N ready connections. If none are ready when the client wants one, they will have to wait around while you create a new one.</p> <p>4/ When the client finishes with an active connection, return it to the ready state if there's less than M ready connections. Otherwise close it. This prevents you from having more than M ready connections.</p> <p>5/ Periodically recycle the ready connections to prevent stale connections. If there's more than N ready connections, just close the oldest connection. Otherwise close it and re-open another.</p> <p>This has the advantage of having enough ready <strong>AND</strong> youthful connections available in your connection pool without overloading the server.</p>
34,046
<p>I built an application which displays the records from database in the window and checks the the database for new records every couple of seconds. The problem is that the window blinks each time I check for new records and I want to fix it. I have tried to compare the old datatable with the new one and refresh only if they are different. Does anyone know what is the best practice for such cases? I tried to do it the following way but it doesn't work:</p> <pre><code>private bool GetBelongingMessages() { bool result = false; DataTable dtTemp = OleDbWorks.GetBelongingMessages(currentCallID); if(dtTemp != dtMessages) { dtMessages = dtTemp; result = true; } else { result = false; } return result; } </code></pre>
<p>First off, it's important to recognize that what you're comparing in your code is the <em>references</em> of the datatables, not the <em>contents</em> of the datatables. In order to determine if both datatables have the same contents, you're going to have to loop through all of the rows and columns and see if they're equal:</p> <pre><code>//This assumes the datatables have the same schema... public bool DatatablesAreSame(DataTable t1, DataTable t2) { if (t1.Rows.Count != t2.Rows.Count) return false; foreach (DataColumn dc in t1.Columns) { for (int i = 0; i &lt; t1.Rows.Count; i++) { if (t1.Rows[i][dc.ColumnName] != t2.Rows[i][dc.ColumnName]) { return false; } } } return true; } </code></pre>
<p>You have to cast objects t1.Rows[i][dc.ColumnName] and t1.Rows[i][dc.ColumnName] otherwise the statement t1.Rows[i][dc.ColumnName] != t2.Rows[i][dc.ColumnName] is always true. I modified the code the following way:</p> <pre><code>for(int i = 0; i &lt; t1.Rows.Count; i++) { if((string)t1.Rows[i][1] != (string)t2.Rows[i][1]) return false; } </code></pre> <p>and it works but it's not an elegant solution.</p>
29,275
<p>Consider the need to develop a lightweight desktop DB application on the Microsoft platforms.</p> <p>It could be done fairly easily with MS Access but I'd like to be able to distribute it to others and I don't want to pay for a runtime license. </p> <p>Requirements:</p> <ul> <li>easy distribution to others</li> <li>no runtime licensing issues</li> </ul> <p>Considerations and Candidates:</p> <ul> <li><a href="http://en.wikipedia.org/wiki/OpenOffice.org_Base" rel="noreferrer">Base from the OpenOffice suite</a>. My concerns were around its stability. </li> <li><a href="http://dev.mysql.com/downloads/" rel="noreferrer">MySQL</a> + writing custom DB code in C++ or Python or whatever seems like a rather heavy-handed solution. </li> </ul> <p><strong>Question</strong>: What are the low cost or free database alternatives to MS Access?</p> <hr> <p><strong>See Also:</strong> <a href="https://stackoverflow.com/questions/126622/open-source-reporting-engines">Open Source Reporting Engines</a></p> <hr> <hr> <p>@Schnapple</p> <p>Bruceatk kind of hit on what I'm thinking of; it's not so much the DB engine as I want the other niceties that Access brings to the party. The nice form designer, the nice reporting engine etc. But you do raise a very good point about the installation footprint. I had considered that but I've not made any firm decisions about which way I'm going with this yet anyway. It'll probably be something fairly lightweight anyway and a small installation footprint would definitely be a plus.</p> <hr> <p>@Remou,</p> <p>No I was unaware that the MS Access 2007 runtime is free; thanks for pointing that out. The last time I'd bothered to investigate it (I don't remember when it was) I think it was a fairly expensive license for the runtime because I think they were trying to sell it to Corporate IT departments.</p> <p>And thanks to everyone else who responded as well; I was completely unaware of those other options you all pointed out.</p>
<p>One thing to keep in mind here is the MS Access product is much more than just the raw database engine. It provides a full application development platform, including form and menu designer, client application language and environment (VBA), and report designer. When you take all those things together, MS Access really has no peer.</p> <p>But for the scope of this question, we're concerned with the raw database engine. With that in mind:</p> <p><a href="http://www.sqlite.org/" rel="nofollow noreferrer">SQLlite</a>,<br> <a href="http://www.firebirdsql.org/" rel="nofollow noreferrer">Firebird</a>,<br> <a href="http://www.vistadb.net/" rel="nofollow noreferrer">VistaDB</a> (not free),<br> <a href="http://www.microsoft.com/sql/editions/compact/default.mspx" rel="nofollow noreferrer">SQL Server Compact Edition</a> (not Express)<br> and now SQL Server LocalDB<br> all come to mind.</p> <p>Another thought: while the original question does ask about desktop databases, its likely some people will land here looking for a database to use with a web site. It's important to remember that these are all <em>in-process</em> databases, and as such are rarely if ever appropriate for use on the web. If you want to build a web site, where it's common to need to support significant concurrent access, you generally want a database <em>server</em> engine, like MS SQL, Postgresql, MySQL, Oracle, or their brethren. At the same time, those <em>server</em> engines are rarely if ever appropriate for a single-user desktop application.</p>
<p>VistaDB is the only alternative if you going to run your website at shared hosting (almost all of them won't let you run your websites under Full Trust mode) and also if you need simple x-copy deployment enabled website.</p>
4,871
<p>How do you turn a Visual Studio build that you'd perform in the IDE into a script that you can run from the command line?</p>
<p>With VS2008 you can do this:</p> <pre><code>devenv solution.sln /build configuration </code></pre>
<p>A more simple way is to change VS 2015 Projects &amp; Solutions configuration: Go to the Tools tab -> Options -> Projects and Solutions -> Build and Run -> On Run, when projects are out of date (choose Always build). VOILA! </p> <p>Now your IDE will automatically build your project when you run (F5) it. Hope this helps, any feedback are welcome.</p>
4,421
<p>How do I truncate a java <code>String</code> so that I know it will fit in a given number of bytes storage once it is UTF-8 encoded?</p>
<p>Here is a simple loop that counts how big the UTF-8 representation is going to be, and truncates when it is exceeded:</p> <pre><code>public static String truncateWhenUTF8(String s, int maxBytes) { int b = 0; for (int i = 0; i &lt; s.length(); i++) { char c = s.charAt(i); // ranges from http://en.wikipedia.org/wiki/UTF-8 int skip = 0; int more; if (c &lt;= 0x007f) { more = 1; } else if (c &lt;= 0x07FF) { more = 2; } else if (c &lt;= 0xd7ff) { more = 3; } else if (c &lt;= 0xDFFF) { // surrogate area, consume next char as well more = 4; skip = 1; } else { more = 3; } if (b + more &gt; maxBytes) { return s.substring(0, i); } b += more; i += skip; } return s; } </code></pre> <p>This <em>does</em> handle <a href="http://en.wikipedia.org/wiki/UTF-16" rel="noreferrer">surrogate pairs</a> that appear in the input string. Java's UTF-8 encoder (correctly) outputs surrogate pairs as a single 4-byte sequence instead of two 3-byte sequences, so <code>truncateWhenUTF8()</code> will return the longest truncated string it can. If you ignore surrogate pairs in the implementation then the truncated strings may be shorted than they needed to be.</p> <p>I haven't done a lot of testing on that code, but here are some preliminary tests:</p> <pre><code>private static void test(String s, int maxBytes, int expectedBytes) { String result = truncateWhenUTF8(s, maxBytes); byte[] utf8 = result.getBytes(Charset.forName("UTF-8")); if (utf8.length &gt; maxBytes) { System.out.println("BAD: our truncation of " + s + " was too big"); } if (utf8.length != expectedBytes) { System.out.println("BAD: expected " + expectedBytes + " got " + utf8.length); } System.out.println(s + " truncated to " + result); } public static void main(String[] args) { test("abcd", 0, 0); test("abcd", 1, 1); test("abcd", 2, 2); test("abcd", 3, 3); test("abcd", 4, 4); test("abcd", 5, 4); test("a\u0080b", 0, 0); test("a\u0080b", 1, 1); test("a\u0080b", 2, 1); test("a\u0080b", 3, 3); test("a\u0080b", 4, 4); test("a\u0080b", 5, 4); test("a\u0800b", 0, 0); test("a\u0800b", 1, 1); test("a\u0800b", 2, 1); test("a\u0800b", 3, 1); test("a\u0800b", 4, 4); test("a\u0800b", 5, 5); test("a\u0800b", 6, 5); // surrogate pairs test("\uD834\uDD1E", 0, 0); test("\uD834\uDD1E", 1, 0); test("\uD834\uDD1E", 2, 0); test("\uD834\uDD1E", 3, 0); test("\uD834\uDD1E", 4, 4); test("\uD834\uDD1E", 5, 4); } </code></pre> <p><strong>Updated</strong> Modified code example, it now handles surrogate pairs.</p>
<p>Based on <a href="https://stackoverflow.com/a/119338/6404321">billjamesdev's answer</a> I've come up with the following method which, as far as I can tell, is the simplest <em>and</em> still works OK with surrogate pairs:</p> <pre><code>public static String utf8ByteTrim(String s, int trimSize) { final byte[] bytes = s.getBytes(StandardCharsets.UTF_8); if ((bytes[trimSize-1] &amp; 0x80) != 0) { // inside a multibyte sequence while ((bytes[trimSize-1] &amp; 0x40) == 0) { // 2nd, 3rd, 4th bytes trimSize--; } trimSize--; } return new String(bytes, 0, trimSize, StandardCharsets.UTF_8); } </code></pre> <p>Some testing:</p> <pre><code>String test = &quot;Aæ尝试&quot;; IntStream.range(1, 16).forEachOrdered(i -&gt; System.out.println(&quot;Size &quot; + i + &quot;: &quot; + utf8ByteTrim(test, i)) ); --- Size 1: A Size 2: A Size 3: A Size 4: Aæ Size 5: Aæ Size 6: Aæ Size 7: Aæ Size 8: Aæ Size 9: Aæ Size 10: Aæ Size 11: Aæ尝 Size 12: Aæ尝 Size 13: Aæ尝试 Size 14: Aæ尝试 Size 15: Aæ尝试 </code></pre>
14,514
<p>I need to make changes to an in-use production database. Just adding a few columns. I've made the changes to the dev database with migrations. What is the best way to update the production database while preserving the existing data and not disrupting operation too much?</p> <p>It's MYSQL and I will be needing to add data to the columns as well for already existing records. One column can have a default value (it's boolean) but the other is a timestamp and should have an arbitrary backdated value. The row counts are not huge.</p> <p>So if I use migrations how do I add data and how do I get it to just do the two (or three - I add data -latest migrations on the production db when it wasn't initially built via migrations (I believe they used the schema instead)?</p>
<p>I always follow this procedure:</p> <ul> <li>Dump prod database with mysqldump command</li> <li>Populate dev / test database with dump using mysql command</li> <li>Run migrations in dev / test</li> <li>Check migration worked</li> <li>Dump prod database with mysqldump command (as it may have changed) keeping backup on server</li> <li>Run migrations on prod (using capristano)</li> <li>Test migration has worked on prod</li> <li>Drink beer (while watching error logs)</li> </ul>
<p>Is there a reason you are not using the same migrations you used in your dev environment?</p>
25,214
<p>Here is the current architecture of my transaction scope source code. The third insert throws an .NET exception (Not a SQL Exception) and it is not rolling back the two previous insert statements. What I am doing wrong?</p> <p><b>EDIT:</b> I removed the try/catch from insert2 and insert3. I also removed the exception handling utility from the insert1 try/catch and put "throw ex". It still does not rollback the transaction.</p> <p><b>EDIT 2:</b> I added the try/catch back on the Insert3 method and just put a "throw" in the catch statement. It still does not rollback the transaction.</p> <p><b>UPDATE:</b>Based on the feedback I received, the "SqlHelper" class is using the SqlConnection object to establish a connection to the database, then creates a SqlCommand object, set the CommandType property to "StoredProcedure" and calls the ExecuteNonQuery method of the SqlCommand.</p> <p>I also did not add Transaction Binding=Explicit Unbind to the current connection string. I will add that during my next test. </p> <pre><code>public void InsertStuff() { try { using(TransactionScope ts = new TransactionScope()) { //perform insert 1 using(SqlHelper sh = new SqlHelper()) { SqlParameter[] sp = { /* create parameters for first insert */ }; sh.Insert("MyInsert1", sp); } //perform insert 2 this.Insert2(); //perform insert 3 - breaks here!!!!! this.Insert3(); ts.Complete(); } } catch(Exception ex) { throw ex; } } public void Insert2() { //perform insert 2 using(SqlHelper sh = new SqlHelper()) { SqlParameter[] sp = { /* create parameters for second insert */ }; sh.Insert("MyInsert2", sp); } } public void Insert3() { //perform insert 3 using(SqlHelper sh = new SqlHelper()) { SqlParameter[] sp = { /*create parameters for third insert */ }; sh.Insert("MyInsert3", sp); } } </code></pre>
<p>I have also run into a similar issue. My problem occurred because the SqlConnection I used in my SqlCommands was already open before the TransactionScope was created, so it never got enlisted in the TransactionScope as a transaction.</p> <p>Is it possible that the SqlHelper class is reusing an instance of SqlConnection that is open before you enter your TransactionScope block?</p>
<p>I dont see your helper class, but transaction scope rollsback if you don't call complete statement even if you get error from .NET code. I copied one example for you. You may be doing something wrong in debugging. This example has error in .net code and similar catch block as yours.</p> <pre><code> private static readonly string _connectionString = ConnectionString.GetDbConnection(); private const string inserttStr = @"INSERT INTO dbo.testTable (col1) VALUES(@test);"; /// &lt;summary&gt; /// Execute command on DBMS. /// &lt;/summary&gt; /// &lt;param name="command"&gt;Command to execute.&lt;/param&gt; private void ExecuteNonQuery(IDbCommand command) { if (command == null) throw new ArgumentNullException("Parameter 'command' can't be null!"); using (IDbConnection connection = new SqlConnection(_connectionString)) { command.Connection = connection; connection.Open(); command.ExecuteNonQuery(); } } public void FirstMethod() { IDbCommand command = new SqlCommand(inserttStr); command.Parameters.Add(new SqlParameter("@test", "Hello1")); ExecuteNonQuery(command); } public void SecondMethod() { IDbCommand command = new SqlCommand(inserttStr); command.Parameters.Add(new SqlParameter("@test", "Hello2")); ExecuteNonQuery(command); } public void ThirdMethodCauseNetException() { IDbCommand command = new SqlCommand(inserttStr); command.Parameters.Add(new SqlParameter("@test", "Hello3")); ExecuteNonQuery(command); int a = 0; int b = 1/a; } public void MainWrap() { TransactionOptions tso = new TransactionOptions(); tso.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted; //TransactionScopeOption.Required, tso try { using (TransactionScope sc = new TransactionScope()) { FirstMethod(); SecondMethod(); ThirdMethodCauseNetException(); sc.Complete(); } } catch (Exception ex) { logger.ErrorException("eee ",ex); } } </code></pre> <p>If you want to debug your transactions, you can use this script to see locks and waiting status etc.</p> <pre><code>SELECT request_session_id AS spid, CASE transaction_isolation_level WHEN 0 THEN 'Unspecified' WHEN 1 THEN 'ReadUncomitted' WHEN 2 THEN 'Readcomitted' WHEN 3 THEN 'Repeatable' WHEN 4 THEN 'Serializable' WHEN 5 THEN 'Snapshot' END AS TRANSACTION_ISOLATION_LEVEL , resource_type AS restype, resource_database_id AS dbid, DB_NAME(resource_database_id) as DBNAME, resource_description AS res, resource_associated_entity_id AS resid, CASE when resource_type = 'OBJECT' then OBJECT_NAME( resource_associated_entity_id) ELSE 'N/A' END as ObjectName, request_mode AS mode, request_status AS status FROM sys.dm_tran_locks l left join sys.dm_exec_sessions s on l.request_session_id = s.session_id where resource_database_id = 24 order by spid, restype, dbname; </code></pre> <p>You will see one SPID for two method calls before calling exception method.</p> <p><img src="https://i.stack.imgur.com/BliCu.png" alt="two calls before exception"></p> <p>Default isolation level is serializable.<a href="http://omerc.blogspot.com/2010/04/transaction-and-locks-in-ms-sql-2008.html" rel="nofollow noreferrer">You can read more about locks and transactions here</a></p>
44,059
<p>How do you properly override <code>isEqual:</code> in Objective-C? The "catch" seems to be that if two objects are equal (as determined by the <code>isEqual:</code> method), they must have the same hash value.</p> <p>The <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaObjects/CocoaObjects.html#//apple_ref/doc/uid/TP40002974-CH4-SW25" rel="noreferrer">Introspection</a> section of the <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/" rel="noreferrer">Cocoa Fundamentals Guide</a> does have an example on how to override <code>isEqual:</code>, copied as follows, for a class named <code>MyWidget</code>:</p> <pre><code>- (BOOL)isEqual:(id)other { if (other == self) return YES; if (!other || ![other isKindOfClass:[self class]]) return NO; return [self isEqualToWidget:other]; } - (BOOL)isEqualToWidget:(MyWidget *)aWidget { if (self == aWidget) return YES; if (![(id)[self name] isEqual:[aWidget name]]) return NO; if (![[self data] isEqualToData:[aWidget data]]) return NO; return YES; } </code></pre> <p>It checks pointer equality, then class equality, and finally compares the objects using <code>isEqualToWidget:</code>, which only checks the <code>name</code> and <code>data</code> properties. What the example <em>doesn't</em> show is how to override <code>hash</code>.</p> <p>Let's assume there are other properties that do not affect equality, say <code>age</code>. Shouldn't the <code>hash</code> method be overridden such that only <code>name</code> and <code>data</code> affect the hash? And if so, how would you do that? Just add the hashes of <code>name</code> and <code>data</code>? For example:</p> <pre><code>- (NSUInteger)hash { NSUInteger hash = 0; hash += [[self name] hash]; hash += [[self data] hash]; return hash; } </code></pre> <p>Is that sufficient? Is there a better technique? What if you have primitives, like <code>int</code>? Convert them to <code>NSNumber</code> to get their hash? Or structs like <code>NSRect</code>?</p> <p>(<strong>Brain fart</strong>: Originally wrote "bitwise OR" them together with <code>|=</code>. Meant add.)</p>
<p>Start with</p> <pre><code> NSUInteger prime = 31; NSUInteger result = 1; </code></pre> <p>Then for every primitive you do</p> <pre><code> result = prime * result + var </code></pre> <p>For objects you use 0 for nil and otherwise their hashcode.</p> <pre><code> result = prime * result + [var hash]; </code></pre> <p>For booleans you use two different values</p> <pre><code> result = prime * result + ((var)?1231:1237); </code></pre> <hr> <h2>Explanation and Attribution</h2> <p>This is not tcurdt's work, and comments were asking for more explanation, so I believe an edit for attribution is fair.</p> <p>This algorithm was popularized in the book "Effective Java", and <a href="http://www.scribd.com/doc/36454091/Effective-Java-Chapter3" rel="nofollow noreferrer">the relevant chapter can currently be found online here</a>. That book popularized the algorithm, which is now a default in a number of Java applications (including Eclipse). It derived, however, from an even older implementation which is variously attributed to Dan Bernstein or Chris Torek. That older algorithm originally floated around on Usenet, and certain attribution is difficult. For example, there is some <a href="http://svn.apache.org/repos/asf/apr/apr/trunk/tables/apr_hash.c" rel="nofollow noreferrer">interesting commentary in this Apache code</a> (search for their names) that references the original source.</p> <p>Bottom line is, this is a very old, simple hashing algorithm. It is not the most performant, and it is not even proven mathematically to be a "good" algorithm. But it is simple, and a lot of people have used it for a long time with good results, so it has a lot of historical support.</p>
<p>Sorry if I risk sounding a complete boffin here but... ...nobody bothered mentioning that to follow 'best practices' you should definitely not specify an equals method that would NOT take into account all data owned by your target object, e.g whatever data is aggregated to your object, versus an associate of it, should be taken into account when implementing equals. If you don't want to take, say 'age' into account in a comparison, then you should write a comparator and use that to perform your comparisons instead of isEqual:.</p> <p>If you define an isEqual: method that performs equality comparison arbitrarily, you incur the risk that this method is misused by another developer, or even yourself, once you've forgotten the 'twist' in your equals interpretation.</p> <p>Ergo, although this is a great q&amp;a about hashing, you don't normally need to redefine the hashing method, you should probably define an ad-hoc comparator instead.</p>
31,719
<p>Is it possible to get the current source line number in Perl? The equivalent in C++ is <code>__LINE__</code>.</p>
<p>The <code>__LINE__</code> literal is documented in the <a href="https://perldoc.perl.org/perldata#Special-Literals" rel="nofollow noreferrer">Special Literals</a> section of the <a href="https://perldoc.perl.org/perldata" rel="nofollow noreferrer">perldata man page</a>.</p> <pre><code>print &quot;File: &quot;, __FILE__, &quot; Line: &quot;, __LINE__, &quot;\n&quot;; </code></pre> <p>or</p> <pre><code>warn(&quot;foo&quot;); </code></pre>
<p>This prints out the line where you are, and also the "stack" (list of lines from the calling programs (scripts/modules/etc) that lead to the place you are now)</p> <pre><code>while(my @where=caller($frame++)) { print "$frame:" . join(",",@where) . "\n"; } </code></pre>
46,327
<p>Ok simple question. I have a JSF application, containing a login page. The problem is if the user loads the login page, leaves it for a while, then tries to login the session expires and a ViewExpiredException is thrown. I could redirect back to the login when this happens, but that isn't very smooth. How can I allow this flow to properly login without an additional attempt?</p>
<p><strong>Update</strong></p> <p>As of Mojarra 2.1.19 / 2.2.0 you can now set the transient attribute of the <code>&lt;f:view&gt;</code> to true:</p> <pre><code>&lt;f:view transient="true"&gt; Your regular content &lt;/f:view&gt; </code></pre> <p>You can read about in on <a href="https://stackoverflow.com/users/157882/balusc">Balusc's</a> blog here:</p> <p><a href="http://balusc.blogspot.com.br/2013/02/stateless-jsf.html" rel="nofollow noreferrer">http://balusc.blogspot.com.br/2013/02/stateless-jsf.html</a></p> <p><strong>Original</strong></p> <p>If you're using Facelets you can create your own ViewHandler to handle this:</p> <pre><code>public class LoginViewHandler extends FaceletViewHandler { public LoginViewHandler( ViewHandler viewHandler ) { super( viewHandler ); } @Override public UIViewRoot restoreView( FacesContext ctx, String viewId ) { UIViewRoot viewRoot = super.restoreView( ctx, viewId ); if ( viewRoot == null &amp;&amp; viewId.equals( "/login.xhtml" ) ) { // Work around Facelet issue initialize( ctx ); viewRoot = super.createView( ctx, viewId ); ctx.setViewRoot( viewRoot ); try { buildView( ctx, viewRoot ); } catch ( IOException e ) { log.log( Level.SEVERE, "Error building view", e ); } } return viewRoot; } } </code></pre> <p>Change "/login.xhtml" to your login page. This checks to see if it can restore your view, and if it cannot and the current view is your login page it will create and build the view for you.</p> <p>Set this in your face-config.xml as follows:</p> <pre><code>&lt;application&gt; &lt;!-- snip --&gt; &lt;view-handler&gt;my.package.LoginViewHandler&lt;/view-handler&gt; &lt;/application&gt; </code></pre> <p>If you're using JSF without Facelets (i.e. JSPs) you can try having the class extend ViewHandlerWrapper - note that buildView() will not be available. Hopefully createView() on it's own will set the view up correctly but I'm not 100% sure with JSF/JSP.</p>
<p>Couple of slightly hacky solutions:</p> <ul> <li>(Very hacky) use a <code>&lt;meta http-equiv="refresh" content="5"/&gt;</code> tag to automatically reload the page every so often.</li> <li>Use a JavaScript function to periodically send a 'ping' request to the server to keep the session alive.</li> </ul> <p>We use <a href="http://www.icefaces.org" rel="nofollow noreferrer">IceFaces</a> at work which automatically detects when your session has expired and displays a pop-up alerting you to the fact. But we do still sometimes have problems on the login page for some reason.</p>
28,616
<p>I have been involved in a lot of projects, both old and new, and one thing that they have in common is that almost none of them have been using unit testing. I prefer to use it, but often the customer isn´t ready to pay for that, and suppose that the code just works as it should.</p> <p>So, do you use unit testing in your projects, or do you rely on your coding skills?</p>
<p>Using unit-testing <em>is</em> a coding skill. </p> <p>I find it adds very little overhead to coding time. On top of that the code produced tends to be much easier to understand and to refactor, with an untold reduction in maintenance time.</p> <p>A full discussion of the benefits here: <a href="https://stackoverflow.com/questions/67299/is-unit-testing-worth-the-effort">Is Unit Testing worth the effort?</a></p>
<p>Unit testing is an essential part of development, and (I have found) will actually reduce the time to completion of a project while improving overall quality, especially when done in a TDD fasion.</p>
36,426
<p>Can the name and icon of an Eclipse view be programmatically changed? I am referring to the name and icon that appear in the tab for the view - which are specified as XML attributes "name" and "icon" in the &lt;view&gt; element in plugin.xml.</p>
<p><code>setPartName(String)</code> and <code>setTitleImage(Image)</code>, both on <code>WorkbenchPart</code> are what you're looking for. </p> <p>Both <code>EditorPart</code>s and <code>ViewPart</code> are extensions of <code>WorkbenchPart</code>. </p> <p>It should be noted that both these methods are <code>protected</code> so should be called from within the part itself.</p>
<p>setPartName(..) in the ViewPart class.</p>
40,787
<p>At a recent discussion on Silverlight the advantage of speed was brought up. The argument for Silverlight was that it performed better in the browser than Javascript because it is compiled (and managed) code.</p> <p>It was then stated that this advantage only applies to IE because IE interprets Javascript which is inefficient when compared to that of other browsers such as Chrome and FireFox which compile Javascript to machine code before execution and as such perform as well as Silverlight.</p> <p>Does anybody have a definitive answer to this performance question. i.e. Do/will Silverlight and Javascript have comparable performance on Chrome and Firefox?</p>
<p>Speculating is fun. Or we could actually try a test or two...</p> <p>That <a href="http://silverlight.net/samples/sl2/silverlightchess/run/Default.html" rel="noreferrer">Silverlight vs. Javascript chess sample</a> has been updated for Silverlight 2. When I run it, C# averages 420,000 nodes per second vs. Javascript at 23,000 nodes per second. I'm running the dev branch of Google Chrome (v. 0.4.154.25). That's still almost an 18x speed advantage for Silverlight.</p> <p>Primes calculation shows a 3x advantage for Silverlight: calculating 1,000,000 primes in <a href="http://www.tobinharris.com/primes.html" rel="noreferrer">Javascript</a> takes 3.7 seconds, in <a href="http://www.itwriting.com/primetest/index.html" rel="noreferrer">Silverlight</a> takes 1.2 seconds. </p> <p>So I think that for calculation, there's still a pretty strong advantage for Silverlight, and my gut feel is that it's likely to stay that way. Both sides will continue to optimize, but there are some limits to what you can optimize in a dynamic language.</p> <p>Silverlight doesn't (yet) have an advantage when it comes to animation. For instance, the <a href="http://www.bubblemark.com/" rel="noreferrer">Bubblemark</a> test shows Javascript running at 170 fps, and Silverlight running at 100 fps. I think we can expect to see that change <a href="http://weblogs.asp.net/scottgu/archive/2008/11/16/update-on-silverlight-2-and-a-glimpse-of-silverlight-3.aspx" rel="noreferrer">when Silverlight 3 comes out, since it will include GPU support</a>.</p>
<p>Sre, if you're using "Internet Exploder" it probably will...</p> <p>If you're using V8 (Chrome) or the upcoming Safari and FireFox, I seriously doubt it ;)</p> <p>I would love to see that Chess thn BTW where IE is playing using Silverlight and Chrome is using Javascript. THAT would rock MSFT...!! ;)</p>
41,706