instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>I'm using jQuery to post a form to a php file, simple script to verify user details.</p> <pre><code>var emailval = $("#email").val(); var invoiceIdval = $("#invoiceId").val(); $.post("includes/verify.php", {invoiceId:invoiceIdval , email:emailval }, function(data) { //stuff here. }); </code></pre> <p>PHP Code:</p> <pre><code>&lt;?php print_r($_POST); ?&gt; </code></pre> <p>I look at the response in firebug, it is an empty array. The array should have at least some value.</p> <p>I can not work out why the <code>$_POST</code> isn't working in the php file. Firebug shows the post to contain the contents posted, email and invoice id, just nothing is actually received in the php file.</p> <p>The form:</p> <pre><code>&lt;form method="post" action="&lt;?=$_SERVER['PHP_SELF']; ?&gt;" enctype="application/x-www-form-urlencoded"&gt; </code></pre> <p>Anyone know what its doing?</p> <p>thanks</p> <hr> <p>found this - <a href="http://www.bradino.com/php/empty-post-array/" rel="nofollow noreferrer">http://www.bradino.com/php/empty-post-array/</a></p> <p>that a sensible route to go?</p>
<p><code>$.post()</code> passes data to the underlying <code>$.ajax()</code> call, which sets <code>application/x-www-form-urlencoded</code> by default, so i don't think it's that.</p> <p>can you try this:</p> <pre><code>var post = $('#myForm').serialize(); $.post("includes/verify.php", post, function(data) { alert(data); }); </code></pre> <p>the <code>serialize()</code> call will grab all the current data in <code>form.myForm</code>.</p>
<p>I had a case where I was using jQuery to disable all the inputs (even the hidden ones I wanted) just before using jQuery to submit the form. I changed my jQuery to only disable the "button" type inputs and now the hidden vars are posted when the form is submitted! It seems that if you set a hidden input to disabled its values aren't posted with the form!</p> <p>Changed:</p> <pre><code>$('input').attr('disabled',true); </code></pre> <p>to:</p> <pre><code>$('input[type=button]').attr('disabled',true); </code></pre>
34,080
<p>Im trying to find out a good JavaScript library that can create a nice "inner-window" popup within a page on my site.</p> <p>I would like to not have to worry about screen positioning (i.e. dont have to calcuate if the size of the window will be off screen, etc...), but just make a new pop-up that has content in it.</p> <p>I'll be using .NET 3.5 ASP.NET (maybe MVC, havent started yet), I know JQuery has great support, but from what I have seen, it doesnt have this type of widget feature.</p> <p>Please note, I do not want to use "frames" in any way, shape, or form! But rather the floating div style approach (or similar).</p> <p>Thanks heaps! Mark</p>
<p><strong>Floating containers, panels and dialogs:</strong></p> <p>For dialog boxes and windows, perhaps a <a href="http://developer.yahoo.com/yui/container/module/" rel="nofollow noreferrer"><strong>YUI module</strong></a> would be a <strong>good solution</strong>.</p> <p><strong>Modal Boxes</strong></p> <p>If you <strong>aren't a javascript programmer</strong>, and you're interested in a more-elaborate modal box, there are jQuery <strong>plugins</strong> <a href="http://leandrovieira.com/projects/jquery/lightbox/" rel="nofollow noreferrer"><strong>offering</strong></a> the <a href="http://jquery.com/demo/thickbox/" rel="nofollow noreferrer"><strong>modal lightbox effect</strong></a>.</p> <p><strong>Sidenote:</strong> There are many libraries offering this kind of functionality, but if the box itself is the only piece you need, keep in consideration that <strong>some libraries will include many things you aren't using</strong>. If you're careful to use only the packages you need, you can keep your page nice and lean.</p> <p><strong>Sidenote:</strong> If you're fairly well-versed with javascript, or wish to become so, remember that you can always <em>write your own</em>. It's common for people in the javascript world to turn straight to libraries. Libraries are an important part of the modern javascript landscape, but sometimes they become a crutch for developers. Writing a few front-end pieces yourself is a great way to dive into front-end development.</p>
<p>Thanks for the help so far, I have just taken a look at light box, and although very nice, I was hoping for a non-page-blocking library, these all seem to (at a first glace) grey-out the rest of the page, I was hoping for less of this, and more just an inline content based window that does not block the rest of the page.</p>
24,372
<p>Can anybody let me know the query to find all the tables that has a date columns on it.</p> <p>Thanks</p>
<p>This should do the trick, just add in additional types if you need them:</p> <pre><code>select so.name table_name ,sc.name column_name ,st.name data_type from sysobjects so inner join syscolumns sc on (so.id = sc.id) inner join systypes st on (st.type = sc.type) where so.type = 'U' and st.name IN ('DATETIME', 'DATE', 'TIME', 'SMALLDATETIME') </code></pre> <p><strong><em>edit:</strong> this also works in Sybase and any other T-SQL variants.</em></p>
<p>I know that this is an old question, but I found it searching for similar problem solution.<br> This what I'm using:</p> <pre><code>SELECT DISTINCT OBJECT_NAME(col.OBJECT_ID) AS [TableName] FROM sys.all_columns col INNER JOIN sys.types typ ON col.user_type_id = typ.user_type_id WHERE col.user_type_id IN (61) </code></pre> <p>You can find all basic datatypes here: <a href="http://www.sqlservercurry.com/2008/06/find-all-columns-with-varchar-and.html" rel="nofollow">http://www.sqlservercurry.com/2008/06/find-all-columns-with-varchar-and.html</a></p> <p>If You want to find all columns with specific type in a specific table just use this:</p> <pre><code>SELECT OBJECT_NAME(col.OBJECT_ID) AS [TableName] ,col.[name] AS [ColName] ,typ.[name] AS [TypeName] FROM sys.all_columns col INNER JOIN sys.types typ ON col.user_type_id = typ.user_type_id WHERE col.user_type_id IN (61) AND OBJECT_NAME(col.OBJECT_ID) = 'TABLE_NAME' </code></pre> <p>Mayby someone will find it usefull :)</p>
46,740
<p>I'm trying to do a domain lookup in vba with something like this:</p> <pre><code>DLookup("island", "villages", "village = '" &amp; txtVillage &amp; "'") </code></pre> <p>This works fine until txtVillage is something like Dillon's Bay, when the apostrophe is taken to be a single quote, and I get a run-time error.</p> <p>I've written a trivial function that escapes single quotes - it replaces "'" with "''". This seems to be something that comes up fairly often, but I can't find any reference to a built-in function that does the same. Have I missed something?</p>
<p>The "Replace" function should do the trick. Based on your code above:</p> <pre><code>DLookup("island", "villages", "village = '" &amp; Replace(txtVillage, "'", "''") &amp; "'") </code></pre>
<p>My solution is much simpler. Originally, I used this SQL expression to create an ADO recordset:</p> <pre><code>Dim sSQL as String sSQL="SELECT * FROM tblTranslation WHERE fldEnglish='" &amp; myString &amp; "';" </code></pre> <p>When <code>myString</code> had an apostrophe in it, like Int'l Electrics, my program would halt. Using double quotes solved the problem.</p> <pre><code>sSQL="SELECT * FROM tblTranslation WHERE fldEnglish="" &amp; myString &amp; "";" </code></pre>
24,375
<p>If I have a control on a page that has its Datasource set to a DataReader, does that control consume the reader at the time the Datasource is set, or does the datareader continue to exist until Databind has been executed? </p> <p>What actually happens under the covers when Databind is executed?</p>
<p>Depending on the Control, DataBind() will Bind the Data to the Control. It does this by Iterating through the DataSource and create the Html and other Controls that are needed.</p> <p>For a DropDownList, DataBind() will create the ListItem for each record in a DataSet or each Element in an ArrayList.</p> <p>Later the Render method is call on the DropDownList, which returns the Html for a Select tag. It also creates the Html for each ListItem by returning Option tags inside the Select tag.</p> <p>For a Label, DataBind() will set the Text to the value you pulled from the Database (for example).</p> <p>If you don't call DataBind() for the specific control, you can also make sure that your DataSource is set for a control and call Page.DataBind(). This will go through the Controls in the Page and call all of the DataBinds for each Control. </p>
<p>What is the control doing with the datareader during databind? Does it copy it into its internal structures and dispose of the datareader then render? </p> <p>If I have 10 controls on a page and set the datasource on each to a different datareader, then called page.databind, will the datareaders exist the entire time (from the point of creation until the point where the page.databind completes it's processing)?</p>
22,269
<p>This seems like a pretty stupid question, but I'm trying to figure out the best way to do this. Would you simply redirect to a /Logout page and have the controller call the FormsAuthentication.SignOut function?</p> <p>That was my first thought, but then I wondered if it could be abused by third party websites. Let's say someone just decides to post a link to your /Logout page. The user would get signed out of your application. Is there a good way to prevent that?</p>
<p>If you are concerned about a user getting accidentally logged out of you application through the use of a malicious link, you can check the Referrer to make sure that the logout is coming from your site (or is NULL in the case where the user simply types the URL in).</p> <p>I actually don't worry about this since logging someone out is annoying but not necessarily a security risk.</p>
<p>You should look for a cookie or something that identifies the client as the true user.</p>
27,140
<p>Does anybody know what hypothetical indexes are used for in sql server 2000? I have a table with 15+ such indexes, but have no idea what they were created for. Can they slow down deletes/inserts?</p>
<p>hypothetical indexes are usually created when you run index tuning wizard, and are suggestions, under normal circumstances they will be removed if the wizard runs OK. </p> <p>If some are left around they can cause some issues, see <a href="http://msdn.microsoft.com/en-us/library/ms190172(SQL.90).aspx" rel="nofollow noreferrer">this link for ways to remove them</a>.</p>
<p>Hypothetical indexes are those generated by the Database Tuning Advisor. Generally speaking, having too many indexes is not a great idea and you should examine your query plans to prune those which are not being used.</p>
17,986
<p>I'm trying to install the .Net framework version 2.0 on embedded Windows XP SP2 (aka XPE).</p> <p>I'm using the XPE specific version of the installer from Microsoft:</p> <p><a href="http://www.microsoft.com/downloads/details.aspx?familyid=c4837dad-5719-4b63-8752-cb0a65802329&amp;displaylang=en" rel="nofollow noreferrer">http://www.microsoft.com/downloads/details.aspx?familyid=c4837dad-5719-4b63-8752-cb0a65802329&amp;displaylang=en</a></p> <p>When the installation starts it fails with the following error:</p> <p>QFE Installer -- Error Cannot connect to the database - please check the database</p> <p>How can I get .Net 2.0 installed on SPE?</p>
<p>Okay, so you're running the installer that is updating your XPE development environment, right? Or are you attempting to run that on a device before you seal it?</p> <p>You need to run that installer on the workstation that has the XPE dev environment (and database) installed. The installer is looking for a specific database on a specific instance of Sql Server, so if you have (or somebody else has) changed it, you'll need to read up on how to specify the connection string to use with the installer.</p> <p>In addition, it's probably trying to connect using your windows account credentials. Make sure you are able to log on to Sql Server, open the DB with the component definitions, and add records to it. Alternatively, if you can specify the connection string you can set a Sql login username and password to use.</p> <p>Profiler is a great tool for troubleshooting the two issues described above.</p> <p>Once you have the components installed, you'll have to add them to your image, check your dependencies and then build it.</p> <hr> <p>If you're trying to just install .NET 2.0 on a machine directly (before you reseal it), you will need the packages for Windows Installer on the machine first. There might be some other dependencies; I haven't done it in a long time so I can't remember. </p> <p>The best way to troubleshoot dependencies on an XPE installation is to put ProcessMonitor from Sysinternals on it. As you run the installer, you'll see where it attempts to find stuff and fails. Take that information back to your XPE IDE and search your components for those files. You then have to add the packages containing those files to your image and try again. Its an arduous process sometimes..,.</p>
<p>HI, i know how to fix it,</p> <p>just install futre-pack 2007 for w XP embedded =(.NET framework2.0 included) :D</p>
24,141
<p>Are the naming conventions similar in different languages? If not, what are the differences?</p>
<p>As others have said, things vary a lot, but here's a rough overview of the most commonly used naming conventions in various languages:</p> <p><code>lowercase, lowercase_with_underscores</code>:</p> <p>Commonly used for local variables and function names (typical C syntax).</p> <p><code>UPPERCASE, UPPERCASE_WITH_UNDERSCORES:</code></p> <p>Commonly used for constants and variables that never change. Some (older) languages like BASIC also have a convention for using all upper case for all variable names.</p> <p><code>CamelCase, javaCamelCase:</code></p> <p>Typically used for function names and variable names. Some use it only for functions and combine it with lowercase or lowercase_with_underscores for variables. When javaCamelCase is used, it's typically used both for functions and variables.</p> <p>This syntax is also quite common for external APIs, since this is how the Win32 and Java APIs do it. (Even if a library uses a different convention internally they typically export with the (java)CamelCase syntax for function names.)</p> <p><code>prefix_CamelCase, prefix_lowercase, prefix_lowercase_with_underscores:</code></p> <p>Commonly used in languages that don't support namespaces (i.e. C). The prefix will usually denote the library or module to which the function or variable belongs. Usually reserved to global variables and global functions. Prefix can also be in UPPERCASE. Some conventions use lowercase prefix for internal functions and variables and UPPERCASE prefix for exported ones.</p> <p>There are of course many other ways to name things, but most conventions are based on one of the ones mentioned above or a variety on those.</p> <p>BTW: I forgot to mention Hungarian notation on purpose.</p>
<p>Years ago an wise old programmer taught me the evils of <a href="http://en.wikipedia.org/wiki/Hungarian_notation" rel="nofollow noreferrer">Hungarian notation</a>, this was a real legacy system, Microsoft adopted it some what in the Windows SDK, and later in MFC. It was designed around loose typed languages like C, and not for strong typed languages like C++. At the time I was programming Windows 3.0 using Borland's Turbo Pascal 1.0 for Windows, which later became Delphi. </p> <p>Anyway long story short at this time the team I was working on developed our own standards very simple and applicable to almost all languages, based on simple prefixes -</p> <ul> <li>a - argument </li> <li>l - local </li> <li>m - member </li> <li>g - global</li> </ul> <p>The emphasis here is on scope, rely on the compiler to check type, all you need care about is scope, where the data lives. This has many advantages over nasty old Hungarian notation in that if you change the type of something via refactoring you don't have to search and replace all instances of it.</p> <p>Nearly 16 years later I still promote the use of this practice, and have found it applicable to almost every language I have developed in. </p>
7,192
<p>I've got a combo-box that sits inside of a panel in Flex 3. Basically I want to fade the panel using a Fade effect in ActionScript. I can get the fade to work fine, however the label of the combo-box does not fade. I had this same issue with buttons and found that their fonts needed to be embedded. No problem. I embedded the font that I was using and the buttons' labels faded correctly. I've tried a similar approach to the combo-box, but it does not fade the selected item label.</p> <p>Here is what I've done so far: Embed code for the font at the top of my MXML in script:</p> <pre><code>[Embed("assets/trebuc.ttf", fontName="TrebuchetMS")] public var trebuchetMSFont:Class; </code></pre> <p>In my init function</p> <pre><code>//register the font. Font.registerFont(trebuchetMSFont); </code></pre> <p>The combobox's mxml:</p> <pre><code>&lt;mx:ComboBox id="FilterFields" styleName="FilterDropdown" left="10" right="10" top="10" fontSize="14"&gt; &lt;mx:itemRenderer&gt; &lt;mx:Component&gt; &lt;mx:Label fontSize="10" /&gt; &lt;/mx:Component&gt; &lt;/mx:itemRenderer&gt; &lt;/mx:ComboBox&gt; </code></pre> <p>And a style that I wrote to get the fonts applied to the combo-box:</p> <pre><code>.FilterDropdown { embedFonts: true; fontFamily: TrebuchetMS; fontWeight: normal; fontSize: 12; } </code></pre> <p>The reason I had to write a style instead of placing it in the "FontFamily" attribute was that the style made all the text on the combo-box the correct font where the "FontFamily" attribute only made the items in the drop-down use the correct font. ­­­­­­­­­­­­­­­­­­­­­­­­­</p>
<p>Hmm, I am not sure why that isn't working for you. Here is an example of how I got it to work:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="fx.play([panel])"&gt; &lt;mx:Style&gt; @font-face { src: local("Arial"); fontFamily: ArialEm; } @font-face { src: local("Arial"); fontFamily: ArialEm; fontWeight: bold; } @font-face { src: local("Arial"); fontFamily: ArialEm; font-style: italic; } &lt;/mx:Style&gt; &lt;mx:XML id="items" xmlns=""&gt; &lt;items&gt; &lt;item label="Item 1" /&gt; &lt;item label="Item 2" /&gt; &lt;item label="Item 3" /&gt; &lt;/items&gt; &lt;/mx:XML&gt; &lt;mx:Panel id="panel" x="10" y="10" width="250" height="200" layout="absolute"&gt; &lt;mx:ComboBox fontFamily="ArialEm" x="35" y="10" dataProvider="{items.item}" labelField="@label"&gt;&lt;/mx:ComboBox&gt; &lt;/mx:Panel&gt; &lt;mx:Fade id="fx" alphaFrom="0" alphaTo="1" duration="5000" /&gt; &lt;/mx:Application&gt; </code></pre> <p>Hope this helps you out.</p>
<p>Thanks for your help. Had exactly the same problem. The trick is in the embedding the "bold" version of the font you are using. Even though the font in your ComboBox isn't set to Bold ...</p>
3,900
<p>Has anyone used C# with a Sales Logix database?</p>
<p>Yes. I have.</p> <p>(Not the most interesting answer on SOB today, but that's what the question asked...)</p>
<p>Yes. I have.</p> <p>(Not the most interesting answer on SOB today, but that's what the question asked...)</p>
17,028
<p>How many ServiceContracts can a WCF service have?</p> <p>Specifically, since a ServiceContract is an attribute to an interface, how many interfaces can I code into one WCF web service? Is it a one-to-one?</p> <p>Does it make sense to separate the contracts across multiple web services?</p>
<p>WCF services can have multiple endpoints, each of which can implement a different service contract.</p> <p>For example, you could have a service declared as follows:</p> <pre><code>[ServiceBehavior(Namespace = "DemoService")] public class DemoService : IDemoService, IDoNothingService </code></pre> <p>Which would have configuration along these lines:</p> <pre><code>&lt;service name="DemoService" behaviorConfiguration="Debugging"&gt; &lt;host&gt; &lt;baseAddresses&gt; &lt;add baseAddress = "http://localhost/DemoService.svc" /&gt; &lt;/baseAddresses&gt; &lt;/host&gt; &lt;endpoint address ="" binding="customBinding" bindingConfiguration="InsecureCustom" bindingNamespace="http://schemas.com/Demo" contract="IDemoService"/&gt; &lt;endpoint address ="" binding="customBinding" bindingConfiguration="InsecureCustom" bindingNamespace="http://schemas.com/Demo" contract="IDoNothingService"/&gt; &lt;/service&gt; </code></pre> <p>Hope that helps, but if you were after the theoretical maximum interfaces you can have for a service I suspect it's some crazily large multiple of 2.</p>
<p>A service can theoretically have any number of Endpoints, and each Endpoint is bound to a particular contract, or interface, so it is possible for a single conceptual (and configured) service to host multiple interfaces via multiple endpoints or alternatively for several endpoints to host the same interface.</p> <p>If you are using the ServiceHost class to host your service, though, instead of IIS, you can only associate a single interface per ServiceHost. I'm not sure why this is the case, but it is.</p>
5,166
<p>I'm porting a process which creates a MASSIVE <code>CROSS JOIN</code> of two tables. The resulting table contains 15m records (looks like the process makes a 30m cross join with a 2600 row table and a 12000 row table and then does some grouping which must split it in half). The rows are relatively narrow - just 6 columns. It's been running for 5 hours with no sign of completion. I only just noticed the count discrepancy between the known good and what I would expect for the cross join, so my output doesn't have the grouping or deduping which will halve the final table - but this still seems like it's not going to complete any time soon.</p> <p>First I'm going to look to eliminate this table from the process if at all possible - obviously it could be replaced by joining to both tables individually, but right now I do not have visibility into everywhere else it is used.</p> <p>But given that the existing process does it (in less time, on a less powerful machine, using the FOCUS language), are there any options for improving the performance of large <code>CROSS JOIN</code>s in SQL Server (2005) (hardware is not really an option, this box is a 64-bit 8-way with 32-GB of RAM)?</p> <p>Details:</p> <p>It's written this way in FOCUS (I'm trying to produce the same output, which is a CROSS JOIN in SQL):</p> <pre><code>JOIN CLEAR * DEFINE FILE COSTCENT WBLANK/A1 = ' '; END TABLE FILE COSTCENT BY WBLANK BY CC_COSTCENT ON TABLE HOLD AS TEMPCC FORMAT FOCUS END DEFINE FILE JOINGLAC WBLANK/A1 = ' '; END TABLE FILE JOINGLAC BY WBLANK BY ACCOUNT_NO BY LI_LNTM ON TABLE HOLD AS TEMPAC FORMAT FOCUS INDEX WBLANK JOIN CLEAR * JOIN WBLANK IN TEMPCC TO ALL WBLANK IN TEMPAC DEFINE FILE TEMPCC CA_JCCAC/A16=EDIT(CC_COSTCENT)|EDIT(ACCOUNT_NO); END TABLE FILE TEMPCC BY CA_JCCAC BY CC_COSTCENT AS COST CENTER BY ACCOUNT_NO BY LI_LNTM ON TABLE HOLD AS TEMPCCAC END </code></pre> <p>So the required output really is a CROSS JOIN (it's joining a blank column from each side).</p> <p>In SQL:</p> <pre><code>CREATE TABLE [COSTCENT]( [COST_CTR_NUM] [int] NOT NULL, [CC_CNM] [varchar](40) NULL, [CC_DEPT] [varchar](7) NULL, [CC_ALSRC] [varchar](6) NULL, [CC_HIER_CODE] [varchar](20) NULL, CONSTRAINT [PK_LOOKUP_GL_COST_CTR] PRIMARY KEY NONCLUSTERED ( [ID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] CREATE TABLE [JOINGLAC]( [ACCOUNT_NO] [int] NULL, [LI_LNTM] [int] NULL, [PR_PRODUCT] [varchar](5) NULL, [PR_GROUP] [varchar](1) NULL, [AC_NAME_LONG] [varchar](40) NULL, [LI_NM_LONG] [varchar](30) NULL, [LI_INC] [int] NULL, [LI_MULT] [int] NULL, [LI_ANLZ] [int] NULL, [LI_TYPE] [varchar](2) NULL, [PR_SORT] [varchar](2) NULL, [PR_NM] [varchar](26) NULL, [PZ_SORT] [varchar](2) NULL, [PZNAME] [varchar](26) NULL, [WANLZ] [varchar](3) NULL, [OPMLNTM] [int] NULL, [PS_GROUP] [varchar](5) NULL, [PS_SORT] [varchar](2) NULL, [PS_NAME] [varchar](26) NULL, [PT_GROUP] [varchar](5) NULL, [PT_SORT] [varchar](2) NULL, [PT_NAME] [varchar](26) NULL ) ON [PRIMARY] CREATE TABLE [JOINCCAC]( [CA_JCCAC] [varchar](16) NOT NULL, [CA_COSTCENT] [int] NOT NULL, [CA_GLACCOUNT] [int] NOT NULL, [CA_LNTM] [int] NOT NULL, [CA_UNIT] [varchar](6) NOT NULL, CONSTRAINT [PK_JOINCCAC_KNOWN_GOOD] PRIMARY KEY CLUSTERED ( [CA_JCCAC] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] </code></pre> <p>With the SQL Code:</p> <pre><code>INSERT INTO [JOINCCAC] ( [CA_JCCAC] ,[CA_COSTCENT] ,[CA_GLACCOUNT] ,[CA_LNTM] ,[CA_UNIT] ) SELECT Util.PADLEFT(CONVERT(varchar, CC.COST_CTR_NUM), '0', 7) + Util.PADLEFT(CONVERT(varchar, GL.ACCOUNT_NO), '0', 9) AS CC_JCCAC ,CC.COST_CTR_NUM AS CA_COSTCENT ,GL.ACCOUNT_NO % 900000000 AS CA_GLACCOUNT ,GL.LI_LNTM AS CA_LNTM ,udf_BUPDEF(GL.ACCOUNT_NO, CC.COST_CTR_NUM, GL.LI_LNTM, 'N') AS CA_UNIT FROM JOINGLAC AS GL CROSS JOIN COSTCENT AS CC </code></pre> <p>Depending on how this table is subsequently used, it should be able to be eliminated from the process, by simply joining to both the original tables used to build it. However, this is an extremely large porting effort, and I might not find the usage of the table for some time, so I was wondering if there were any tricks to <code>CROSS JOIN</code>ing big tables like that in a timely fashion (especially given that the existing process in FOCUS is able to do it more speedily). That way I could validate the correctness of my building of the replacement query and then later factor it out with views or whatever.</p> <p>I am also considering factoring out the UDFs and string manipulation and performing the CROSS JOIN first to break the process up a bit.</p> <p><strong>RESULTS SO FAR:</strong></p> <p>It turns out that the UDFs do contribute a lot (negatively) to the performance. But there also appears to be a big difference between a 15m row cross join and a 30m row cross join. I do not have SHOWPLAN rights (boo hoo), so I can't tell whether the plan it is using is better or worse after changing indexes. I have not refactored it yet, but am expecting the entire table to go away shortly.</p>
<p>Examining that query shows only one column used from one table, and only two columns used from the other table. Due to the very low numbers of columns used, this query can be easily enhanced with covering indexes:</p> <pre><code>CREATE INDEX COSTCENTCoverCross ON COSTCENT(COST_CTR_NUM) CREATE INDEX JOINGLACCoverCross ON JOINGLAC(ACCOUNT_NO, LI_LNTM) </code></pre> <p>Here are my questions for further optimization:</p> <p>When you put the query in query analyzer and whack the "show estimated execution plan" button, it will show a graphical representation of what it's going to do.</p> <p>Join Type: There should be a nested loop join in there. (the other options are merge join and hash join). If you see nested loop, then ok. If you see merge join or hash join, let us know.</p> <p>Order of table access: Go all the way to the top and scroll all the way to the right. The first step should be accessing a table. Which table is that and what method is used(index scan, clustered index scan)? What method is used to access the other table?</p> <p>Parallelism: You should see the little jaggedy arrows on almost all icons in the plan indicating that parallelism is being used. If you don't see this, there is a major problem!</p> <p>That udf_BUPDEF concerns me. Does it read from additional tables? Util.PADLEFT concerns me less, but still.. what is it? If it isn't a Database Object, then consider using this instead:</p> <pre><code>RIGHT('z00000000000000000000000000' + columnName, 7) </code></pre> <p>Are there any triggers on JOINCCAC? How about indexes? With an insert this large, you'll want to drop all triggers and indexes on that table.</p>
<p>Break down the query to make it a plain simple cross join.</p> <pre> <code> SELECT CC.COST_CTR_NUM, GL.ACCOUNT_NO ,CC.COST_CTR_NUM AS CA_COSTCENT ,GL.ACCOUNT_NO AS CA_GLACCOUNT ,GL.LI_LNTM AS CA_LNTM -- I don't know what is BUPDEF doing? but remove it from the query for time being -- ,udf_BUPDEF(GL.ACCOUNT_NO, CC.COST_CTR_NUM, GL.LI_LNTM, 'N') AS CA_UNIT FROM JOINGLAC AS GL CROSS JOIN COSTCENT AS CC </code> </pre> <p>See how good is the simple cross join? (without any functions applied on it)</p>
46,258
<p>I'm not really asking about how programmers learn how to program. More about specific technologies. If I wanted to learn Hibernate, how do I know what I should know prior to Hibernate? Should I learn JPA before, during or after Hibernate? Is there a better solution to Hibernate? (And I'm not really looking for information on Hibernate specifically)</p> <p>Maybe stackoverflow is the place to find these answers, but it seems like with the shear vastness of frameworks, apis, libraries, programming languages, platforms, and whatever other techie word you want to use, it takes an extremely long time to come up to speed on what technology to use, when and what you need to know prior to using it.</p>
<p>Sometimes the best way to learn is to just dig in to a framework. Sure, you could use someones wrapper API around something, but if there is something wrong w/ hibernate, then you wouldn't know what's happening.</p> <p>And to answer "how do i know what i should know prior to hibernate", you don't, that's why you are learning. When learning about c++, started out with simple data types, but i didn't know about pointers yet, didn't need to, but i learned about them when i got there. Just gotta jump in and start playing around.</p>
<p>A lot of the time the documentation and/or tutorial for any technology or project will mention what prior knowledge is assumed or useful.</p> <p>So for example hibernate: <a href="http://www.hibernate.org/hib_docs/v3/reference/en/html_single/#tutorial-intro" rel="nofollow noreferrer">http://www.hibernate.org/hib_docs/v3/reference/en/html_single/#tutorial-intro</a></p> <p>"This tutorial is intended for new users of Hibernate but requires Java and SQL knowledge"</p>
12,140
<pre><code>int x = n / 3; // &lt;-- make this faster // for instance int a = n * 3; // &lt;-- normal integer multiplication int b = (n &lt;&lt; 1) + n; // &lt;-- potentially faster multiplication </code></pre>
<p>This is the fastest as the compiler will optimize it if it can depending on the output processor.</p> <pre><code>int a; int b; a = some value; b = a / 3; </code></pre>
<p>Easy computation ... at most n iterations where n is your number of bits:</p> <pre><code>uint8_t divideby3(uint8_t x) { uint8_t answer =0; do { x&gt;&gt;=1; answer+=x; x=-x; }while(x); return answer; } </code></pre>
20,654
<p>I am using cura with M3D entry level printer.</p> <p>When I print things more than 6-7cm/2.5-3inches, at the end of the print, the hot end sink back into the print then gets stuck as it tries to return to idle position.</p> <p>Please see the attached photo. Has anyone had this problem? Thank you<a href="https://i.stack.imgur.com/2xpD4.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2xpD4.jpg" alt="enter image description here"></a></p> <p>The last 20 lines of gcode is:</p> <pre><code>G0 X50.83 Y49.982 G1 F600 X50.541 Y49.975 E4399.62304 G1 X50.268 Y49.985 E4399.62637 G1 X49.999 Y49.999 E4399.63024 G1 X49.73 Y50.012 E4399.6341 G1 X49.457 Y50.023 E4399.63742 G1 X49.168 Y50.016 E4399.63941 G0 F7200 X49.28 Y49.87 ;TIME_ELAPSED:6301.614981 G1 F1500 E4393.13941 M107 M104 S0 M140 S0 ;Retract the filament G92 E1 G1 E-1 F300 G28 X0 Y0 M84 M82 ;absolute extrusion mode M104 S0 ;End of Gcode </code></pre>
<p>As Oscar commented, check the tail end of your gcode files. Most slicing software includes commands to move the head to x=0,y=0 at the very least. I am a bit surprised that your files don't appear to have this, since Cura does apply said code. </p> <p>Possiblly there's something lacking in your printer's firmware and it doesn't recognize some of the gcode commands.</p>
<p>As Oscar commented, check the tail end of your gcode files. Most slicing software includes commands to move the head to x=0,y=0 at the very least. I am a bit surprised that your files don't appear to have this, since Cura does apply said code. </p> <p>Possiblly there's something lacking in your printer's firmware and it doesn't recognize some of the gcode commands.</p>
1,033
<p>I have a windows mobile 5.0 app, written in C++ MFC, with lots of dialogs. One of the devices I'm currently targetting does not have a tab key, so I would like to use another key to move between controls. This is fine for buttons but not edit controls or combo boxes. I have looked at a <a href="https://stackoverflow.com/questions/52098/how-do-you-navigate-out-of-a-combobox-on-a-windows-mobile-device-without-a-tab">similar question</a> but the answer does not really suit. I've tried overriding the CDialog::OnKeyDown to no avail, and would rather not have to override the keystroke functionality for every control in every dialog. My thoughts so far are to write new classes replacing CEdit and CComboBox, but as always am just checking if there is an easier way, such as temporarily re-programming another key.</p>
<p>I don't know MFC <strong>that good</strong>, but maybe you could pull it off by subclassing window procedures of all those controls with a single class, which would only handle cases of pressing cursor keys and pass the rest of events to the original procedures.</p> <p>You would have to provide your own mechanism of moving to an appropriate control, depending on which cursor key was pressed but it may be worth the usability gains.</p> <p>If that worked, you could enumerate all dialog controls and subclass them automatically.</p> <p>Windows Mobile 6 allows switching between dialog controls using cursors by default - it's a new, more "smartphoney" way of moving around the UI and it's incredibly convenient.</p>
<p>Can you not use the D-Pad to navigate between fields?</p>
20,043
<p>I have written my program in c# .net. I want to convert it in to a powershell cmdlet. I was instructed to use pssnapin and getproc programs. Can anyone plz help me out..</p> <p>Regards Arun</p>
<p>So, here's the PSCmdlet-Class[from medata], that you can inherit from.</p> <pre><code>namespace System.Management.Automation { public abstract class PSCmdlet : Cmdlet { protected PSCmdlet(); public PSHost Host { get; } public CommandInvocationIntrinsics InvokeCommand { get; } public ProviderIntrinsics InvokeProvider { get; } public InvocationInfo MyInvocation { get; } public string ParameterSetName { get; } public SessionState SessionState { get; } public PathInfo CurrentProviderLocation(string providerId); public Collection&lt;string&gt; GetResolvedProviderPathFromPSPath(string path, out ProviderInfo provider); public string GetUnresolvedProviderPathFromPSPath(string path); public object GetVariableValue(string name); public object GetVariableValue(string name, object defaultValue); } } </code></pre> <p>In order to get your cmdlets loaded, you need to sign them additionally, because Powershell does not execute not signed code.</p>
<p>Check also <a href="http://blogs.msdn.com/daiken/" rel="nofollow noreferrer">http://blogs.msdn.com/daiken/</a>. In particular all the months from February 2007 to June 2007. You'll find the Visual Studio template link (for 2005, also works in Express), and several examples/labs.</p>
47,246
<p>I've recently started work on the Compact Framework and I was wondering if anyone had some recommendations for unit testing beyond what's in VS 2008. MSTest is <em>ok</em>, but debugging the tests is a nightmare and the test runner is <em>so</em> slow.</p> <p>I see that NUnitLite on codeplex is an option, but it doesn't look very active; it's also in the roadmap for NUnit 3.0, but who knows when that will come out. Has anyone had any success with it?</p>
<p>What we've done that really improves our efficiency and quality is to multi target our mobile application. That is to say with a very little bit of creativity and a few conditional compile tags and custom project configurations it is possible to build a version of your mobile application that also runs on the desktop. </p> <p>If you put all your business logic you need tested in a separate project/assembly then this layer can be very effectively tested using any of the desktop tools you are already familiar with.</p>
<p>We use NUnitLite, although I think we did have had to add some code to it in order for it to work. </p> <p>One of the problems we found is that if you are using parts of the platform that only exist in CF, then you can only run those tests in NUnitLite on an emulator or Windows Mobile device, which makes it hard to run the tests as part of an integrated build process. We got round this by added a new test attribute allowing you to disable the tests what would only run on the CF (typically these would be p/invoking out to some windows mobile only dll).</p>
3,531
<p>Is it possible to redirect all of the output of a Bourne shell script to somewhere, but with shell commands inside the script itself?</p> <p>Redirecting the output of a single command is easy, but I want something more like this:</p> <pre><code>#!/bin/sh if [ ! -t 0 ]; then # redirect all of my output to a file here fi # rest of script... </code></pre> <p>Meaning: if the script is run non-interactively (for example, cron), save off the output of everything to a file. If run interactively from a shell, let the output go to stdout as usual.</p> <p>I want to do this for a script normally run by the FreeBSD periodic utility. It's part of the daily run, which I don't normally care to see every day in email, so I don't have it sent. However, if something inside this one particular script fails, that's important to me and I'd like to be able to capture and email the output of this one part of the daily jobs.</p> <p>Update: Joshua's answer is spot-on, but I also wanted to save and restore stdout and stderr around the entire script, which is done like this:</p> <pre><code># save stdout and stderr to file # descriptors 3 and 4, # then redirect them to &quot;foo&quot; exec 3&gt;&amp;1 4&gt;&amp;2 &gt;foo 2&gt;&amp;1 # ... # restore stdout and stderr exec 1&gt;&amp;3 2&gt;&amp;4 </code></pre>
<p>Addressing the question as updated.</p> <pre><code>#...part of script without redirection... { #...part of script with redirection... } &gt; file1 2&gt;file2 # ...and others as appropriate... #...residue of script without redirection... </code></pre> <p>The braces '{ ... }' provide a unit of I/O redirection. The braces must appear where a command could appear - simplistically, at the start of a line or after a semi-colon. (<em>Yes, that can be made more precise; if you want to quibble, let me know.</em>)</p> <p>You are right that you can preserve the original stdout and stderr with the redirections you showed, but it is usually simpler for the people who have to maintain the script later to understand what's going on if you scope the redirected code as shown above.</p> <p>The relevant sections of the Bash manual are <a href="https://www.gnu.org/software/bash/manual/bash.html#Command-Grouping" rel="noreferrer">Grouping Commands</a> and <a href="https://www.gnu.org/software/bash/manual/bash.html#Redirections" rel="noreferrer">I/O Redirection</a>. The relevant sections of the POSIX shell specification are <a href="http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_09_04" rel="noreferrer">Compound Commands</a> and <a href="http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_07" rel="noreferrer">I/O Redirection</a>. Bash has some extra notations, but is otherwise similar to the POSIX shell specification.</p>
<p>I finally figured out how to do it. I wanted to not just save the output to a file but also, find out if the bash script ran successfully or not!</p> <p>I've wrapped the bash commands inside a function and then called the function <code>main_function</code> with a tee output to a file. Afterwards, I've captured the output using <code>if [ $? -eq 0 ]</code>.</p> <pre><code>#! /bin/sh - main_function() { python command.py } main_function &gt; &gt;(tee -a &quot;/var/www/logs/output.txt&quot;) 2&gt;&amp;1 if [ $? -eq 0 ] then echo 'Success!' else echo 'Failure!' fi </code></pre>
40,611
<p>When working on a big C/C++ project, do you have some specific rules regarding the <em>#include</em> within source or header files?</p> <p>For instance, we can imagine to follow one of these two excessive rules:</p> <ol> <li><em>#include</em> are forbidden in <em>.h</em> files; it is up to each <em>.c</em> file to include all the headers it needs</li> <li>Each <em>.h</em> file should include all its dependancies, i.e. it should be able to compile alone without any error.</li> </ol> <p>I suppose there is trade-off in between for any project, but what is yours? Do you have more specific rules? Or any link that argues for any of the solutions? </p>
<p>If you include H-files exclusively into C-files, then including a H-file into a C-file might cause compilation to fail. It might fail because you may have to include 20 other H-files upfront, and even worse, you have to include them in the right order. With a real lot of H-files, this system ends up to be an administrative nightmare in the long run. All you wanted to do was including one H-file and you ended up spending two hours to find out which other H-files in which order you will need to include as well.</p> <p>If a H-file can only be successfully included into a C-file in case another H-file is included first, then the first H-file should include the second one and so on. That way you can simply include every H-file into every C-file you like without having to fear that this may break compilation. That way you only specify your direct dependencies, yet if these dependencies themselves also have dependencies, its up to them to specify those.</p> <p>On the other hand, don't include H-files into H-files if that isn't necessary. <code>hashtable.h</code> should only include other header files that are required to use your hashtable implementation. If the implementation itself needs <code>hashing.h</code>, then include it in <code>hashtable.c</code>, not in <code>hashtable.h</code>, as only the implementation needs it, not the code that only would like to use the final hashtable.</p>
<p>Pt. 1 fails when you would like to have precompiled headers through a certain header; eg. this is what StdAfx.h are for in VisualStudio: you put all common headers there...</p>
21,973
<p>I would like the fastest and most accurate function <code>boolean isReachable(String host, int port)</code> that passes the following JUnit tests under the conditions below. Timeout values are specified by the JUnit test itself, and may be considered "unreachable."</p> <p><strong>Please note:</strong> All answers must be platform-independent. This means that <code>InetAddress.isReachable(int timeout)</code> is not going to work, since it relies on port <code>7</code> to do a ping on Windows (ICMP ping being an undocumented function on Windows), and this port is blocked in this setup.</p> <p>LAN Setup:</p> <ul> <li><code>thisMachine</code> (<code>192.168.0.100</code>)</li> <li><code>otherMachine</code> (<code>192.168.0.200</code>)</li> <li><strong>no</strong> machine is called <code>noMachine</code> or has the IP <code>192.168.0.222</code> (always unreachable)</li> <li>both machines are running Apache Tomcat on port <code>8080</code>; all other ports are unreachable (including port <code>7</code>)</li> <li><code>example.com</code> (<code>208.77.188.166</code>) is running a webserver on port <code>80</code> and is only reachable when the LAN is connected to the Internet</li> </ul> <p>Occasionally, the LAN is disconnected from the Internet in which case only local machines called by IP address are reachable (all others are unreachable; there's no DNS).</p> <p><strong>All tests are run on <code>thisMachine</code>.</strong></p> <pre><code>@Test(timeout=1600) // ~320ms per call (should be possible to do better) public void testLocalhost() { // We can always reach ourselves. assertTrue(isReachable("localhost", 8080)); assertTrue(isReachable("127.0.0.1", 8080)); assertTrue(isReachable("thisMachine", 8080)); // Even if there's no DNS! assertTrue(isReachable("192.168.0.100", 8080)); assertFalse(isReachable("localhost", 80)); // Nothing on that port. } @Test(timeout=5500) // ~1867ms per call (should be able to do better) public void testLAN() { assertTrue(isReachable("192.168.0.200", 8080)); // Always connected to the LAN. assertFalse(isReachable("192.168.0.222", 8080)); // No such a machine. assertFalse(isReachable("noMachine", 8080)); // No such machine. } </code></pre> <p>The following test is only run when the LAN is <strong>disconnected</strong> from the Internet.</p> <pre><code>@Test(timeout=5600) // ~1867ms per call (reasonable?) public void testNoDNS() { assertFalse(isReachable("otherMachine", 8080)); // No DNS. assertFalse(isReachable("example.com", 80)); // No DNS &amp; no Internet. assertFalse(isReachable("208.77.188.166", 80)); // No Internet. } </code></pre> <p>The following test is only run when the LAN is <strong>connected</strong> to the Internet.</p> <pre><code>@Test(timeout=5600) // ~1867ms per call (reasonable?) public void testHaveDNS() { assertTrue(isReachable("otherMachine", 8080)); // DNS resolves local names. assertTrue(isReachable("example.com", 80)); // DNS available. assertTrue(isReachable("208.77.188.166", 80)); // Internet available. } </code></pre>
<p>Firstly you need to recognise that you have <em>potentially</em> conflicting requirements; IP sockets are not time deterministic. The quickest you can ever detect unreachability is after your elapsed timeout. You can only detect reachability quicker.</p> <p>Assuming reachability/isReachable is your real objective, you should just use a straightforward non-blocking socket IO as shown in the <a href="http://java.sun.com/j2se/1.4.2/docs/guide/nio/example/Ping.java" rel="noreferrer">Java Ping</a> simulator, the example connects to the time service but would work equally well on 8080.</p>
<p>My most recent solution depends using a <code>TimedSocket</code> (<a href="http://www.javaworld.com/jw-09-1999/jw-09-timeout.html" rel="nofollow noreferrer">source code</a>) with 3000ms timeout while performing a connect.</p> <p>Timings:</p> <ul> <li>1406ms : <code>testLocalHost()</code></li> <li>5280ms : <code>testLAN()</code></li> </ul> <p>Can't even get these to work properly:</p> <ul> <li><code>testNoDNS()</code></li> <li><code>testHaveDNS()</code></li> </ul>
23,696
<p>How to unit test the windows workflows?</p>
<p>K. Scott Allen has posted <a href="http://odetocode.com/Blogs/scott/archive/2006/08/02/5492.aspx" rel="nofollow noreferrer">this</a>, which provides an approach to unit testing custom activities (although he says that he is not satisfied). A similar approach is presented by Ron Jacobs <a href="http://blogs.msdn.com/rjacobs/archive/2008/08/26/unit-testing-workflows.aspx" rel="nofollow noreferrer">here</a> and <a href="http://blogs.msdn.com/rjacobs/archive/2008/08/27/unit-testing-activities-with-windows-workflow-foundation.aspx" rel="nofollow noreferrer">here</a>.</p> <p>Another approach is presented by Maurice <a href="http://msmvps.com/blogs/theproblemsolver/archive/2008/06/02/unit-testing-custom-workflow-activities.aspx" rel="nofollow noreferrer">here</a> and <a href="http://msmvps.com/blogs/theproblemsolver/archive/2008/06/11/unit-testing-asynchronous-workflow-activities.aspx" rel="nofollow noreferrer">here</a> (he uses <a href="http://www.typemock.com/" rel="nofollow noreferrer">TypeMock</a> as Will already <a href="https://stackoverflow.com/questions/182740/workflow-unit-testing#182888">mentioned</a>).</p>
<p>MS dropped the ball on making workflows easily mockable and testable. If you want to do thorough tests on your custom activities you'll need to purchase a mocking framework that can mock sealed types such as <a href="http://www.typemock.com/" rel="nofollow noreferrer">TypeMock.</a> Otherwise, you'll have to write your code around the limitations of Workflow.</p>
22,088
<p>I have a a property defined as:</p> <pre><code>[XmlArray("delete", IsNullable = true)] [XmlArrayItem("contact", typeof(ContactEvent)), XmlArrayItem("sms", typeof(SmsEvent))] public List&lt;Event&gt; Delete { get; set; } </code></pre> <p>If the List&lt;> Delete has no items</p> <pre><code>&lt;delete /&gt; </code></pre> <p>is emitted. If the List&lt;> Delete is set to null</p> <pre><code>&lt;delete xsi:nil="true" /&gt; </code></pre> <p>is emitted. Is there a way using attributes to get the delete element not to be emitted if the collection has no items?</p> <p><a href="https://stackoverflow.com/questions/69296/xml-serialization-and-empty-collections#69407">Greg</a> - Perfect thanks, I didn't even read the IsNullable documentation just assumed it was signalling it as not required.</p> <p><a href="https://stackoverflow.com/questions/69296/xml-serialization-and-empty-collections#69518">Rob Cooper</a> - I was trying to avoid ISerializable, but Gregs suggestion works. I did run into the problem you outlined in (1), I broke a bunch of code by just returning null if the collection was zero length. To get around this I created a EventsBuilder class (the class I am serializing is called Events) that managed all the lifetime/creation of the underlying objects of the Events class that spits our Events classes for serialization.</p>
<p>If you set IsNullable=false or just remove it (it is false by default), then the "delete" element will not be emitted. This will work only if the collection equals to null.</p> <p>My guess is that there is a confusion between "nullability" in terms of .NET, and the one related to nullable elements in XML -- those that are marked by xml:nil attribute. XmlArrayAttribute.IsNullable property controls the latter.</p>
<p>You could always implement IXmlSerializer and perform the serialization manually.</p> <p>See <a href="http://www.codeproject.com/KB/cs/IXmlSerializable.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/cs/IXmlSerializable.aspx</a> for an example.</p>
9,470
<p>Could somebody please explain to me what happens here?<br> I am creating a binding in code. </p> <p>The target object is a UserControl<br> The target property is a boolean DependencyProperty<br> The source object is a FrameworkElement and implements INotifyPropertyChanged<br> The source property is of type ObservableCollection </p> <p>What happens:</p> <ul> <li><p>The binding is created in code, the result BindingExpressionBase looks fine, the mode is OneWay, the target value gets set correctly (at this time)</p> <p>Binding b = new Binding();<br> b.Path = "SourceProperty";<br> b.Source = SourceObject;<br> BindingExpressionBase e = this.SetBinding(TargetProperty, b); </p></li> <li><p>The source property then gets changed as a result of another databinding. The UserControl tries to fire the PropertyChanged event.</p></li> <li><p>....but nobody is listening. PropertyChanged is null.</p></li> </ul> <p>I am sure that nothing else is assigned to the target property, so it should still be bound. Why is the binding not listening for the PropertyChanged event?</p>
<p>Alright, I found the answer myself. This is a bug in Silverlight..</p> <p>The code that does the following </p> <pre><code>if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } </code></pre> <p>must be directly on the class that you bind to, not on its ancestor. I had it inside a FirePropertyChanged() method on a base class and moving it to the derived class made the difference.</p>
<p>For anyone else who is experiencing this: <strong>make sure you are implementing INotifyPropertyChanged on your ViewModel</strong>!</p>
36,012
<p>Can anybody have good answer when should be database driven development be used and when should domain driven development be used. These both development approach have their importance in their respected areas. But I am not so clear which approach is appropriate in what type of situation. Any recommendation?</p>
<p>First for some background, Martin Fowler actually described three different "patterns" in his book Patterns of Enterprise Arcitecture. Transaction Script, Active Record and Domain Model. DDD uses the domain model pattern for the overall architecture and describes a lot of practices and patterns to implement and design this model.</p> <p>Transaction script is an architecture where you don't have any layering. The same piece of code reads/writes the database, processes the data and handles the user interface.</p> <p>Active Record is one step up from that. You split off your UI, your business logic and data layer still live together in active record objects that are modeled after the database.</p> <p>A domain model decouples the business logic that lives in your model from your data-layer. The model knows nothing about the database.</p> <p>And now we come to the interesting part:<br> The cost of this added separation is of course extra work. The benefits are better maintainability and flexibility.<br> Transaction script is good when you have few or no business rules, you just want to do data-entry and have no verification steps or all the verification is implemented in the database.<br> Active record adds some flexibility to that. Because you decouple your UI you can for example reuse the layer beneath it between applications, you can easilly add some business rules and verification logic to the business objects. But because these are still tightly coupled to the database changes in the datamodel can be very expensive.<br> You use a domain model when you want to decouple your business logic from the database. This enables you to handle changing requirements easier. Domain Driven Design is a method to optimally use this added flexibility to implement complex solutions without being tied to a database implementation.</p> <p>Lots of tooling makes data-driven solutions easier. In the microsoft space it is very easy to visually design websites where all the code lives right behind the web-page. This is a typical transaction script solution and this is great to easilly create simple applications. Ruby on rails has tools that make working with active record objects easier. This might be a reason to go data-driven when you need to develop simpler solutions. For applications where behaviour is more important than data and it's hard to define all the behaviour up front DDD is the way to go.</p>
<p>Domain Driven Development is surely the way to go. it makes more sense and adds flexibility.</p>
39,747
<p>With common lisp and I am assuming the introspection properties. How can I add code to common lisp code that will tell me when a function is called and when has finished executing. I want to take any lisp code and this particular modification to the code. I figure with lisp's AST analysis, this should be possible.</p>
<p>You can use <a href="http://www.sbcl.org/manual/Function-Tracing.html" rel="nofollow noreferrer"><code>(trace function)</code></a> for a simple mechanism. For something more involved, here is a good discussion from <a href="http://groups.google.com/group/comp.lang.lisp/browse_thread/thread/75ddcdcc160508b0?pli=1" rel="nofollow noreferrer">comp.lang.lisp</a>.</p> <pre><code>[CL_USER]&gt; (defun fac (n) "Naïve factorial implementation" (if (&lt; 1 n) (* n (fac (- n 1))) 1)) FAC [CL_USER]&gt; (trace fac) ;; Tracing function FAC. (FAC) [CL_USER]&gt; (fac 5) 1. Trace: (FAC '5) 2. Trace: (FAC '4) 3. Trace: (FAC '3) 4. Trace: (FAC '2) 5. Trace: (FAC '1) 5. Trace: FAC ==&gt; 1 4. Trace: FAC ==&gt; 2 3. Trace: FAC ==&gt; 6 2. Trace: FAC ==&gt; 24 1. Trace: FAC ==&gt; 120 120 [CL_USER]&gt; </code></pre>
<p>Common lisp has a TRACE function that reports the function, arguments and resulting value of each call specified. Here is the doc page for Steel Bank's version, but you should find something similar in most implementations:</p> <p><a href="http://www.sbcl.org/manual/Function-Tracing.html" rel="nofollow noreferrer">http://www.sbcl.org/manual/Function-Tracing.html</a></p> <p>The system also includes a profiler: </p> <p><a href="http://www.sbcl.org/manual/Deterministic-Profiler.html" rel="nofollow noreferrer">http://www.sbcl.org/manual/Deterministic-Profiler.html</a></p>
28,674
<p>I've often read that corporations will save millions once Internet Explorer 6 is finally laid to rest, but reading quotes like that make me wonder just how much time people are spending on IE6 development. I'll be happy once IE6 goes, but I've found that if I write valid HTML and CSS, use a JavaScript framework, keep the transparent images issue in mind, and don't try to over-complicate my design, I only need to write a few lines of IE6-specific CSS, which usually takes about 10-15 minutes. So I'm curious, how much time, effort, and money do you or your corporation spend on preparing your sites for IE6? Also, at what point will you drop IE6 support? If you've already dropped support, what has been your experience in terms of saved time and money and what has the switch done to your conversion rates and customer satisfaction?</p>
<p>According to <a href="http://www.w3schools.com/browsers/browsers_stats.asp" rel="nofollow noreferrer">some</a> - <a href="http://www.adtech.info/news/pr-08-07_en.htm" rel="nofollow noreferrer">browser</a> - <a href="http://www.thecounter.com/stats/2008/September/browser.php" rel="nofollow noreferrer">statistics</a>, IE6 market share is still bigger than Chrome, Safari and Opera together, nearly as much as IE7.</p> <p>Unless you target a very specific market (indeed check your stats to know for sure), neglecting to make your site looking at least decent with IE6 seems a bit foolish today...</p> <p>I won't take the road to tell visitors what browser to use, for sure!</p>
<p>Unfortunately, I have a bunch of friends in other businesses that are sticking with IE6, and don't have a plan to upgrade.</p> <p>They don't like the tabs in IE7, they don't want to go with another browser, etc, etc, etc.</p> <p>There is enough of this that filters back to me, that I continue to test against IE6, and will do so for the indefinite future. Doesn't make me happy...just do it.</p>
25,624
<p>I come from a Java background, where packages are used, not namespaces. I'm used to putting classes that work together to form a complete object into packages, and then reusing them later from that package. But now I'm working in C++.</p> <p>How do you use namespaces in C++? Do you create a single namespace for the entire application, or do you create namespaces for the major components? If so, how do you create objects from classes in other namespaces?</p>
<p>Namespaces are packages essentially. They can be used like this:</p> <pre><code>namespace MyNamespace { class MyClass { }; } </code></pre> <p>Then in code:</p> <pre><code>MyNamespace::MyClass* pClass = new MyNamespace::MyClass(); </code></pre> <p>Or, if you want to always use a specific namespace, you can do this:</p> <pre><code>using namespace MyNamespace; MyClass* pClass = new MyClass(); </code></pre> <p><strong>Edit:</strong> Following what <a href="https://stackoverflow.com/questions/41590/how-do-you-properly-use-namespaces-in-c#41624">bernhardrusch</a> has said, I tend not to use the "using namespace x" syntax at all, I usually explicitly specify the namespace when instantiating my objects (i.e. the first example I showed).</p> <p>And as you asked <a href="https://stackoverflow.com/questions/41590/how-do-you-properly-use-namespaces-in-c#41615">below</a>, you can use as many namespaces as you like.</p>
<p>std :: cout</p> <p>The prefix std:: indicates that the names cout and endl are defined inside the namespace named std. Namespaces allow us to avoidinadvertent collisions between the names we define and uses of those same names inside a library. All the names defined by the standard library are in the stdnamespace. Writing std:: cout uses the scope operator (the ::operator) to saythat we want to use the name cout that is defined in the namespace std. will show a simpler way to access names from the library.</p>
6,292
<p>as a follow up on my <a href="https://stackoverflow.com/questions/318208/cast-to-combined-generic">previous question</a> Having a function with combined generic bounds such as:</p> <pre><code>&lt;T extends Foo &amp; Bar&gt; void doStuff(T argument) { //do stuff wich should only be done if arguments is both foo and bar } </code></pre> <p>Because this is not castable from a unspecified object, you need to have knowledge of some object which actually implements these interfaces. it seems to me that needing to know the specific type of the object argument to pass to <code>doStuff(T a)</code> is a violation of Demeter's law.</p> <p>The function doesn't specify the need to know the actual class (there could be many different ones), and i really don't want to know it as knowing this class increases the dependency in my code base.</p> <p>is using these bounds an anti pattern? and if so how should one best avoid it?</p> <p>the case scenario involved one interface specifying the object is persistent and the other specified object having a related entity. the <code>doStuff(T a)</code> function in this case persisted the related entity when it was persisted. however nonpersistent entities can also have a related entity, but should not be processed by the <code>doStuff(T a)</code> function</p>
<p>I wouldn't consider combined generic bounds an anti-pattern. At least I've got some uses for them in my code. For instance, the following sample code finds the biggest Number instance in a collection using compareTo from the Comparable interface:</p> <pre><code>&lt;T extends Number &amp; Comparable&lt;T&gt;&gt; T max(Collection&lt;T&gt; numbers) </code></pre>
<p>The anti-pattern is casting.</p> <p>However, fancy generics footwork may be confusing to non-advanced programmers. Usage of such types and method should be much easier than their implementation.</p>
41,419
<p>Over the last few months/years, I have shared a folder or two with numerous people on my domain. How do I easily revoke those shares to keep access to my system nice and tidy?</p>
<p>Using computer management (an MMC snap-in. See Control Panel Administrative tools) you can see a list of all folders that are shared. You could delete the shares or change the permissions on the share to only allow access for certain people or groups.</p>
<p>On Windows XP, go to:</p> <pre><code>Administrative Tools &gt; Computer Management &gt; System Tools &gt; Shared Folders &gt; Shares </code></pre> <p>This page lists all shares and lets you remove them easily, in one place.</p>
4,583
<p>I need to show only one element at a time when a link is clicked on. Right now I'm cheating by hiding everything again and then toggling the element clicked on. This works, unless i want EVERYTHING to disappear again. Short of adding a "Hide All" button/link what can i do? I would like to be able to click on the link again, and hide it's content.</p> <p>EDIT: Pseudo's code would have worked, but the html here mistakenly led you to believe that all the links were in one div. instead of tracking down where they all were, it is easier to call them by their ID.</p> <p>Here's what I have so far:</p> <pre><code>$(document).ready(function(){ //hides everything $("#infocontent *").hide(); //now we show them by which they click on $("#linkjoedhit").click(function(event){ $("#infocontent *").hide(); $("#infojoedhit").toggle(); return false; }); $("#linkgarykhit").click(function(event){ $("#infocontent *").hide(); $("#infogarykhit").toggle(); return false; }); }); </code></pre> <p>and the html looks like:</p> <pre><code>&lt;div id="theircrappycode"&gt; &lt;a id="linkjoedhit" href=""&gt;Joe D&lt;/a&gt;&lt;br/&gt; &lt;a id="linkgarykhit" href=""&gt;Gary K&lt;/a&gt; &lt;/div&gt; &lt;div id="infocontent"&gt; &lt;p id="infojoedhit"&gt;Information about Joe D Hitting.&lt;/p&gt; &lt;p id="infogarykhit"&gt;Information about Gary K Hitting.&lt;/p&gt; &lt;/div </code></pre> <p>there are about 20 links like this. Because I am not coding the actual html, I have no control over the actual layout, which is horrendous. Suffice to say, this is the only way to organize the links/info.</p>
<pre><code>$("#linkgarykhit").click(function(){ if($("#infogarykhit").css('display') != 'none'){ $("#infogarykhit").hide(); }else{ $("#infocontent *").hide(); $("#infogarykhit").show(); } return false; }); </code></pre> <hr> <p>We could also <a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself" rel="nofollow noreferrer">DRY</a> this up a bit:</p> <pre><code>function toggleInfoContent(id){ if($('#' + id).css('display') != 'none'){ $('#' + id).hide(); }else{ $("#infocontent *").hide(); $('#' + id).show(); } } $("#linkgarykhit").click(function(){ toggleInfoContent('infogarykhit'); return false; }); $("#linkbobkhit").click(function(){ toggleInfoContent('infobobkhit'); return false; }); </code></pre>
<p>I just started with <code>jQuery</code>, so I don't know if this is dumb or not.</p> <pre><code>function DoToggleMagic(strParagraphID) { strDisplayed = $(strParagraphID).css("display"); $("#infocontent *").hide(); if (strDisplayed == "none") $(strParagraphID).toggle(); } $(document).ready(function(){ //hides everything $("#infocontent *").hide(); //now we show them by which they click on $("#linkjoedhit").click(function(event){ DoToggleMagic("#infojoedhit"); return false; }); $("#linkgarykhit").click(function(event){ DoToggleMagic("#infogarykhit"); return false; }); }); </code></pre>
20,387
<p>For some reason when I attempt to make a request to an Ajax.net web service with the ScriptService attribute set, an exception occurs deep inside the protocol class which I have no control over. Anyone seen this before?</p> <p>Here is the exact msg: System.IndexOutOfRangeException: Index was outside the bounds of the array. at System.Web.Services.Protocols.HttpServerType..ctor(Type type) at System.Web.Services.Protocols.HttpServerProtocol.Initialize() at System.Web.Services.Protocols.ServerProtocol.SetContext(Type type, HttpContext ontext, HttpRequest request, HttpResponse response) at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean&amp; abortProcessing)</p> <p>thx Trev</p>
<p>This is usually an exception while reading parameters into the web service method...are you sure you're passing the number/type of parameters the method is expecting?</p>
<p>Also make sure your web.config is setup properly for asp.net ajax:</p> <p><a href="https://web.archive.org/web/20080914214955/http://asp.net/ajax/documentation/live/ConfiguringASPNETAJAX.aspx" rel="nofollow noreferrer">http://www.asp.net/AJAX/Documentation/Live/ConfiguringASPNETAJAX.aspx</a></p>
11,207
<p>My 3D printer makes weird sounds. When it's at >75% printing speed the extruder motor makes a "tac tac" sound and it goes backwards, pushing the filament back, for a small interval of time. I have tried changing the nozzle temperature and I'm unable to work this out alone. </p> <p>Has someone had the same problem?</p> <p>This is the 3D printer: <a href="http://www.dx.com/es/p/geeetech-high-quality-wood-geeetech-prusa-i3-pro-w-3d-printer-kit-469707?tc=EUR" rel="noreferrer">Geeetech High Quality Wood Geeetech Prusa I3 Pro W 3D Printer Kit</a>.</p>
<p>@Ecnerwal is right: that noise you hear is the extruder not being able to push the filament, and the stepper can't push any harder. When the extruder tries to push harder than it can, it gives up, and the "spring" tension it created in the filament forces it to go backwards a tiny bit. Then it tries again.</p> <p>Possible causes/fixes:</p> <ul> <li><p>Temperature too low -- this makes the filament not liquid enough to push through the nozzle easily. For ABS, you should be in the 230-240 range.</p></li> <li><p>Clogged nozzle -- take the nozzle off (while hot) and try heating it with a torch to burn out anything that might be in there.</p></li> <li><p>Bad filament -- If the filament has contamination in it, or is too large to fit through the hot end in places (I.E. it gets up to 1.9mm instead of 1.75mm)</p></li> <li><p>Stepper current too low -- I'm not sure if you can adjust the current that is sent to your stepper motors, but if it is too low, the stepper can not provide enough torque to push the filament through. I don't see the stepper drivers on the site, so I don't know if you can adjust them or not.</p></li> </ul>
<p>It could be a result of filament building up around the drive gear.</p> <ul> <li>disassemble your extruder to expose the drive gear (the gear that drives the filament down to the heat element). </li> <li>clean any filament build-up out of the the teeth.</li> </ul> <p>Filament can sometimes build up around the gear over time when the extruder temp is not high enough to efficiently melt the filament. This occurs more commonly with ABS I've noticed, probably partly due to its higher heat resistance. However, this affect is ultimately an issue of poor quality filament (aka cheap).</p>
636
<p>I am aware of <a href="http://cocoamysql.sourceforge.net/" rel="noreferrer">CocoaMySQL</a> but I have not seen a Mac GUI for SQLite, is there one?</p> <p>My Google search didn't turn up any Mac related GUI's which is why I'm asking here rather than Google.</p>
<p><a href="https://addons.mozilla.org/en-US/firefox/addon/5817" rel="noreferrer">SQLite Manager for FireFox</a></p>
<p>Razorsql can handle many kinds of databases.</p>
12,625
<p>I made previously a question: <a href="https://stackoverflow.com/questions/236354/error-handling-when-taking-user-input">error handling when taking user input</a></p> <p>and I made the suggested changes:</p> <pre><code>char displayMainMenu() { char mainMenuChoice; cout &lt;&lt; "\nQuadratic equation: a*X^2 + b*X + c = 0 main menu: "; cout &lt;&lt; "\n &lt;r&gt; Give new coefficients"; cout &lt;&lt; "\n &lt;c&gt; Calculate equations solutions"; cout &lt;&lt; "\n &lt;t&gt; Terminate the program"; cout&lt;&lt;"Enter choice : "; cin&gt;&gt;mainMenuChoice; return mainMenuChoice; } int main() { bool done = false; while(!done) { char choice = displayMainMenu(); switch(tolower(choice)) { case 'r': cout&lt;&lt;"Entered case 'r'"; break; case 'c': cout&lt;&lt;"Entered case 'c'"; break; case 't': cout&lt;&lt;"Entered case 't'"; break; default: cout&lt;&lt;"Invalid choice! Try again"&lt;&lt;endl; } } return 0; } </code></pre> <p>The new problem is that if the user enters by mistake lets say "ter" i get the following :( :</p> <pre><code>Quadratic equation: a*X^2 + b*X + c = 0 main menu: &lt;r&gt; Give new coefficients &lt;c&gt; Calculate equations solutions &lt;t&gt; Terminate the program Enter choice : ter Entered case 't' Quadratic equation: a*X^2 + b*X + c = 0 main menu: &lt;r&gt; Give new coefficients &lt;c&gt; Calculate equations solutions &lt;t&gt; Terminate the program Enter choice : Invalid choice! Try again Quadratic equation: a*X^2 + b*X + c = 0 main menu: &lt;r&gt; Give new coefficients &lt;c&gt; Calculate equations solutions &lt;t&gt; Terminate the program Enter choice : Invalid choice! Try again </code></pre> <p>How could I avoid this from happening??</p>
<p>In your <code>displayMainMenu()</code> function, instead of reading in a <code>char</code>, read in a string. Throw out (with a warning) any input that is greater than one character in length.</p> <p>You can use</p> <pre><code>char str[101] std::cin.getline(str, 101); </code></pre> <p>in place of </p> <pre><code>cin &gt;&gt; mainMenuChoice; </code></pre> <p>in order to read the string.</p>
<p>Try this:</p> <pre><code>string displayMainMenu() { string mainMenuChoice; cout &lt;&lt; "\nQuadratic equation: a*X^2 + b*X + c = 0 main menu: "; cout &lt;&lt; "\n &lt;r&gt; Give new coefficients"; cout &lt;&lt; "\n &lt;c&gt; Calculate equations solutions"; cout &lt;&lt; "\n &lt;t&gt; Terminate the program"; cout &lt;&lt; "\nEnter choice : "; getline(cin, mainMenuChoice); return mainMenuChoice; } int main() { bool done = false; while(!done) { string choice = displayMainMenu(); if (choice.size() &gt; 1 || choice.size() &lt; 0) cout&lt;&lt;"Invalid choice! Try again"&lt;&lt;endl; switch(tolower(choice[0])) { case 'r': cout&lt;&lt;"Entered case 'r'"; break; case 'c': cout&lt;&lt;"Entered case 'c'"; break; case 't': cout&lt;&lt;"Entered case 't'"; break; default: cout&lt;&lt;"Invalid choice! Try again"&lt;&lt;endl; } } return 0; } </code></pre> <p>Use getline(istream, string &amp;) to read in a full line at a time (not including the eol). Check that it's the right length, and then look at only the first character.</p>
29,263
<p>i tried the following</p> <ol> <li><code>svnadmin create svn_repos</code></li> <li><code>svn import my_first_proj file:///c:/svn_repos -m "initial import"</code></li> <li><code>svn checkout file:///c:/svn_repos</code></li> </ol> <p>and the command returned</p> <pre><code>A svn_repos\trunk A svn_repos\trunk\Sample.txt.txt A svn_repos\branches A svn_repos\branches\my_pers_branch Checked out revision 1. </code></pre> <p>Yet the <code>.svn</code> folder was not created in the checked out folders. Because of which [I guess], I'm not able to do <code>svn copy</code> or <code>svn merge</code>.</p> <p>Why does this occur? what is the problem? is there anything wrong in my commands</p>
<p>Perhaps you're expecting to find that .svn directory inside the my_first_proj directory. Currently, your svn is checked out inside a "svn_repos" directory, relative to the path you typed in the checkout command. What you may want to do is :</p> <pre><code>svn checkout --force file:///c:/svn_repos/ my_first_proj </code></pre> <p>Which checks out a repository inside an existing directory. The usual approach is to checkout to another directory the first time, though.</p>
<p>Please provide some more details:</p> <p>What directory are you in when you perform each command?</p> <p>It looks to me like you may be checking out your project into the repository itself?</p> <p>Also, what operating system are you using?</p>
35,049
<p>Please help!</p> <p><em>Background info</em></p> <p>I have a WPF application which accesses a SQL Server 2005 database. The database is running locally on the machine the application is running on.</p> <p>Everywhere I use the Linq DataContext I use a using { } statement, and pass in a result of a function which returns a SqlConnection object which has been opened and had an SqlCommand executed using it before returning to the DataContext constructor.. I.e.</p> <pre><code>// In the application code using (DataContext db = new DataContext(GetConnection())) { ... Code } </code></pre> <p>where getConnection looks like this (I've stripped out the 'fluff' from the function to make it more readable, but there is no additional functionality that is missing).</p> <pre><code>// Function which gets an opened connection which is given back to the DataContext constructor public static System.Data.SqlClient.SqlConnection GetConnection() { System.Data.SqlClient.SqlConnection Conn = new System.Data.SqlClient.SqlConnection(/* The connection string */); if ( Conn != null ) { try { Conn.Open(); } catch (System.Data.SqlClient.SqlException SDSCSEx) { /* Error Handling */ } using (System.Data.SqlClient.SqlCommand SetCmd = new System.Data.SqlClient.SqlCommand()) { SetCmd.Connection = Conn; SetCmd.CommandType = System.Data.CommandType.Text; string CurrentUserID = System.String.Empty; SetCmd.CommandText = "DECLARE @B VARBINARY(36); SET @B = CAST('" + CurrentUserID + "' AS VARBINARY(36)); SET CONTEXT_INFO @B"; try { SetCmd.ExecuteNonQuery(); } catch (System.Exception) { /* Error Handling */ } } return Conn; } </code></pre> <p><strong>I do not think that the application being a WPF one has any bearing on the issue I am having.</strong></p> <p><em>The issue I am having</em> </p> <p>Despite the SqlConnection being disposed along with the DataContext in Sql Server Management studio I can still see loads of open connections with :</p> <pre><code>status : 'Sleeping' command : 'AWAITING COMMAND' last SQL Transact Command Batch : DECLARE @B VARBINARY(36); SET @B = CAST('GUID' AS VARBINARY(36)); SET CONTEXT_INFO @B </code></pre> <p>Eventually the connection pool gets used up and the application can't continue. </p> <p>So I can only conclude that somehow running the SQLCommand to set the Context_Info is meaning that the connection doesn't get disposed of when the DataContext gets disposed. </p> <p>Can anyone spot anything obvious that would be stopping the connections from being closed and disposed of when the DataContext they are used by are disposed?</p>
<p>From <a href="http://msdn.microsoft.com/en-us/library/bb292288.aspx" rel="noreferrer">MSDN</a> (<code>DataContext Constructor (IDbConnection)</code>):</p> <blockquote> <p>If you provide an open connection, the DataContext will not close it. Therefore, do not instantiate a DataContext with an open connection unless you have a good reason to do this.</p> </blockquote> <p>So basically, it looks like your connections are waiting for GC to finalize them before they will be released. If you have lots of code that does this, one approach might be to overide <code>Dispose()</code> in the data-context's partial class, and close the connection - just be sure to document that the data-context assumes ownership of the connection!</p> <pre><code> protected override void Dispose(bool disposing) { if(disposing &amp;&amp; this.Connection != null &amp;&amp; this.Connection.State == ConnectionState.Open) { this.Connection.Close(); this.Connection.Dispose(); } base.Dispose(disposing); } </code></pre> <p>Personally, I would happily give it (regular data-context, w/o the hack above) an open connection as long as I was "using" the connection (allowing me to perform multiple operations) - i.e.</p> <pre><code>using(var conn = GetConnection()) { // snip: some stuff involving conn using(var ctx = new FooContext(conn)) { // snip: some stuff involving ctx } // snip: some more stuff involving conn } </code></pre>
<p>The <code>Dispose</code> should close the connections, as <a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.close.aspx" rel="nofollow noreferrer">MSDN</a> points out:</p> <blockquote> <p>If the SqlConnection goes out of scope, it won't be closed. Therefore, you must explicitly close the connection by calling Close or Dispose. Close and Dispose are functionally equivalent. If the connection pooling value Pooling is set to true or yes, the underlying connection is returned back to the connection pool. On the other hand, if Pooling is set to false or no, the underlying connection to the server is closed.</p> </blockquote> <p>My guess would be that your problem has something to do with <code>GetContext()</code>.</p>
33,767
<p>I am stress testing a .NET web application. I did this for 2 reasons: I wanted to see what performance was like under real world conditions and also to make sure we hadn't missed any problems during testing. We had 30 concurrent users in the application using it as they would during the normal course of their jobs. Most users had multiple windows of the application open.</p> <ul> <li>10 Users: Not bad</li> <li>20 Users: Slowing down </li> <li>30 Users: Very, very slow but no timeouts</li> </ul> <p>It was loaded on the production server. It is a virtual server with a 2.66G Hz Xeon processor and 2 GB of RAM. We are using Win2K3 SP2. We have .NET 1.1 and 2.0 loaded and are using SQLExpress SP1.</p> <p>We rechecked the indexes on all of the tables afterword and they were all as they should be.</p> <p>How can we improve our application's performance?</p>
<p>This is just something that I thought of, but check to see how much memory SQL Server is using when you have 20+ users - one of the limitations of the Express version is that it is <a href="http://www.microsoft.com/sql/prodinfo/features/compare-features.mspx" rel="nofollow noreferrer">limited to 1GB of RAM</a>. So it might just be a simple matter of there not being enough memory available to to server due to the limitations of Express.</p>
<p>Update: Looks like SQL Server express is not the problem as they were using the same product in previous version of the application. I think your next step is in identifying the bottlenecks. If you are sure it is in the database layer, I would recommend taking a profiler trace and bringing down the execution time of the most expensive queries.</p> <p>This is another link I use for collecting statistics from SQL Server Dynamic Management Views (DMVs) and related Dynamic Management Functions (DMFs). Not sure if we can use in the Express edition. <a href="http://msdn.microsoft.com/en-us/magazine/cc135978.aspx" rel="nofollow noreferrer">Uncover Hidden Data to Optimize Application Performance</a>.</p> <hr> <p>Are you using SQL Server Express for a web app? As far as I know, it has some limitations for production deployment.</p> <p><a href="http://msdn.microsoft.com/en-us/library/ms144275.aspx" rel="nofollow noreferrer">SQL Server Express</a> is free and can be redistributed by ISV's (subject to agreement). <strong>SQL Server Express is</strong> <strong>ideal for learning and building desktop and small server applications</strong>. This edition is the best choice for independent software vendors, non-professional developers, and hobbyists building client applications. If you need more advanced database features, SQL Server Express can be seamlessly upgraded to more sophisticated versions of SQL Server.</p>
8,352
<p>I am trying to use <code>ResourceBundle#getStringArray</code> to retrieve a <code>String[]</code> from a properties file. The description of this method in the documentation reads:</p> <blockquote> <p>Gets a string array for the given key from this resource bundle or one of its parents.</p> </blockquote> <p>However, I have attempted to store the values in the properties file as multiple individual key/value pairs:</p> <pre><code>key=value1 key=value2 key=value3 </code></pre> <p>and as a comma-delimited list:</p> <pre><code>key=value1,value2,value3 </code></pre> <p>but neither of these is retrievable using <code>ResourceBundle#getStringArray</code>.</p> <p>How do you represent a set of key/value pairs in a properties file such that they can be retrieved using <code>ResourceBundle#getStringArray</code>?</p>
<p>A <code>Properties</code> object can hold <strong><code>Object</code>s</strong>, not just <code>String</code>s. That tends to be forgotten because they're overwhelmingly used to load .properties files, and so often will only contain <code>String</code>s. <a href="https://web.archive.org/web/20081217073139/http://java.sun.com/j2se/1.4.2/docs/api/java/util/ResourceBundle.html#getStringArray(java.lang.String)" rel="nofollow noreferrer">The documentation</a> indicates that calling <code>bundle.getStringArray(key)</code> is equivalent to calling <code>(String[]) bundle.getObject(key)</code>. That's the problem: the value isn't a <code>String[]</code>, it's a <code>String</code>.</p> <p>I'd suggest storing it in comma-delimited format and calling <code>split()</code> on the value.</p>
<pre><code>key=value1;value2;value3 String[] toArray = rs.getString("key").split(";"); </code></pre>
27,943
<p>I've seen both done in some code I'm maintaining, but don't know the difference. Is there one?</p> <p>let me add that myCustomer is an instance of Customer</p>
<p>The result of both are exactly the same in your case. It will be your custom type that derives from <code>System.Type</code>. The only real difference here is that when you want to obtain the type from an instance of your class, you use <code>GetType</code>. If you don't have an instance, but you know the type name (and just need the actual <code>System.Type</code> to inspect or compare to), you would use <code>typeof</code>.</p> <h3>Important difference</h3> <p>EDIT: Let me add that the call to <code>GetType</code> gets resolved at runtime, while <code>typeof</code> is resolved at compile time.</p>
<p>The typeof operator takes a type as a parameter. It is resolved at compile time. The GetType method is invoked on an object and is resolved at run time. The first is used when you need to use a known Type, the second is to get the type of an object when you don't know what it is.</p> <pre><code>class BaseClass { } class DerivedClass : BaseClass { } class FinalClass { static void RevealType(BaseClass baseCla) { Console.WriteLine(typeof(BaseClass)); // compile time Console.WriteLine(baseCla.GetType()); // run time } static void Main(string[] str) { RevealType(new BaseClass()); Console.ReadLine(); } } // ********* By Praveen Kumar Srivastava </code></pre>
16,886
<p>I have committed, and pushed, several patches: A1-->A2-->A3-->A4 (HEAD)</p> <p>Everyone's pulled these changesets into their local copy.</p> <p>Now we want to "roll back" to A2, and continue developing from there - essentially throwing away A3 and A4. What's the best way to do this?</p>
<p>From the root directory of your working copy just do</p> <pre><code>git checkout A2 -- . git commit -m 'going back to A2' </code></pre> <hr> <p>Using <a href="http://www.kernel.org/pub/software/scm/git/docs/git-revert.html" rel="noreferrer"><code>git revert</code></a> for this purpose would be cumbersome, since you want to get rid of a whole series of commits and <code>revert</code> undoes them one at a time.</p> <p>You do not want <a href="http://www.kernel.org/pub/software/scm/git/docs/git-revert.html" rel="noreferrer"><code>git reset</code></a> either. That will merely change your <code>master</code> branch pointer: you are left with no record of the mistaken direction. It is also a pain to coordinate: since the commit you changed <code>master</code> to is not a child of the remote repository’s <code>master</code> branch pointer, pushing will fail – unless you add <code>-f</code> (force) or delete the <code>master</code> branch in the remote repository first and recreate it by pushing. But then everyone who tries to pull will still have the old history in their local <code>master</code> branch, so once <code>origin/master</code> diverges, <code>git pull</code> will try to perform a merge. This is not the end of the world: they can get out of this situation by doing <code>git rebase --onto origin/master $old_origin_master_commit master</code> (ie. rebase their local commits made on top of the old <code>origin/master</code> onto the top of the new <code>origin/master</code>). But Git will not know to do this automatically so you have to coordinate with every collaborator. In short, don’t do that.</p>
<p>You want <code>git-revert</code> <strike>and <code>git-reset</code> depending on how you want to treat A3 and A4. To remove all trace of A3 and A4, use <code>git-reset --hard</code>.</strike> To keep A3 and A4 and record the fact you are reverting, use <code>git-revert</code>. </p> <p><strong>edit</strong>: Aristotle Pagaltzis's <code>git-checkout</code> solution is superior, though for small reverts I don't see a problem with <code>git-revert</code>. None the less, I ask future upvotes be given to <a href="https://stackoverflow.com/questions/218023/rolling-back-in-git#221137">Aristotle Pagaltzis's answer</a></p> <p>I found <a href="http://www-cs-students.stanford.edu/~blynn/gitmagic/" rel="nofollow noreferrer">git magic</a> to be a good resource for git.</p>
26,810
<p>I'm not a C++ developer, but I've always been interested in compilers, and I'm interested in tinkering with some of the GCC stuff (particularly LLVM).</p> <p>On Windows, GCC requires a POSIX-emulation layer (cygwin or MinGW) to run correctly.</p> <p>Why is that?</p> <p>I use lots of other software, written in C++ and cross-compiled for different platforms (Subversion, Firefox, Apache, MySQL), and none of them require cygwin or MinGW.</p> <p>My understanding about C++ best-practice programming is that you can write reasonably platform-neutral code and deal with all the differences during the compilation process.</p> <p>So what's the deal with GCC? Why can't it run natively on Windows?</p> <hr> <p>EDIT:</p> <p>Okay, the two replies so far say, basically, "GCC uses the posix layer because it uses the posix headers".</p> <p>But that doesn't really answer the question.</p> <p>Let's say I already have a set of headers for my favorite standard library. Why would I still need the posix headers?</p> <p>Does GCC require cygwin/mingw to actually <em>RUN</em>?</p> <p>Or does it only need the emulation layer for headers and libraries? If so, why can't I just give it a "lib" directory with the required resources?</p> <hr> <p>EDIT AGAIN:</p> <p>Okay, I'll try again to clarify the question...</p> <p>I also write code in <a href="http://digitalmars.com/d" rel="noreferrer">the D Programming Language</a>. The official compiler is named "dmd" and there are official compiler binaries for both Windows and linux.</p> <p>The Windows version doesn't require any kind of POSIX emulation. And the Linux version doesn't require any kind of Win32 emulation. If the compiler has assumptions about its environment, it hides those assumptions pretty well.</p> <p>Of course, I have to tell the compiler where to find the standard library and where to find libraries to statically or dynamically link against.</p> <p>GCC, by contrast, insists on pretending it's operating within a posix environment, and it asks ME to humor those assumptions by setting up an emulation layer.</p> <p>But what, exactly, within GCC relies on that layer? Is it just looking for stdlib headers, and it assumes it'll find those headers within "/usr/lib"?</p> <p>If that's the case, shouldn't I just be able to tell it to look in "C:/gcc/lib" to find those header files?</p> <p>Or does GCC itself rely on the POSIX libraries to access the file system (and to do other low-level stuff)? If that's the case, then I wonder why they don't just statically link with their favorite windows POSIX libraries. Why require the user to set up the dependencies, when they could build those dependencies right into the application?</p>
<p>Actually, the question premise is wrong: <a href="http://www.mingw.org/" rel="noreferrer">MinGW</a> GCC does <strong>NOT</strong> require Cygwin.</p> <p>You will see you don't need Cygwin at all. It runs natively on Windows (32-bit, at least). Both the toolchain and the produced binaries are independent of Cygwin.</p> <p>The MinGW compilers available in Cygwin are different: they are built on the Cygwin platform, to generate code which does not depend on the Cygwin runtime. The compilers themselves do depend on Cygwin in that case. But that's because you installed them from Cygwin.</p>
<p>Because the people behing GCC hate Windows with a passion (read Stallman some day). So when porting GCC to Windows, they do their best to pretend it's just another Unix.</p> <p>That, and they probably don't want to spend time on removing POSIX dependencies from the code.</p>
22,783
<p>I'm setting up my first site using the asp authentication provider and using the built in asp.net login control.</p> <p>My question, is the password encrypted or hashed as it's sent to the server using the asp.net login control? or do I need to use https/ssl to accomplish this?</p> <p>Thanks</p>
<p>Go with HTTPS.</p> <p>Per <a href="http://msdn.microsoft.com/en-us/library/ms178329.aspx" rel="noreferrer">MSDN</a>, "By default, the ASP.NET login controls work in plain text over HTTP. If you are concerned about security, use HTTPS with SSL encryption."</p>
<p>The any text based data is sent as is to the server regardless of the language used by the server as this is controlled by the HTML Framework. You can create a Javascript encryption or hash algorith and use that prior to submitting the form data.</p> <p>However the most secure method would be to use HTTPS.</p>
27,595
<p>What are the differences between these two and which one should I use?</p> <pre><code>string s = &quot;Hello world!&quot;; String s = &quot;Hello world!&quot;; </code></pre>
<p><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/string" rel="noreferrer"><code>string</code></a> is an alias in C# for <a href="https://learn.microsoft.com/en-us/dotnet/api/system.string" rel="noreferrer"><code>System.String</code></a>.<br /> So technically, there is no difference. It's like <a href="https://stackoverflow.com/questions/62503/c-int-or-int32-should-i-care"><code>int</code> <em>vs.</em> <code>System.Int32</code></a>.</p> <p>As far as guidelines, it's generally recommended to use <code>string</code> any time you're referring to an object.</p> <p>e.g.</p> <pre><code>string place = &quot;world&quot;; </code></pre> <p>Likewise, I think it's generally recommended to use <code>String</code> if you need to refer specifically to the class.</p> <p>e.g.</p> <pre><code>string greet = String.Format(&quot;Hello {0}!&quot;, place); </code></pre> <h3>This is the style that Microsoft tends to use in <a href="https://learn.microsoft.com/en-us/dotnet/api/system.string.format#examples" rel="noreferrer">their examples</a>.</h3> <p>It appears that the guidance in this area may have changed, as <a href="https://github.com/StyleCop" rel="noreferrer">StyleCop</a> now enforces the use of the C# specific aliases.</p>
<p>There are at least 4 differences:</p> <p>1- string is a reserved word, but String is just a class name. This means that string cannot be used as a variable name by itself.</p> <p>2- you can't use String without &quot;using System&quot;.so you write less code by using &quot;string&quot;.</p> <p>3- 'String' is better naming convention than 'string', as it is a type not variable.</p> <p>4- &quot;string&quot; is a C# keyword and syntax highlighted in most coding editors, but not &quot;String&quot;.</p>
2,871
<p>I once heard a prominent scientist say, of global warming, that he didn't realize how much he would have to learn about politics.</p> <p>I just read an excellent article in DDJ about the <a href="http://en.wikipedia.org/wiki/Jacobsen_v._Katzer" rel="nofollow noreferrer">Jacobsen verus Katzer</a> case. When in university, I didn't know how much <strong><em>I</em></strong> would have to learn about the law.</p> <p>It seems to me that a big hole in the classic comp sci education is that of legal issues. Many of us talk about licenses, copyright, copyleft, prior art, etc, but our terms are often vague and probably inaccurate.</p> <p>What are some resources where the average developer can learn about copyright law and become an informed citizen of IT? </p>
<p><a href="http://www.groklaw.net/" rel="nofollow noreferrer">groklaw</a> would seem to be a good starting point for open source issues</p>
<p>The Nolo book <em>Legal Guide to Web &amp; Software Development</em> discusses copyright and other issues as they pertain to software developers.</p> <p><a href="https://rads.stackoverflow.com/amzn/click/com/1413305326" rel="nofollow noreferrer" rel="nofollow noreferrer">http://www.amazon.com/Legal-Guide-Software-Development-CD-Rom/dp/1413305326/</a></p>
26,447
<p>near the top of the code i see things like, </p> <p>btn_dropdown._visible = false; mcMenuBkg._visible = false;</p> <p>but I can't find these assets anywhere in the library or in any code, how does this make any sense?</p> <p>The movie clips in the library that look the same have different names and I can delete them entirely and they still show up when I compile and run, or I can add trace statements into their code and they never get called.</p> <p>where on earth are these assets defined?</p>
<p>In theory, any clip you see at runtime could be dynamically created, by making an empty MC and drawing in whatever contents you like with the drawing API. However, if you see clips in the library that are similar to what's showing up at runtime, then it's very unlikely that that's happening.</p> <p>Your first step should probably be another look through the library. Remember that instance names don't have to be the same as MC names; even if something is called "Menu Holder" in the library there might be an instance of it somewhere called "mcMenuBkg" or whatever. But the fact that you can delete stuff without changing the output is mysterious.</p> <p>So, other possibilities: contents are being loaded externally, or imported via runtime sharing. If feasible, try moving your SWF to a temp directory and running it from there; that should break all loads (unless contents are loaded from a remote URL).</p> <p>Or, you're looking at the wrong clips in the library. If it's a crufty project there may be unused stuff in there. Try expanding the library wide enough to see the "Use count" column, and select "update use counts" from the library menu. Anything with a count of 1 or higher is part of your FLA's stage content - either it's sitting on the main stage or it's a child of something that is. Clips with a use count of 0 may still be used if they have a linkage ID; they could be created at runtime with <code>attachMovie()</code>. However, for any clip with a use count of 0 and no linkage id, it's safe to assume that it's unused, and irrelevant to what happens at runtime.</p> <p>If none of that helps, the only things that come to mind are sanity checks... open up everything on the stage and every clip with a linkage id, and check for empty/invisible MCs. Check the Movie's export settings to make absolutely sure the SWF you're checking is the same one being published. And just for grins, open up the "Scenes" panel and make sure that some diabolical fiend hasn't put important content on a separate scene where no sane man would look for it.</p> <p>Vague answer for a vague question. :D Hope it helps...</p>
<p>You can create movie clips with code dynamically.</p> <p>This means that you may not have them in your assets if you are unable to find them.</p> <p>You can create any type of symbol using a constructor out of thin air with actionscript alone.</p> <p>I would search the code for one of these</p> <pre><code>var mybutton:SimpleButton=new SimpleButton(); </code></pre>
28,498
<p>I know you can put &lt;% if %> statements in the ItemTemplate to hide controls but the column is still there. You cannot put &lt;% %> statements into the LayoutTemplate which is where the column headings are declared, hence the problem. Does anyone know of a better way?</p>
<p>Here's another solution that I just did, seeing that I understand what you want to do:</p> <p><strong>Here's your ASCX / ASPX</strong></p> <pre><code> &lt;asp:ListView ID="ListView1" runat="server" DataSourceID="MyDataSource" ItemPlaceholderID="itemPlaceHolder" OnDataBound="ListView1_DataBound"&gt; &lt;LayoutTemplate&gt; &lt;table border="1"&gt; &lt;tr&gt; &lt;td&gt;Name&lt;/td&gt; &lt;td&gt;Age&lt;/td&gt; &lt;td runat="server" id="tdIsSuperCool"&gt;IsSuperCool&lt;/td&gt; &lt;/tr&gt; &lt;asp:PlaceHolder ID="itemPlaceHolder" runat="server" /&gt; &lt;/table&gt; &lt;/LayoutTemplate&gt; &lt;ItemTemplate&gt; &lt;tr&gt; &lt;td&gt;&lt;%# Eval("Name") %&gt;&lt;/td&gt; &lt;td&gt;&lt;%# Eval("Age") %&gt;&lt;/td&gt; &lt;td runat="server" id="myCol" visible='&lt;%# (bool)Eval("IsSuperCool") %&gt;'&gt;true&lt;/td&gt; &lt;/tr&gt; &lt;/ItemTemplate&gt; &lt;/asp:ListView&gt; &lt;asp:ObjectDataSource ID="MyDataSource" runat="server" DataObjectTypeName="BusinessLogicLayer.Thing" SelectMethod="SelectThings" TypeName="BusinessLogicLayer.MyObjectDataSource" /&gt; </code></pre> <p><strong>Here's the code behind</strong></p> <pre><code>/// &lt;summary&gt; /// Handles the DataBound event of the ListView1 control. /// &lt;/summary&gt; /// &lt;param name="sender"&gt;The source of the event.&lt;/param&gt; /// &lt;param name="e"&gt;The &lt;see cref="System.EventArgs"/&gt; instance containing the event data.&lt;/param&gt; protected void ListView1_DataBound(object sender, EventArgs e) { ListView1.FindControl("tdIsSuperCool").Visible = false; } </code></pre> <p>Do whatever you want in the databound. Because the column is now runat server, and you're handling the DataBound of the control, when you do ListView1.FindControl("tdIsSuperCool") you're in the Layout template so that works like a champ.</p> <p>Put whatever business logic that you want to control the visibility of the td and you're good.</p>
<p>You can always set the column width to 0 (zero) if you don't find a better way.</p>
9,622
<p>I'm trying to leverage the using block more and more these days when I have an object that implements IDisposable but one thing I have not figured out is how to catch an exception as I would in a normal try/catch/finally ... any code samples to point me in the right direction?</p> <p>Edit: The question was modified after reading through the replies. It was "How to Throw an exception in a using block with .NET 2.0?" but I was actually looking for a way to catch these exceptions inside a using block.</p> <hr> <p>I'm looking for more detail on rolling my own catching block inside a using block.</p> <p>Edit: What I wanted to avoid is having to use a try/catch/finally inside my using block like @Blair showed. But maybe this is a non issue...</p> <p>Edit: @Blair, this is exactly what I was looking for, thanks for the detailed reply!</p>
<p>I don't really understand the question - you throw an exception as you normally would. If <code>MyThing</code> implements <code>IDisposable</code>, then:</p> <pre><code>using ( MyThing thing = new MyThing() ) { ... throw new ApplicationException("oops"); } </code></pre> <p>And <code>thing.Dispose</code> will be called as you leave the block, as the exception's thrown. If you want to combine a try/catch/finally and a using, you can either nest them:</p> <pre><code>try { ... using ( MyThing thing = new MyThing() ) { ... } ... } catch ( Exception e ) { .... } finally { .... } </code></pre> <p>(Or put the try/catch/finally in the using):</p> <pre><code>using ( MyThing thing = new MyThing() ) { ... try { ... } catch ( Exception e ) { .... } finally { .... } ... } // thing.Dispose is called now </code></pre> <p>Or you can unroll the <code>using</code> and explicitly call <code>Dispose</code> in the <code>finally</code> block as @Quarrelsome demonstrated, adding any extra exception-handling or -recovery code that you need in the <code>finally</code> (or in the <code>catch</code>).</p> <p>EDIT: In response to @Toran Billups, if you need to process exceptions aside from ensuring that your <code>Dispose</code> method is called, you'll either have to use a <code>using</code> and <code>try/catch/finally</code> or unroll the <code>using</code> - I don't thinks there's any other way to accomplish what you want.</p>
<p>You need to have a try statement to catch an exception </p> <p>Either you can use an try statement within the using block or you can use a using block in a try block </p> <p>But you need to use a try block to catch any exceptions occuring </p>
5,673
<p>If I have 3 different views which are defined in 3 corresponding functions, namely:</p> <pre><code>- (UIView *)getView1 { /*...*/ } - (UIView *)getView2 { /*...*/ } - (UIView *)getView3 { /*...*/ } </code></pre> <p>These are added to <code>self.view</code> when a particular view is required.</p> <p>My question is, how do we know which of these views is currently being displayed? Is there a parameter that will identify which view is the current view?</p>
<p>You can tag each view with with an integer and later read the tag to determine which view is active (assuming you are replacing <code>self.view</code>).</p> <pre><code>#define TAG_VIEW_1 1 #define TAG_VIEW_2 2 #define TAG_VIEW_3 3 ... [ [self getView1()] setTag:TAG_VIEW_1 ]; [ [self getView2()] setTag:TAG_VIEW_2 ]; [ [self getView3()] setTag:TAG_VIEW_3 ]; ... if ( self.view.tag == TAG_VIEW_1 ) { // do something } else if ( self.view.tag == TAG_VIEW_2 ) { // etc } ... </code></pre>
<p>All UIView's have a <a href="http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIView_Class/UIView/UIView.html#//apple_ref/occ/instp/UIView/window" rel="nofollow noreferrer">window property</a> which is set when it is being displayed in a window and set to nil when it is removed. You can get the value of the window property to see if a view is currently being displayed in a window:</p> <pre><code>BOOL isDisplayed = self.view.window != nil; </code></pre> <p>You can also override <a href="http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIView_Class/UIView/UIView.html#//apple_ref/occ/instm/UIView/willMoveToWindow:" rel="nofollow noreferrer">willMoveToWindow:</a> in a subclass of UIView and it will be called whenever the view is added to or removed from a window.</p>
49,129
<p>My <a href="http://rads.stackoverflow.com/amzn/click/B007KG0ZYI" rel="noreferrer">12V DC 30A Power Supply 360W Power Supply</a> is really cheap, and it's worked well for setting up the motors; but now that I'm on to the heated bed, which uses considerably more Ampage than that of just the motors, I'll confess, I'm getting frightened to continue using it; if the summer was a bit longer, maybe it wouldn't bother me, but we're getting into the cold months, and now I'm afraid of ending up using too much ampage just trying to heat the bed in the winter months...(and I don't mean my bed). Is there anything I should look out for in terms of using the either the cheap power supply I already have, or are there certain specs on a new not-so-cheap power supply that I ought to be using instead? </p>
<p>A MK2 heatbed will draw around 12A. The motors and hotend draw only very little power (around 2A, 5A peak), so the 30A supply you have has significant headroom (it is often recommended to derate a power supply by 20%, so a 30A supply would be good for 24A - you're still well under that). It should work fine, even given its dubious provenance.</p> <p>Winter versus summer should not make a big difference. The largest power draw is during the heat up phase. In winter, the bed will use slightly more power to stay warm, but regardless of whether it is summer or winter the peak power draw during heat up will be the same.</p> <p>The cheapness of these supplies tends to be reflected in more output ripple (but for heating the bed and running the motors you don't need a very stable voltage) and improper filtering. This may inject noise back into the mains, possibly affecting other equipment nearby. Should this occur, you can just stop using the power supply. However, in my experience, they can deliver the rated power just fine. They're not completely horrible.</p> <p>Your biggest concern should be whether the wires that lead to your heated bed can handle the current and whether the screw terminals are properly tightened. During the first use, you should check that the power supply does not get extremely hot. If it's so hot it's impossible to touch for more than 1-2 seconds you should not use it.</p>
<p>I've used a similar cheap psu before. It'll work without blowing up but my heatbed struggled to get up to 60c, swapped psus with one I had lying around from a desktop and there was a huge difference. </p>
382
<p>How can one get Visual Studio 2005/2008 to reference assemblies in the 64-bit GAC instead of the 32-bit GAC? We are settin the target platfom to x64 and the compiler is throwing the error of</p> <blockquote> <p>Error 2 Warning as Error: Assembly generation -- Referenced assembly 'System.Data.dll' targets a different processor Common</p> <p>Error 3 Warning as Error: Assembly generation -- Referenced assembly 'mscorlib.dll' targets a different processor Common</p> <p>Error 4 Assembly signing failed; output may not be signed -- The system cannot find the file specified. Common</p> </blockquote> <hr> <p><strong>Update 29 Dec 08</strong></p> <p>Been trying out <a href="http://blogs.msdn.com/astebner/archive/2005/11/28/497693.aspx" rel="nofollow noreferrer">Aaron Stebner's suggestions</a> to place 64-bit assemblies onto an isolated location (e.g. C:\Windows\Microsoft.NET\Framework64\v2.0.50727\GAC_64) and creating additional entries in the registry like HKLM\SOFTWARE\Microsoft.NETFramework\AssemblyFolders\GAC_64 or HKLM\SOFTWARE\Microsoft.NETFramework\v2.0.50727\AssemblyFoldersEx\GAC_64 but Visual Studio 2005 is still not picking it up....</p>
<p>I'm not sure why you would need to do this. .NET code that isn't specifically compiled for 32 bit will run 64 bit if it can. This includes the base framework libraries. In short, there is no reason that I know of to compile your assemblies specifically for 64 bit (other than referencing unmanaged 64 bit dlls, but you're talking about the GAC).</p> <p>Some more information might help here.</p>
<p>Have you set x64 platform for all projects in your solution in Configuration Manager ?</p>
27,786
<p>Google is not being my friend - it's been a long time since my stats class in college...I need to calculate the start and end points for a trendline on a graph - is there an easy way to do this? (working in C# but whatever language works for you)</p>
<p>OK, here's my best pseudo math:</p> <p>The equation for your line is:</p> <p>Y = a + bX</p> <p>Where:</p> <p>b = (sum(x*y) - sum(x)sum(y)/n) / (sum(x^2) - sum(x)^2/n)</p> <p>a = sum(y)/n - b(sum(x)/n)</p> <p>Where sum(xy) is the sum of all x*y etc. Not particularly clear I concede, but it's the best I can do without a sigma symbol :)</p> <p>... and now with added Sigma</p> <p>b = (&Sigma;(xy) - (&Sigma;x&Sigma;y)/n) / (&Sigma;(x^2) - (&Sigma;x)^2/n)</p> <p>a = (&Sigma;y)/n - b((&Sigma;x)/n)</p> <p>Where &Sigma;(xy) is the sum of all x*y etc. and n is the number of points</p>
<p>Thank You so much for the solution, I was scratching my head.<br> Here's how I applied the solution in Excel.<br> I successfully used the two functions given by MUHD in Excel:<br> a = (sum(x*y) - sum(x)sum(y)/n) / (sum(x^2) - sum(x)^2/n)<br> b = sum(y)/n - b(sum(x)/n)<br> (careful my a and b are the b and a in MUHD's solution).<br> <br> - Made 4 columns, for example:<br> NB: my values y values are in B3:B17, so I have n=15;<br> my x values are 1,2,3,4...15.<br> 1. Column B: Known x's<br> 2. Column C: Known y's<br> 3. Column D: The computed trend line<br> 4. Column E: B values * C values (E3=B3*C3, E4=B4*C4, ..., E17=B17*C17)<br> 5. Column F: x squared values<br> I then sum the columns B,C and E, the sums go in line 18 for me, so I have B18 as sum of Xs, C18 as sum of Ys, E18 as sum of X*Y, and F18 as sum of squares.<br> To compute a, enter the followin formula in any cell (F35 for me):<br> F35=(E18-(B18*C18)/15)/(F18-(B18*B18)/15)<br> To compute b (in F36 for me):<br> F36=C18/15-F35*(B18/15)<br> Column D values, computing the trend line according to the y = ax + b:<br> D3=$F$35*B3+$F$36, D4=$F$35*B4+$F$36 and so on (until D17 for me).<br> <br> Select the column datas (C2:D17) to make the graph.<br> HTH.</p>
6,483
<p>I understand what <a href="http://msdn.microsoft.com/en-us/library/ms404247.aspx" rel="noreferrer">System.WeakReference</a> does, but what I can't seem to grasp is a practical example of what it might be useful for. The class itself seems to me to be, well, a hack. It seems to me that there are other, better means of solving a problem where a WeakReference is used in examples I've seen. What's the canonical example of where you've really got to use a WeakReference? Aren't we trying to get <i>farther</i> away from this type of behavior and use of this class? </p>
<p>One useful example is the guys who run DB4O object oriented database. There, WeakReferences are used as a kind of light cache: it will keep your objects in memory only as long as your application does, allowing you to put a real cache on top.</p> <p>Another use would be in the implementation of weak event handlers. Currently, one big source of memory leaks in .NET applications is forgetting to remove event handlers. E.g.</p> <pre><code>public MyForm() { MyApplication.Foo += someHandler; } </code></pre> <p>See the problem? In the above snippet, MyForm will be kept alive in memory forever as long as MyApplication is alive in memory. Create 10 MyForms, close them all, your 10 MyForms will still be in memory, kept alive by the event handler.</p> <p>Enter WeakReference. You can build a weak event handler using WeakReferences so that someHandler is a weak event handler to MyApplication.Foo, thus fixing your memory leaks!</p> <p>This isn't just theory. Dustin Campbell from the DidItWith.NET blog posted <a href="http://diditwith.net/PermaLink,guid,aacdb8ae-7baa-4423-a953-c18c1c7940ab.aspx" rel="noreferrer">an implementation of weak event handlers</a> using System.WeakReference.</p>
<p>There are two reasons why you would use <code>WeakReference</code>. </p> <ol> <li><p><strong>Instead of global objects declared as static</strong>: Global objects are declared as static fields and static fields cannot be GC'ed (garbage-collected) until the <code>AppDomain</code> is GC'ed. So you risk out-of-memory exceptions. Instead, we can wrap the global object in a <code>WeakReference</code>. Even though the <code>WeakReference</code> itself is declared static, the object it points to will be GC'ed when memory is low. </p> <p>Basically, use <code>wrStaticObject</code> instead of <code>staticObject</code>.</p> <pre><code>class ThingsWrapper { //private static object staticObject = new object(); private static WeakReference wrStaticObject = new WeakReference(new object()); } </code></pre> <p>Simple app to prove that static object is garbage-collected when AppDomain is.</p> <pre><code>class StaticGarbageTest { public static void Main1() { var s = new ThingsWrapper(); s = null; GC.Collect(); GC.WaitForPendingFinalizers(); } } class ThingsWrapper { private static Thing staticThing = new Thing("staticThing"); private Thing privateThing = new Thing("privateThing"); ~ThingsWrapper() { Console.WriteLine("~ThingsWrapper"); } } class Thing { protected string name; public Thing(string name) { this.name = name; Console.WriteLine("Thing() " + name); } public override string ToString() { return name; } ~Thing() { Console.WriteLine("~Thing() " + name); } } </code></pre> <p>Note from the output below <code>staticThing</code> is GC'ed at the very end even after <code>ThingsWrapper</code> is - i.e. GC'ed when <code>AppDomain</code> is GC'ed.</p> <pre><code>Thing() staticThing Thing() privateThing ~Thing() privateThing ~ThingsWrapper ~Thing() staticThing </code></pre> <p>Instead we can wrap <code>Thing</code> in a <code>WeakReference</code>. As <code>wrStaticThing</code> can be GC'ed, we'll need a lazy-loaded method which I've left out for brevity. </p> <pre><code>class WeakReferenceTest { public static void Main1() { var s = new WeakReferenceThing(); s = null; GC.Collect(); GC.WaitForPendingFinalizers(); if (WeakReferenceThing.wrStaticThing.IsAlive) Console.WriteLine("WeakReference: {0}", (Thing)WeakReferenceThing.wrStaticThing.Target); else Console.WriteLine("WeakReference is dead."); } } class WeakReferenceThing { public static WeakReference wrStaticThing; static WeakReferenceThing() { wrStaticThing = new WeakReference(new Thing("wrStaticThing")); } ~WeakReferenceThing() { Console.WriteLine("~WeakReferenceThing"); } //lazy-loaded method to new Thing } </code></pre> <p>Note from output below that <code>wrStaticThing</code> is GC'ed when GC thread is invoked.</p> <pre><code>Thing() wrStaticThing ~Thing() wrStaticThing ~WeakReferenceThing WeakReference is dead. </code></pre></li> <li><p><strong>For objects that are time-consuming to initialize</strong>: You do not want objects that are time-consusming to init to be GC'ed. You can either keep a static reference to avoid that (with cons from above point) or use <code>WeakReference</code>. </p></li> </ol>
3,637
<p>I know that this question has already been asked <a href="https://stackoverflow.com/questions/41207/javascript-interactive-shell-with-completion">HERE</a> but sadly none of the answers suggest a javascript standalone shell that has auto completion. I am reopening this question again, in the hope that some new answers might be found.</p>
<p>According to <a href="http://blog.norrisboyd.com/2008/03/better-line-editing-for-rhino-shell.html" rel="noreferrer">this blog post</a>, autocompletion is now available for <a href="https://developer.mozilla.org/en/Rhino_Shell" rel="noreferrer">Rhino</a>, as long as the <a href="http://jline.sourceforge.net/" rel="noreferrer">JLine</a> library is included.</p>
<p>If you're looking at client side Javascript, have you looked at <a href="http://getfirebug.com/" rel="nofollow noreferrer">Firebug</a>? It gives you command completion for the current window - including any pulled in libraries, etc?</p> <p>You can run it as a plugin from Firefox, or include it in any web pages for other browsers (not sure whether completion works with firebug lite)</p>
32,609
<p>I'm working now on a page that has a column of boxes styled with sexy shadows and corners and whatnot using the example <a href="http://www.schillmania.com/content/projects/even-more-rounded-corners/" rel="nofollow noreferrer">here</a>. I have to admit, I don't fully understand how that CSS works, but it <em>looks</em> great.</p> <p>Inside the topmost box is a text-type input used for searching. That search box is wired up to a <a href="http://developer.yahoo.com/yui/autocomplete/" rel="nofollow noreferrer">YUI autocomplete</a> widget.</p> <p>Everything works fine in Firefox3 on Mac, FF2 on Windows, Safari on Mac. In IE7 on WinXP, the autocomplete suggestions render underneath the round-cornered boxes, making all but the first one unreadable (although you can still see enough peeking out between boxes that I'm comfortable IE7 really is getting more than one suggestion).</p> <p>Where could I start looking to correct the problem?</p> <p>Here's what success looks like in FF2 on WinXP:</p> <p><img src="https://farm4.static.flickr.com/3042/2866012663_f5db805775_o.jpg" alt="alt text"></p> <p>And here's what failure looks like in IE7:</p> <p><img src="https://farm4.static.flickr.com/3105/2866012677_7535c1485f_o.jpg" alt="alt text"></p>
<p>Jeremy,</p> <p>Sorry for this being so late, but hopefully the answer will be of use to you in a future project.</p> <p>The problem here is that IE creates a new stacking order anytime there is an element with position:relative, meaning that z-index itself is not the only controlling factor. You can read more about this here:</p> <p><a href="http://therealcrisp.xs4all.nl/meuk/IE-zindexbug.html" rel="nofollow noreferrer">http://therealcrisp.xs4all.nl/meuk/IE-zindexbug.html</a></p> <p>To solve the problem, if I'm understanding your problem correctly, apply position:relative to the container that wraps your whole autocomplete implementation (and then position:absolute to your results container). That should create an independent stacking order in IE for those elements that allows them to float over the other position:relative stacks that appear later in the page.</p> <p>Regards, Eric</p>
<p>I'm not <em>totally</em> understanding the setup that's leading to the problem, but you might want to explore the useIFrame property of the YUI Autocomplete object -- it layers an iframe object beneath the autocomplete field, which allows the field to then float above the objects that are obscuring it in IE's buggy layout.</p> <p><a href="http://developer.yahoo.com/yui/docs/YAHOO.widget.AutoComplete.html#property_useIFrame" rel="nofollow noreferrer">http://developer.yahoo.com/yui/docs/YAHOO.widget.AutoComplete.html#property_useIFrame</a></p> <p>But the docs say that this matters in 5.5 &lt; IE &lt; 7, so this might not be the issue you're experiencing. So again, without totally understanding the setup you're working with, you might also want to try to experiment with various <a href="http://developer.mozilla.org/en/Understanding_CSS_z-index" rel="nofollow noreferrer">z-index</a> values for the autocomplete field and the surrounding block-level elements.</p>
11,454
<p>I'm looking for an implementation of CRC32 in C or C++ that is explicitly licensed as being no cost or public domain. The implementation <a href="http://www.networkdls.com/Software/View/CRC32" rel="noreferrer">here</a> seems nice, but the only thing it says about the license is "source code", which isn't good enough. I'd prefer non LGPL so I don't have to fool around with a DLL (my app is closed source). I saw the adler32 implementation in zlib, but I'm checking small chunks of data, which adler is not good for. </p>
<p>Use the <a href="http://www.boost.org/" rel="noreferrer">Boost C++ libraries</a>. There is a <a href="http://www.boost.org/doc/libs/release/libs/crc/index.html" rel="noreferrer">CRC</a> included there and the <a href="http://www.boost.org/LICENSE_1_0.txt" rel="noreferrer">license</a> is good.</p>
<p><a href="https://github.com/rurban/smhasher" rel="nofollow noreferrer">rurban's fork of SMHasher</a> (the original SMHasher seems abandoned) has hardware CRC32 support. The changes were added before the initial commit, but try comparing <a href="https://github.com/rurban/smhasher/blame/fbb0fda71354140899a9c347c3057d159d18537a/CMakeLists.txt#L35" rel="nofollow noreferrer">the new CMakeLists.txt</a> and <a href="https://code.google.com/p/smhasher/source/browse/trunk/CMakeLists.txt" rel="nofollow noreferrer">the old one</a> (which doesn't mention SSE at all).</p> <p>The best option is probably <a href="https://github.com/jtkukunas/zlib" rel="nofollow noreferrer">Intel's zlib fork with PCLMULQDQ support</a> described in <a href="http://www.intel.com/content/dam/www/public/us/en/documents/white-papers/fast-crc-computation-generic-polynomials-pclmulqdq-paper.pdf" rel="nofollow noreferrer">this paper</a>. This library <a href="https://github.com/jtkukunas/zlib/blob/e176b3c23ace88d5ded5b8f8371bbab6d7b02ba8/deflate.c#L190" rel="nofollow noreferrer">also has the SSE 4.2 optimizations</a>.</p> <p>If you don't need portability and you're on Linux, you can use the kernel's implementation (which is hardware accelerated if available): <a href="https://stackoverflow.com/a/11156040/309483">https://stackoverflow.com/a/11156040/309483</a></p>
38,910
<p>I have a simple HTML upload form, and I want to specify a default extension ("*.drp" for example). I've read that the way to do this is through the ACCEPT attribute of the input tag, but I don't know how exactly.</p> <pre><code>&lt;form enctype="multipart/form-data" action="uploader.php" method="POST"&gt; Upload DRP File: &lt;input name="Upload Saved Replay" type="file" accept="*.drp"/&gt;&lt;br /&gt; &lt;input type="submit" value="Upload File" /&gt; &lt;/form&gt; </code></pre> <p><strong>Edit</strong> I know validation is possible using javascript, but I would like the user to only see ".drp" files in his popup dialog. Also, I don't care much about server-side validation in this application.</p>
<p>I use javascript to check file extension. Here is my code:</p> <p>HTML</p> <pre><code>&lt;input name="fileToUpload" type="file" onchange="check_file()" &gt; </code></pre> <p>.. ..</p> <p>javascript</p> <pre><code>function check_file(){ str=document.getElementById('fileToUpload').value.toUpperCase(); suffix=".JPG"; suffix2=".JPEG"; if(str.indexOf(suffix, str.length - suffix.length) == -1|| str.indexOf(suffix2, str.length - suffix2.length) == -1){ alert('File type not allowed,\nAllowed file: *.jpg,*.jpeg'); document.getElementById('fileToUpload').value=''; } } </code></pre>
<p>Another solution with a few lines</p> <pre><code>function checkFile(i){ i = i.substr(i.length - 4, i.length).toLowerCase(); i = i.replace('.',''); switch(i){ case 'jpg': case 'jpeg': case 'png': case 'gif': // do OK stuff break; default: // do error stuff break; } } </code></pre>
31,698
<p>I'd like them to be easy to bundle, with few dependencies and easy to use.</p>
<p>Do you want to highlight Java code or use a Java lib to highlight some other code?</p> <p>I use these two: <a href="https://jhighlight.dev.java.net/" rel="noreferrer">https://jhighlight.dev.java.net/</a> (server-side) for xml and <a href="http://code.google.com/p/syntaxhighlighter/" rel="noreferrer">http://code.google.com/p/syntaxhighlighter/</a> (js lib) for other stuff. The latter has something called 'brushes' which are "pluggable" .js for several langauges. If you are doing simple highlighting, I recommend the ,js approach.</p>
<p>RSyntaxTextArea is worked for me<a href="http://bobbylight.github.io/RSyntaxTextArea/" rel="nofollow">Here</a></p> <pre><code> RSyntaxTextArea textArea = new RSyntaxTextArea(); textArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA); textArea.setCodeFoldingEnabled(true); RTextScrollPane rs = new RTextScrollPane(textArea); </code></pre>
27,316
<p>I'm working on a simple little function to download a file from an SSL-enabled website using the WinInet functions, namely InternetOpen and InternetOpenURL. I had was initially failing the call to InternetOpenURL with a <code>ERROR_INTERNET_INVALID_CA</code> (12045) because I was using a self-signed certificate on my test server, and found out (<a href="http://support.microsoft.com/kb/q182888/" rel="nofollow noreferrer">http://support.microsoft.com/kb/q182888/</a>) that the fix seemed to be to use the InternetQueryOption/InternetSetOption combination to pass various flags to <code>INTERNET_OPTION_SECURITY_FLAGS</code> option. Now, however, InternetQueryOption fails with a <code>ERROR_INTERNET_INCORRECT_HANDLE</code> (12018) response from GetLastError(). Any ideas why this would be the case? I'm using the handle that came directly from InternetOpen, which previously worked fine with a non-SSL InternetOpenURL. Shouldn't this be the correct handle?</p> <p>I don't have the actual code (different computer), but it is very similar to the following, and fails on InternetGetOption with <code>ERROR_INTERNET_INCORRECT_HANDLE</code>:</p> <pre><code> HINTERNET hReq = InternetOpen(...) if (!hReq) { printf("InternetOpen Error: %d", GetLastError()); } DWORD dwFlags = 0; DWORD dwBuffLen = sizeof(dwFlags); BOOL ret = false; ret = InternetQueryOption(hReq, INTERNET_OPTION_SECURITY_FLAGS, (LPVOID)&amp;dwFlags, &amp;dwBuffLen); if (!ret) { printf("InternetQueryOption Error: %d", GetLastError()); } dwFlags |= SECURITY_FLAG_IGNORE_UNKNOWN_CA; ret = InternetSetOption(hReq, INTERNET_OPTION_SECURITY_FLAGS, &amp;dwFlags, sizeof (dwFlags) ); if (!ret) { printf("InternetSetOption Error: %d", GetLastError()); } InternetOpenURL(hReq, ...) </code></pre>
<p>I used to receive similar error. I then passed the handle returned by a HttpOpenRequest(...) to InternetQueryOption and it worked just fine. Try it out.</p>
<p>I see you're not checking the <code>hReq</code> you get back from <code>InternetOpen</code>. Perhaps that is the root of your problem. See what this tells you if you add it right after the call to <code>InternetOpen</code>:</p> <pre><code>if (hReq == NULL) { printf("InternetOpen Error: %d", GetLastError()); } </code></pre>
35,286
<p>I am pretty new to php, but I am learning! I have a simple form on a client website. I am testing the form and when I click submit, I get the following error:</p> <p>Form Mail Script</p> <pre><code>Wrong referrer (referring site). For security reasons the form can only be used, if the referring page is part of this website. Note for the Admin: Please add the name of your server to the referrer variable in the index.php configuration file: mywebsite.com </code></pre> <p>Powered by Form Mail Script</p> <p>I am looking through the forms configuration and support files but I do not understand exactly what it is I need to change.</p> <p>Can someone please explain to me what the Admin note above means and how to fix it?</p>
<p>You are obviously using the Form Mail script on your page. It has a security feature that prevents other domains from submitting to the form. This is done to prevent bots from using the script to send out spam.</p> <p>In the configuration for the form mail script or in the script itself, you will find an array or variable with the referrers listed. This is the sites that you want to allow calling of this form mail. You should add your own domain to this list or assign it to this variable.</p> <p>Sorry, I haven't used this script, so I can't be more specific.</p>
<p>Doing a quick search for the error you're seeing, I found this link: <a href="http://www.stadtaus.com/forum/t-3528.html" rel="nofollow noreferrer">http://www.stadtaus.com/forum/t-3528.html</a> </p> <p>Not sure if that helps you in this case since I'm unfamiliar with the tool you're using but it seemed like a good fit.</p>
33,351
<p>We have consumed a third party web service and are trying to invoke it from an ASP.NET web application. However when I instantiate the web service the following System.InvalidOperationException exception is thrown:</p> <blockquote> <p>Method 'ABC.XYZ' can not be reflected. System.InvalidOperationException: Method 'ABC.XYZ' can not be reflected. ---> System.InvalidOperationException: The XML element 'MyDoc' from namespace '<a href="http://mysoftware.com/ns" rel="noreferrer">http://mysoftware.com/ns</a>' references a method and a type. Change the method's message name using WebMethodAttribute or change the type's root element using the XmlRootAttribute.</p> </blockquote> <p>From what I can gather there appears to be some ambiguity between a method and a type in the web service. Can anyone clarify the probably cause of this exception and is there anything I can do to rectify this or should I just go to the web service owners to rectify?</p> <p>Edit: Visual Studio 2008 has created the proxy class. Unfortunately I can't provide a link to the wsdl as it is a web service for a locally installed thrid party app.</p>
<p>I ran into the same problem earlier today. The reason was - the class generated by Visual Studio and passed as a parameter into one of the methods did not have a default parameterless constructor. Once I have added it, the error had gone.</p>
<p>I got the same message but mine was caused by a missing System.Runtime.Serialization.dll since I tried to run a 3.5 application on a machine with only .NET 2.0 installed.</p>
16,088
<p>I'm not sure if this a settings problem or an HTML problem, but on a page layout I'm working on, Firefox does not render the stylesheet immediately. Meaning for maybe half a second I can see the unstyled page, then the stylesheet kicks in and it renders as I expect.</p> <p>All my stylesheets are in external css files loaded in the head tag. I'm not encountering this on Flock (which is a Firefox variant) nor on Google Chrome/IE.</p> <p>Any idea how to avoid it?</p>
<p>Try disabling firebug.</p>
<p>In my case turning off Firebug didn't help. From the other hand I happend to use <strong>@import</strong> in my css and when i removed it - the <strong>FOUC</strong> (Flash Of Unstyled Content) was gone. That is very strange because this behaviour is mostly referred to <strong>IE</strong> (<a href="http://www.bluerobot.com/web/css/fouc.asp/" rel="nofollow noreferrer">http://www.bluerobot.com/web/css/fouc.asp/</a>)</p>
49,318
<p>I have seen 3d surface plots of data before but i do not know what software i could use to make it.</p> <p>I have 3 series of data (X, Y, Z) basically i want each of the rows on the table to be a point in 3d space, all joined as a mesh. The data is currently csv, but i can change the format, as it is data i generated myself.</p> <p>Can anyone help</p>
<p>If your x &amp; y points topologically lie on a grid, then you can use MESH. They don't need to have even spacing; they just need to be organized so that x(r:r+1,c:c+1) and y(r:r+1,c:c+1) define a quadrilateral on your mesh, for each row r and column c.</p> <p>If your data do not lie on a grid, but you know what the faces should be, look at the PATCH function.</p> <p>If you only have points and you don't know anything about the surface, you need to first solve the <a href="http://www.compgeom.com/~piyush/rups.html" rel="nofollow noreferrer">surface reconstruction</a> problem. I've used cocone; there are other good packages there too. Once you have the reconstructed surface, then you can use PATCH to display it.</p>
<p>gnuplot or <a href="http://www.scilab.org/" rel="nofollow noreferrer">scilab</a></p> <p>Below is a script for SciLab that I wrote awhile back. It reads in three columns separated by tabs. You can easily change this to fit your needs, pretty self-explanatory. Here is a quick guide to <a href="http://spiff.rit.edu/classes/phys317/lectures/readwrite.html" rel="nofollow noreferrer">reading/writing in scilab</a> and the one I reference below is <a href="http://spiff.rit.edu/classes/phys317/examples/plot_from_file.sci" rel="nofollow noreferrer">here</a>:</p> <pre><code>function plot_from_file(datafile) // // Make a simple x-y-z plot based on values read from a datafile. // We assume that the datafile has three columns of floating-point // values seperated by tabs. // set verbose = 1 to see lots of diagnostics verbose = 1; // open the datafile (quit if we can't) fid = mopen(datafile, 'r'); if (fid == -1) error('cannot open datafile'); end // loop over all lines in the file, reading them one at a time num_lines = 0; while (true) // try to read the line ... [num_read, val(1), val(2), val(3)] = mfscanf(fid, "%f\t%f\t%f"); if (num_read &lt;= 0) break end if (verbose &gt; 0) fprintf(1, 'num_lines %3d num_read %4d \n', num_lines, num_read); end if (num_read ~= 3) error('didn''t read three points'); end // okay, that line contained valid data. Store in arrays num_lines = num_lines + 1; x_array(num_lines) = val(1); y_array(num_lines) = val(2); z_array(num_lines) = val(3); end // now, make the plot plot3d2(x_array, y_array, z_array); // close the datafile mclose(fid); endfunction </code></pre>
33,502
<p>I want to initialize a struct element, split in declaration and initialization. This is what I have:</p> <pre><code>typedef struct MY_TYPE { bool flag; short int value; double stuff; } MY_TYPE; void function(void) { MY_TYPE a; ... a = { true, 15, 0.123 } } </code></pre> <p>Is this the way to declare and initialize a local variable of <code>MY_TYPE</code> in accordance with C programming language standards (C89, C90, C99, C11, etc.)? Or is there anything better or at least working?</p> <p><strong>Update</strong> I ended up having a static initialization element where I set every subelement according to my needs.</p>
<p>In (ANSI) C99, you can use a <strong>designated initializer</strong> to initialize a structure:</p> <pre><code>MY_TYPE a = { .flag = true, .value = 123, .stuff = 0.456 }; </code></pre> <p>Other members are initialized as zero: &quot;Omitted field members are implicitly initialized the same as objects that have static storage duration.&quot; (<a href="https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html" rel="noreferrer">https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html</a>)</p>
<p>I've been looking for a nice way to initialize my struct, and I've got to using the below (C99). This lets me initialize either a single structure or an array of structures in the same way as plain types.</p> <pre><code>typedef struct { char *str; size_t len; jsmntok_t *tok; int tsz; } jsmn_ts; #define jsmn_ts_default (jsmn_ts){NULL, 0, NULL, 0} </code></pre> <p>This can be used in the code as:</p> <pre><code>jsmn_ts mydata = jsmn_ts_default; /* initialization of a single struct */ jsmn_ts myarray[10] = {jsmn_ts_default, jsmn_ts_default}; /* initialization of first 2 structs in the array */ </code></pre>
42,850
<p>I need to allow other Python applications to register callback functions for events in my application. These need to have priorities associated with them (so a callback with a priority of 10 runs before a callback with a priority of 1) and callback functions need to be able to signal errors to the dispatcher.</p> <p>These are all lightweight callbacks running in the same process, so I don't need to send signals across process boundaries.</p> <p>Is there a good Python library to handle this, or do I need to write my own?</p>
<p>Are these other applications running in another address space? If so, you'll need to use an interprocess communication library like <a href="http://www.freedesktop.org/wiki/Software/dbus" rel="nofollow noreferrer">D-BUS</a>.</p> <p>If you're just sending signals in the same process, try <a href="http://pypi.python.org/pypi/PyDispatcher/2.0.1" rel="nofollow noreferrer">PyDispatcher</a></p>
<p>What platform are you running under? GObject is the basis of the GTK GUI that's widely-used under Linux, and it supports event loops with prioritizable events like this.</p>
14,389
<p>Can I convert a string representing a boolean value (e.g., 'true', 'false') into a intrinsic type in JavaScript?</p> <p>I have a hidden form in HTML that is updated based upon a user's selection within a list. This form contains some fields which represent boolean values and are dynamically populated with an intrinsic boolean value. However, once this value is placed into the hidden input field it becomes a string.</p> <p>The only way I could find to determine the field's boolean value, once it was converted into a string, was to depend upon the literal value of its string representation.</p> <pre><code>var myValue = document.myForm.IS_TRUE.value; var isTrueSet = myValue == 'true'; </code></pre> <p>Is there a better way to accomplish this?</p>
<h1>Do:</h1> <pre><code>var isTrueSet = (myValue === 'true'); </code></pre> <p>using the identity operator (<code>===</code>), which doesn't make any implicit type conversions when the compared variables have different types.</p> <p>This will set <code>isTrueSet</code> to a boolean <code>true</code> if the string is &quot;true&quot; and boolean <code>false</code> if it is string &quot;false&quot; or not set at all.</p> <hr /> <h2>Don't:</h2> <p>You should probably <strong>be cautious about using these two methods</strong> for your specific needs:</p> <pre><code>var myBool = Boolean(&quot;false&quot;); // == true var myBool = !!&quot;false&quot;; // == true </code></pre> <p>Any string which isn't the empty string will evaluate to <code>true</code> by using them. Although they're the cleanest methods I can think of concerning to boolean conversion, I think they're not what you're looking for.</p>
<p>Just do a:</p> <pre><code>var myBool = eval (yourString); </code></pre> <p>Examples:</p> <pre><code>alert (eval ("true") == true); // TRUE alert (eval ("true") == false); // FALSE alert (eval ("1") == true); // TRUE alert (eval ("1") == false); // FALSE alert (eval ("false") == true); // FALSE; alert (eval ("false") == false); // TRUE alert (eval ("0") == true); // FALSE alert (eval ("0") == false); // TRUE alert (eval ("") == undefined); // TRUE alert (eval () == undefined); // TRUE </code></pre> <p>This method handles the empty string and undefined string naturally as if you declare a variable without assigning it a value.</p>
33,059
<p>In Oracle, what is the difference between :</p> <pre><code>CREATE TABLE CLIENT ( NAME VARCHAR2(11 BYTE), ID_CLIENT NUMBER ) </code></pre> <p>and</p> <pre><code>CREATE TABLE CLIENT ( NAME VARCHAR2(11 CHAR), -- or even VARCHAR2(11) ID_CLIENT NUMBER ) </code></pre>
<p>Let us assume the database character set is UTF-8, which is the recommended setting in recent versions of Oracle. In this case, some characters take more than 1 byte to store in the database.</p> <p>If you define the field as <code>VARCHAR2(11 BYTE)</code>, Oracle can use up to 11 bytes for storage, but you may not actually be able to store 11 characters in the field, because some of them take more than one byte to store, e.g. non-English characters.</p> <p>By defining the field as <code>VARCHAR2(11 CHAR)</code> you tell Oracle it can use enough space to store 11 characters, no matter how many bytes it takes to store each one. A single character may require up to 4 bytes.</p>
<p>In simple words when you write <code>NAME VARCHAR2(11 BYTE)</code> then only 11 Byte can be accommodated in that variable.</p> <p>No matter which characters set you are using, for example, if you are using Unicode (UTF-16) then only half of the size of Name can be accommodated in <code>NAME</code>.</p> <p>On the other hand, if you write <code>NAME VARCHAR2(11 CHAR)</code> then <code>NAME</code> can accommodate 11 CHAR regardless of their character encoding.</p> <p><code>BYTE</code> is the default if you do not specify <code>BYTE</code> or <code>CHAR</code></p> <p>So if you write <code>NAME VARCHAR2(4000 BYTE)</code> and use Unicode(UTF-16) character encoding then only 2000 characters can be accommodated in <code>NAME</code></p> <p>That means the size limit on the variable is applied in <code>BYTES</code> and it depends on the character encoding that how many characters can be accommodated in that vraible.</p>
10,710
<p>I have a very painful library which, at the moment, is accepting a C# string as a way to get arrays of data; apparently, this makes marshalling for pinvokes easier. </p> <p>So how do I make a ushort array into a string by bytes? I've tried:</p> <pre><code>int i; String theOutData = ""; ushort[] theImageData = inImageData.DataArray; //this is as slow like molasses in January for (i = 0; i &lt; theImageData.Length; i++) { byte[] theBytes = System.BitConverter.GetBytes(theImageData[i]); theOutData += String.Format("{0:d}{1:d}", theBytes[0], theBytes[1]); } </code></pre> <p>I can do it this way, but it doesn't finish in anything remotely close to a sane amount of time.</p> <p>What should I do here? Go unsafe? Go through some kind of IntPtr intermediate?</p> <p>If it were a char* in C++, this would be significantly easier...</p> <p>edit: the function call is</p> <pre><code>DataElement.SetByteValue(string inArray, VL Length); </code></pre> <p>where VL is a 'Value Length', a DICOM type, and the function itself is generated as a wrapper to a C++ library by SWIG. It seems that the representation chosen is string, because that can cross managed/unmanaged boundaries relatively easily, but throughout the C++ code in the project (this is GDCM), the char* is simply used as a byte buffer. So, when you want to set your image buffer pointer, in C++ it's fairly simple, but in C#, I'm stuck with this weird problem.</p> <p>This is hackeration, and I know that probably the best thing is to make the SWIG library work right. I really don't know how to do that, and would rather a quick workaround on the C# side, if such exists.</p>
<p>P/Invoke can actually handle what you're after most of the time using StringBuilder to create writable buffers, for example see <a href="http://www.pinvoke.net/search.aspx?search=GetWindowText" rel="noreferrer">pinvoke.net on GetWindowText and related functions</a>.</p> <p>However, that aside, with data as ushort, I assume that it is encoded in UTF-16LE. If that is the case you can use Encoding.Unicode.GetString(), but that will exepect a byte array rather than a ushort array. To turn your ushorts into bytes, you can allocate a separate byte array and use Buffer.BlockCopy, something like this:</p> <pre><code>ushort[] data = new ushort[10]; for (int i = 0; i &lt; data.Length; ++i) data[i] = (char) ('A' + i); string asString; byte[] asBytes = new byte[data.Length * sizeof(ushort)]; Buffer.BlockCopy(data, 0, asBytes, 0, asBytes.Length); asString = Encoding.Unicode.GetString(asBytes); </code></pre> <p>However, if unsafe code is OK, you have another option. Get the start of the array as a ushort*, and hard-cast it to char*, and then pass it to the string constructor, like so:</p> <pre><code>string asString; unsafe { fixed (ushort *dataPtr = &amp;data[0]) asString = new string((char *) dataPtr, 0, data.Length); } </code></pre>
<p>I don't like this much, but it seems to work given the following assumptions:</p> <p><strong>1.</strong> Each ushort is an ASCII char between 0 and 127</p> <p><strong>2.</strong> (Ok, I guess there is just one assumption)</p> <pre><code> ushort[] data = inData; // The ushort array source Byte[] bytes = new Byte[data.Length]; // Assumption - only need one byte per ushort int i = 0; foreach(ushort x in data) { byte[] tmp = System.BitConverter.GetBytes(x); bytes[i++] = tmp[0]; // Note: not using tmp[1] as all characters in 0 &lt; x &lt; 127 use one byte. } String str = Encoding.ASCII.GetString(bytes); </code></pre> <p>I'm sure there are better ways to do this, but it's all I could come up with quickly.</p>
34,538
<p>I'm messing around with 2D game development using C++ and DirectX in my spare time. I'm finding that the enterprisey problem domain modeling approach doesn't help as much as I'd like ;)</p> <p>I'm more or less looking for a "best practices" equivalent to basic game engine design. How entities should interact with each other, how animations and sounds should be represented in an ideal world, and so on. </p> <p>Anyone have good resources they can recommend? </p>
<p><a href="http://www.gamedev.net" rel="noreferrer">Gamedev.net</a> is usually where I turn to get an idea of what other people in the game development community are doing.</p> <p>That said, I'm afraid that you'll find that the idea of "best practices" in game development is more volatile than most. Games tend to be such specialized applications that it's near impossible to give any "one size fits all" answers. What works great for Tetris is going to be useless with Asteroids, and a model that works perfectly for Halo is likely to fail miserably for Mario.</p> <p>You'll also find quickly that there's no such thing as an "industry standard" for texture, mesh, level, sound, or animation formats. Everyone just rolls their own or uses whatever is convenient to the platform. You do occasionally see things like <a href="http://www.collada.org" rel="noreferrer">COLLADA</a>, which is nice, but it's still just an intermediate format designed to make writing exporters easier.</p> <p>If you're new to game development, my advice would be this: Don't kill yourself over your code structure on your first go. Try a simple game, like asteroids, and just hack away until it works, no matter how "ugly" the code is. Use simple formats that you are familiar with without worrying about how well they'll hold up in larger projects. Don't worry about plugins, skins, editors, or any of that other fluff. Just make it WORK! Then, when you're done with that first, all important game, pick another, and this time around clean up one or two aspects of your code (but don't go overboard!) From there, iterate! </p> <p>I promise you that this will get you farther faster than any amount of poking around online for the "right way" ever could (this coming from someone who's done a LOT of poking).</p> <p>And one last thought for you: If you feel more comfortable working in a more well defined space, take a look at <a href="http://creators.xna.com/" rel="noreferrer">XNA</a> or a similar library. They'll pre-define some of the "best" formats to use and give you tools to work with them, which takes some of the initial guesswork out.</p> <p>Good luck, and above all else remember: Games (and their development) are supposed to be FUN! Don't get too caught up on the small stuff!</p>
<p>Since it has not been mentioned yet, why not start by looking at an existing engine that has been released to the community? Since you're talking 2D, I would go way back and recommend something like <a href="http://abuse.zoy.org/browser/abuse/trunk" rel="nofollow noreferrer"><strong>Abuse</strong></a>. Yes, it's ancient and most of the interesting bits are in Lisp -- but the game got very popular for a while which means they were doing something right. </p> <p>As it happens, I think the fact that so much of the original game was in Lisp is a very useful lesson. Pick the most robust language/tool and do not worry about performance. You can always optimize the slow parts in C later.</p>
21,683
<p>I have used an update command to update the whole table in an Sql Server 2000 database by mistake. I was actually meaning to update just one row. Now all the 2000 rows contain the update. Is there a way to roll back this change?</p>
<p>Unless you started your update with an explicit transaction, no.</p> <p>However, you might be able to use <a href="http://www.red-gate.com/products/SQL_Log_Rescue/index.htm" rel="nofollow noreferrer">Log Rescue</a> . I'm not sure though if this can help you in this case. </p> <p>A better option might be to restore a backup to a new database and merge the old and new tables.</p>
<p>No, not unless you have a backup to revert to.</p> <p>I've done that mistake once. Now I start every manual operation with BEGIN TRAN. The worst that can happen then is that you forget to COMMIT TRAN and keep a lock on the table.</p>
35,901
<p><a href="https://i.stack.imgur.com/Bujra.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Bujra.png" alt="0.200 mm layer height, single wall" /></a></p> <p><a href="https://i.stack.imgur.com/gCYkr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gCYkr.png" alt="0.075 mm layer height, 2walls, no infill" /></a></p> <ul> <li>These lines exist on all prints, PLA, ABS.</li> <li>They're 0.8 mm apart [20T 2GT pulley, 1.8°/step motor = 1 line/4 full-steps]</li> <li>Start to disappear above 75 mm/s but will still appear on slower axis when printing diagonal lines or curves</li> <li>Custom built frame, cross bar (Ultimaker style) using linear rails</li> <li>dual-motor (4 total on X-Y) + separate driver (1 motor/driver)</li> <li>Running Smoothieware on Smoothieboard 5X [A5984 drivers, 32 microstep]</li> </ul> <p>Tried all these with no improvement:</p> <p><strong>TL;DR problem is somewhere between drivers and motors</strong></p> <ul> <li>Switched to 6.625:1 geared extruder</li> <li>Tried parallel, series, single coil on the 8 wires motor and 2 other different motors</li> <li>Enable fast decay mode on A5984</li> <li>Motor current from 0.5 A to 1.8 A</li> <li>PLA temp from 170~200 °C</li> <li>Acceleration as low as 100 mm/s2</li> <li>**Changed 20T to 16T pulleys. The pattern scaled down proportional to the change in tooth count. Ruled out mechanical issues.</li> </ul>
<p>The fact that these are all perfectly spaced, and don't mirror the edges of irregular prints, makes me think it's definitely not ghosting. That said, I can't see the Y direction on either print, just the X direction, so this all assumes it's only happening in one direction. One thing to think about: Your motors have typically 2 opposing coils, and they get activated by taking 4 steps: (North, off, South): N/o o/N S/o o/S If these are spaced out exactly 4 steps apart, that would imply that one of your coils is either underpowered or overpowered on the motor controlling that direction's movement. That would lead to your motor torque dipping and increasing, leading to slightly uneven print speed. This is 100% speculative and might be a goose chase since you've got 4 X/Y motors and it seems to happen in both the X and Y axis. The chances of having that many motors exhibit the same deficiency is astronomical.</p> <p>That said, I've got little experience with multiple motors per axis. Another thing you might look into is whether the motors are fighting each other at all. If, for example, the motor-side pulley isn't aligned exactly the same way on both X motors, or the motors get out of sync with each other, because of the way the motor's holding torque falls as you get away from a full step position, you might find that one motor is holding the other back slightly, or pulling it forward towards the nearest full step. Again, this is all speculative, but it might be worth looking into. You can typically figure out the full step location by killing power to the machine and letting the motors settle into a full step on their own without the belts or other drive mechanisms attached. I'd unhook the belts, kill the power, get the motors settled (with a bit of a nudge if necessary), and then see if your belt perfectly settles into both pulleys in that location. You might find that the belt teeth don't quite line up on both pulleys, and the only way I can think of that would fix that specific problem is spinning the motor until it matches, or even physically relocating the motor closer or farther relative to the other on the same axis.</p> <p>YMMV, best of luck.</p>
<p>This is a great blog post, <a href="https://www.evernote.com/shard/s211/client/snv?noteGuid=701c36c4-ddd5-4669-a482-953d8924c71d&amp;noteKey=1ef992988295487c98c268dcdd2d687e&amp;sn=https%3A%2F%2Fwww.evernote.com%2Fshard%2Fs211%2Fsh%2F701c36c4-ddd5-4669-a482-953d8924c71d%2F1ef992988295487c98c268dcdd2d687e&amp;title=Taxonomy%2Bof%2BZ%2Baxis%2Bartifacts%2Bin%2Bextrusion-based%2B3d%2Bprinting" rel="nofollow noreferrer">Taxonomy of Z axis artifacts in extrusion-based 3d printing</a>, explaining what I think I am seeing, although I'm not entirely sure what I'm seeing in your photos.</p> <p>The short version is if your z-rods are threaded in an imperial unit, inches/fractions of inches, instead of metric, you get a repeating decimal value (think about converting 1/3 to decimal), which can lead to a rounding error depending on the chosen layer height.</p> <p>Without knowing how exactly you built your machine it's hard to say more but the post goes over a number of things I almost did wrong (like anti-wobble caps on top of the z rods for Prusa i3s...)</p>
1,189
<p>I need to take a Word document that is a template of sorts...collect user input to populate specific fields in that template..then generate a PDF file that includes the completed template as well as a few other document types. Does anyone have a good suggestion on a component to achieve this? Preferably one that does not require Microsoft Office to be installed on the web server.</p>
<p>Try Aspose Words for .net. From their website: "Aspose.Words enables .NET and Java applications to read, modify and write Word® documents without utilizing Microsoft Word." Utilizing Aspose Words with Aspose PDF permits you to output to PDF.</p> <p>One thing you do NOT want to do is install MS Word on your production server. Loading those objects is SLOW and EATS memory. You won't be able to use the CutePDF Writer unless you also install MS Word on the server. Yeck.</p>
<p>Is there a reason to use Word? If you start with a PDF with Form fields, you can either allow the user to fill out the fields, or do it programatically with iTextSharp's PDF stamper. </p> <p>If you need to use MSOffice 2000/2003 components programmatically, you can try Office Web Components. They do need to be installed on the server, but can be used by .NET and Com apps to interact with office file types. More info here...<a href="http://en.wikipedia.org/wiki/Office_Web_Components" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Office_Web_Components</a></p> <p>If you dig about on an office CD you should find the OWC installer for your version. I haven't worked with 2007, but I assume there is something similar available. </p> <p>iTextSharp and OWC are no-cost, check the licensing for more details.</p>
11,094
<p>I have a base class in which I want to specify the methods a child class must have, but not implement them itself. However, the methods in a child class may have a different number of paramaters to the definition in the base class.</p> <p>Having tried this with an abstract method, php doesn't allow this. Is it possible?</p>
<p>Short of specifying the abstract method with no parameters and requiring the subclassed method to access the args through func_get_args, I don't see how this would be possible.</p>
<p>I don't think this is an answer that you will want to use in production as it will be fairly slow, but just for the sake of it I tried to write something using Reflection, which seems to work. You will still get an E_STRICT because method declarations in subclasses are apparently supposed to match.</p> <pre><code>class a { protected $requiredMethodsInSubclass = array( 'method1', 'method2', 'method3' ); public function __construct() { $reflObject = new ReflectionObject($this); $className = $reflObject-&gt;getName(); if ($className == __CLASS__) { //this class is being instanciated directly , so don't worry about any subclasses return; } foreach ($this-&gt;requiredMethodsInSubclass as $methodName) { try { $reflMethod = $reflObject-&gt;getMethod($methodName); } catch (ReflectionException $e) { //method not anywhere trigger_error("Method $methodName is not declared in class " . __CLASS__ . " or subclass $className", E_USER_ERROR); continue; } $declaringClass = $reflMethod-&gt;getDeclaringClass(); if ($declaringClass-&gt;getName() == __CLASS__) { //method is declared in this class, not subclass trigger_error("Method $methodName is not declared in subclass $className", E_USER_ERROR); } } } public function method1() { } public function method2($a) { } } class b extends a { public function __construct() { parent::__construct(); //some stuff } public function method2($a, $b, $c) { } } $b = new b(); </code></pre>
47,223
<p>I've printed mostly ABS in the past and encountered <a href="https://www.google.com/#q=3d+printing+layer+delamination">delamination</a> between layers many times. I've ensured the following conditions regularly:</p> <ul> <li>Build plate is level</li> <li>Base of print isn't warped (using ABS slurry)</li> <li>Prevent air draft. I've added acrylic panels to the sides of the machine and the machine is in a custom cupboard.</li> <li>Nozzle temperature at about 225C</li> <li>HBP temperature at about 112C (I live in NW USA, so the ambient temperature is typically fairly cool).</li> <li>Using MakerBot filament</li> </ul> <p>What are some other variables to consider to help prevent delamination between layers?</p>
<p>Cool environmental conditions are the single biggest contributor to ABS delamination. Delamination or edge/corner cracking is caused by warping stresses when the first layer adhesion is stronger than the interlayer bonding. Or it happens when the heated build plate allows a strong non-warping foundation to be built until the print is too tall to be adequately warmed by the plate. In either case, the corners of the first layer can't lift, so the print cracks elsewhere to relieve the stress. </p> <p>All ABS warping stress, in turn, is caused by the repeated thermal contraction of the fresh plastic layer at the top of the print. The FDM process sticks hot, expanded plastic onto cool, contracted plastic. When the new layer cools, it tries to contract, but it's stuck to a layer that is already fully cooled/contracted. This generates a large shear stress between the two layers. The accumulation of those shear stresses over many consecutive layers generates a large-scale bending force on the entire print. That's what causes both warping and delamination. </p> <p><a href="https://i.stack.imgur.com/HZZam.png" rel="noreferrer"><img src="https://i.stack.imgur.com/HZZam.png" alt="enter image description here"></a></p> <p>The less the previous layer cools below the glass point of the plastic, the less thermal contraction it experiences before the next layer goes down, and therefore the less warping stress will accumulate as the <em>next</em> layer cools.</p> <p>Environment temp is the biggest thing you can control:</p> <ul> <li>If your printer's environment is below 35C, you probably shouldn't even bother printing ABS. </li> <li>A 50C environment is significantly better and will have minimal problems with warping and delamination. This is within the ambient temp ratings of most motors and electronics. Air-cooled extruders can typically extrude ABS reliably up to about 60C ambient, at which point they may be prone to clogging. And don't forget about plastic structural parts in your printer.</li> <li>Industrial ABS printers with heated build chambers print ABS in a 75-85C environment, with lots of airflow. In terms of cooling regimes, ABS in an 80C chamber acts very similar to PLA in a room-temp environment. No warping, but lots of airflow required for good detail. </li> </ul> <p>Printing ABS at a higher nozzle temperature (say 240-250C) will also improve layer adhesion so delamination is less likely to occur. The same warping stresses will be there, but the layer bonding may be stronger than the internal stresses in the part so it survives printing.</p>
<p>wall size and filling are also parameters. If wall size is too thin delamination is more visible</p>
273
<p>I have two Django projects and applications running on the same Apache installation. Both projects and both applications have the same name, for example myproject.myapplication. They are each in separately named directories so it looks like .../dir1/myproject/myapplication and .../dir2/myproject/myapplication. </p> <p>Everything about the actual public facing applications works fine. When I log into either of the admin sites it seems ok, but if I switch and do any work on the opposite admin site I get logged out of the first one. In short I can't be logged into both admin sites at once. Any help would be appreciated.</p>
<p>Set the <a href="http://docs.djangoproject.com/en/dev/topics/http/sessions/#session-cookie-domain" rel="noreferrer">SESSION&#x5F;COOKIE&#x5F;DOMAIN</a> option. You need to set the domain for each of your sites so the cookies don't override each other.</p> <p>You can also use SESSION&#x5F;COOKIE&#x5F;NAME to make the cookie names different for each site.</p>
<p>Well, if they have the same project and application names, then the databases and tables will be the same. Your django_session table which holds the session information is the same for both sites. You have to use different project names that will go in different MySQL (or whatever) databases.</p>
42,388
<p>What is the best way to make a <code>&lt;div&gt;</code> fade away after a given amount of time (without using some of the JavaScript libraries available).</p> <p>I'm looking for a very lightweight solution not requiring a huge JavaScript library to be sent to the browser.</p>
<p>Not sure why you'd be so against using something like jQuery, which would make accomplishing this effect all but trivial, but essentially, you need to wrap a series of changes to the -moz-opacity, opacity, and filter:alpha CSS rules in a setTimeout().</p> <p>Or, use jQuery, and wrap a fadeOut() call in setTimeout. Your choice.</p>
<p>I know you're down on libraries, but I'd recommend taking a look at moo.fx: <a href="http://moofx.mad4milk.net/" rel="nofollow noreferrer">http://moofx.mad4milk.net/</a> - I think it's like 3k.</p> <p>jQuery is pretty damn small too.</p>
15,101
<p>I've just installed MediaWiki on a web server. Obviously it needs lots of privileges during installation to set up its database correctly. Now that it's installed can I safely revoke some privileges (e.g. create table, drop table?) Or might it need to create more tables later (when they are first needed?) If not then I would prefer to grant it as few privileges as possible.</p>
<p>After the installation, MediaWiki doesn't need to create any more tables. I'd suggest giving the user insert, select, and lock permission.</p> <pre><code>grant select,lock tables,insert on media_wiki_db.* to 'wiki'@'localhost' identified by 'password'; </code></pre>
<p>Change the user that mediawiki connects as in LocalSettings.php and then using phpMyAdmin, you can edit the privileges of that user (that is, if you aren't comfortable granting and revoking privileges from the mysql console).</p> <p><a href="http://www.phpmyadmin.net/home_page/index.php" rel="nofollow noreferrer">http://www.phpmyadmin.net/home_page/index.php</a></p>
13,107
<p>Is enterprise library for exception handling and logging efficient in terms of its memory usage for the functionality provided?</p> <p>What are the pros and cons? Thanks </p>
<p>I doubt that the enterprise library is going to be your performance bottleneck. I'd say use it, measure your application's performance, find the bottleneck and go from there. Fretting about what performance <em>might</em> be isn't going to give you any useful data for your scenario.</p> <p>That said, I've had good luck with the Enterprise Library Application Logging Block and I'd recommend it in most cases. :)</p>
<p>Given the larger memory and faster processing of today's (and recent) computers, I did not have inefficiency problems. The efficiency I found in the enterprise library is that I did not have to write and test it myself. And, because of its consistency and documentation, I don't have to spend much time teaching it to anyone else either. Granted, I have not specifically tested it for speed, and you could likely write a much more targeted custom version without as much overhead... But again, the efficiency is in using the library itself and moving on to solve other, more important problems.</p>
22,772
<p>I want to display print dialog in servlet/jsp. Below is my code:</p> <pre><code>DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE; PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet () ; PrintService printService[] = PrintServiceLookup.lookupPrintServices(flavor, pras); PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService(); PrintService service = javax.print.ServiceUI.printDialog(null, 200, 200, printService, defaultService, flavor, pras); if (service != null) { DocPrintJob job = service.createPrintJob(); Doc doc = new SimpleDoc(decodedImageData, flavor, null); job.print(doc, null); } </code></pre> <p>It works well in a standalone application. However, I am not able to display print dialog in servlet/jsp.</p>
<p>You need to be aware that it is not the client that is executing your code here. It's the server.</p> <p>You'll have to make a javascript function for that to work.</p>
<p>I would call <code>window.print();</code> in javascript. Try it below.</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;a href="javascript:print()"&gt;Print&lt;/a&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
43,791
<p>I'm trying to compile code from F# to use in Silverlight. I compile with:</p> <p>--noframework --cliroot "C:\program Files\Microsoft Silverlight\2.0.31005.0" --standalone</p> <p>This generates a standalone assembly that references the SL framework. But when I try to add a reference to the generated assembly, I get this error:</p> <blockquote> <p>You can only add project references to other Silverlight projects in the solution.</p> </blockquote> <p>What is the VS plugin doing to determine that this isn't a Silverlight assembly? Here's the manifest:</p> <pre><code>// Metadata version: v2.0.50727 .assembly extern mscorlib { .publickeytoken = (7C EC 85 D7 BE A7 79 8E ) // |.....y. .ver 2:0:5:0 } .assembly FSSLLibrary1 { // --- The following custom attribute is added automatically, do not uncomment ------- // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 01 01 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } .module 'F#-Module-FSSLLibrary1' // MVID: {49038883-5D18-7281-A745-038383880349} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY // Image base: 0x04120000 </code></pre> <p>I don't understand what it's finding that it doesn't like; it's pure verifiable IL. I compared to a SL "class library" assembly, and it looks the same. The only difference was some attributes, but I deleted those and VS still let me reference the DLL. I even added unverifiable IL to the "SL library" DLL and it still loaded.</p> <p>Any suggestions?</p> <p><em>Update:</em> I've done some poking around, and it doesn't seem to be the manifest that matters. It doesn't like something in the IL from the FSharp libraries. They are peverifiable, but something in there is triggering the rejection. </p>
<p><strong>Answer!</strong></p> <p>Apparently the problem is that when you add a reference to the bin\Release or bin\Debug, Visual Studio (or the Silverlight project system) decides to try to reference the project. This fails for whatever reason.</p> <p>If you copy the F# output DLL to another location, then the reference goes through just fine. (This will be a file reference, not a project reference, of course.)</p> <p>Then setup dependencies so the F# library builds first, then you can use a file reference to get the F#-generated binary.</p> <p><em>Update:</em> One more apparent issue. If I turn optimize code on, then I get this error:</p> <pre><code>C:\test\SilverlightApplication1\FSC(0,0): error FS0193: internal error: the module/namespace 'System' from compilation unit 'mscorlib' did not contain the namespace, module or type 'MarshalByRefObject' </code></pre> <p>If I keep optimized code off, this goes away and everything works fine.</p>
<p>Visual Studio uses the IsSilverlightAssembly() function in the Microsoft.VisualStudio.Silverlight.SLUtil type to check if a reference can be set.</p> <p>David Betz has a nice blog post describing the details <a href="http://www.netfxharmonics.com/2008/12/Reusing-NET-Assemblies-in-Silverlight" rel="nofollow noreferrer">here</a>.</p>
29,325
<p>Sorry for asking an implement my feature question type question last time. I am new to Stackoverflow.com and also to php that's why.</p> <p>What I was trying to ask is:</p> <p>I have made a admin account. Members have registration page so a member will register. When user registers in the database table I will have a field for which 0 value will be initialised which means he is not approved. In admin account I have code to get the list of members. The code is given below:</p> <pre><code>&lt;h2&gt;&lt;?php echo "User list"; ?&gt;&lt;/h2&gt; &lt;table border="0" cellpadding="0" cellspacing="0"&gt; &lt;tr bgcolor="#f87820"&gt; &lt;td&gt;&lt;img src="img/blank.gif" alt="" width="10" height="25"&gt;&lt;/td&gt; &lt;td class="tabhead"&gt;&lt;img src="img/blank.gif" alt="" width="150" height="6"&gt;&lt;br&gt;&lt;b&gt;&lt;?php echo "first name"; ?&gt;&lt;/b&gt;&lt;/td&gt; &lt;td class="tabhead"&gt;&lt;img src="img/blank.gif" alt="" width="150" height="6"&gt;&lt;br&gt;&lt;b&gt;&lt;?php echo "lastname name"; ?&gt;&lt;/b&gt;&lt;/td&gt; &lt;td class="tabhead"&gt;&lt;img src="img/blank.gif" alt="" width="150" height="6"&gt;&lt;br&gt;&lt;b&gt;&lt;?php echo "member id"; ?&gt;&lt;/b&gt;&lt;/td&gt; &lt;td class="tabhead"&gt;&lt;img src="img/blank.gif" alt="" width="50" height="6"&gt;&lt;br&gt;&lt;b&gt;&lt;?php echo "delete"; ?&gt;&lt;/b&gt;&lt;/td&gt; &lt;td&gt;&lt;img src="img/blank.gif" alt="" width="10" height="25"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;?php } $result=mysql_query("SELECT member_id,firstname,lastname,login FROM members ORDER BY firstname"); $i = 0; while($row = mysql_fetch_array($result)) { if ($i &gt; 0) { echo "&lt;tr valign='bottom'&gt;"; echo "&lt;td bgcolor='#ffffff' height='1' style='background-image:url(img/strichel.gif)' colspan='6'&gt;&lt;/td&gt;"; echo "&lt;/tr&gt;"; } echo "&lt;tr valign='middle'&gt;"; echo "&lt;td class='tabval'&gt;&lt;img src='img/blank.gif' alt='' width='10' height='20'&gt;&lt;/td&gt;"; echo "&lt;td class='tabval'&gt;&lt;b&gt;".$row['lastname']."&lt;/b&gt;&lt;/td&gt;"; echo "&lt;td class='tabval'&gt;".$row['firstname']." &lt;/td&gt;"; echo "&lt;td class='tabval'&gt;".$row['member_id']." &lt;/td&gt;"; echo "&lt;td class='tabval'&gt;&lt;a onclick=\"return &lt;/span&gt;&lt;/a&gt;&lt;/td&gt;"; echo "&lt;td class='tabval'&gt;&lt;/td&gt;"; echo "&lt;/tr&gt;"; $i++; } ?&gt; &lt;/table&gt; in this i wanna add tho more things in the table 1 to delete a member and 2 to have approved or denied option for that i made two functiom below code is to delete if($_REQUEST['action']=="del") { $memberId = mysql_real_Escape_string($_REQUEST['member_id']); mysql_query("DELETE FROM members WHERE member_id=$memberId"); } </code></pre> <p>below one for approving members</p> <p>But my problem is I don't know how to include a button or radio button in the table which can pass value delete or approve to these functions.</p> <p>Please tell me how the syntax is to add this button so that for approving I can change the value 0 that I gave in the database to 1 so that member get approved.</p>
<p>Try this:</p> <pre><code>echo '&lt;td&gt;&lt;a href="http://yourwebsite/yourscriptname.php?action=del&amp;amp;member_id=' . htmlspecialchars($row['member_id']) . '"&gt;Delete&lt;/a&gt;'; if ($row['approved'] == 0) { echo '&amp;nbsp;&lt;a href="http://yourwebsite/yourscriptname.php?action=approve&amp;amp;member_id=' . htmlspecialchars($row['member_id']) . '"&gt;Approve&lt;/a&gt;'; } echo '&lt;/td&gt;'; </code></pre> <p>And make sure ALL of your database values are being sent to the browser in htmlspecialchars().</p> <p>On the flipside,</p> <pre><code>$member_id = 0; if (isset($_GET['member_id'])) $member_id = intval($_GET['member_id']); $action = ''; if (isset($_GET['action'])) $action = $_GET['action']; $sql = ''; switch($action) { case 'approve': $sql = "UPDATE members SET approval = 1 WHERE member_id = $member_id"; break; case 'delete': $sql = "DELETE FROM member WHERE member_id = $member_id"; break; } if (!empty($sql) &amp;&amp; !empty($member_id)) { // execute the sql. } </code></pre>
<p>What I would do is to set up a form inside of the table.</p> <p><code>?&gt; &lt;form name="deleteUser" id="deleteUser" method="post" action=""&gt; &lt;input type="hidden" name="member_id" id="member_id" value="&lt;?php echo $row['member_id'] ?&gt; &lt;input type="submit" name="action" id="action" value="del" /&gt; &lt;/form&gt;&lt;?php </code></p> <p>I would insert that in between your <code>&lt;td&gt;</code> tag. </p> <p><code>&lt;td class='tabval'&gt;INSERT HERE&lt;/td&gt;"; </code></p>
47,225
<p>I'm trying to resize an embedded object. The issue is that when the mouse hovers over the object, it takes "control" of the mouse, swallowing up movement events. The result being that you can expand the div containing the object, but when you try to shrink it, if the mouse enters the area of the object the resize halts. </p> <p>Currently, I hide the object while moving. I'm wondering if there's a way to just prevent the object from capturing the mouse. Perhaps overlaying another element on top of it that prevents mouse events from reaching the embedded object?</p> <hr> <p>using ghosting on the resize doesn't work for embedded objects, btw.</p> <hr> <p>Adding a bounty, as I can't ever seem to get this working. To collect, simply do the following:</p> <p>Provide a webpage with a PDF embedded in it, centered on the page. The pdf can't take up the entire page; make its width/height 50% the width of the browser window or something.</p> <p>Use jQuery 1.2.6 to add resize to every side and corner of the pdf. </p> <p>The pdf MUST NOT CAPTURE THE MOUSE and stop dragging WHEN SHRINKING THE PDF. That means when I click on the edge of the pdf and drag, when the mouse enters the display box of the pdf, the resize operation continues.</p> <p>This must work in IE 7. Conditional CSS (if gte ie7 or whatever) hacks are fine.</p> <hr> <p>Hmmm... I'm thinking it might be an issue with iframe...</p> <pre><code> &lt;div style="text-align:center; padding-top:50px;"&gt; &lt;div id="doc" style="width:384px;height:512px;"&gt; &lt;iframe id="docFrame" style="width: 100%; height: 100%;" src='http://www.ready.gov/america/_downloads/sampleplan.pdf'&gt; &lt;/iframe&gt;&lt;/div&gt;&lt;/div&gt; &lt;div id="data"&gt;&lt;/div&gt; &lt;script type="text/javascript"&gt; $(document).ready(function() { var obj = $('#docFrame'); $('#doc').resizable({handles:'all', resize: function(e, ui) { $('#data').html(ui.size.width + 'x' + ui.size.height); obj.attr({width: ui.size.width, height: ui.size.height}); }}); }); &lt;/script&gt; </code></pre> <p>This doesn't work. When your mouse strays into the iframe the resize operation stops.</p> <hr> <p>There are some good answers; if the bounty runs out before I can get around to vetting them all I'll reinstate the bounty (same 150 points).</p>
<p>Well I was utterly unable to find a XPS Document Viewer example or whatnot, but I was able to come up with <a href="http://www.rootspot.com/stackoverflow/box.php" rel="nofollow noreferrer"><code>this working sample</code></a>. It doesn't use the overlay idea, but it's a pdf that you can resize...</p> <p><strong>edit</strong> the thing that made this work without the overlay was the <code>wmode</code> param being set to <code>transparent</code>. I'm not really familiar with the details but it made it play nice on IE7. Also works on Firefox, Chrome, Safari and Opera.</p> <p><strong>new edit</strong> having serious trouble getting it to work with frames. Some information I've found is not very encouraging. Is it impossible to have it with an <code>&lt;object&gt;</code>? Or an <code>&lt;object&gt;</code> inside the iframe?</p>
<p>Overlay.</p> <p>One word answers prohibited, this sentence no verb.</p>
21,193
<p>Greetings.</p> <p>I'm trying to implement some multithreaded code in an application. The purpose of this code is to validate items that the database gives it. Validation can take quite a while (a few hundred ms to a few seconds), so this process needs to be forked off into its own thread for each item.</p> <p>The database may give it 20 or 30 items a second in the beginning, but that begins to decline rapidly, eventually reaching about 65K items over 24 hours, at which point the application exits.</p> <p>I'd like it if anyone more knowledgeable could take a peek at my code and see if there's any obvious problems. No one I work with knows multithreading, so I'm really just on my own, on this one.</p> <p>Here's the code. It's kinda long but should be pretty clear. Let me know if you have any feedback or advice. Thanks!</p> <pre><code>public class ItemValidationService { /// &lt;summary&gt; /// The object to lock on in this class, for multithreading purposes. /// &lt;/summary&gt; private static object locker = new object(); /// &lt;summary&gt;Items that have been validated.&lt;/summary&gt; private HashSet&lt;int&gt; validatedItems; /// &lt;summary&gt;Items that are currently being validated.&lt;/summary&gt; private HashSet&lt;int&gt; validatingItems; /// &lt;summary&gt;Remove an item from the index if its links are bad.&lt;/summary&gt; /// &lt;param name="id"&gt;The ID of the item.&lt;/param&gt; public void ValidateItem(int id) { lock (locker) { if ( !this.validatedItems.Contains(id) &amp;&amp; !this.validatingItems.Contains(id) ){ ThreadPool.QueueUserWorkItem(sender =&gt; { this.Validate(id); }); } } } // method private void Validate(int itemId) { lock (locker) { this.validatingItems.Add(itemId); } // ********************************************* // Time-consuming routine to validate an item... // ********************************************* lock (locker) { this.validatingItems.Remove(itemId); this.validatedItems.Add(itemId); } } // method } // class </code></pre>
<p>The thread pool is a convenient choice if you have <em>light weight</em> sporadic processing that isn't time sensitive. However, I recall reading on MSDN that it's not appropriate for large scale processing of this nature.</p> <p>I used it for something quite similar to this and regret it. I took a worker-thread approach in subsequent apps and am much happier with the level of control I have.</p> <p>My favorite pattern in the worker-thread model is to create a master thread which holds a queue of tasks items. Then fork a bunch of workers that pop items off that queue to process. I use a blocking queue so that when there are no items the process, the workers just block until something is pushed onto the queue. In this model, the master thread produces work items from some source (db, etc.) and the worker threads consume them.</p>
<p>I would be concerned about performance here. You indicated that the database may give it 20-30 items per second and an item could take up to a few seconds to be validated. That could be quite a large number of threads -- using your metrics, worst case 60-90 threads! I think you need to reconsider the design here. Michael mentioned a nice pattern. The use of the queue really helps keep things under control and organized. A semaphore could also be employed to control number of threads created -- i.e. you could have a maximum number of threads allowed, but under smaller loads, you wouldn't necessarily have to create the maximum number if fewer ended up getting the job done -- i.e. your own pool size could be dynamic with a cap.</p> <p>When using the thread-pool, I also find it more difficult to monitor the execution of threads from the pool in their performing the work. So, unless it's fire and forget, I am in favor of more controlled execution. I know you mentioned that your app exits after the 65K items are all completed. How are you monitoring you threads to determine if they have completed their work -- i.e. all queued workers are done. Are you monitoring the status of all items in the HashSets? I think by queuing your items up and having your own worker threads consume off that queue, you can gain more control. Albeit, this can come at the cost of more overhead in terms of signaling between threads to indicate when all items have been queued allowing them to exit.</p>
17,480
<p>In TFS when you merge branch A to branch B and checkin, you get a single changeset on B (typically with a comment like "merged A->B"). </p> <p>This means B doesn't have any of the checkin history from A. So if someone created a new file on branch A, you can't tell who created it from branch B. And if someone updated a file on A, you can't tell who did the update from branch B.</p> <p>Is there any way to see this kind of detailed changeset history across branches? Some kind of power toy, or third party tool, or anything?</p> <p>Update: The TFS Power Toy tfpt history /followbranches tool does not "expand merges," it only "expands branches" and therefore doesn't solve this problem.</p>
<p>TFS 2010 will include support for this.</p> <p>Brian Harry talks about it in <a href="http://channel9.msdn.com/pdc2008/TL52/" rel="noreferrer">this presentation</a>.</p> <p>You will now be able to see where a change originated and who made it after the change has been merged to a different branch.</p>
<p>Might want to try the TFS Follow branch History tool:</p> <p><a href="http://www.codeplex.com/TFSBranchHistory" rel="nofollow noreferrer"><a href="http://www.codeplex.com/TFSBranchHistory" rel="nofollow noreferrer">http://www.codeplex.com/TFSBranchHistory</a></a></p>
6,789
<p>Given a document written with normal quotes, e.g.</p> <pre><code>Ben said "buttons, dear sir". I replied "Did you say 'buttons'?" to him. </code></pre> <p>What ways can one turn these sort of things into LaTeX quotes, with the appropriate semantics. i.e.</p> <pre><code>Ben said ``buttons, dear sir''. I replied ``Did you say `buttons'?'' to him. </code></pre> <p>So that LaTeX produces:</p> <pre><code>Ben said “buttons, dear sir”. I replied “Did you say ‘buttons’?” </code></pre> <p>My first thought is to turn to a regex. However, I'm not getting any hits from Google or the regex libraries for "LaTeX quotes regular expression", and of course "TeX quotes regular expression" seems to return too many.</p> <p>Thank you.</p>
<p>In general, this problem is harder than it looks.</p> <p>The simplest cases <em>can</em> be treated with regular expressions, but for more general situations you will almost certainly need to build a recursive parser: regular expression will only work if there is no nesting.</p> <p>The big problem is going to be associated with identifying single <code>"'"</code>s that are not paired---as is contractions (the <code>"'"</code> in <code>"don't"</code> should not be changed, <em>and</em> should not be paired).</p> <hr> <p>Lets see if we can write a usable EBNF description:</p> <pre><code>input: text+ text: uquote|squote|dquote squote "'" text "'" dquote """ text """ uquote: [contraction|.]+ contraction: [A-Za-z]+ "'" [A-Za-z]+ </code></pre> <p>which is limited to contractions that have the <code>"'"</code> in the middle of the word. All the associated action will just echo the input, except that the <code>squote</code> and <code>dquote</code> terms replace the quotes as appropriate.</p> <hr> <p>I used regular expressions followed by human fix-ups for a fairly simple one-off, but that would be labor intensive for on-going work.</p>
<p>Simply, use `` for opening quotations and '' for closing</p>
45,092
<p>I have two strings</p> <pre><code>&lt;EM&gt;is &lt;i&gt;love&lt;/i&gt;&lt;/EM&gt;,&lt;PARTITION /&gt; </code></pre> <p>and</p> <pre><code>&lt;EM&gt;is &lt;i&gt;love&lt;/i&gt;,&lt;PARTITION /&gt; </code></pre> <p>I want a regex to match the second string completely but should not match the first one. Please help.</p> <p>Note: Everything can change except the EM and PARTITION tags.</p>
<p>If you want to match a string entirely if it does not contain a certain substring, use a regex to match the substring, and return the whole string if the regex does not match. You didn't say which language you're using, but you tagged your question with .NET, so here goes in C#:</p> <pre><code>if (Regex.IsMatch(subjectString, "&lt;/EM&gt;")) { return null; } else { return subjectString; } </code></pre> <p>Since is just a bit of literal text, you don't even need to use a regular expression:</p> <pre><code>if (subjectString.Contains("&lt;/EM&gt;")) { return null; } else { return subjectString; } </code></pre> <p>In a situation where all you could use is a regex, try this:</p> <pre><code>\A((?!&lt;/EM&gt;).)*\Z </code></pre> <p>The regex-only solution will be far less efficient than the above code samples.</p>
<p>I don't think you're asking the right question. This regex matches the second string completely and not the first:</p> <pre>/^&lt;EM&gt;is &lt;i&gt;love&lt;\/i&gt;,&lt;PARTITION \/&gt;$/</pre> <p>But obviously, you want to match a class of strings, not just the second string... right? Define the class of strings you want to match and you can be 1 step closer to getting the regular expression you need.</p>
41,365
<p>Sometimes, when we're doing small changes to our web apps, e.g. bug fixes, we don't build a whole new WAR-file each time, but merely replace just the affected class files in the exploded web app directory under <code>WEB-INF/classes</code> and restart the app.</p> <p>Is that okay?</p>
<p>I'd say that probably isn't a best practice, because of versioning: how do you know which version of the application you've got deployed? If you deploy a .war file your build process can take care of updating a build number (from source control, or separately, whatever - as long as each build has a different number it's OK).</p> <p>If you're using continuous integration (and it's definitely a good idea to be) then your build process should be kicking out an 'artifact' (war file) each time you make changes in source code. also perhaps tagging the code in version control with the build number.</p> <p>So, when you deploy your web app, you know exactly which version is running and which source code makes up that version.</p> <p>Making small incremental changes by updating individual .class files I'd say is probably not a good idea for anything other than local developer testing.</p>
<p>Agree with PHill; it seems the time savings are negligible and the potential risks are many</p>
27,279
<p>I recently discussed editors with a co-worker. He uses one of the less popular editors and I use another (I won't say which ones since it's not relevant and I want to avoid an editor flame war). I was saying that I didn't like his editor as much because it doesn't let you do find/replace with regular expressions.</p> <p>He said he's never wanted to do that, which was surprising since it's something I find myself doing all the time. However, off the top of my head I wasn't able to come up with more than one or two examples. Can anyone here offer some examples of times when they've found regex find/replace useful in their editor? Here's what I've been able to come up with since then as examples of things that I've actually had to do:</p> <ol> <li><p>Strip the beginning of a line off of every line in a file that looks like:<br> <code>Line 25634 :</code><br> <code>Line 632157 :</code></p></li> <li><p>Taking a few dozen files with a standard header which is slightly different for each file and stripping the first 19 lines from all of them all at once.</p></li> <li><p>Piping the result of a MySQL select statement into a text file, then removing all of the formatting junk and reformatting it as a Python dictionary for use in a simple script.</p></li> <li><p>In a CSV file with no escaped commas, replace the first character of the 8th column of each row with a capital A.</p></li> <li><p>Given a bunch of GDB stack traces with lines like<br> <code>#3 0x080a6d61 in _mvl_set_req_done (req=0x82624a4, result=27158) at ../../mvl/src/mvl_serv.c:850</code><br> strip out everything from each line except the function names.</p></li> </ol> <p>Does anyone else have any real-life examples? The next time this comes up, I'd like to be more prepared to list good examples of why this feature is useful.</p>
<p>Just last week, I used regex find/replace to convert a CSV file to an XML file.</p> <p>Simple enough to do really, just chop up each field (luckily it didn't have any escaped commas) and push it back out with the appropriate tags in place of the commas.</p>
<p>The first thing I do with any editor is try to figure out it's Regex oddities. I use it all the time. Nothing really crazy, but it's handy when you've got to copy/paste stuff between different types of text - SQL &lt;-> PHP is the one I do most often - and you don't want to fart around making the same change 500 times.</p>
7,510
<p>I'm working on a system with four logical CPS (two dual-core CPUs if it matters). I'm using make to parallelize twelve trivially parallelizable tasks and doing it from cron.</p> <p>The invocation looks like:</p> <pre><code>make -k -j 4 -l 3.99 -C [dir] [12 targets] </code></pre> <p>The trouble I'm running into is that sometimes one job will finish but the next one won't startup even though it shouldn't be stopped by the load average limiter. Each target takes about four hours to complete and I'm wondering if this might be part of the problem.</p> <p>Edit: Sometimes a target does fail but I use the -k option to have the rest of the make still run. I haven't noticed any correlation with jobs failing and the next job not starting.</p>
<p>I'd drop the '-l'</p> <p>If all you plan to run the the system is this build I <em>think</em> the -j 4 does what you want.</p> <p>Based on my memory, if you have anything else running (crond?), that can push the load average over 4.</p> <p><a href="http://sunsite.ualberta.ca/Documentation/Gnu/make-3.79/html_chapter/make_5.html#SEC47" rel="nofollow noreferrer">GNU make ref</a></p>
<p>Does make think one of the targets is failing? If so, it will stop the make after the running jobs finish. You can use -k to tell it to continue even if an error occurs.</p>
5,589
<p>In my existing (Pre-SVN 1.5) merge strategy, we create a copy of the Trunk (called BasePoint) at the moment of branch-creation for referencing later during the merge.</p> <p>When we need to merge a branch back into the trunk, we perform 2 operations.</p> <ol> <li><p>Merge from BasePoint to LatestTrunk (Trunk has likely moved on since the original branch) into Working copy of Branch and then commit.</p> <p>At this point we typically check that the merge into the branch has not damaged anything</p> </li> <li><p>Merge from LatestTrunk to LatestBranch back into Working copy of trunk and then commit.</p> </li> </ol> <p>Documentation suggests that I use the new reintegrate merge on the Trunk and Merge from the Branch.</p> <p><strong>Do I need to merge from the trunk into the dev branch first or is this included in the new reintegrate option?</strong></p> <p>To put it another way, does the new <code>merge --reintegrate</code> functionality represent 'each of my previous merges' or 'the whole operation' ?</p> <p>(FWIW I am using TortoiseSVN 1.5.1)</p>
<p>The short answer is, <strong>You still have to do both steps.</strong></p> <p><a href="http://svnbook.red-bean.com/en/1.5/svn-book.html#svn.branchmerge.basicmerging" rel="noreferrer">The SVN book</a> explains the process for merging as:</p> <ol> <li>svn merge <a href="http://trunk/path" rel="noreferrer">http://trunk/path</a> while in a branch working copy</li> <li>svn merge --reintegrate <a href="http://branch/path" rel="noreferrer">http://branch/path</a> while in a trunk working copy</li> </ol> <p>Notice the lack of revision numbers. This probably doesn't feel like a huge win. The new coolness is the ability to re-run the merge as you are coding in your branch, allowing you to keep the branch up to date with changes in trunk (without recording revision numbers by hand!). SVN keeps track of what needs to be merged in from trunk and what changes are unique to the branch. When you are done with the branch, --reintegrate uses that data to automatically merge only the branch changes back to trunk.</p>
<p>I believe reintegrate does not actually do the two operations, but instead is used to merge back into trunk from an updated branch. You will still need to do the first set of merge/commit operations to update the branch first.</p> <p>Here is a link to the <a href="http://svnbook.red-bean.com/en/1.5/svn-book.html#svn.branchemerge.basicmerging.stayinsync" rel="nofollow noreferrer">Subversion Book</a>. It is possible to get this book in dead tree format.</p> <p>From the link, it sounds like using --reintegrate handles some weird cases, probably like merge usually does compared to just using straight patches (read the section "Why Not Use Patches Instead?").</p>
20,965
<p>I'm doing a website for a family member's wedding. A feature they requested was a photo section where all the guests could go after the wedding and upload their snaps. I said this was a stellar idea and I went off to build it.</p> <p>Well there's just the one problem: logistics. Upload speeds are slow and photos from modern cameras are huge (2-5+Megs). </p> <p>I will only need ~800px wide images and some of them might require rotating so ideally I'm looking about using a client-side editor to do three things:</p> <ol> <li>Let users pick multiple files</li> <li>Let them rotate some images so they're the right way up</li> <li>Resize them and then upload</li> </ol> <p>And in my dream world, it'd be free and open source. Any ideas?</p> <p>Just a reminder: this is something the guests have to use. Some of them will be pretty computer savvy but others will be almost completely illiterate. Installing desktop apps isn't really an option. And I assume 98% of them have Flash and Java installed.</p> <p>Edit: I'd prefer a Flash/Java option over SilverLight, not least because it has a smaller install rate at the moment, but also because I'm on Linux and I'd like to test it =)</p>
<p>The most common solution for this is a java applet, although most of them are not free. Examples:</p> <ul> <li><a href="http://www.jumploader.com/" rel="nofollow noreferrer">http://www.jumploader.com/</a></li> <li><a href="http://www.aurigma.com/Products/ImageUploader/OnlineDemo.aspx" rel="nofollow noreferrer">http://www.aurigma.com/Products/ImageUploader/OnlineDemo.aspx</a></li> <li><a href="http://www.javaatwork.com/java-upload-applet/details.html" rel="nofollow noreferrer">http://www.javaatwork.com/java-upload-applet/details.html</a></li> <li>JUpload, mentioned by ScArcher2</li> </ul>
<p>GIMP (<a href="http://www.gimp.org/" rel="nofollow noreferrer">http://www.gimp.org/</a>) is a good tool for doing resize and is open source.</p>
9,996
<p>Our web site (running Rails) freezes IE6 nearly every time. The same code, deployed on a different server, does not freeze IE6. Where and how should we start tracking this down?</p>
<p>You need to determine the difference between them, so I'd start out with the following:</p> <pre><code>curl -D first.headers -o first.body http://first.example.com curl -D second.headers -o second.body http://second.example.com diff -u first.headers second.headers diff -u first.body second.body </code></pre>
<p>Perhaps some more info that will help you.</p> <p>We had the same problem and narrowed it also down to the GZIP compression. The key was that we had gzip compression on for our ScriptResources, which also deliver the javascripts used by the controls in our .NET page.</p> <p>Apperently there is a bug in IE6 that causes is to freeze, we believe that the browser receives the files and parses them <strong>before unpacking them</strong>, which causes the freeze.</p> <p>For now we have turned off the gzip compression, but as we have a large number of files provided through the ScriptsResource manager we need a different solution.</p>
16,811
<p>I'm playing with an embedded Linux device and looking for a way to get my application code to communicate with a web interface. I need to show some status information from the application on the devices web interface and also would like to have a way to inform the application of any user actions like uploaded files etc. PHP-seems to be a good way to make the interface, but the communication part is harder. I have found the following options, but not sure which would be the easiest and most convenient to use.</p> <p><strong>Sockets.</strong> Have to enable sockets for the PHP first to try this. Don't know if enabling will take much more space.</p> <p><strong>Database.</strong> Seems like an overkill solution.</p> <p><strong>Shared file.</strong> Seems like a lot of work.</p> <p><strong>Named pipes.</strong> Tried this with some success, but not sure if there will be problems with for example on simultaneous page loads. Maybe sockets are easier?</p> <p>What would be the best way to go? Is there something I'm totally missing? How is this done in those numerous commercial Linux based network switches?</p>
<p>I recently did something very similar using sockets, and it worked really well. I had a Java application that communicates with the device, which listened on a server socket, and the PHP application was the client.</p> <p>So in your case, the PHP client would initialize the connection, and then the server can reply with the status of the device.</p> <p>There's plenty of tutorials on how to do client/server socket communication with most languages, so it shouldn't take too long to figure out.</p>
<p>Embedded linux boxes for routing with web interface don't use PHP. They use CGI and have shell scripts deliver the web page.</p> <p>For getting information from the application to the web interface, the Shared file option seems most reasonable to me. The application can just write information into the file which is read by PHP.</p> <p>The other way round it looks not so good at first. PHP supports locking of files, but it most probably doesn't work on a system level. Perhaps one solution is that in fact every PHP script which has information for the application creates it own file (with a unique id filename, e.g. based on timestamp + random value). The application could watch a designated directory for these files to pop-up. After processing them, it could just delete them. For that, the application only needs write permission on the directory (so file ownership is not an issue).</p>
42,718
<p>In rails I want to log some information in a different log file and not the standard development.log or production.log. I want to do this logging from a model class.</p>
<p>You can create a Logger object yourself from inside any model. Just pass the file name to the constructor and use the object like the usual Rails <code>logger</code>:</p> <pre><code>class User &lt; ActiveRecord::Base def my_logger @@my_logger ||= Logger.new("#{Rails.root}/log/my.log") end def before_save my_logger.info("Creating user with name #{self.name}") end end </code></pre> <p>Here I used a class attribute to memoize the logger. This way it won't be created for every single User object that gets created, but you aren't required to do that. Remember also that you can inject the <code>my_logger</code> method directly into the <code>ActiveRecord::Base</code> class (or into some superclass of your own if you don't like to monkey patch too much) to share the code between your app's models.</p>
<p>The Logging framework, with its deceptively simple name, has the sophistication you crave!</p> <p>Follow the very short instructions of <a href="https://github.com/TwP/logging-rails" rel="nofollow">logging-rails</a> to get started filtering out noise, getting alerts, and choosing output in a fine-grained and high-level way.</p> <p>Pat yourself on the back when you are done. Log-rolling, daily. Worth it for that alone.</p>
43,829
<p>We have created a control that needs to persist data via the ViewState property of the Control class. Our class subclasses control strictly to get access to the ViewState property (it's protected on the Page object). We are adding the control to Page.Controls in OnInit, and then attempt to set the ViewState property in OnPreLoad.</p> <p>When we decode and examine the ViewState of the page, our values have not been written out, and are thus not available for later retrieval.</p> <p>Does anyone know how we can get our control to participate in the ViewState process?</p>
<p>The issue is adding the control to the Page directly. Unfortunately this is too high up the controls hierarchy to participate in the Forms ViewState Handling. If you add the control onto the actual ASPNet Form's Controls collection somewhere then it will successfully participate in LoadViewStateRecursive and SaveViewStateRecursive.</p>
<p>Try creating your control in OnInit, then add it to the Page.Controls during OnLoad.</p>
15,872
<p>I'm reading ScottGu's blog about ASP.NET MVC, and found a lot of code cannot compile or doesn't work as expected. </p> <p><a href="http://weblogs.asp.net/scottgu/archive/2007/11/13/asp-net-mvc-framework-part-1.aspx" rel="nofollow noreferrer">http://weblogs.asp.net/scottgu/archive/2007/11/13/asp-net-mvc-framework-part-1.aspx</a> <a href="http://weblogs.asp.net/scottgu/archive/2007/12/03/asp-net-mvc-framework-part-2-url-routing.aspx" rel="nofollow noreferrer">http://weblogs.asp.net/scottgu/archive/2007/12/03/asp-net-mvc-framework-part-2-url-routing.aspx</a></p> <p>So, did ASP.NET MVC go through huge change after his blogging? any up-to-date online tutorial about ASP.NET MVC?</p>
<p>That code is based on asp.net mvc 1.0 Preview2. Version 1 has been released, and Version 2 is currently in beta. Check out the samples at <a href="http://asp.net/mvc" rel="nofollow noreferrer">http://asp.net/mvc</a> to get updated samples</p>
<p>Take a look here:</p> <p><a href="http://www.asp.net/mvc/" rel="nofollow noreferrer">http://www.asp.net/mvc/</a></p> <p>It HAS changed a lot, it was presented as a new beta version on PDC in LA in October...</p>
43,638
<p>We're working on an hospital information system that is being written on C# and using NHibernate to map objects to database. MVC pattern is being used to separate business logic from UI. Here is the problem,</p> <p>How do you get variable sized different set of strings to UI?</p> <p>For example a <code>Contact</code> object have a property named <code>City</code> that holds which city contact lives. In country that the app is written for has more than 80 cities. How could you write those cities to a combo box? (or a data grid, tables, ...) In this example the city number is fixed. There is no need to add another city for a long time. (If the city list changes, recompiling is not a problem)</p> <p>For example a <code>Contact</code> object have another property named <code>FooBar</code> which is going to be hold 1000 different string values and these values is going to be selected from a combo box for that property. And this set can be grown if users want. How do you load the combo box with these values? (If the string list statically written to combo box object, recompiling is a problem)</p> <p>I have different solutions as below</p> <ol> <li>All string values statically written to combo box in code or designer</li> <li>Get the values from a resource file</li> <li>Write those values to an XML file (Actually same as above, but no need to recompile)</li> <li>Make a <code>City</code> object and get the values into a list from <code>CITY</code> table with NHibernate</li> <li>Make a class named <code>StringHolder</code> which has a <code>Type</code> and <code>Value</code> property. All string values(including <code>City</code> and <code>FooBar</code>) would be written in just one table named <code>STRINGHOLDER</code>. And get those values with a key like "CITY" or "FOOBAR" with NHibernate.</li> </ol> <p>Which one would you choose? Or could you suggest me another one?</p> <p>Thanks all</p>
<p>I would vote for solution #4. That's the way I have always done it in similar situations. It just seems like a cleaner solution.</p>
<p>How do you feel of using List&lt;string&gt; for a list of City? Load this list of strings in your DAL or BL and then pass it on to UI.</p> <p>Same solution should be good for FooBar values too.</p> <p>In case you have IDs associated with City or FooBar, say NY and its numeric ID in DB is 1, then you can use KeyValuePair&lt;TKey, TValue&gt;. With generics you can dictate what data goes in this KeyValuePair. City name or FooBar's string value can be key and numeric ID can be value.</p> <p>Just 2 cents.</p>
26,860
<p>How do I hide/lock a few tables in Oracle so that only my application has access to modify those data in the table?</p>
<p>Create a user/login to the DB that you can control. Assign that user as the owner (using grants) of the tables you need to "hide/lock". Use grants to make the tables inaccessible ( or read only) to other users.</p>
<p>After creating the user, make sure you remove the grants for other users. By default, default users have the grant. So make sure only your user has all the the grants</p>
44,593
<p>Is it possible to use an <a href="http://en.wikipedia.org/wiki/ASP.NET" rel="noreferrer">ASP.NET</a> web.sitemap with a jQuery <a href="http://users.tpg.com.au/j_birch/plugins/superfish/" rel="noreferrer">Superfish</a> menu? </p> <p>If not, are there any standards based browser agnostic plugins available that work with the web.sitemap file?</p>
<p>I found this question while looking for the same answer... everyone <em>says</em> it's possible but no-one gives the actual solution! I seem to have it working now so thought I'd post my findings...</p> <p>Things I needed:</p> <ul> <li><p><a href="http://users.tpg.com.au/j_birch/plugins/superfish/#download" rel="noreferrer">Superfish</a> which also includes a version of <a href="http://jquery.com/" rel="noreferrer">jQuery</a></p></li> <li><p><a href="http://cssfriendly.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=2159" rel="noreferrer">CSS Friendly Control Adaptors</a> download DLL and .browsers file (into /bin and /App_Browsers folders respectively)</p></li> <li><p><a href="http://msdn.microsoft.com/en-us/library/yy2ykkab.aspx" rel="noreferrer">ASP.NET SiteMap</a> (a .sitemap XML file and <code>siteMap</code> provider entry in web.config)</p></li> </ul> <p>My finished <code>Masterpage.master</code> has the following <code>head</code> tag:</p> <pre><code>&lt;head runat="server"&gt; &lt;script type="text/javascript" src="/script/jquery-1.3.2.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="/script/superfish.js"&gt;&lt;/script&gt; &lt;link href="~/css/superfish.css" type="text/css" rel="stylesheet" media="screen" runat="server" /&gt; &lt;script type="text/javascript"&gt; $(document).ready(function() { $('ul.AspNet-Menu').superfish(); }); &lt;/script&gt; &lt;/head&gt; </code></pre> <p>Which is basically all the stuff needed for the jQuery Superfish menu to work. Inside the page (where the menu goes) looks like this (based on <a href="http://www.devx.com/asp/Article/31889" rel="noreferrer">these instructions</a>):</p> <pre><code>&lt;asp:SiteMapDataSource ID="SiteMapDataSource" runat="server" ShowStartingNode="false" /&gt; &lt;asp:Menu ID="Menu1" runat="server" DataSourceID="SiteMapDataSource" Orientation="Horizontal" CssClass="sf-menu"&gt; &lt;/asp:Menu&gt; </code></pre> <p>Based on the documentation, this seems like it SHOULD work - but it doesn't. The reason is that the <code>CssClass="sf-menu"</code> gets overwritten when the Menu is rendered and the <code>&lt;ul&gt;</code> tag gets a <code>class="AspNet-Menu"</code>. I thought the line <code>$('ul.AspNet-Menu').superfish();</code> would help, but it didn't. </p> <p><strong>ONE MORE THING</strong></p> <p>Although it is a hack (and please someone point me to the correct solution) I was able to get it working by opening the <code>superfish.css</code> file and <em>search and replacing</em> <strong>sf-menu</strong> with <strong>AspNet-Menu</strong>... and voila! the menu appeared. I thought there would be some configuration setting in the <code>asp:Menu</code> control where I could set the <code>&lt;ul&gt;</code> class but didn't find any hints via google.</p>
<p>The SiteMapDataSource control should be able to bind to any hierarchical data bound control. I'm not familiar with superfish but I know there are plenty of jQueryish controls out there to do this.</p>
12,929