instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>I'm trying to use <code>SQLBindParameter</code> to prepare my driver for input via <code>SQLPutData</code>. The field in the database is a <code>TEXT</code> field. My function is crafted based on MS's example here:
<a href="http://msdn.microsoft.com/en-us/library/ms713824(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms713824(VS.85).aspx</a>.</p>
<p>I've setup the environment, made the connection, and prepared my statement successfully but when I call <code>SQLBindParam</code> (using code below) it consistently fails reporting: <code>[Microsoft][SQL Native Client]Invalid precision value</code></p>
<pre><code>int col_num = 1;
SQLINTEGER length = very_long_string.length( );
retcode = SQLBindParameter( StatementHandle,
col_num,
SQL_PARAM_INPUT,
SQL_C_BINARY,
SQL_LONGVARBINARY,
NULL,
NULL,
(SQLPOINTER) col_num,
NULL,
&length );
</code></pre>
<p>The above relies on the driver in use returning "N" for the <code>SQL_NEED_LONG_DATA_LEN</code> information type in <code>SQLGetInfo</code>. My driver returns "Y". How do I bind so that I can use <code>SQLPutData</code>?</p>
|
<p>you're passing NULL as the buffer length, this is an in/out param that shoudl be the size of the col_num parameter. Also, you should pass a value for the ColumnSize or DecimalDigits parameters. </p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms710963(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms710963(VS.85).aspx</a></p>
|
<p>you're passing NULL as the buffer length, this is an in/out param that shoudl be the size of the col_num parameter. Also, you should pass a value for the ColumnSize or DecimalDigits parameters. </p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms710963(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms710963(VS.85).aspx</a></p>
| 10,960
|
<p>Considering "private" is the default access modifier for class Members, why is the keyword even needed?</p>
|
<p>It's for you (and future maintainers), not the compiler.</p>
|
<p>Actually, if the class or struct is not declared with an access modifier it defaults to internal. </p>
<p>So if you want to make it private, use private.</p>
| 16,629
|
<p>What I have is a collection of classes that all implement the same interface but can be pretty wildly different under the hood. I want to have a config file control which of the classes go into the collection upon starting the program, taking something that looks like :</p>
<pre><code><class1 prop1="foo" prop2="bar"/>
</code></pre>
<p>and turning that into :</p>
<pre><code>blah = new class1();
blah.prop1="foo";
blah.prop2="bar";
</code></pre>
<p>In a very generic way. The thing I don't know how to do is take the string <code>prop1</code> in the config file and turn that into the actual property accessor in the code. Are there any meta-programming facilities in C# to allow that?</p>
|
<p>It may be easier to serialise the classes to/from xml, you can then simply pass the XmlReader (which is reading your config file) to the deserializer and it will do the rest for you..</p>
<p><a href="http://www.diranieh.com/NETSerialization/XMLSerialization.htm" rel="noreferrer">This is a pretty good article on serialization</a></p>
<h2>Edit</h2>
<p>One thing I would like to add, even though reflection is powerful, it requires you to know some stuff about the type, such as parameters etc.</p>
<p>Serializing to XML doesnt need any of that, and you can still have type safety by ensuring you write the fully qualified type name to the XML file, so the same type is automatically loaded.</p>
|
<p>Reflection is what you want. Reflection + TypeConverter. Don't have much more time to explain, but just google those, and you should be well on your way. Or you could just use the xml serializer, but then you have to adhere to a format, but works great.</p>
| 5,114
|
<p>I have a multi dimensional OLAP cube with a number of dimensions. Some of these dimensions have hierarchies. The users would like to perform 'what-if' analysis on the measures in the cube by changing the hierarchies in the dimensions. </p>
<p>For example, they want to know the impact on departmental resource budgets by moving employees between departments or the movement in cost of manufacture if a product is moved from one factory to another.</p>
<p>Does anyone have a straight forward way to do this in a modern OLAP engine?</p>
|
<p>have you taken a look here? <a href="http://office.microsoft.com/en-us/excel/HA011265551033.aspx" rel="nofollow noreferrer">http://office.microsoft.com/en-us/excel/HA011265551033.aspx</a> if you are using sql server and excel, you want the "Excel Add-in for SQL Server Analysis Services" and you can perform writeback to the cubes. Might not be exactly what you want, but it is the closest I have come across.</p>
<p>"What-if analysis and writeback What-if analysis enables you to initiate a "what-if" scenario by updating data and analyzing the effects of changes on your data. You can save the scenario for future analysis. When you save the scenario, changes you made to data (known as writeback data) are written to the cube. Once you write back changes, the data is available for future analysis and can be viewed by and shared with others who have access to the cube."</p>
|
<p>There may be tools that allow this sort of analysis, but I only have experience of writing MDX, which ought to be able to help you.</p>
<p>Typical 'what if' analysis is more about changing values in the OLAP cube (e.g. change net sales from 845.45 to 700.00 and see what happens to gross profit). Your case is a bit different as you want to move members within a hierarhy, but keep the same values.</p>
<p>I haven't worked through a full solution, but the way I would approach it would be to create a new 'calculated member' or set (on the fly) and use that to build up the new hierarchy that you want. Your query can then use that on one axis.</p>
<p>Look carefully into 'visual totals' as there may be potential pitfalls there!</p>
| 5,457
|
<p>I am trying to write a formula in ActionScript 3 that will give me var "z" (please see image below) in degrees, which I will then convert to radians.</p>
<p>I will already know the value of vars "x" and "y". Using trigonometry, how can I calculate the length of the hypotenuse and therefore the variable angle of var z? A solution in either AS3 or psuedocode would be very helpful. Thanks.</p>
<p><img src="https://i.stack.imgur.com/B0nfz.jpg" alt="triangle"></p>
|
<p>What you need is this:</p>
<pre><code>var h:Number = Math.sqrt(x*x + y*y);
var z:Number = Math.atan2(y, x);
</code></pre>
<p>That should give you the angle in radians, you might need to swap x/y and possibly add or remove 90 degrees but it should do the trick! (Note that you don't even need <strong>h</strong> to get <strong>z</strong> when you're using atan2)</p>
<p>I use multiplication instead of Math.pow() just because Math is pretty slow, you can do:</p>
<pre><code>var h:Number = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
</code></pre>
<p>And it should be exactly the same.</p>
|
<p>What @Patrick said, also the hypotenuse is <code>sqrt(x^2 + y^2)</code>.</p>
| 8,002
|
<p>I'm coming from the open source world, and interested in giving ASP.NET a spin. But I'm having a little trouble separating the tools from the platform itself in regards to the licensing. I've downloaded Visual Web Developer 2008 Express, but not sure how different this is from one of the full-featured Visual Studio licenses -- and whether or not my Express license will prevent me from using all the features of ASP.NET.</p>
<p>Is a Visual Studio license just an IDE, or does it include pieces of .NET not available to the Express license? What about the other tools like IIS and SQL Server?</p>
<p>Thanks.</p>
|
<p>All of .net is available in the .net SDK, so in theory you will not need Visual Studio at all.</p>
<p>Now, there are some things that Express will not do. For example, the Database Designer is not very comprehensive and adding different remote databases is not or only very hardly possible. Still, in code you can connect to everything.</p>
<p>There is also no Remote Debugger, no support for creating Setup Files (well, that does not apply to ASP.net anyway), no real Publish Web Site Feature (although that can be <a href="https://web.archive.org/web/20150930210630/http://blogs.msdn.com:80/b/jamesche/archive/2007/09/27/automating-aspnet-compiler-in-visual-web-developer.aspx" rel="nofollow noreferrer">added manually</a> as it's just a Frontend for a SDK tool), no integrated Unit testing (and Microsoft <a href="https://weblogs.asp.net/nunitaddin/microsoft-vs-testdriven-net-express" rel="nofollow noreferrer">loves to threaten people</a> who add it), etc.</p>
<p>For a full comparison, see here:</p>
<p><a href="https://web.archive.org/web/20090118182937/http://msdn.microsoft.com:80/en-us/vstudio/products/cc149003.aspx" rel="nofollow noreferrer">Visual Studio 2008 Editions</a></p>
<p>But as said: Functionality of .net is all in the SDK, Visual Studio is just making it a bit easier to work with.</p>
|
<p>Visual Studio is just the IDE. You could theoretically create every file in Notepad and compile manually with just the .net framework.</p>
<p>IIS is an operating system feature, and SQL Server has different flavors with different capabilites.</p>
| 7,572
|
<p>For a long time, I thought that to start a new project we only need 3 basic tools.
1) A Build System (e.g. Maven & CruiseControl)
2) A Version Control System (e.g. CVS & SVN & GIT)
3) A Bug Tracking System (e.g. Bugzilla)</p>
<p>Yesterday, a senior guy told me that we need at least one thing more. That is KPI(Key Performance Index). Without KPI, it is impossible to measure whether the project is progressing well or not.</p>
<p>KPI is kind of SOFT tool compared to Maven/SVN/Bugzilla. I believe since I missed SOFT tools, there must be some other kind of tools I missed. So, anybody get some ideas what other basic tools necessary for a new project?</p>
|
<p>A project management tool for team members, customers or users.</p>
<p>One of the most important parts is interacting with people, a project management tool allows you show the progress/milstone and organized the feature request, defect and resources along with other features like forum, nofications and document uploading. This gives your customer a clear view of the project.</p>
<p>Redmine works very well for me.</p>
|
<p>We've found a wiki to be invaluable for recording specs, designs, thoughts, questions, and just about any other "living" information we need to remember.</p>
<p>Atlassian offers Confluence, a very inexpensive ($1200) web-based wiki that just <em>worked</em> for us out of the box. It's very customizable but took almost zero effort for us to start using it. There's a great deal of community support (they use their own tool), and many plug-ins are available. Download from <a href="http://www.atlassian.com/software/confluence/ConfluenceDownloadCenter.jspa" rel="nofollow noreferrer">http://www.atlassian.com/software/confluence/ConfluenceDownloadCenter.jspa</a> or try it online at <a href="http://confluence.demo.atlassian.com/display/ds/Confluence+Overview" rel="nofollow noreferrer">http://confluence.demo.atlassian.com/display/ds/Confluence+Overview</a>.</p>
<p><em>I do not work for Atlassian; I'm just a <strong>very</strong> satisfied customer!</em></p>
| 31,878
|
<p>We are trying to look at optimizing our localization testing. </p>
<p>Our QA group had a suggestion of a special mode to force all strings from the resources to be entirely contained of X. We already API hijack LoadString, and the MFC implementation of it, so doing it should not be a major hurdle. </p>
<p>My question is how would you solve the formatting issues?</p>
<pre><code>Examples -
CString str ;
str . LoadString ( IDS_MYSTRING ) ;
where IDS_MYSTRING is "Hello World", should return "XXXXX XXXXX"
where IDS_MYSTRING is "Hello\nWorld", should return "XXXXX\nXXXXX"
where IDS_MYSTRING is "Hello%dWorld", should return "XXXXX%dXXXXX"
where IDS_MYSTRING is "Hello%.2fWorld", should return "XXXXX%.2fXXXXX"
where IDS_MYSTRING is "Hello%%World", should return "XXXXX%%XXXXX"
</code></pre>
<p>So in summary the string should work if used in a printf or Format statement, it should honor escape characters.</p>
<p>So this is a pure code question, C++/MFC, </p>
<pre><code>CString ConvertStringToXXXX ( const CString& aSource )
{
CString lResult = aSource ;
// Insert your code here
return lResult ;
}
</code></pre>
<p>I know this could be done using tools on the .RC files, but we want to build English, then run like so -</p>
<p>application -L10NTEST</p>
|
<p>If this approach is to highlight formatted strings (or format sequences) in the application (i.e. all text appearing other than XXXX), you could locate the escape sequence (using regex perhaps) and insert block quotes around the formatted (substituted) values, <br>e.g. Some\ntext -> Some[\n]text</p>
<p>You get readability (all strings as XXX might be hard to use the application) and also get to detect non-resource (hardcoded) strings.</p>
<p>Having said that, if you're looking to detect non resource loaded strings (hardcoded strings), instead of substituting Xs, why not just prefix the string? You'll easily be able to tell resource loaded strings from hardcoded strings easily,
<br>e.g. Some\ntext -> [EN]Some\ntext</p>
<p>Hope it helps?</p>
|
<p>You can apply compiler theory here and generate your scanner and parser using <a href="http://dinosaur.compilertools.net/" rel="nofollow noreferrer">flex/bison</a> (lex/yacc, or whatever tools). You can define \w+ as word, which can match both "Hello" and "World" etc..</p>
| 23,089
|
<p>When creating a web application, and lets say you have a User object denoting a single user, what do you think is the best way to store that the user has logged in?</p>
<p>Two ways I've thought about have been:</p>
<ul>
<li>Stored the user database id in a session variable</li>
<li>Stored the entire user object in a session variable</li>
</ul>
<p>Any better suggestions, any issues with using the above ways? Perhaps security issues or memory issues, etc, etc.</p>
|
<p>I recommend storing the id rather than the object. The downside is that you have to hit the database every time you want to get that user's information. However, unless every millisecond counts in your page, the performance shouldn't be an issue. Here are two advantages:</p>
<ol>
<li><p>If the user's information changes somehow, then you won't be storing out-of-date information in your session. For example, if a user is granted extra privileges by an admin, then those will be immediately available without the user needing to log out and then log back in.</p></li>
<li><p>If your session information is stored on the hard drive, then you can only store serializable data. So if your User object ever contains anything like a database connection, open socket, file descriptor, etc then this will not be stored properly and may not be cleaned up properly either.</p></li>
</ol>
<p>In most cases these concerns won't be an issue and either approach would be fine.</p>
|
<p>I store the user in the session, usually. The can't-change-until login problem can be solved by replacing the object in the session with a new copy after you've made changes.</p>
| 4,135
|
<p>Can you mix .net languages within a single project? So pre-compiled, I would like to call classes and methods of other source files.</p>
<p>For both web and apps? </p>
<p>In particular I'd be interested in F# and C#.</p>
|
<p>You can mix languages in a single assembly with <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=22914587-B4AD-4EAE-87CF-B14AE6A939B0&displaylang=en" rel="noreferrer">ILMerge</a> and <a href="http://msdn.microsoft.com/en-us/library/0k6kkbsd.aspx" rel="noreferrer">MSBuild</a>.</p>
<p><a href="http://www.hanselman.com/blog/MixingLanguagesInASingleAssemblyInVisualStudioSeamlesslyWithILMergeAndMSBuild.aspx" rel="noreferrer">Here</a> is a very good example about it.</p>
|
<p>you can specify the language in each assembly project (library DLL) and use several of these in the same solution, but i don't think you can mix languages within the same assembly</p>
| 23,895
|
<p>Here's my problem - I have some code like this:</p>
<pre><code><mx:Canvas width="300" height="300">
<mx:Button x="800" />
</mx:Canvas>
</code></pre>
<p>So the problem is that the Button inside the canvas has an x property way in excess of the Canvas's width - since it's a child of the Canvas, the Canvas masks it and creates some scrollbars for me to scroll over to the button.</p>
<p>What I'd like is to display the button - 800 pixels to the left of the Canvas without the scrollbars while still leaving the button as a child of the Canvas. How do I do that?</p>
|
<p>I figured it out - apparently the Container has a property called clipContent - here's the description from Adobe:</p>
<p><em>Whether to apply a clip mask if the positions and/or sizes of this container's children extend outside the borders of this container. If false, the children of this container remain visible when they are moved or sized outside the borders of this container. If true, the children of this container are clipped.</em></p>
<p><em>If clipContent is false, then scrolling is disabled for this container and scrollbars will not appear. If clipContent is true, then scrollbars will usually appear when the container's children extend outside the border of the container. For additional control over the appearance of scrollbars, see horizontalScrollPolicy and verticalScrollPolicy.
The default value is true.</em></p>
<p>So basically - to show the button outside of the bounds of the container I need to do the following:</p>
<pre><code><mx:Canvas width="300" height="300" clipContent="false" >
<mx:Button x="800" />
</mx:Canvas>
</code></pre>
<p>That was easier than I thought it was going to be. :)</p>
<p><a href="http://livedocs.adobe.com/flex/3/langref/mx/core/Container.html#clipContent" rel="noreferrer">Here's the official doc...</a></p>
|
<p>You should be able to use the <strong>includeInLayout</strong> property also, which would allow you to apply it to each child component independently.</p>
| 18,835
|
<p>Is there any way to display scrollabletext in loose xaml? The equivalent in HTML would be </p>
<pre><code><div style="overflow:scroll">some long bit of text here</div>
</code></pre>
<p>Can you do this in loose xaml? </p>
<p>From my experiments so far it seems that in loose xaml:</p>
<ol>
<li>You cannot use TextBox -- it must be TextBlock. </li>
<li>TextBlock doesn't seem to have any styling settings which would make it scrollable.</li>
<li>ScrollViewer doesn't seem to be allowed in loose xaml.</li>
</ol>
<p>Any help gratefully appreciated.</p>
|
<p>Typically, if you see an issue with authentication where it works in IE 6 but not IE 7, I'd check to make sure Kerberos is configured correctly.</p>
<p>Running as Network Service, your Kerberos SPNs should attached to the machine account. As a domain account, the SPN's need to be on that account.</p>
<p>As to why IE 6 is different than IE 7, its most likely due to some of the Kerberos HotFixes that apply to CNames and ticket time outs. Search MS Support for "kerberos HotFix"</p>
<p>To turn off Kerberos for the site:</p>
<p>cscript adsutil.vbs set w3svc/###/NTAuthenticationProviders "NTLM"</p>
<p>Where ### is the SiteID from the MetaBase.</p>
|
<p>You can try to disable "Enable integrated authentication" in Options, Advanced Settings.
But I don't know if there isn't some side effects.</p>
| 27,874
|
<p>I have a module that sends an email to a specified email address but I want to default the email recipient to the portal administrator. How can I retrieve this information?</p>
|
<p>If you are in the context of a control inheriting from <code>PortalModuleBase</code>, <code>PortalSettings</code> is available as a property, so it would just look like</p>
<pre><code>PortalSettings.Email
</code></pre>
|
<pre><code>' get the current portal
Dim portSettings As PortalSettings = PortalController.GetCurrentPortalSettings
' get email address
Dim email as string = portSettings.Email
</code></pre>
| 36,994
|
<p>I'm attempting to determine the row length in bytes of a table by executing the following stored procedure:</p>
<pre><code>CREATE TABLE #tmp
(
[ID] int,
Column_name varchar(640),
Type varchar(640),
Computed varchar(640),
Length int,
Prec int,
Scale int,
Nullable varchar(640),
TrimTrailingBlanks varchar(640),
FixedLenNullInSource varchar(640),
Collation varchar(256)
)
INSERT INTO #tmp exec sp_help MyTable
SELECT SUM(Length) FROM #tmp
DROP TABLE #tmp
</code></pre>
<p>The problem is that I don't know the table definition (data types, etc..) of the table returned by 'sp_help.'</p>
<p>I get the following error:</p>
<pre><code>Insert Error: Column name or number of supplied values does not match table definition.
</code></pre>
<p>Looking at the sp_help stored procedure does not give me any clues.</p>
<p>What is the proper CREATE TABLE statement to insert the results of a sp_help?</p>
|
<p>How doing it this way instead? </p>
<pre><code>CREATE TABLE tblShowContig
(
ObjectName CHAR (255),
ObjectId INT,
IndexName CHAR (255),
IndexId INT,
Lvl INT,
CountPages INT,
CountRows INT,
MinRecSize INT,
MaxRecSize INT,
AvgRecSize INT,
ForRecCount INT,
Extents INT,
ExtentSwitches INT,
AvgFreeBytes INT,
AvgPageDensity INT,
ScanDensity DECIMAL,
BestCount INT,
ActualCount INT,
LogicalFrag DECIMAL,
ExtentFrag DECIMAL
)
GO
INSERT tblShowContig
EXEC ('DBCC SHOWCONTIG WITH TABLERESULTS')
GO
SELECT * from tblShowContig WHERE ObjectName = 'MyTable'
GO
</code></pre>
|
<p>I can't help you with creating a temp table to store sp_help information, but I can help you with calculating row lengths. Check out this <a href="http://msdn.microsoft.com/en-us/library/aa933068.aspx" rel="nofollow noreferrer">MSDN article</a>; it helps you calculate such based on the field lengths, type, etc. Probably wouldn't take too much to convert it into a SQL script you could reuse by querying against sysobjects, etc.</p>
<p>EDIT:</p>
<p>I'm redacting my offer to do a script for it. My way was nowhere near as easy as Vendoran's. :) </p>
<p>As an aside, I take back what I said earlier about not being able to help with the temp table. I can: You can't do it. sp_help outputs seven rowsets, so I don't think you'll be able to do something as initially described in the original question. I think you're stuck using a different method to come up with it.</p>
| 28,141
|
<p>I have this CheckBoxList on a page:</p>
<pre><code><asp:checkboxlist runat="server" id="Locations" datasourceid="LocationsDatasource"
datatextfield="CountryName" datavaluefield="CountryCode" />
</code></pre>
<p>I'd like to loop through the checkbox elements on the client using Javascript and grab the value of each checked checkbox, but the values don't appear to be available on the client side. The HTML output looks like this:</p>
<pre><code><table id="ctl00_Content_Locations" class="SearchFilterCheckboxlist" cellspacing="0" cellpadding="0" border="0" style="width:235px;border-collapse:collapse;">
<tr>
<td><input id="ctl00_Content_Locations_0" type="checkbox" name="ctl00$Content$Locations$0" /><label for="ctl00_Content_Locations_0">Democratic Republic of the Congo</label></td>
</tr><tr>
<td><input id="ctl00_Content_Locations_1" type="checkbox" name="ctl00$Content$Locations$1" /><label for="ctl00_Content_Locations_1">Central African Republic</label></td>
</tr><tr>
<td><input id="ctl00_Content_Locations_2" type="checkbox" name="ctl00$Content$Locations$2" /><label for="ctl00_Content_Locations_2">Congo</label></td>
</tr><tr>
<td><input id="ctl00_Content_Locations_3" type="checkbox" name="ctl00$Content$Locations$3" /><label for="ctl00_Content_Locations_3">Cameroon</label></td>
</tr><tr>
<td><input id="ctl00_Content_Locations_4" type="checkbox" name="ctl00$Content$Locations$4" /><label for="ctl00_Content_Locations_4">Gabon</label></td>
</tr><tr>
<td><input id="ctl00_Content_Locations_5" type="checkbox" name="ctl00$Content$Locations$5" /><label for="ctl00_Content_Locations_5">Equatorial Guinea</label></td>
</tr>
</code></pre>
<p></p>
<p>The values ("cd", "cg", "ga", etc.) are nowhere to be found. Where are they? Is it even possible to access them on the client, or do I need to build this checkboxlist myself using a repeater or something?</p>
|
<p>I finally have the answer I've been looking for!</p>
<p>The asp.net CheckboxList control <em>does</em> in fact render the value attribute to HTML - it has been working for me in a Production site for over a year now! (We ALWAYS have EnableViewState turned off for all our sites and it still works, without any tweaks or hacks)</p>
<p>However, all of a sudden, it stopped working one day, and our CheckboxList checkboxes no longer were rendering their value attribute in HTML! WTF you say? So did we! It took a while to figure this out, but since it had been working before, we knew there had to be a reason. The reason was an accidental change to our web.config!</p>
<pre><code><pages controlRenderingCompatibilityVersion="3.5">
</code></pre>
<p>We removed this attribute from the pages configuration section and that did the trick!</p>
<p>Why is this so? We reflected the code for the CheckboxList control and found this in the RenderItem method:</p>
<pre><code>if (this.RenderingCompatibility >= VersionUtil.Framework40)
{
this._controlToRepeat.InputAttributes.Add("value", item.Value);
}
</code></pre>
<p>Dearest dev brothers and sisters do not despair! ALL the answers I searched for here on Stackexchange and the rest of the web gave erroneous information! As of .Net 4.0 asp.net renders the value attribute of the checkboxes of a CheckboxList:</p>
<pre><code><input type="checkbox" value="myvalue1" id="someid" />
</code></pre>
<p>Perhaps not practically useful, Microsoft gave you the ability to add a "controlRenderingCompatibilityVersion" to your web.config to turn this off by setting to a version lower than 4, which for our purposes is completely unnecessary and in fact harmful, since javascript code relied on the value attribute...</p>
<p>We were getting chk.val() equal to "on" for all our checkboxes, which is what originally alerted us to this problem in the first place (using jquery.val() which gets the value of the checkbox. Turns out "on" is the value of a checkbox that is checked... Learn something every day).</p>
|
<p>Swapna, Your answer absolutely works. So in order to check if the check box in the ASP.Net Checkboxlist is checked and then accumulate the list as a comma-delimited string, you can do as</p>
<p>C# Code-behind</p>
<pre><code>ChkboxList1.DataSource = dsData;
ChkboxList1.DataTextField = "your-display-column-name";
ChkboxList1.DataValueField = "your-identifier-column-name";
ChkboxList1.DataBind();
foreach (ListItem li in ChkboxList1.Items)
{
li.Attributes.Add("DataValue", li.Value);
}
</code></pre>
<p>Then in Javascript do</p>
<pre><code>var selValues = "";
var ChkboxList1Ctl = document.getElementById("ChkboxList1");
var ChkboxList1Arr = null;
var ChkboxList1Attr= null;
if (ChkboxList1Ctl != null)
{
ChkboxList1Arr = ChkboxList1Ctl.getElementsByTagName("INPUT");
ChkboxList1Attr = ChkboxList1Ctl.getElementByTagName("span");
}
if (ChkboxList1Arr != null)
{
for (var i = 0; i < ChkboxList1Arr.length; i++)
{
if (ChkboxList1Arr[i].checked)
selValues += ChkboxList1Attr[i].getAttribute("DataValue") + ",";
}
if (selValues.length > 0)
selValues = selValues.substr(0, selValues.length - 1);
}
</code></pre>
| 21,740
|
<p>Yeah, its a bit on this side of pointless, but I was wondering... I've got all these codebehind files cluttering my MVC app. The only reason why I need these files, as far as I can tell, is to tell ASP.NET that my page extends from ViewPage rather than Page. </p>
<p>I've tried a couple different Page directives changes, but nothing I've found will allow me to identify the base class for the page AND let me delete the codebehind files.</p>
<p>Is there a way to do it?</p>
<p><strong>UPDATE</strong>: I'm trying to inherit from a strongly-typed ViewPage! Seems like its possible to inherit from a regular ViewPage...</p>
|
<p>Delete the codebehind and use a page directive like this:</p>
<pre><code><%@ Page Title="Title" Inherits="System.Web.Mvc.ViewPage" Language="C#" MasterPageFile="~/Views/Layouts/Site.Master" %>
</code></pre>
<p>Or, if you want to get rid of the codebehind but still want to use strongly typed view, then read this link: <a href="http://devlicio.us/blogs/tim_barcz/archive/2008/08/13/strongly-typed-viewdata-without-a-codebehind.aspx" rel="nofollow noreferrer">http://devlicio.us/blogs/tim_barcz/archive/2008/08/13/strongly-typed-viewdata-without-a-codebehind.aspx</a></p>
<p>Here is a cut and paste of what this would look like:</p>
<pre><code><%@ Page Inherits="System.Web.Mvc.ViewPage`1[[ABCCompany.MVC.Web.Models.LoginData, ABCCompany.MVC.Web]]" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" %>
</code></pre>
|
<p>Straight out of the box you should be able to delete the .designer.cs and nothing will break. The other code behind can be useful, for instance if you'd like to strongly type your viewdata.</p>
| 24,223
|
<p>Where can I download a PyLucene+JCC Windows build compiled for python 2.6?</p>
<p>Jose</p>
|
<p>Not tested but there appears to be an egg here:</p>
<p><a href="http://code.google.com/p/pylucene-win32-binary/" rel="nofollow noreferrer">http://code.google.com/p/pylucene-win32-binary/</a></p>
|
<p>you might want to see <a href="http://mail-archives.apache.org/mod_mbox/lucene-pylucene-dev/200902.mbox/%3Calpine.OSX.2.00.0902181122530.1109@yuzu.local%3E" rel="nofollow noreferrer">this recent mailing list post</a> and the related thread. There's also a <a href="http://markmail.org/message/d6tfni5sdqywwfoy" rel="nofollow noreferrer">pylucene-dev</a> thread that seems apropos. Unfortunately, none of these things have what you want; you'll still have to build it yourself. </p>
<p>If you're really feeling charitable, you can publish the steps + binaries once you figure it out, but I don't know. </p>
| 43,867
|
<p>Just a simple question about my FEP sheet getting dented after print.
I just bought an Elegoo Mars 2 Pro and had trouble getting it to stick to the bed, after some painful bed leveling and realizing my exposure times were too low for maroon resin, I finally got it to stick to the bed by the 4th print.</p>
<p>Now before I start my next print, I want to know what causes the indents in the FEP sheet below so I can prevent it from happening again.</p>
<p><a href="https://i.stack.imgur.com/Jqxah.jpg" rel="nofollow noreferrer" title="FEP sheet with noticeable dents"><img src="https://i.stack.imgur.com/Jqxah.jpg" alt="FEP sheet with noticeable dents" title="FEP sheet with noticeable dents" /></a></p>
<p>Is it too High exposure time, bed leveled too low/tight, or both?
Now I will also note, that this print was with the standard rook test print the mars recommends you do first, also that my print was very hard to remove from the bed when finished, I had to use a lot of force to rip it off.</p>
|
<p>The rook is normally difficult to remove, it's designed this way.</p>
<p>Have you tried resetting the height of you build Plate?
If it makes a grinding sound when doing the first 2 or three layers your build plate might be traveling too low.</p>
<p>Also try re-leveling your build plate, e.g. I pushed so hard when I tried to take my rook off that I un-leveled it.</p>
|
<p>You have not done anything wrong!</p>
<p>Usually, each resin type is suitable for a specific VAT floor. For example, for PDMS floor you should use very specific types of resins.</p>
<p>FEP is known to be very strong and difficult to ruin. But still a couple of things you need to consider:</p>
<ul>
<li>When the resin cures it does generate a substantial amount of heat, you definitely can decrease it by a better level (less resin) or dimming (slower chemical reaction). Some FEPs could stand 450 °C.</li>
<li>Separation force, it will depend on the area being solidified and how strong the resin stick to your FEP.</li>
<li>How tightened the FEP is also important. You do not want it to be very tight.</li>
</ul>
| 2,011
|
<p>I have a (derived) Menu control, that displays a rather large list of items from a custom data source. I need to disable ViewState on the menu to avoid the very annoying "Can't select a disabled or unselectable menu item" when some other control causes the current selection to change on a postback.</p>
<p>Unfortunately, when ViewState is disabled for the Menu, the postbacks generated <em>by</em> the menu aren't raising any events. If I enable ViewState, the OnMenuItemClick event is raised. If I disable ViewState, OnMenuItemClick is not raised. I'm perplexed.</p>
<p>I need to leave ViewState off for the menu, so how can I handle postbacks from the actual menu?</p>
<p>At this point I'm leaning towards using the Menu's Load event, parsing the __EVENTTARGET to see if it's the Menu, and going from there. This would technically process the postback event before it would normally but that's ok, I guess.</p>
<p>Any better ideas?</p>
|
<p>I've figured out the essence of the problem. Using Reflector we can see the important part(s) of the low level method that handles the actual postback and then raises the event:</p>
<pre><code>string str = HttpUtility.HtmlDecode(eventArgument);
...
MenuItem item = this.Items.FindItem(str.Split(new char[] { '\\' }), 0);
if (item != null)
this.OnMenuItemClick(new MenuEventArgs(item));
</code></pre>
<p>As you can see the MenuEventArgs is handed a MenuItem. If one cannot be found in the current Items collection that matches the incoming post data, then the event is not raised. With ViewState disabled, the menu doesn't have any Items (they would have been rebuilt using ViewState). So the event won't be raised.</p>
<p>To work around this, I've told the menu to build itself during Load using the not-yet-updated data (at this point it will be the same as it was at the end of the last request). This is essentially the same as rebuilding the menu from ViewState, so I don't feel bad in regards to performance, or whatever. OnMenuItemClick is then fired as expected. Lastly, during PreRender I tell the Menu to rebuild once again, so it reflects the changes that happened during the postback processing portion of the lifecycle.</p>
<p>I wasted a lot of time on this, so hopefully this info can help somebody else in a similar situation.</p>
|
<p>In Page_Load rebind the control to the sitemapdata and check if IsPostBack.</p>
<pre><code>if (IsPostBack) {
Menu.DataBind();
}
</code></pre>
<p>this work for me and reduce the viewstate.</p>
| 29,200
|
<p>I'd like to display a repeating event on a date/time display in an app. This date time display can take the form of a calendar, but it could also just be a list of upcoming events. </p>
<p><strong>What is the best way to handle tracking this event that can repeat?</strong> </p>
<p><em>For example: Should the event be stored once in the database and projected out / repeated several times in the display code? Should the event be stored several times and then just rendered?</em></p>
|
<p>I did something like this before and I based my schema off of SQL Servers sysschedules table.</p>
<p><a href="http://technet.microsoft.com/en-us/library/ms178644.aspx" rel="nofollow noreferrer">http://technet.microsoft.com/en-us/library/ms178644.aspx</a></p>
<p>The schema linked above will allow you to store the schedule for a job (event). Then you can calculate what dates the event occurs on based off of the schedule. This may be a lengthy calculation, so I would try to cache that result somewhere. </p>
|
<p>I think it depends on type of event it is. Is it like Christmas where once it comes along and happens you really aren't interested in it until the next occurrence? Or is it a task like, "Make sure I call my mom every month", where if it happens and you missed it you wouldn't want it to go away?</p>
<p>One way I recently implemented the latter was to have a record that had next_occurrence (date), reoccurence_period (weekly, monthly, yearly, etc) columns. So that as the next occurence approched it would show up in the list. Once it passed the list item would have a recycle icon that once pressed would update the record to the next future occurence.</p>
<p>Again, i'm not sure if this applies to your situation, but it worked well for mine. </p>
| 46,645
|
<p>I'm more of a programmer than a designer, and I'm trying to embrace <code><div></code>s rather than using tables but am getting stuck.</p>
<p>Here's what I'm trying to do. I am setting up a survey page. I want each question's text to sit at the top of the blue div, and wrap if it's too long. I want all of the red divs to line up at the top right corner of the container div.</p>
<p><a href="http://img528.imageshack.us/img528/4330/divsforsurveyop2.jpg" rel="nofollow noreferrer">Layout http://img528.imageshack.us/img528/4330/divsforsurveyop2.jpg</a></p>
<p>Here's what I've started with, it works fine so long as the frame is more than 420 pixels wide. Then the red div skips to the next line. I think I may have approached it wrong, perhaps I should be floating things to the right?</p>
<pre><code>.greencontainer{
width:100%;
spacing : 10 10 10 10 ;
float: left;
}
.redcontainer{
float: left;
width: 20px;
padding: 2 0 2 0;
font-size: 11px;
font-family: sans-serif;
text-align: center;
}
.bluecontainer{
clear: both;
float: left;
width: 400px;
padding: 2 2 2 10;
font-size: 11px;
font-family: sans-serif;
text-align: left;
}
</code></pre>
|
<p>Here is what I would do:</p>
<pre><code><div class="greencontainer">
<div class="redcontainer">
<input type="checkbox" />
</div>
<div class="bluecontainer">
<label>Text about this checkbox...</label>
</div>
</div>
</code></pre>
<p>with css:</p>
<pre><code>.greencontainer{
float:left;
clear:left;
width:100%;
}
.redcontainer{
float:right;
width:20px;
}
.bluecontainer{
margin-right:20px;
}
</code></pre>
<p>PS Padding values should always have units, unless they are zero.</p>
|
<p>Very little testing here, but I <em>think</em> you'll want "clear: both;" on .greencontainer instead of "float: left". Also remove "clear: both" from .bluecontainer</p>
<p>See more info at: <a href="http://www.quirksmode.org/css/clearing.html" rel="nofollow noreferrer">http://www.quirksmode.org/css/clearing.html</a></p>
| 33,354
|
<p>I would like to be able to say things like</p>
<p><strong>cd [.fred]</strong> and have my default directory go there,
and my prompt change to indicate the full path to my current location.</p>
|
<p>Just type</p>
<p><code>cd:==set default</code> </p>
<p>at the command prompt. You can also put this in your LOGIN.COM file, but be sure to put a $ in front, i.e.</p>
<p><code>$ cd:==set default</code></p>
<p>To change your prompt to show your default, something like this may work up to a point</p>
<p><code>$ set prompt='f$env("default")'</code></p>
<p>There is a problem though with the fact that VMS prompt has maximum 32 characters, and your default might be longer than that. Have a look at <a href="http://www.phrack.com/issues.html?issue=19&id=2" rel="noreferrer">this page</a> for a way around that problem.</p>
|
<p>Use HGSD which implements an SD (short for SET DEFAULT) command. Just google it. It is an improved version by Hunter Goatley of an older implementation.</p>
<p>The only thing it cannot handle (yet), are logicals with multiple translations. Other than that, It works like a charm, and you do not need to type in complete directory names. You can even move to the next directory on the same level. </p>
<p>It can also set the prompt if you have the right privileges in one go, so your prompt will reflect your default directory, just like in the old days on DOS.</p>
| 15,869
|
<p>I'm currently modifying a Java script in Rational Functional Tester and I'm trying to tell RFT to wait for an object with a specified set of properties to appear. Specifically, I want to wait until a table with X number of rows appear. The only way I have been able to do it so far is to add a verification point that just verifies that the table has X number of rows, but I have not been able to utilize the wait for object type of VP, so this seems a little bit hacky. Is there a better way to do this?</p>
<p>Jeff</p>
|
<p>No, there is not a built-in waitForProperty() type of method, so you cannot do something simple like tableObject.waitForProperty("rowCount", x);</p>
<p>Your options are to use a verification point as you already are doing (if it ain't broke...) or to roll your own synchronization point using a do/while loop and the find() method.</p>
<p>The <code>find()</code> codesample below assumes that <code>doc</code> is an html document. Adjust this to be your parent java window.</p>
<pre><code>TestObject[] tables = doc.find(atDescendant(".rowCount", x), false);
</code></pre>
<p>If you are not familiar with <code>find()</code>, do a search in the RFT API reference in the help menu. <code>find()</code> will be your best friend in RFT scripting.</p>
|
<p>You can do one thing.... you can try getting the particular property and check that you are getting the desired value of that. If not then iterate in a IF loop.</p>
<pre><code>while (!flag) {
if (obj.getproperty(".text").equals("Desired Text")) {
flag = true
}
}
</code></pre>
| 12,168
|
<p>A good friend of mine works for a large asp.net shop, with a web farm with many web servers (dozens). The application logs exceptions and messages to the event log on each box (not to a centralized location).</p>
<p>Does anyone know of a convenient way to perform unified reporting on event logs on a number of different boxes?</p>
<p>Or, which is better:
- write tools that connect to each event log on each box?
- change architecture to log events to the database?
- some other mechanism I haven't considered?</p>
|
<p>I would use <a href="http://logging.apache.org/log4net/index.html" rel="nofollow noreferrer">Log4Net</a> (or something similar) for the logging, saving the files to disk, and rotating log file periodically. (I'm not a big fan of the Windows event log, personally.) Then have a background service on each box which uploads the log file into a database table - keeping track of which log entry came from which box.</p>
<p>This gives simple searching over the whole web farm while maintaining the information about which log entry came from where.</p>
<p>Similar questions:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/290304/is-writing-server-log-files-to-a-database-a-good-idea">"Is writing server log files to a database a good idea?"</a></li>
<li><a href="https://stackoverflow.com/questions/327460/logging-for-web-application">"Logging for web application"</a></li>
</ul>
|
<p>Members of my ASP.Net development team are enthusiastic users of the free software from BareMetal called <a href="http://www.baremetalsoft.com/baretail/index.php" rel="nofollow noreferrer">Bare Tail</a> to read plain text log files when they need to quickly determine the source of a production issue. I believe that you can read from multiple files at the same time (on different tabs).</p>
<p>You could still upload the log file data to a database, if desired. But, writing to and reading from a local log file is much faster and simpler than writing to a database. And, once a web app is stabilized in production, the most likely source of exceptions may well be loss of the database connection. One way around that is to try to write to the database, and if that fails, write to a log file. You could then use a tool like this to more easily read the log file data.</p>
| 42,661
|
<p>I have a script which uses pexpect to start a CLI program. It works a bit like a shell where you get a prompt where you can enter some commands.</p>
<p>The problem I have, I think, is that this program uses a coloured prompt.</p>
<p>This is what I do </p>
<pre><code>import pprint
import pexpect
1 a = pexpect.spawn('program')
2 a.expect("prompt>")
3 print "---------start------------"
4 print(a.before)
5 a.sendline("command")
6 a.expect("prompt>")
7 print "---------before------------"
8 pprint.pprint(a.before)
9 print "---------after------------"
10 pprint.pprint(a.after)
</code></pre>
<p>This is the output:</p>
<pre><code>> python borken.py
---------start------------
A lot of text here from the enjoying programs start-up, lorem ipsum ...
---------before------------
' \x1b[0m\x1b[8D\x1b[K\x1b[1m\x1b[34m'
---------after------------
'prompt>'
</code></pre>
<p>For some reason the first prompt colour coding borkens up things and a.before at line 8 is garbled, normal print does not work, even if I see that the command at line 5 actually produced a lot of output.</p>
<p>Does someone know what the problem could be, or is it possible to set the terminal type in pexpect to avoid the colours?</p>
<p>I am using tcsh shell</p>
|
<p>Ok, I found the answer. csl's answer set me on the right path.</p>
<p>pexpect has a "env" option which I thought I could use. like this:</p>
<pre><code>a = pexpect.spawn('program', env = {"TERM": "dumb"})
</code></pre>
<p>But this spawns a new shell which does not work for me, our development environment
depends on a lot of environmental variables :/</p>
<p>But if I do this before spawning a shell:</p>
<pre><code>import os
os.environ["TERM"] = "dumb"
</code></pre>
<p>I change the current "TERM" and "dumb" does not support colours, which fixed my issue.</p>
|
<p>Couldn't find anything in <a href="http://pexpect.sourceforge.net/pexpect.html" rel="nofollow noreferrer">the pexpect documentation</a> for setting terminals, but you could probably start your program explicitly with a shell, and then set the terminal type there:</p>
<pre><code>shell_cmd = 'ls -l | grep LOG > log_list.txt'
child = pexpect.spawn('/bin/bash', ['-c', shell_cmd])
child.expect(pexpect.EOF)
</code></pre>
<p>You could try something like</p>
<pre><code>child = pexpect.spawn('TERM=vt100 /bin/bash', ['-c', shell_cmd])
</code></pre>
<p>You can also start bash with --norc and similar to avoid reading the initialization files. Check out the <a href="http://linux.die.net/man/1/bash" rel="nofollow noreferrer">bash man page</a>.</p>
| 46,784
|
<p>I've upgraded my stepper drivers.</p>
<p>I'm looking to understand why my stepper motors made noise in the first place.</p>
|
<p>Stepper motors contain two distinct sets of coils. The current in these coils is governed by your stepper motor driver.</p>
<p><a href="https://i.stack.imgur.com/RaDxb.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RaDxb.gif" alt="Stepper motor diagram (WikiForU.com)"></a></p>
<p>To move the motor in either direction, the coils are being driven one after another, and in different directions.
Imagine this being a normal 3-phase AC motor, but instead of three phases, only two are used.</p>
<p>A "full steps" (1/1 "microstepping") would mean switching one coil off and the other on - resulting in a jerky motion to the next position. Real stepper motors have multiple sets of those coils (rather than two like in the diagram) - usually 200 or 400, giving 1.8° or 0.9° of rotation per "full step".</p>
<p>Such motion is usually not desired, since the immediate movement of the motor creates noise and vibration.
If both coils are driven with less current (71% of the full current, the reciprocal of the square root of 2, so that the total force on the motor remains the same) during the switch from one current to the other, another position can be achieved - a "half step" between two full steps.</p>
<p>This can be repeated for higher number of "microsteps", with 16 being the usual compromise.</p>
<p>Optimal smoothness - and next to no noise - would be achieved by driving the stepper motor with pure sine waves. The closer a stepper driver can get to that pure sine wave, the lower the noise made by the stepper motor will be:</p>
<p><a href="https://i.stack.imgur.com/GobdA.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GobdA.jpg" alt="Microstepping plot (eeNewspower.com)"></a></p>
<p>Some stepper motor drivers, most notably the TMC family of chips, can generate 256 microsteps internally, approximating a sine wave quite well.</p>
<p>Other stepper motor drivers (like the LV8729) can also handle 128 microsteps, but they require the printer control board to send an individual step signal for each of those steps - which may limit speed because of the additional load on the board's MCU.</p>
|
<p>To make a stepper perform a step, block signals are send to energize the coils to position the rotor. Such a block signal causes abrupt motion and triggers harmonic frequencies. This is audible as stepper noise. If the block signal is smoothed, the motion is more fluent and less noise will be observed. A similar effect is achieved using micro-stepping. </p>
<p>It could be that the new stepper drivers use more/less microsteps<sup>1)</sup> or a smoothed/block<sup>1)</sup> signal opposed to the previous drivers, hence less/more<sup>1)</sup> noise.</p>
<hr>
<p><sup>1)</sup><sub> The question does not state if the noise is reduced or increased, but noise reduction is most probable</sub></p>
| 1,388
|
<p>Suppose to have a code like this:</p>
<pre><code><div class="notSelected">
<label>Name
<input type="text" name="name" id="name" />
</label>
<div class="description">
Tell us what's your name to make us able to fake to be your friend
when sending you an email.
</div>
</div>
</code></pre>
<p>Now suppose I've something like this (it's just an example) for each element of a form.
I'd like to change the style from notSelected to Selected when:</p>
<ul>
<li>User focus on the input element</li>
<li>User move the mouse over a notSelected div</li>
</ul>
<p>When he change focus the Selected div should became notSelected again.</p>
<p>I'd like to do something like this to increment the size of the text of the selected div. Anyway it could be cool make other changes too so I'd prefer to change the class attribute.</p>
<p>What is the best way to do something like this in JavaScript? Is there any JavaScript framework that can boost me doing this thing? So it will be easy to add effects like fading etc...</p>
<p>I downloaded MooTools but with a fast read of the docs I did not see how to do this without having a specific ID for any of the forms div, but is the first time I use it. I've no problem using any other framework, but if you suggest one, please write also what should I look for specifically.</p>
|
<p>I would recommend a look at jQuery for your task. It is quite easy to learn and produces nice effects quickly. But your described effect alone, pure JavaScript would also be enough.</p>
<p>Make your DIVs always have a class called "selectable". You can toggle other CSS classes later on. Create a CSS class named "selected" and give it the desired look.</p>
<pre><code><div class="selectable"> (=off) vs. <div class="selectable selected"> (=on)
</code></pre>
<p>Then add something like this to the scripts section of your document:</p>
<pre><code>$(document).ready(function(){
// handle mouseover and mouseout of the parent div
$("div.selectable").mouseover(
function() {
$(this).addClass("selected").addClass("mouseIsOver");
}
).mouseout(
function() {
$(this).removeClass("selected").removeClass("mouseIsOver");
}
);
// handle focus and blur of the contained input elememt,
// unless it has already been selected by mouse move
$("div.selectable input").focus(
function() {
$(this).parents("div.selectable").not(".mouseIsOver").addClass("selected");
}
).blur(
function() {
$(this).parents("div.selectable").not(".mouseIsOver").removeClass("selected");
}
);
});
</code></pre>
<p>This is untested so there might be a glitch in it, but it will give you the general idea where to start.</p>
<p>P.S: Changing text size on mouse move may not be the best of all ideas. It leads to rearranging the page layout which is annoying for the user.</p>
|
<p>Yet another unrelated-to-the-original-question answer but... jQuery also has an alternative syntax for doing mouseover/mouseout stuff called hover.</p>
<pre><code>$(element).hover(function(){ /* mouseover */ }, function(){ /* mouseout */ });
</code></pre>
<p>Example,</p>
<pre><code>$('ul#nav li').hover(function() {
$(this).addClass('highlight');
}, function() {
$(this).removeClass('highlight');
});
</code></pre>
<p>Sorry for those double $'s, I can't seem to figure out how to escape that.</p>
| 26,580
|
<p>I have many requires and includes and i was wondering if there's something that can help me look at the whole of php code when a webpage is loaded. the reason i'm asking is that after fiddling with some code i cannot put any php code anymore as it will not be "sensed" by the compiler. like if i put anything inside the php tags </p>
<p>it won't give me an error saying the function doesn't exist.
Thanks to anyone taking the time reading this.</p>
|
<p>Not entirely sure what you are after...</p>
<p>The get_included_files function can allow you to view a list of all of the files php has loaded at that point.</p>
<p>You may also find using grep or the "find in files" function in your editor (if it has one) can help you track down something in the code that you know is there any can't find.</p>
<p>And finally, the errors thing - call the following functions at the top of your script to make sure errors are being output:</p>
<pre><code>error_reporting(E_ALL);
ini_set('display_errors', 1);
</code></pre>
<p>This still won't catch parse errors.</p>
<p>Please don't use those in a live system, only in development - it's not good to show error messages to users, and they contain info that might aid anyone looking to compromise your system.</p>
<p>So.... not sure of the question, but I've answered what I think it might be.</p>
|
<p>You can't look at PHP code that's not running on your computer. The idea is that the code inside the PHP tags (<code><?php ?></code>) is popped out, run, and then whatever the output is is snuck back in where the tags were before the final version is sent to your computer. Thus, you can't see the code on your machine.</p>
<p>What you need to do is get an FTP client to FTP into the server in order to see the code.</p>
| 44,520
|
<p>What are the C++ coding and file organization guidelines you suggest for people who have to deal with lots of interdependent classes spread over several source and header files?</p>
<p>I have this situation in my project and solving class definition related errors crossing over several header files has become quite a headache.</p>
|
<p>Some general guidelines:</p>
<ul>
<li>Pair up your interfaces with implementations. If you have <code>foo.cxx</code>, everything defined in there had better be declared in <code>foo.h</code>.</li>
<li>Ensure that every header file #includes all other necessary headers or forward-declarations necessary for independent compilation.</li>
<li>Resist the temptation to create an "everything" header. They're always trouble down the road.</li>
<li>Put a set of related (and interdependent) functionality into a single file. Java and other environments encourage one-class-per-file. With C++, you often want one <em>set of</em> classes per file. It depends on the structure of your code.</li>
<li>Prefer forward declaration over <code>#include</code>s whenever possible. This allows you to break the cyclic header dependencies. Essentially, for cyclical dependencies across separate files, you want a file-dependency graph that looks something like this:
<ul>
<li><code>A.cxx</code> requires <code>A.h</code> and <code>B.h</code></li>
<li><code>B.cxx</code> requires <code>A.h</code> and <code>B.h</code></li>
<li><code>A.h</code> requires <code>B.h</code></li>
<li><code>B.h</code> is independent (and forward-declares classes defined in <code>A.h</code>)</li>
</ul></li>
</ul>
<p>If your code is intended to be a library consumed by other developers, there are some additional steps that are important to take:</p>
<ul>
<li>If necessary, use the concept of "private headers". That is, header files that are required by several source files, but never required by the public interface. This could be a file with common inline functions, macros, or internal constants.</li>
<li>Separate your public interface from your private implementation at the filesystem level. I tend to use <code>include/</code> and <code>src/</code> subdirectories in my C or C++ projects, where <code>include/</code> has all of my public headers, and <code>src/</code> has all of my sources. and private headers.</li>
</ul>
<p>I'd recommend finding a copy of John Lakos' book <em>Large-Scale C++ Software Design</em>. It's a pretty hefty book, but if you just skim through some of his discussions on physical architecture, you'll learn a lot.</p>
|
<p>One more point in addition to the others here:</p>
<blockquote>
<p>Don't include any private definitions
in an include file. E.g. any
definition that is only used in
xxx.cpp should be in xxx.cpp, not
xxx.h. </p>
</blockquote>
<p>Seems obvious, but I see it
frequently.</p>
| 45,031
|
<p>I have 3 divs where only one is visible by default, they each contain information about a product. Below this divs is a list of 3 images which are images of the products. By default of course the 1st list item is selected and has <code>class="selected"</code>. When a different product image is clicks then <code>class="selected"</code> moves to that list item and the div above it changes to hidden and the div containing the other product information needs to appear.</p>
<p>I have searched all over the place for a plugin which can do what I want, they are all limited in some way which stops me doing from doing it.</p>
|
<p>Consider the following code:</p>
<pre><code><img id="img1" src="1.jpg" desc="d1" class="selected prodImg" />
<img id="img2" src="2.jpg" desc="d2" class="prodImg" />
<img id="img3" src="3.jpg" desc="d3" class="prodImg"/>
<div id="d1">description 1</div>
<div id="d2" class="hidden">description 2</div>
<div id="d3" class="hidden">description 3</div>
<script>
$(".prodImg").click(function() {
if ($(this).hasClass("selected")) return;
$("#" + $(".selected").attr("desc")).addClass("hidden");
$(".selected").removeClass("selected");
$("#" + $(this).attr("desc")).removeClass("hidden");
$(this).addClass("selected");
});
</script>
</code></pre>
<p>This should get you pretty close. You need to define the relationship between your images and divs... so I added a 'desc' attribute to the images. The extra 'prodImg' class on the images allows you to ensure that only those images are being wired up for this type of swap in and out behavior.</p>
|
<pre><code><script>
$(".prodImg").click(function() {
if ($(this).hasClass("selected")) return;
$('.prodImg').removeClass('selected');
$(this).addClass('selected');
var name = $(this).attr('desc');
$('.'+name).removeClass();
$('.'+name).addClass('');
});
</script>
</code></pre>
<p>I hope this can help you!</p>
| 28,870
|
<p>I need to get existing web pages into an existing ASP.NET web site project in Visual Studio 2008. I simply tried to drag and drop the whole file folder content into the Visual Studio Solution Explorer or even to copy them into the web site folder.</p>
<p>Both ways, Visual Studio seems unable to map the .designer.cs files to the corresponding .aspx (or .master) file, even after restarting the whole IDE. The Solution Explorer entry looks in a way like this:</p>
<pre><code>- Main.aspx
Main.aspx.cs
Main.aspx.designer.cs
</code></pre>
<p>Can I make Visual Studio file the designer-file below the aspx-file in any way? I strongly hope there is a simpler way than manually creating each file and copying and pasting the contents into each file by hand.</p>
|
<p>It sounds like you are trying to bring web application files into a web site. <em>IIf that is the case</em>, The designer files are not even needed. Just dont include them. They are generated and compiled in at runtime when the website runs.</p>
|
<p>try copying the files through the filesystem and then right clicking on the project and selecting to add an existing item at which point you can choose all at once and this usually puts them in the proper places.</p>
| 21,505
|
<p>I'm teaching/helping a student to program.</p>
<p>I remember the following process always helped me when I started; It looks pretty intuitive and I wonder if someone else have had a similar approach.</p>
<ol>
<li>Read the problem and understand it ( of course ) .</li>
<li>Identify possible "functions" and variables.</li>
<li>Write how would I do it step by step ( algorithm ) </li>
<li>Translate it into code, if there is something you cannot do, create a function that does it for you and keep moving.</li>
</ol>
<p>With the time and practice I seem to have forgotten how hard it was to pass from problem description to a coding solution, but, by applying this method I managed to learn how to program.</p>
<p>So for a project description like: </p>
<blockquote>
<p><em>A system has to calculate the price of an Item based on the following rules ( a description of the rules... client, discounts, availability etc.. etc.etc. )</em></p>
</blockquote>
<p>I first step is to understand what the problem is.</p>
<p>Then identify the item, the rules the variables etc.</p>
<p>pseudo code something like:</p>
<pre><code>function getPrice( itemPrice, quantity , clientAge, hourOfDay ) : int
if( hourOfDay > 18 ) then
discount = 5%
if( quantity > 10 ) then
discount = 5%
if( clientAge > 60 or < 18 ) then
discount = 5%
return item_price - discounts...
end
</code></pre>
<p>And then pass it to the programming language..</p>
<pre><code>public class Problem1{
public int getPrice( int itemPrice, int quantity,hourOdDay ) {
int discount = 0;
if( hourOfDay > 10 ) {
// uh uh.. U don't know how to calculate percentage...
// create a function and move on.
discount += percentOf( 5, itemPriece );
.
.
.
you get the idea..
}
}
public int percentOf( int percent, int i ) {
// ....
}
}
</code></pre>
<p>Did you went on a similar approach?.. Did some one teach you a similar approach or did you discovered your self ( as I did :( ) </p>
|
<p>I go via the test-driven approach.</p>
<h3>1. I write down (on paper or plain text editor) a list of tests or specification that would satisfy the needs of the problem.</h3>
<pre><code>- simple calculations (no discounts and concessions) with:
- single item
- two items
- maximum number of items that doesn't have a discount
- calculate for discounts based on number of items
- buying 10 items gives you a 5% discount
- buying 15 items gives you a 7% discount
- etc.
- calculate based on hourly rates
- calculate morning rates
- calculate afternoon rates
- calculate evening rates
- calculate midnight rates
- calculate based on buyer's age
- children
- adults
- seniors
- calculate based on combinations
- buying 10 items in the afternoon
</code></pre>
<h3>2. Look for the items that I think would be the easiest to implement and write a test for it. E.g single items looks easy</h3>
<p>The sample using Nunit and C#.</p>
<pre><code>[Test] public void SingleItems()
{
Assert.AreEqual(5, GetPrice(5, 1));
}
</code></pre>
<p>Implement that using:</p>
<pre><code>public decimal GetPrice(decimal amount, int quantity)
{
return amount * quantity; // easy!
}
</code></pre>
<p>Then move on to the two items.</p>
<pre><code>[Test]
public void TwoItemsItems()
{
Assert.AreEqual(10, GetPrice(5, 2));
}
</code></pre>
<p>The implementation still passes the test so move on to the next test.</p>
<h3>3. Be always on the lookout for duplication and remove it. You are done when all the tests pass and you can no longer think of any test.</h3>
<p>This doesn't guarantee that you will create the most efficient algorithm, but as long as you know what to test for and it all passes, it will guarantee that you are getting the right answers.</p>
|
<p>Keep in mind, if you get 5% off then another 5% off, you don't get 10% off. Rather, you pay 95% of 95%, which is 90.25%, or 9.75% off. So, you shouldn't add the percentage.</p>
| 16,614
|
<p>I want to insert a new row into an Access database. I'm looking at doing something like: </p>
<pre><code>oConnection = new Connection("connectionstring")
oTable = oCennection.table("Orders")
oRow = oTable.NewRow
oRow.field("OrderNo")=21
oRow.field("Customer") = "ABC001"
oTable.insert
</code></pre>
<p>Which seems to be a sensible way of doing things to me. </p>
<p>However, All examples I look for on the net seem to insert data by building SQL statements, or by creating a "SELECT * From ...", and then using this to create a multitude of objects, one of which appears to allow you to ...<br>
- populate an array with the current contents of the table.<br>
- insert a new row into this array.<br>
- update the database with the changes to the array. </p>
<p>What's the easiest way of using vb.net to insert data into an Access database?<br>
Is there a method I can use that is similar to my pCode above? </p>
|
<p>This is one way: </p>
<pre><code>cn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\emp.mdb;")
cn.Open()
str = "insert into table1 values(21,'ABC001')"
cmd = New OleDbCommand(str, cn)
cmd.ExecuteNonQuery
</code></pre>
<p>I would make a dataset, add a tableadapter connected to the Access database, then let the tableadapter create update/delete/modify for me. Then you just could do like this (assuming your database has a usertable and you mapped that up in the dataset):</p>
<pre><code> Dim UserDS As New UserDS
Dim UserDA As New UserDSTableAdapters.UsersTableAdapter
Dim NewUser As UserDS.UsersRow = UserDS.Users.NewUsersRow
NewUser.UserName = "Stefan"
NewUser.LastName = "Karlsson"
UserDS.User.AddUserRow(NewUser)
UserDA.Update(UserDS.Users)
</code></pre>
|
<p>Unfortunately, the world doesn't re-arrange itself to suit how you think it should work. If you want to work with a database, it's a good idea to get at least somewhat comfortable with SQL, as that is generally how it's done.</p>
<p>On the bright side, there is a whole category of products that do kind of what you want. You can look for an Object-Relational Mappings (ORM) tool like ActiveRecord, NHibernate, or LINQ. But still learn some SQL.</p>
| 43,770
|
<p>How often does Akamai refresh cache?</p>
<p>We use Akamai to cache frequently accessed files. When uploading and overwriting files to the Akamai FTP, I can't see the new file reflected live.</p>
<p>Anybody have any experience with this?</p>
|
<p>It is configurable. You will need to talk to whoever in your organisation manages your Akamai account. They will have access to change how and what things are cached. If necessary, they can put you in touch with a technical contact at Akamai.</p>
|
<p>Files on the Akamai network can be tuned with whatever cache configuration the end customer requires. Typically the two most common approaches to cache design I see are:</p>
<ol>
<li>Configuring based on file extension. (e.g. *.css, *.js, etc)</li>
<li>Configuring based on path. (/product/test /checkout, etc)</li>
</ol>
<p>If you enable the following pragma headers to your request then you can inspect the HTTP response headers and determine the cache length of the file - it's included in the cache key.</p>
<p>Pragma: akamai-x-cache-on, akamai-x-cache-remote-on, akamai-x-check-cacheable, akamai-x-get-cache-key, akamai-x-get-extracted-values, akamai-x-get-ssl-client-session-id, akamai-x-get-true-cache-key, akamai-x-serial-no, akamai-x-get-request-id,akamai-x-get-nonces,akamai-x-get-client-ip,akamai-x-feo-trace</p>
<p>e.g the following indicates a file cached for 4 days:</p>
<p>x-cache-key:S/L/3568/82745/<strong>4d</strong>/mirror-somedomain.akadns.net/contentimages/meganav/020118/2018-02-01-someimg.jpg cid=_site_locale=us&site_language=en_</p>
| 45,769
|
<p>I have just edited a new post, <a href="https://3dprinting.stackexchange.com/questions/4153/help-understanding-bridge-settings">Help understanding bridge settings</a>, so that the video would be "inlined" and playable in the post itself<sup>1</sup>.</p>
<p>However, the video does not show up, and only the raw link (<code>https://youtu.be/HaeCBru3mOI</code>) is displayed:</p>
<blockquote>
<p><a href="https://i.stack.imgur.com/f7jmC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/f7jmC.png" alt="Only raw link is visible" /></a></p>
</blockquote>
<p>This is the markup:</p>
<blockquote>
<p><a href="https://i.stack.imgur.com/ukkfG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ukkfG.png" alt="Markup of post" /></a></p>
</blockquote>
<p>I have used the <em>same</em> markup method, for inlining the video clip as this post, <a href="https://aviation.stackexchange.com/questions/34121/is-atc-communication-subject-to-fcc-profanity-regulations">Is ATC communication subject to FCC profanity regulations?</a>, on SE.Aviation:</p>
<blockquote>
<p><a href="https://i.stack.imgur.com/kgTCg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kgTCg.png" alt="Markup on SE.Aviation" /></a></p>
</blockquote>
<p>and there the video clip is inlined:</p>
<blockquote>
<p><a href="https://i.stack.imgur.com/LrHrI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LrHrI.png" alt="Post on SE.Aviation showing inline video clip" /></a></p>
</blockquote>
<hr />
<h3>TL;DR</h3>
<p>Is video inlining disabled on SE.3D Printing, or is it because we are still beta?</p>
<p>If it can be enabled , then should/could it be enabled?</p>
<p>I personally think it would be useful to enable it, and save a few mouse clicks (and RSI) having to open the video in another tab/window etc. What do other people think?</p>
<hr />
<p><sup>1</sup> See <a href="https://meta.stackexchange.com/questions/121209/allow-embedded-html5-youtube-video?rq=1">Allow embedded HTML5 YouTube video</a></p>
|
<p>Per answer to <a href="https://meta.stackexchange.com/questions/296832/what-are-the-limitations-in-beta">What are the limitations in Beta</a></p>
<p>"Inline videos is a feature that is off by default on all sites and only turned on if the community thinks it's necessary to improve the quality of a good portion of their question base." </p>
|
<p>A note of caution, <a href="https://stackoverflow.com/c/moderators/questions/257#answer-261">this post</a> on the Stack Moderators site, Pᴀᴜʟsᴛᴇʀ2's post, <a href="https://stackoverflow.com/c/moderators/questions/257">How do you request embedded video for your site?</a> - As mods can only follow these links I've included the content below:</p>
<blockquote>
<p>I don't know how exactly to request it, but I do want to point at one
pretty big downside.</p>
<p><strong>The player is pretty darn big.</strong> Plus, my experience is that it has a tendency to eat CPU cycles for breakfast.</p>
<p>I looked at the numbers <a href="https://space.meta.stackexchange.com/questions/883/are-there-ways-to-make-posts-with-images-better-for-low-connect-speed-users-doe/885#comment3547_885">about a year ago over on Space Exploration
Meta</a>.
What I found was:</p>
<blockquote>
<p>Loading <a href="https://space.stackexchange.com/q/21891/415">https://space.stackexchange.com/q/21891/415</a> without using the browser cache downloads 7642 KB for me just now. Of that,
<code>www.youtube.com</code> is responsible for 3182 KB and <code>i.stack.imgur.com</code>
another 2729 KB. Excluding just the embedded images and the
video-related downloads leaves about 1.7 MB to be downloaded. That's
still a sizable chunk of data for what basically amounts to a few
pages of text, but not quite as extreme as 7.6 MB.</p>
</blockquote>
<p>So one video embed adds about 3 MB download for everyone viewing the
post, regardless of whether or not they are in any way interested in
the video. (I think the video itself is downloaded on demand, so if
someone actually watches the video, that adds even more data, but at
that point at least they have some interest in it.) In situations
where connections are metered by the megabyte, this can add up
quickly, and is something that should be kept in mind before turning
on this feature. Not everyone is on a fast,
no-extra-charge-per-megabyte connection.</p>
<p>(Yes, I'm big on keeping text as mostly text. I'm old-fashioned in
that regard.)</p>
</blockquote>
<p>Also <a href="https://stackoverflow.com/c/moderators/questions/257#answer-260">this post</a>:</p>
<blockquote>
<blockquote>
<p>Are there any downsides to having embedded video (performance or otherwise)?</p>
</blockquote>
<p>Yep, <a href="https://meta.stackexchange.com/a/279637/295232">performance could be an issue</a>. Also, malicious users could post links to videos with ... questionable ... content (though this could be alleviated by requiring some reputation to post embedded videos, just as some sites do with pictures).</p>
</blockquote>
| 41
|
<p>I have long tables generated by datagrid control that go beyond the page width. I would like to convert that into separate table for each row or definition list where each field name is followed by field value.</p>
<p>How would I do that. </p>
|
<p>Uses jquery. If you have more than one table you'll need to change it to accommodate that. Also, just appends to the end of the document. If you want it elsewhere, find the element you want to place it after and insert it into the DOM at that point.</p>
<pre><code>$(document).ready(
function() {
var headers = $('tr:first').children();
$('tr:not(:first)').each(
function(i,row) {
var cols = jQuery(row).children();
var dl = jQuery('<dl></dl>');
for (var i=0, len = headers.length; i < len; ++i) {
var dt = jQuery('<dt>');
dt.text( jQuery(headers[i]).text() );
var dd = jQuery('<dd>');
dd.text( jQuery(cols[i]).text() );
dl.append(dt).append(dd);
}
$('body').append(dl);
}
);
$('table').remove();
}
);
</code></pre>
|
<p>Here's a reference:</p>
<p><a href="http://www.mail-archive.com/flexcoders@yahoogroups.com/msg15534.html" rel="nofollow noreferrer">http://www.mail-archive.com/flexcoders@yahoogroups.com/msg15534.html</a></p>
<p>The google terms I think you want are "invert datagrid". You'll get lots of hits.</p>
| 37,584
|
<p>I've been asked to help out on an XNA project with the AI. I'm not totally new to the concepts (pathfinding, flocking, etc.) but this would be the first "real" code. I'd be very thankful for any resources (links or books); I want to make sure I do this right.</p>
|
<p>The standard textbook and a great place to start is Russel and Norvig's <a href="https://rads.stackoverflow.com/amzn/click/com/0137903952" rel="noreferrer" rel="nofollow noreferrer"><em>Artificial Intelligence: A Modern Approach</em></a>. You can also get <a href="http://ocw.mit.edu/OcwWeb/Electrical-Engineering-and-Computer-Science/6-034Spring-2005/CourseHome/" rel="noreferrer">MIT's Intro AI course</a> via <a href="http://ocw.mit.edu/" rel="noreferrer">OpenCourseWare</a></p>
|
<p>I would second: Programming Game AI by example (Matt Buckland) </p>
<p>This book gives great algorithms that should easly port to XNA.</p>
| 4,443
|
<p>I'm wondering if this is a good design. I have a number of tables that require address information (e.g. street, post code/zip, country, fax, email). Sometimes the same address will be repeated multiple times. For example, an address may be stored against a supplier, and then on each purchase order sent to them. The supplier may then change their address and any subsequent purchase orders should have the new address. It's more complicated than this, but that's an example requirement.</p>
<p>Option 1
Put all the address columns as attributes on the various tables. Copy the details down from the supplier to the PO as it is created. Potentially store multiple copies of the </p>
<p>Option 2
Create a separate address table. Have a foreign key from the supplier and purchase order tables to the address table. Only allow insert and delete on the address table as updates could change more than you intend. Then I would have some scheduled task that deletes any rows from the address table that are no longer referenced by anything so unused rows were not left about. Perhaps also have a unique constraint on all the non-pk columns in the address table to stop duplicates as well.</p>
<p>I'm leaning towards option 2. Is there a better way?</p>
<p>EDIT: I must keep the address on the purchase order as it was when sent. Also, it's a bit more complicated that I suggested as there may be a delivery address and a billing address (there's also a bunch of other tables that have address information).</p>
<p>After a while, I will delete old purchase orders en-masse based on their date. It is after this that I was intending on garbage collecting any address records that are not referenced anymore by anything (otherwise it feels like I'm creating a leak).</p>
|
<p>I actually use this as one of my interview questions. The following is a good place to start:</p>
<pre><code>Addresses
---------
AddressId (PK)
Street1
... (etc)
</code></pre>
<p>and</p>
<pre><code>AddressTypes
------------
AddressTypeId
AddressTypeName
</code></pre>
<p>and</p>
<pre><code>UserAddresses (substitute "Company", "Account", whatever for Users)
-------------
UserId
AddressTypeId
AddressId
</code></pre>
<p>This way, your addresses are totally unaware of how they are being used, and your entities (Users, Accounts) don't directly know anything about addresses either. It's all up to the linking tables you create (UserAddresses in this case, but you can do whatever fits your model).</p>
<p>One piece of somewhat contradictory advice for a potentially large database: go ahead and put a "primary" address directly on your entities (in the Users table in this case) along with a "HasMoreAddresses" field. It seems icky compared to just using the clean design above, but can simplify coding for typical use cases, and the denormalization can make a big difference for performance.</p>
|
<p>In the case of orders, you would never want to update the address as the person (or company) address changed if the order has been sent. You meed the record of where the order was actually sent if there is an issue with the order.</p>
<p>The address table is a good idea. Make a unique constraint on it so that the same entity cannot have duplicate addresses. You may still get them as users may add another one instead of looking them up and if they spell things slightly differently (St. instead of Street) the unique constraint won't prevent that. Copy the data at the time the order is created to the order. This is one case where you want the multiple records because you need a historical record of what you sent where. Only allowing inserts and deletes to the table makes no sense to me as they aren't any safer than updates and involve more work for the database. An update is done in one call to the database. If an address changes in your idea, then you must first delete the old address and then insert the new one. Not only more calls to the databse but twice the chance of making a code error.</p>
| 39,506
|
<p>Where X is any programming language (C#, Javascript, Lisp, Perl, Ruby, Scheme, etc) which supports some flavour of closures. </p>
<p>Some limitations are mentioned in the <a href="http://ivan.truemesh.com/archives/000411.html" rel="noreferrer">Closures in Python</a> (compared to Ruby's closures), but the article is old and many limitations do not exist in modern Python any more.</p>
<p>Seeing a code example for a concrete limitation would be great.</p>
<p><strong>Related questions</strong>:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/13857/can-you-explain-closures-as-they-relate-to-python">Can you explain closures (as they relate to Python)?</a></li>
<li><a href="https://stackoverflow.com/questions/36636/what-is-a-closure">What is a ‘Closure’?</a></li>
<li><a href="https://stackoverflow.com/questions/111102/how-does-a-javascript-closure-work">How does a javascript closure work ?</a></li>
</ul>
|
<p>The most important limitation, currently, is that you cannot assign to an outer-scope variable. In other words, closures are read-only:</p>
<pre><code>>>> def outer(x):
... def inner_reads():
... # Will return outer's 'x'.
... return x
... def inner_writes(y):
... # Will assign to a local 'x', not the outer 'x'
... x = y
... def inner_error(y):
... # Will produce an error: 'x' is local because of the assignment,
... # but we use it before it is assigned to.
... tmp = x
... x = y
... return tmp
... return inner_reads, inner_writes, inner_error
...
>>> inner_reads, inner_writes, inner_error = outer(5)
>>> inner_reads()
5
>>> inner_writes(10)
>>> inner_reads()
5
>>> inner_error(10)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 11, in inner_error
UnboundLocalError: local variable 'x' referenced before assignment
</code></pre>
<p>A name that gets assigned to in a local scope (a function) is always local, unless declared otherwise. While there is the 'global' declaration to declare a variable global even when it is assigned to, there is no such declaration for enclosed variables -- yet. In Python 3.0, there is (will be) the 'nonlocal' declaration that does just that.</p>
<p>You can work around this limitation in the mean time by using a mutable container type:</p>
<pre><code>>>> def outer(x):
... x = [x]
... def inner_reads():
... # Will return outer's x's first (and only) element.
... return x[0]
... def inner_writes(y):
... # Will look up outer's x, then mutate it.
... x[0] = y
... def inner_error(y):
... # Will now work, because 'x' is not assigned to, just referenced.
... tmp = x[0]
... x[0] = y
... return tmp
... return inner_reads, inner_writes, inner_error
...
>>> inner_reads, inner_writes, inner_error = outer(5)
>>> inner_reads()
5
>>> inner_writes(10)
>>> inner_reads()
10
>>> inner_error(15)
10
>>> inner_reads()
15
</code></pre>
|
<p>The better workaround until 3.0 is to include the variable as a defaulted parameter in the enclosed function definition:</p>
<pre>
def f()
x = 5
def g(y, z, x=x):
x = x + 1
</pre>
| 17,121
|
<p>We are about to get a canned package in that has been modified to our needs. I'm part of the team setup to prepare tests for it. It has an Oracle back end and I believe it's written in C++ .NET.</p>
<p>My question is what free or open source testing tools would you recommend.</p>
<p>Thanks</p>
<p>Ken</p>
|
<p>For regression testing of our applications I use a free tool called AutoHotKey <a href="http://www.autohotkey.com/" rel="nofollow noreferrer">http://www.autohotkey.com/</a>. It is simple, batch configurable, and can work for virtually any application you have. Not exactly designed for black box testing, but a good free tool to add to your toolbox.</p>
<p>While there are a few good commercial applications for black box testing of applications (HoloDeck <a href="http://www.sisecure.com/holodeck/index.shtml" rel="nofollow noreferrer">http://www.sisecure.com/holodeck/index.shtml</a>, Cenzic Hailstorm <a href="http://www.cenzic.com/" rel="nofollow noreferrer">http://www.cenzic.com/</a>), the only open source applications that I know about only test network security (Spike <a href="http://www.immunitysec.com/resources-freesoftware.shtml" rel="nofollow noreferrer">http://www.immunitysec.com/resources-freesoftware.shtml</a>, OWASP WebScarab <a href="http://www.owasp.org/index.php/Category:OWASP_WebScarab_Project" rel="nofollow noreferrer">http://www.owasp.org/index.php/Category:OWASP_WebScarab_Project</a>, and Nikto <a href="http://www.cirt.net/nikto2" rel="nofollow noreferrer">http://www.cirt.net/nikto2</a>)</p>
|
<p>What do you expect from such a tool? I don't know of any tool that can arbitrarily test any piece of software.</p>
| 6,323
|
<p>If I have an object implementing the <code>Map</code> interface in Java and I wish to iterate over every pair contained within it, what is the most efficient way of going through the map?</p>
<p>Will the ordering of elements depend on the specific map implementation that I have for the interface?</p>
|
<pre class="lang-java prettyprint-override"><code>Map<String, String> map = ...
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + "/" + entry.getValue());
}
</code></pre>
<p>On Java 10+:</p>
<pre class="lang-java prettyprint-override"><code>for (var entry : map.entrySet()) {
System.out.println(entry.getKey() + "/" + entry.getValue());
}
</code></pre>
|
<p>I copied the data of a map to another with this code:</p>
<pre><code>HashMap product =(HashMap)shopping_truck.get(i);
HashMap tmp = new HashMap();
for (Iterator it = product.entrySet().iterator(); it.hasNext();) {
Map.Entry thisEntry = (Map.Entry) it.next();
tmp.put(thisEntry.getKey(), thisEntry.getValue());
}
</code></pre>
| 6,906
|
<p>I have been learning about the basics of C# but haven't come across a good explanation of what this is:</p>
<pre><code>var l = new List<string>();
</code></pre>
<p>I don't know what the <code><string></code> is doing or if it's the <code>List</code> that is doing the magic. I have also seen objects been thrown within the <code>< ></code> tags.</p>
<p>Can someone explain this to me with examples, please?</p>
|
<p>That is the generic syntax for C#.</p>
<p>The basic concept is that it allows you to use a Type placeholder and substitute the actual real type in at compile time.</p>
<p>For example, the old way:</p>
<pre><code>ArrayList foos = new Arraylist();
foos.Add("Test");
</code></pre>
<p>worked by making ArrayList store a list of System.Objects (The base type for all things .NET).</p>
<p>So, when adding or retrieving an object from the list, The CLR would have to cast it to object, basically what really happens is this:</p>
<pre><code>foos.Add("Test" as System.Object);
string s = foos[1] as String.
</code></pre>
<p>This causes a performance penalty from the casting, and its also unsafe because I can do this:</p>
<pre><code>ArrayList listOfStrings = new ArrayList();
listOfStrings.Add(1);
listOfStrings.Add("Test");
</code></pre>
<p>This will compile just fine, even though I put an integer in listOfStrings.</p>
<p>Generics changed all of this, now using Generics I can declare what Type my collection expects:</p>
<pre><code>List<int> listOfIntegers = new List<int>();
List<String> listOfStrings = new List<String>();
listOfIntegers.add(1);
// Compile time error.
listOfIntegers.add("test");
</code></pre>
<p>This provides compile-time type safety, as well as avoids expensive casting operations.</p>
<p>The way you leverage this is pretty simple, though there are some advanced edge cases. The basic concept is to make your class type agnostic by using a type placeholder, for example, if I wanted to create a generic "Add Two Things" class.</p>
<pre><code>public class Adder<T>
{
public T AddTwoThings(T t1, T t2)
{
return t1 + t2;
}
}
Adder<String> stringAdder = new Adder<String>();
Console.Writeline(stringAdder.AddTwoThings("Test,"123"));
Adder<int> intAdder = new Adder<int>();
Console.Writeline(intAdder.AddTwoThings(2,2));
</code></pre>
<p>For a much more detailed explanation of generics, I can't recommend enough the book CLR via C#.</p>
|
<p>< > is for generics. In your specific example, it means that the List is a List of strings, not say a list of ints.</p>
<p>Generics are used to allow a type to be, well, generic. It's used ALOT in Collections to allow them to take different types so that they can function much like a normal array and still catch invalid types being assigned at compile time. Basically it allows a class to say "I need to be associated with some specific type T, but I don't want to hard code exactly what that type is, and let the user select it.". A simple array for instance might look something like:</p>
<pre><code>public class MyArray<T> {
private T[] _list;
public MyArray() : this.MyArray(10);
public MyArray(int capacity)
{ _list = new T[capacity]; }
T this[int index] {
get { return _list[index]; }
set { _list[index] = value; }
}
}
</code></pre>
<p>Here, we have a private list of type T that is accessed by using our class like a normal array. We don't care what type it is, it doesn't matter to our code. But anyone using the class could use it as, say <code>MyArray<string></code> to create a list of strings, while someone else might use it as <code>MyArray<bool></code> and create a list of flags.</p>
| 18,774
|
<p>Is there a way to detect if the user is holding down the shift key (or other modifier keys) when executing a javascript bookmarklet?</p>
<p>In my tests of Safari 3.1 and Firefox 3, <code>window.event</code> is always undefined.</p>
|
<p>If you're looking for a way to detect the mouse position while the bookmarklet is being physically clicked, no, there is no way. Since the bookmarklet is positioned outside of any page (this area is generally called the browser "chrome" - which is confusing since there's now a browser with that name) it's not possible to detect JavaScript-related events there.</p>
<p>That being said, if you created this as a Firefox extension then you would have access to event information, JavaScript, and keyboard modifiers. But that doesn't appear to be what you're looking for.</p>
|
<p>window.event is an IE only. Event objects are passed to an event listener as an argument in firefox and safari. So you can tell in IE, but not in any other popular browser.</p>
| 17,052
|
<p>I'm putting together a script to find remove duplicates in a large library of images. At the moment I'm doing a two pass filter of first finding files of the same size and then doing a sha256 on a 10240 byte piece of the file to get a fingerprint of the files with the same size (code <a href="http://parand.com/say/index.php/2008/10/15/python-script-for-finding-and-removing-duplicate-files/" rel="noreferrer">here</a>).</p>
<p>It works well, but I'm guessing there are probably checksums built in to the jpeg format that I could use instead of doing the sha256. </p>
<p>Does anyone know if there are checksums or other components that could act as checksums / fingerprints? If so, is there an efficient way to access them?</p>
|
<p>I don't think the JPEG specification includes any kind of checksum in the way you're describing.</p>
<p>A JPEG can contain a thumbnail as part of its EXIF metadata, though. It's not a perfect indicator, since it's possible for two different images to have the same thumbnail. There's at least one documented case of a thumbnail not being replaced after the image had undergone substantial modifications, said thumbnail revealing much more than the publisher had intended.</p>
|
<p>In JPEG standard(ITU-T.81) i believe there isn't any field/syntax element which has a checksum or such, for the whole compressed jpeg image file. Unless a customised application puts such filed in the Application segment, or as meta data for which segments are provided in the standard.
So to serve your purpose, what you are doing is one soln.
Other could be some kind a application wrapper which will call some binary file compare utlitiy (like beyond compare, or even a windows command <strong>fc /b</strong>) and check the result of that compare utility and take the decision u want to.</p>
<p>-AD</p>
| 26,734
|
<p>I'm programming an application for a <a href="http://www.microchip.com/stellent/idcplg?IdcService=SS_GET_PAGE&nodeId=2591" rel="nofollow noreferrer">32 bit processor with limited memory</a> (512k flash, 32k RAM).</p>
<p>The <a href="http://www.newhavendisplay.com/index.cfm/page/ptype=product/product_id=524/category_id=240/home_id=165/mode=prod/prd524.htm" rel="nofollow noreferrer">display</a> on this device is 128x160 with 16 bit color, which would normally consume 40k ram if I were to buffer it on my processor. I don't have that much RAM, so I'm looking for techniques, tips, tricks, ideas for generating screen data on the fly.</p>
<p>Things that might help:</p>
<ul>
<li>Perhaps you know of a resource for this sort of limitation</li>
<li>Maybe you've generated attractive graphics on the fly</li>
<li>Is there a generic algorithm I might use to combine elements in program memory (including alpha blending) on the fly while I scan the display</li>
<li>Simple vector rendering techniques (or free (bsd/mit/apache) source)</li>
<li>???</li>
</ul>
<p>I do have a multiplier, but no floating point processor. The display itself has a very simple controller and memory for the display - but reads and writes are expensive so I don't want to use that as my workspace if I can avoid it.</p>
<p>-Adam</p>
|
<p>In a way, you are in pretty much the same situation game developers where at the time of the Tandys, Spectrums and early PCs. So, here's my recommendation:</p>
<p>You should read Michael Abrash writings on computer graphics. They were written in a time where a floating point co-processor was an optional piece of hardware, and they describe a lot of the basic techniques (Bresenham lines, etc.) used in the old (supposedly 'bad') software-rendered days.</p>
<p>You can read most of his "Black Book" <a href="http://www.byte.com/abrash/" rel="nofollow noreferrer">here</a>.</p>
<p>Additionaly, you can probably find a lot of the old BBS files that most people used back in the day to learn graphics programming <a href="http://www.textfiles.com/directory.html" rel="nofollow noreferrer">here</a>. Just search for Graphics, Lines, and what not.</p>
<p>Hope that helps!</p>
<p><strong>Update:</strong> I also recall using <a href="http://tfpsly.free.fr/Docs/3dIca/3dica.htm" rel="nofollow noreferrer">this</a> in my first attempts at drawing things on the screen. Can't tell how much time I spent trying to understand the maths behind it (well, to be fair I was like 15 at the time). Very good (and simple) introduction to 3D, and a very nice premier on transformations, polygon-fillers and interpolation.</p>
|
<p>Some ideas that would combine nice graphics and low memory:</p>
<ul>
<li>Store backgrounds and sprites in flash.</li>
<li>Store dynamically generated graphics in RAM using a palette to half the bytes.</li>
<li>Use the windowing feature of the LCD driver to only update the part of the screen you need to.</li>
</ul>
| 20,998
|
<p>I'm using this database where the date colomn is a numeric value instead of a Date value. </p>
<p>Yes, I know I can change that with a mouseclick, but all the applications using that database were made by one of my predecessors (and everyone after him just ignored it and built on). So if I'd change it to Date a lot af applications would fail. :(</p>
<p>Well, I am making an overview of that database, ranging from one specfic date to another. I tried using a dropdown list but as you can tell, a thousand options in one list is terribly inconvenient, even ugly. </p>
<p>I rather have small inputfields for day - month - year, but there comes waltzing in the numeric date in the database. I would have to calculate the date back to the numeric value somehow... </p>
<p>There must be an easy solution to this. Right?<br /><br /><br /><br />
I'm using ASP(vbscript) for the application, it's for an intraweb, and I have an Access Database.</p>
|
<p>Access will convert to a number for you, as was mentioned, the dates are stored as numbers.</p>
<pre><code>Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset("TestTable")
rs.AddNew
rs!NumberDate = Now() 'Value stored, eg, 39791.4749074074 '
rs.Update
rs.MoveLast
'To show that it converts back to the correct date / time '
Debug.Print Format(rs!NumberDate, "dd/mm/yyyy hh:nn:ss")
</code></pre>
<p>EDIT re comment: Here is a small test that shows dates returned:</p>
<pre><code>Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
strFile = "C:\Docs\LTD.mdb"
cn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & strFile & ";" & _
"Persist Security Info=False"
strSQL = "SELECT NumberDate FROM TestTable WHERE NumberDate= #2008/12/7#"
rs.Open strSQL, cn, 3, 3
rs.MoveLast
MsgBox rs.RecordCount
</code></pre>
|
<p>Access stores date internally as a floating point number (number of days since 31.12.1899 or something), have you tried using CDate() to convert the number back to a date? You should be able to query using BETWEEN then.</p>
<p>Another possibility is that the date is stored numerically but not converted (i.e 31121899), in this case you should be able to get the appropriate date parts using either Format() or Day() or Month() or Year().</p>
<p>Hope this helps.</p>
| 45,869
|
<p>Has anyone implemented Lightbox style background dimming on a modal dialog box in a MFC/non .net app.<br>
I think the procedure would have to be something like:</p>
<p>steps:</p>
<ol>
<li><p>Get dialog parent HWND or CWnd* </p></li>
<li><p>Get the rect of the parent window and draw an overlay with a translucency over that window </p></li>
<li>allow the dialog to do it's modal draw routine, e.g DoModal()</li>
</ol>
<p>Are there any existing libraries/frameworks to do this, or what's the best way to drop a translucent overlay in MFC?<br>
<strong>edit</strong> Here's a mockup of what i'm trying to achieve if you don't know what 'lightbox style' means<br>
<strong>Some App</strong>:<br>
<img src="https://farm4.static.flickr.com/3065/2843243996_8a4536f516_o.png" alt="alt text"> </p>
<p>with a lightbox dialog box<br>
<img src="https://farm4.static.flickr.com/3280/2842409249_4a1c7f5810_o.png" alt="alt text"></p>
|
<p>Here's what I did* based on Brian's links<br>
First create a dialog resource with the properties:</p>
<ul>
<li>border <strong>FALSE</strong></li>
<li>3D look <strong>FALSE</strong></li>
<li>client edge <strong>FALSE</strong></li>
<li>Popup style</li>
<li>static edge <strong>FALSE</strong></li>
<li>Transparent <strong>TRUE</strong></li>
<li>Title bar <strong>FALSE</strong> </li>
</ul>
<p>and you should end up with a dialog window with no frame or anything, just a grey box.
override the Create function to look like this: </p>
<pre><code>BOOL LightBoxDlg::Create(UINT nIDTemplate, CWnd* pParentWnd)
{
if(!CDialog::Create(nIDTemplate, pParentWnd))
return false;
RECT rect;
RECT size;
GetParent()->GetWindowRect(&rect);
size.top = 0;
size.left = 0;
size.right = rect.right - rect.left;
size.bottom = rect.bottom - rect.top;
SetWindowPos(m_pParentWnd,rect.left,rect.top,size.right,size.bottom,NULL);
HWND hWnd=m_hWnd;
SetWindowLong (hWnd , GWL_EXSTYLE ,GetWindowLong (hWnd , GWL_EXSTYLE ) | WS_EX_LAYERED ) ;
typedef DWORD (WINAPI *PSLWA)(HWND, DWORD, BYTE, DWORD);
PSLWA pSetLayeredWindowAttributes;
HMODULE hDLL = LoadLibrary (_T("user32"));
pSetLayeredWindowAttributes =
(PSLWA) GetProcAddress(hDLL,"SetLayeredWindowAttributes");
if (pSetLayeredWindowAttributes != NULL)
{
/*
* Second parameter RGB(255,255,255) sets the colorkey
* to white LWA_COLORKEY flag indicates that color key
* is valid LWA_ALPHA indicates that ALphablend parameter
* is valid - here 100 is used
*/
pSetLayeredWindowAttributes (hWnd,
RGB(255,255,255), 100, LWA_COLORKEY|LWA_ALPHA);
}
return true;
}
</code></pre>
<p>then create a small black bitmap in an image editor (say 48x48) and import it as a bitmap resource (in this example IDB_BITMAP1)<br>
override the WM_ERASEBKGND message with:</p>
<pre><code>BOOL LightBoxDlg::OnEraseBkgnd(CDC* pDC)
{
BOOL bRet = CDialog::OnEraseBkgnd(pDC);
RECT rect;
RECT size;
m_pParentWnd->GetWindowRect(&rect);
size.top = 0;
size.left = 0;
size.right = rect.right - rect.left;
size.bottom = rect.bottom - rect.top;
CBitmap cbmp;
cbmp.LoadBitmapW(IDB_BITMAP1);
BITMAP bmp;
cbmp.GetBitmap(&bmp);
CDC memDc;
memDc.CreateCompatibleDC(pDC);
memDc.SelectObject(&cbmp);
pDC->StretchBlt(0,0,size.right,size.bottom,&memDc,0,0,bmp.bmWidth,bmp.bmHeight,SRCCOPY);
return bRet;
}
</code></pre>
<p>Instantiate it in the DoModal of the desired dialog, Create it like a Modal Dialog i.e. on the stack(or heap if desired), call it's Create manually, show it then create your actual modal dialog over the top of it: </p>
<pre><code>INT_PTR CAboutDlg::DoModal()
{
LightBoxDlg Dlg(m_pParentWnd);//make sure to pass in the parent of the new dialog
Dlg.Create(LightBoxDlg::IDD);
Dlg.ShowWindow(SW_SHOW);
BOOL ret = CDialog::DoModal();
Dlg.ShowWindow(SW_HIDE);
return ret;
}
</code></pre>
<p>and this results in something <strong>exactly</strong> like my mock up above </p>
<p>*there are still places for improvment, like doing it without making a dialog box to begin with and some other general tidyups.</p>
|
<p>I think you just need to create a window and set the transparency. There is an MFC <a href="http://www.codeproject.com/KB/dialog/CGlassDialog.aspx" rel="nofollow noreferrer">CGlassDialog sample on CodeProject</a> that might help you. There is also an <a href="http://www.codeproject.com/KB/winsdk/quaker1.aspx" rel="nofollow noreferrer">article</a> on how to do this with the Win32 APIs.</p>
| 7,490
|
<p>What is the correct way to do this? For example, how would I change a stored procedure with this signature:</p>
<pre><code>CREATE PROCEDURE dbo.MyProcedure
@Param BIT = NULL
AS
SELECT *
FROM dbo.SomeTable T
WHERE T.SomeColumn = @Param
</code></pre>
<p>So that giving @Param with a value of 1 or 0 performs the filter, but not specifying it or passing NULL performs no filtering?</p>
|
<p>Assuming that NULL means "don't care" then use</p>
<pre><code>CREATE PROCEDURE dbo.MyProcedure
@Param BIT = NULL
AS
SELECT *
FROM dbo.SomeTable T
WHERE T.SomeColumn = @Param OR @Param IS NULL
</code></pre>
|
<p>I happen to think that the cleanest way of doing this is (in T-SQL) is:</p>
<pre><code>SELECT * FROM TABLE WHERE column = ISNULL(@param, column)
</code></pre>
<p>Other RDBMS would prefer COALESCE instead of ISNULL.</p>
<p>I think it's more obvious what the intent is here, especially as you start to add other OR clauses, and it also keeps you from needing parens when combining with AND clauses.</p>
<p>In my (very) limited testing, there was also a negligible perf increase using ISNULL versus OR @p IS NULL. Not that I'm advocating using ISNULL <em>because</em> of the perf increase (which is extremely marginal at best, and is subject to very specific cases at worst) but it's nice to know it doesn't have a significant cost. Frankly, I'm not sure why it'd make a difference either way, but the execution plan shows about a 1% difference in the filter cost.</p>
| 23,322
|
<p>I want to create a class that takes string array as a constructor argument and has command line option values as members vals. Something like below, but I don't understand how the Bistate works.</p>
<pre><code>import scalax.data._
import scalax.io.CommandLineParser
class TestCLI(arguments: Array[String]) extends CommandLineParser {
private val opt1Option = new Flag("p", "print") with AllowAll
private val opt2Option = new Flag("o", "out") with AllowAll
private val strOption = new StringOption("v", "value") with AllowAll
private val result = parse(arguments)
// true or false
val opt1 = result(opt1Option)
val opt2 = result(opt2Option)
val str = result(strOption)
}
</code></pre>
|
<p>Here are shorter alternatives to that pattern matching to get a boolean:</p>
<pre><code>val opt1 = result(opt1Option).isInstanceOf[Positive[_]]
val opt2 = result(opt2Option).posValue.isDefined
</code></pre>
<p>The second one is probably better. The field <strong>posValue</strong> is an Option (there's <strong>negValue</strong> as well). The method <strong>isDefined</strong> from Option tells you whether it is a Some(x) or None.</p>
|
<p>So if I want to assign to variable boolean value of whether flag is found I have to do like below?</p>
<pre><code>val opt1 = result(opt1Option) match {
case Positive(_) => true
case Negative(_) => false
}
</code></pre>
<p>Isn't there a way to write this common case with less code than that?</p>
| 31,364
|
<p>Which browsers other than Firefox support Array.forEach()? <a href="http://developer.mozilla.org/En/Core_JavaScript_1.5_Reference:Objects:Array:forEach#Compatibility" rel="noreferrer">Mozilla say it's an extension to the standard</a> and I realise it's trivial to add to the array prototype, I'm just wondering what other browsers support it?</p>
|
<p>The <a href="http://en.wikipedia.org/wiki/JavaScript" rel="noreferrer" title="JavaScript - Wikipedia, the free encyclopedia">JavaScript</a> article of Wikipedia lists the JS versions by browser. forEach is <a href="http://developer.mozilla.org/en/New_in_JavaScript_1.6" rel="noreferrer" title="New in JavaScript 1.6">part of JavaScript 1.6</a>. So it is supported indeed by most browsers, except Opera 9.02 (which I just tested). Opera 9.5 (which I just installed!) supports it, along with indexOf for Array.</p>
<p>Surprisingly, it is not official. I don't see its support in the page <a href="http://www.opera.com/docs/specs/opera95/js/ecma/" rel="noreferrer">ECMAScript support in Opera 9.5</a>. Perhaps it is an overlook or perhaps only a partial support they don't want to advertise.</p>
|
<p>If you need all browsers to support this and other JavaScript 1.6 to 1.8 functions, I would suggest using the customizable <a href="http://jpaq.org/" rel="nofollow" title="jPaq">jPaq</a> library. The functions are implemented in the way that was suggested by Mozilla.</p>
| 18,958
|
<p>I'm trying to debug a rather complicated formula evaluator written in T-SQL UDFs (don't ask) that <strong>recursively</strong> (but indirectly through an intermediate function) calls itself, blah, blah.</p>
<p>And, of course, we have a bug.</p>
<p>Now, using PRINT statements (that can then be read from ADO.NET by implementing a handler for the InfoMessage event), I can simulate a trace for stored procedures.</p>
<p>Doing the same for UDF results in a compile time message:</p>
<pre><code>Invalid use of side-effecting or time-dependent operator in 'PRINT' within a function.
</code></pre>
<p>I get the message (PRINT does some stuff like resetting <code>@@ROWCOUNT</code> which definitly is a no-no in UDFs, but how can I trace through the calls? I want to have this trace printed out, so I can study it without getting distracted by stepping through the calls in the debugger...</p>
<p><strong>EDIT:</strong> I have tried to use the SQL Profiler (this was a first time one for me), but I can't figure out what to trace for: Although I can get the trace to output the queries sent to the database, they are opaque in the sense that I can't drill down to the Expression-UDFs called: I can trace the actual Stored Procedure invoked, but the UDFs called by this procedure are not listed. Am I missing something? I guess not...</p>
<p><strong>EDIT #2:</strong> Allthough the (auto-)accepted answer does trace the function calls - very helpful, thanks - it does not help in finding out what parameters were <em>passed</em> to the function. This, of course, is essential in <strong>debugging</strong> recursive functions. I will post if I find any sollution at all...</p>
|
<p>Why not use SQL Profiler with statement level events added?</p>
<p><strong>Edit</strong>: Add events for Stored Procedures : SP:Stmt Starting or SP:Stmt Completed
Use variables to debug if needed, i.e. set @debug='i am here'; UDF's, while not technically stored procedures, will get traced with the statement level events. </p>
|
<p>I second the SQL Profiler suggestion. Take some time to set it up so that only the events you are interested in are logged to cut output size. You can output the trace to a file - I have frequently then loaded that file back into a table to enable analysis. (extremely handy for performance analysis, though no doubt someone will tell me that 2008 has this all built in somwehere...)</p>
<p>Sometimes you won't have permissions to run SQL Profiler as it does slow the server down - ask your DBA to grant you permission on your Dev server. They shouldn't have any problems with that.</p>
| 45,920
|
<p>I seem to make this mistake every time I set up a new development box. Is there a way to make sure you don't have to manually assign rights for the ASPNET user? I usually install .Net then IIS, then Visual Studio but it seems I still have to manually assign rights to the ASPNET user to get everything running correctly. Is my install order wrong?</p>
|
<p>Install IIS, then .NET. The .NET installation will automatically register the needed things with IIS.</p>
<p>If you install .NET first, run this:</p>
<pre><code>%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -i
</code></pre>
<p>to run the registration parts, and </p>
<pre><code>%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -ga userA
</code></pre>
<p>to set up the security rights for userA</p>
|
<p>If you install first IIS and then .Net, it'll be OK.</p>
<p>In your scenario - use <a href="http://msdn.microsoft.com/en-us/library/k6h9cz8h(VS.80).aspx" rel="nofollow noreferrer">Aspnet_regiis.exe -qa <em>user</em></a> (not available for .Net < 2.0)</p>
| 11,373
|
<p>Visual Studio Solution files contain two GUID's per project entry. I figure one of them is from the AssemblyInfo.cs</p>
<p>Does anyone know for sure where these come from, and what they are used for?</p>
|
<p>Neither GUID is the same GUID as from AssemblyInfo.cs (that is the GUID for the assembly itself, not tied to Visual Studio but the end product of the build).</p>
<p>So, for a typical line in the sln file (open the .sln in notepad or editor-of-choice if you wish to see this):</p>
<pre><code>Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsoleSandbox", "ConsoleSandbox\ConsoleSandbox.csproj", "{55A1FD06-FB00-4F8A-9153-C432357F5CAC}"
</code></pre>
<p>The second GUID is a unique GUID for the project itself. The solution file uses this to map other settings to that project:</p>
<pre><code>GlobalSection(ProjectConfigurationPlatforms) = postSolution
{55A1FD06-FB00-4F8A-9153-C432357F5CAC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{55A1FD06-FB00-4F8A-9153-C432357F5CAC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{55A1FD06-FB00-4F8A-9153-C432357F5CAC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{55A1FD06-FB00-4F8A-9153-C432357F5CAC}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
</code></pre>
<p>The first GUID is actually a GUID that is the unique GUID for the solution itself (I believe). If you have a solution with more than one project, you'll actually see something like the following:</p>
<pre><code>Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsoleSandbox", "ConsoleSandbox\ConsoleSandbox.csproj", "{55A1FD06-FB00-4F8A-9153-C432357F5CAC}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Composite", "..\CompositeWPF\Source\CAL\Composite\Composite.csproj", "{77138947-1D13-4E22-AEE0-5D0DD046CA34}"
EndProject
</code></pre>
|
<p><a href="http://msdn.microsoft.com/en-us/library/bb165951(VS.80).aspx" rel="noreferrer">According to MSDN</a>: </p>
<blockquote>
<p>[The <code>Project</code>] statement contains the
unique project GUID and the project
type GUID. This information is used by
the environment to find the project
file or files belonging to the
solution, and the VSPackage required
for each project. The project GUID is
passed to IVsProjectFactory to load
the specific VSPackage related to the
project, then the project is loaded by
the VSPackage.</p>
</blockquote>
| 7,642
|
<p>This is a follow on to this <a href="https://stackoverflow.com/questions/232500/how-to-configure-security-when-calling-wcf-service-from-net-20-client">question</a>. I am trying to avoid using the x509 certificate method as that makes my client installs more complex. If basicHttpBinding is not the only option, where are some samples of other binding methods. </p>
<p>My clients are on .Net 2.0, I don't have access to System.ServiceModel namespace as that didn't come out until 3.0.</p>
<p>Update: To be clear,
clients: .Net 2.0,
web service: .net3.5/WCF</p>
|
<p>The problem isn't a mismatch between .Net 2.0 services and WCF and the various bindings - they are (with a few notable exceptions that shouldn't be a problem in your case) very compatible protocols.</p>
<p>WSE 3.0 (which runs on the 2.0 .Net framework) is particularly close. You can use this with either basicHttpBinding or with wsHttpBinding and a few tweaks. 'Jimmy' Skowronski's article <a href="http://devlicio.us/blogs/ziemowit_skowronski/archive/2007/07/18/interoperability-between-wcf-and-wse-3-0.aspx" rel="nofollow noreferrer">here</a> and the MSDN article <a href="http://msdn.microsoft.com/en-us/magazine/cc163597.aspx" rel="nofollow noreferrer">here</a> cover most of the basics.</p>
<p>You can also code a custom binding that will let you side step the few incompatibilities between WSE and WCF (like the mandate for a secure transport when using WCF and basic authentication)</p>
<p>Your problem as I understand it is how to manage the authentication - in you previous question you ruled out Windows authenticaion. Kerberos works in both WCF or WSE but that is even more complicated.</p>
<p>Unless you delve into you own authentication schemes you are (as far as I know) limited to using basic authentication (so each client supplies a user name or password, this could be the same for all clients depending on your needs) or certificate based authentication. </p>
<p>Toran's answer is a good starter for using basic authentication.</p>
<p>I think maybe a good approach would be to look at the requirements from the .Net 2.0 (and WSE*) side of things first - establish an authenticaion mechanism that fits with your client deployments, then work out how to accept that authentication with WCF. </p>
<p>WCF can accept pretty much anything WSE 3.0 can send (with the only exceptions I can think of off the top of my head being the version of the addressing specification, and some slightly tighter security requirement)</p>
|
<p>You could require SSL + Username/Password with basicHttp.</p>
<p>First the below is what your client would use in .NET 2.0 to auth w/ your WCF service.</p>
<pre><code>Dim client As WebServiceClient = New WebServiceClient("basicHttpWebService")
client.ClientCredentials.UserName.UserName = "username"
client.ClientCredentials.UserName.Password = "password"
</code></pre>
<p>Next, a sample config for your WCF service to require SSL + Membership provider credentials</p>
<pre><code> <bindings>
<basicHttpBinding>
<binding name="basicHttp">
<security mode="TransportWithMessageCredential">
<transport/>
<message clientCredentialType="UserName"/>
</security>
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="NorthwindBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceAuthorization principalPermissionMode="UseAspNetRoles"/>
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="MembershipProvider"/>
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
</code></pre>
<p>The only thing I'm not sure about is that to use the first section in the client app you might need the WCF/WPF extensions CTP installed because I typically right click and "add service reference" instead of the ASMX "add web reference" - if so this extension for VS2005 does require .NET 3.0 to be installed. But with a simple "add web reference" you should still be able enter a username/password ... I just don't know what this vb/c# would look like ...</p>
| 29,070
|
<p>I'm writing an article about editing pages in order to hand pick what you really want to print. There are many tools (like "Print What you like") but I also found this script. Anyone knows anything about it? I haven't found any kind of documentation or references.</p>
<pre><code>javascript:document.body.contentEditable='true'; document.designMode='on'; void 0
</code></pre>
<p>Thanks!</p>
|
<p>The contentEditable property is what you want -- It's supported by IE, Safari (and by chrome as a byproduct), and I <em>think</em> firefox 3 (alas not FFX2). And hey, it's also part of HTML5 :D</p>
<p>Firefox 2 supports designMode, but that is restricted to individual frames, whereas the contentEditable property applies applies to individual elements, so you can have your editable content play more nicely with your page :D</p>
<p>[Edit (olliej): Removed example as contentEditable attribute doesn't get past SO's output filters (despite working in the preview) :( ]</p>
<p>[Edit (olliej): I've banged up a very simple <a href="http://www.nerget.com/contentEditableDemo.html" rel="noreferrer">demo</a> to illustrate how it behaves]</p>
<p>[Edit (olliej): So yes, the contentEditable attribute in the linked demo works fine in IE, Firefox, and Safari. Alas resizing is a css3 feature only webkit seems to support, and IE is doing its best to fight almost all of the CSS. <em>sigh</em>]</p>
|
<p>It enables the browser's in-built editing functionality where available. As is mentioned above, designMode is Gecko and contentEditable is everyone else (and added to Gecko 1.9). These features are used as the basis of (nearly?) every WYSIWYG editor built with HTML/Javascript. If you're simply typing/deleting, nothing more should be necessary than the script you provided. (Everything from 'void' on is superfluous though.)</p>
<p>For documentation on how these features can be used in an application, the best reference is Mozilla's <a href="http://www.mozilla.org/editor/midas-spec.html" rel="nofollow noreferrer">Midas specification</a> (<a href="http://msdn.microsoft.com/en-us/library/aa969729(VS.85).aspx" rel="nofollow noreferrer">MSDN</a> may be of some use as well...).</p>
| 21,274
|
<p>I'm interested in using an Object-Relational Mapping package for an upcoming project. This project will begin as an ASP.NET application but will have lots of functionality that will eventually be shared with WinForms applications. Can anyone suggest some good, free ORM packages that work well in both ASP.NET and WinForms situations? </p>
|
<p>SubSonic is not as extensive as nHibernate; rather, it is a straight forward Active Record 1 class per table Data Access Layer. </p>
<p>Some of the features are a query tool, ability to execute stored procedures and a scaffolding app in ASP.net. You can be up and running within 30 minutes or less, with a tiny learning curve and minimal configuration in the Config.app file.</p>
|
<p>I've been using SubSonic for about a year now for a handful of ASP.NET apps as well as a WinForms app. It is extremely easy to get started with and I have not yet been "painted into a corner" by choosing it -- there is almost always some way to do what you need, usually easily. I estimate it has shaved 30% off of our development time. Not a true ORM tool but provides a great productivity boost.</p>
| 25,263
|
<p>Is there a simple attribute or data contract that I can assign to a function parameter that prevents <code>null</code> from being passed in C#/.NET? Ideally this would also check at compile time to make sure the literal <code>null</code> isn't being used anywhere for it and at run-time throw <code>ArgumentNullException</code>.</p>
<p>Currently I write something like ...</p>
<pre><code>if (null == arg)
throw new ArgumentNullException("arg");
</code></pre>
<p>... for every argument that I expect to not be <code>null</code>.</p>
<p>On the same note, is there an opposite to <code>Nullable<></code> whereby the following would fail:</p>
<pre><code>NonNullable<string> s = null; // throw some kind of exception
</code></pre>
|
<p>There's nothing available at compile-time, unfortunately.</p>
<p>I have a bit of a <a href="https://web.archive.org/web/20081231232311/http://msmvps.com/blogs/jon_skeet/archive/2008/10/06/non-nullable-reference-types.aspx" rel="noreferrer">hacky solution</a> which I posted on my blog recently, which uses a new struct and conversions.</p>
<p>In .NET 4.0 with the <a href="http://research.microsoft.com/contracts/" rel="noreferrer">Code Contracts</a> stuff, life will be a lot nicer. It would still be quite nice to have actual language syntax and support around non-nullability, but the code contracts will help a lot.</p>
<p>I also have an extension method in <a href="http://pobox.com/~skeet/csharp/miscutil" rel="noreferrer">MiscUtil</a> called ThrowIfNull which makes it a bit simpler.</p>
<p>One final point - any reason for using "<code>if (null == arg)</code>" instead of "<code>if (arg == null)</code>"? I find the latter easier to read, and the problem the former solves in C doesn't apply to C#.</p>
|
<p>Ok this reply is a bit late, but here is how I am solving it:</p>
<pre><code>public static string Default(this string x)
{
return x ?? "";
}
</code></pre>
<p>Use this exension method then you can treat null and empty string as the same thing.</p>
<p>E.g. </p>
<pre><code>if (model.Day.Default() == "")
{
//.. Do something to handle no Day ..
}
</code></pre>
<p>Not ideal I know as you have to remember to call default everywhere but it is one solution.</p>
| 37,155
|
<p>I have created a timeclock application in C# that connects to a web service on our server in order to clock employees in/out. The application resides in the system tray and clocks users out if they shut down/suspend their machines or if they are idle for more than three hours to which it clocks them out at the time of last activity.</p>
<p>My issue arises that when a user brings his machine back up from a sleep state (which fires the SystemEvents.PowerModeChanged event), the application attempts to clock the employee back in but the network connection isn't fully initialized at that time and the web-service call times out. </p>
<p>An obvious solution, albeit it a hack, would be to put a delay on the clock in but this wouldn't necessarily fix the problem across the board. What I am looking to do is a sort of "relentless" clock in where it will wait until it can see the server until it actually attempts to clock in.</p>
<p>What is the best method to determine if a connection to a web service can be made?</p>
|
<p>The best way is going to be to actually try to make the connection and catch the errors. You can ping the machine, but that will only tell you if the machine is running and on the network, which doesn't necessarily reflect on whether the webservice is running and available.</p>
|
<p>When handling the event, put your connection code into a method that will loop through until success, catching errors and retrying. </p>
<p>Even a delay wouldn't be perfect as depending on the individual systems and other applications running it can take varying times for the network connection to be re-established.</p>
| 16,352
|
<p>The Alt+Space command doesn't work on Putty (at least for me). So, if I've to minimize or maximize my PuTTY windows, I'll have to use the mouse which is very uncomfortable. Did anyone get around this problem?</p>
<p>Thanks for your time!</p>
|
<p>Never mind, there's a setting for that.</p>
<p>Window -> Behavior -> (System Menu Appears on Alt+SPACE checkbox)</p>
|
<p>You should go to Window/Behavior and check Full screen on Alt-Enter. Save the session, so you'll be able to use this shortcut to convert into full screen mode.</p>
| 33,260
|
<p>I have this .NET web app that draws a table in Page_Load.</p>
<p>Then after that it handles the events, which should change the table drawn in Page_Load.
This is very inefficient.</p>
<p>Is there a way to execute the code (which draws the table) after it finishes handling all events? (instead of doing it in Page_Load)</p>
<p>Thank you in advance.</p>
|
<p>You need to handle an event that occurs after the control events, but before the page is rendered, such as <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.page.loadcomplete.aspx" rel="nofollow noreferrer">LoadComplete</a> or <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.control.prerender.aspx" rel="nofollow noreferrer">PreRender</a>.</p>
<p>Check out the <a href="http://msdn.microsoft.com/en-us/library/ms178472.aspx" rel="nofollow noreferrer">ASP.NET Page Life Cycle Overview</a> for more info.</p>
|
<p>Check out the OnPreRender event in the page lifecycle.</p>
<p>-Oisin</p>
| 39,592
|
<p>Given an array like {"one two", "three four five"}, how'd you calculate the total number of words contained in it using LINQ?</p>
|
<p>You can do it with SelectMany:</p>
<pre><code>var stringArray = new[] {"one two", "three four five"};
var numWords = stringArray.SelectMany(segment => segment.Split(' ')).Count();
</code></pre>
<p><a href="http://msdn.microsoft.com/en-us/library/system.linq.enumerable.selectmany.aspx" rel="nofollow noreferrer">SelectMany</a> flattens the resulting sequences into one sequence, and then it projects a whitespace split for each item of the string array...</p>
|
<p>Not an answer to the question (that was to use LINQ to get the combined word count in the array), but to add related information, you can use strings.split and strings.join to do the same:</p>
<p>C#:</p>
<pre><code>string[] StringArray = { "one two", "three four five" };
int NumWords = Strings.Split(Strings.Join(StringArray)).Length;
</code></pre>
<p>Vb.Net: </p>
<pre><code> Dim StringArray() As String = {"one two", "three four five"}
Dim NumWords As Integer = Split(Join(StringArray)).Length
</code></pre>
| 48,810
|
<p>Is it possible for the .NET CLR to support Objective-C? Are there any reasons (either from a legal or implementational) standpoint why this wouldn't be possible?</p>
<p>In the spirit of cross-platform application development, it would be nice to be able to write and run Objective-C applications on Windows machines. At least I think it would.</p>
|
<p>Objective-C is a strict superset of C. As such, it's got a lot of features, like pointers, that translate poorly onto .NET. Of course, it may be that -- in practice -- most Objective-C programs are written in such a way that they would also compile against a more tightly-defined version of the language specification that was more restrictive but could be translated into safe code.</p>
<p>Assuming this is the case, the method dispatch part of Objective-C is a natural fit for the dynamic capabilities of the <a href="http://en.wikipedia.org/wiki/Dynamic_Language_Runtime" rel="nofollow noreferrer">DLR</a>. I've actually considered creating such a port.</p>
|
<p>What about <a href="https://en.wikipedia.org/wiki/Objective-J" rel="nofollow noreferrer">Objective-J</a> and <a href="https://en.wikipedia.org/wiki/Cappuccino_(software)" rel="nofollow noreferrer">Cappuccino</a> for .Net, rather than Objective-C and <a href="https://en.wikipedia.org/wiki/Cocoa_%28API%29" rel="nofollow noreferrer">Cocoa</a>? Objective-J is just as appealing as Objective-C, however, Objective-J is closer to C# than Objective-C (no pointers, garbage collection, etc.)</p>
<p>I recently asked about this on the Cappuccino developers forum, and they pointed me towards Jurassic (a JavaScript compiler for .NET). They also said that Cappuccino works fine on IronJS. So, it looks like the components are there (Objective-J → JavaScript → .NET), but the bridge linking them together has to be built.</p>
| 30,479
|
<p>How would you handle cross database queries in different environments. For example, db1-development and db2-development, db1-production and db2-production. </p>
<p>If I want to do a cross-database query in development from db2 to db1 I could use the fully qualified name, [db1-development].[schema].[table]. But how do I maintain the queries and stored procedures between the different environments? [db1-development].[schema].[table] will not work in production because the database names are different.</p>
<p>I can see search and replace as a possible solution but I am hoping there is a more elegant way to solve this problem. If there are db specific solutions, I am using SQL Server 2005.</p>
|
<p>Why are the database names different between dev and prod? It'd, obviously, be easiest if they were the same.</p>
<p>If it's a single table shared, then you could create a view over it - which only requires that you change that view when moving to production.</p>
<p>Otherwise, you'll want to <a href="http://msdn.microsoft.com/en-us/library/ms177544(SQL.90).aspx" rel="noreferrer">create a SYNONYM</a> for the objects, and make sure to always reference that. You'll still need to change the SYNONYM creation scripts, but that can be done in a build script fairly easily, I think.</p>
|
<p>For this reason, it's not practical to use different names for development and production databases. Using the same db name on development, production, and optionally, acceptance/Q&A environments, makes your SQL code much easier to maintain.</p>
<p>However, if you really have to, you could get creative with views and dynamic SQL. For example, you put the actual data retrieval query inside a view, and then you select like this:</p>
<pre><code>declare @environment varchar(10)
set @environment = 'db-dev' -- input parameter, comes from app layer
declare @sql varchar(8000)
set @sql = 'select * from ' + @environment + '.dbo.view'
execute(@sql)
</code></pre>
<p>But it's far from pretty...</p>
| 40,615
|
<p>So I have xml that looks like this:
</p>
<pre class="lang-html prettyprint-override"><code><todo-list>
<id type="integer">#{id}</id>
<name>#{name}</name>
<description>#{description}</description>
<project-id type="integer">#{project_id}</project-id>
<milestone-id type="integer">#{milestone_id}</milestone-id>
<position type="integer">#{position}</position>
<!-- if user can see private lists -->
<private type="boolean">#{private}</private>
<!-- if the account supports time tracking -->
<tracked type="boolean">#{tracked}</tracked>
<!-- if todo-items are included in the response -->
<todo-items type="array">
<todo-item>
...
</todo-item>
<todo-item>
...
</todo-item>
...
</todo-items>
</todo-list>
</code></pre>
<p>How would I go about using .NET's serialization library to deserialize this into C# objects? </p>
<p>Currently I'm using reflection and I map between the xml and my objects using the naming conventions.</p>
|
<p>Create a class for each element that has a property for each element and a List or Array of objects (use the created one) for each child element. Then call System.Xml.Serialization.XmlSerializer.Deserialize on the string and cast the result as your object. Use the System.Xml.Serialization attributes to make adjustments, like to map the element to your ToDoList class, use the XmlElement("todo-list") attribute.</p>
<p>A shourtcut is to load your XML into Visual Studio, click the "Infer Schema" button and run "xsd.exe /c schema.xsd" to generate the classes. xsd.exe is in the tools folder. Then go through the generated code and make adjustments, such as changing shorts to ints where appropriate.</p>
|
<p>i had the same questions few years back that how abt mapping xml to C# classes or creating C# classes which are mapped to our XMLs, jst like we do in entity Framework (we map tables to C# classes). I created a framework finally, which can create C# classes out of your XML and these classes can be used to read/write your xml. Have a <a href="http://www.stepupframeworks.com/Home/products/xml-object-mapping-xom/" rel="nofollow">look</a></p>
| 28,026
|
<p>I have an array of characters that are Points and I want to take any character and be able to loop through that array and find the top 3 closest (using Point.distance) neighbors. Could anyone give me an idea of how to do this?</p>
|
<p>This is a new and improved version of the code I posted last night. It's composed of two classes, the PointTester and the TestCase. This time around I was able to test it too!</p>
<p><strong>We start with the TestCase.as</strong></p>
<pre><code>package {
import flash.geom.Point;
import flash.display.Sprite;
public class TestCase extends Sprite {
public function TestCase() {
// some data to test with
var pointList:Array = new Array();
pointList.push(new Point(0, 0));
pointList.push(new Point(0, 0));
pointList.push(new Point(0, 0));
pointList.push(new Point(1, 2));
pointList.push(new Point(9, 9));
// the point we want to test against
var referencePoint:Point = new Point(10, 10);
var resultPoints:Array = PointTester.findClosest(referencePoint, pointList, 3);
trace("referencePoint is at", referencePoint.x, referencePoint.y);
for each(var result:Object in resultPoints) {
trace("Point is at:", result.point.x, ", ", result.point.y, " that's ", result.distance, " units away");
}
}
}
}
</code></pre>
<p><strong>And this would be PointTester.as</strong></p>
<pre><code>package {
import flash.geom.Point;
public class PointTester {
public static function findClosest(referencePoint:Point, pointList:Array, maxCount:uint = 3):Array{
// this array will hold the results
var resultList:Array = new Array();
// loop over each point in the test data
for each (var testPoint:Point in pointList) {
// we store the distance between the two in a temporary variable
var tempDistance:Number = getDistance(testPoint, referencePoint);
// if the list is shorter than the maximum length we don't need to do any distance checking
// if it's longer we compare the distance to the last point in the list, if it's closer we add it
if (resultList.length <= maxCount || tempDistance < resultList[resultList.length - 1].distance) {
// we store the testing point and it's distance to the reference point in an object
var tmpObject:Object = { distance : tempDistance, point : testPoint };
// and push that onto the array
resultList.push(tmpObject);
// then we sort the array, this way we don't need to compare the distance to any other point than
// the last one in the list
resultList.sortOn("distance", Array.NUMERIC );
// and we make sure the list is kept at at the proper number of entries
while (resultList.length > maxCount) resultList.pop();
}
}
return resultList;
}
public static function getDistance(point1:Point, point2:Point):Number {
var x:Number = point1.x - point2.x;
var y:Number = point1.y - point2.y;
return Math.sqrt(x * x + y * y);
}
}
}
</code></pre>
|
<p>It might be worth mentioning that, if the number of points is large enough for performance to be important, then the goal could be achieved more quickly by keeping two lists of points, one sorted by X and the other by Y. One could then find the closest 3 points in O(logn) time rather than O(n) time by looping through every point.</p>
| 19,226
|
<p>How can we get information regarding poorly performing sqls(taking too much time for execution)</p>
<p>Does MS SQL server maintains tables/views (Similar to v$sql in Oracle) for storing sql queries.</p>
|
<p>I Use the SQL Profiler to collect statistic data wich I then can use to nail down where there are need to do some work, tweak indexes and so on.</p>
<p>Here are some tips about monitoring with Profiler:
<a href="http://www.developer.com/db/article.php/3490086" rel="nofollow noreferrer">http://www.developer.com/db/article.php/3490086</a>
<a href="http://vyaskn.tripod.com/analyzing_profiler_output.htm" rel="nofollow noreferrer">http://vyaskn.tripod.com/analyzing_profiler_output.htm</a></p>
|
<p>take a look at sys.dm_exec_query_stats and <a href="http://glennberrysqlperformance.spaces.live.com/blog/cns!45041418ECCAA960!828.entry" rel="nofollow noreferrer">this page</a>. SQL Server 2005+ only.</p>
| 40,973
|
<p>On occasion, I get the following error in design mode of some user controls in Visual Studio 2008:</p>
<blockquote>
<p>The file 'UserControl.vb' does not
support code parsing or generation
because it is not contained within a
project that supports code.</p>
</blockquote>
<p>It doesn't happen on a consistent basis, but it happens enough to be annoying. Are there any common causes of this error?</p>
<p>And yes, it is in a project that supports code - last I checked, WinForms projects typically have code in them!</p>
|
<p>It is a bug in VS. It happens in VS2005 as well. </p>
<p>Don't waste your time: close VS, open it again and everything should work fine.</p>
|
<p>I had reverted (through source control) changes to my project file, which removed the file from my solution (specifically the .Designer file). However, I still had the file open in Visual Studio and attempting to show the designer for it caused this error.</p>
<p>I clicked the "Show All Files" button at the top of Solution Explorer, found the files that weren't included. Right-clicking and selecting "Include in Project" and rebuilding fixed the issue for me.</p>
| 48,245
|
<p>I am playing with Microsoft's TreeView control and I am trying to force a data update of some sorts while editing a node's label, similar to UpdateData for a grid.</p>
<p>Basically, in my editor, I have a Save button and this TreeView control: what I want is when I am editing a node's label in the TreeView, if I click on the Save button I want to be able to commit the node's label I was editing.</p>
|
<p><code>volatile</code> is needed if you are reading from a spot in memory that, say, a completely separate process/device/whatever may write to.</p>
<p>I used to work with dual-port ram in a multiprocessor system in straight C. We used a hardware managed 16 bit value as a semaphore to know when the other guy was done. Essentially we did this:</p>
<pre><code>void waitForSemaphore()
{
volatile uint16_t* semPtr = WELL_KNOWN_SEM_ADDR;/*well known address to my semaphore*/
while ((*semPtr) != IS_OK_FOR_ME_TO_PROCEED);
}
</code></pre>
<p>Without <code>volatile</code>, the optimizer sees the loop as useless (The guy never sets the value! He's nuts, get rid of that code!) and my code would proceed without having acquired the semaphore, causing problems later on.</p>
|
<p>One use I should remind you is, in the signal handler function, if you want to access/modify a global variable (for example, mark it as exit = true) you have to declare that variable as 'volatile'.</p>
| 9,816
|
<p>How do you go about checking that an IIS website is successfully using Kerberos and not falling back on NTLM?</p>
|
<p>One way I found to test in code that you are using Kerberos is that that the HTTP_AUTHORIZATION header for NTLM always starts with the following:</p>
<pre><code>Negotiate TlRMTVNTUA
</code></pre>
<p>If the header doesn't start with text then the browser is authenticating using Kerberos.</p>
|
<p>Well, Negotiate can also be Kerberos, because it is a wrapper over Kerberos and NTLM. Like other guys said, Wireshark (or Network Monitor) and Security event log will not cheat you.</p>
| 40,849
|
<p>This web page <a href="http://www.w3schools.com/ASP/prop_sessionid.asp" rel="noreferrer">http://www.w3schools.com/ASP/prop_sessionid.asp</a> states that a session ID is generated on the ServerSide.</p>
<p>If this is the case, then how does a server know it's still the same client on the 2nd request response cycle? </p>
<p>Surely the SessionId would be generated on the ClientSide so that the client would be sure of passing the same value to the server?</p>
|
<p>The SessionID is generated Server Side, but is stored on the Client within a Cookie. Then everytime the client makes a request to the server the SessionID is used to authenticate the existing session for the client.</p>
|
<p>The server will generate a session id if none exists. But once it has been generated, the client can pass that id back to the server. If the client modifies that id, you would likely get an error from the server, and a new id generated.</p>
| 28,946
|
<p>How to print line numbers to the log. Say when outputting some information to the log, I also want to print the line number where that output is in the source code. As we can see in the stack trace, it displays the line number where the exception has occurred. Stack trace is available on the exception object.</p>
<p>Other alternative could be like manually including the line number when printing to the log. Is there any other way?</p>
|
<p>From <a href="https://web.archive.org/web/20100818065334/http://blog.taragana.com:80/index.php/archive/core-java-how-to-get-java-source-code-line-number-file-name-in-code/" rel="noreferrer">Angsuman Chakraborty</a> (archived) :</p>
<pre><code>/** Get the current line number.
* @return int - Current line number.
*/
public static int getLineNumber() {
return Thread.currentThread().getStackTrace()[2].getLineNumber();
}
</code></pre>
|
<p>My way it works for me</p>
<pre><code>String str = "select os.name from os where os.idos="+nameid; try {
PreparedStatement stmt = conn.prepareStatement(str);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
a = rs.getString("os.n1ame");//<<<----Here is the ERROR
}
stmt.close();
} catch (SQLException e) {
System.out.println("error line : " + e.getStackTrace()[2].getLineNumber());
return a;
}
</code></pre>
| 14,031
|
<p>What happen when SQL Server 2005 happen to reach the maximum for an IDENTITY column? Does it start from the beginning and start refilling the gap? </p>
<p>What is the behavior of SQL Server 2005 when it happen?</p>
|
<p><strong>You will get an overflow error when the maximum value is reached</strong>. If you use the bigint datatype with a maximum value of <code>9,223,372,036,854,775,807</code> this will most likely never be the case. </p>
<p>The error message you will get, will look like this:</p>
<pre><code>Msg 220, Level 16, State 2, Line 10
Arithmetic overflow error for data type tinyint, value = 256.
</code></pre>
<p><a href="http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=4038424&SiteID=1&pageid=0" rel="noreferrer">(Source)</a></p>
<p>As far as I know MS SQL provides no functionality to fill the identity gaps, so you will either have to do this by yourself or change the datatype of the identity column.</p>
<p>In addition to this you can set the start value to the smallest negative number, to get an even bigger range of values to use.</p>
<p><a href="http://mssqlserver.wordpress.com/2006/12/01/what-happens-when-my-integer-identity-runs-out-of-scope/" rel="noreferrer">Here is a good blog post about this topic</a>.</p>
|
<p>If the identity column is an Integer, then your max is 2,147,483,647. You will get an overflow error if you exceed it. </p>
<p>If you think this is a risk, just use the BIGINT datatype, which gives you up to 9,223,372,036,854,775,807. Can't imagine a database table with that many rows.</p>
<p>Further discussion <a href="http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=4038424&SiteID=1&pageid=0" rel="nofollow noreferrer">here</a>. (Same link as xsl mentioned).</p>
| 32,787
|
<p>I'm confused by the discussion and advancement both of a new version of HTML and a new version of XHTML. Are they competitors? If so, what is likeliest to be the adopted future of the web? If not, what is the differing non-competing purpose for each?</p>
<p>Are we due to have a BluRay/HDVD battle here? Is there ultimately any clear decision? I fear a future where browsers pick and choose among the easiest and/or flashiest features of each to implement, leaving web developers trying to sort out the lowest common denominator for any new web app.</p>
|
<p>HTML 5 is meant for web applications whereas XHTML2 is meant for documents. From the <a href="http://www.w3.org/TR/html5/introduction.html#relationship0" rel="nofollow noreferrer">HTML 5 working draft</a>:</p>
<blockquote>
<p>XHTML2 defines a new HTML vocabulary with better features for hyperlinks, multimedia content, annotating document edits, rich metadata, declarative interactive forms, and describing the semantics of human literary works such as poems and scientific papers.</p>
<p>However, it lacks elements to express the semantics of many of the non-document types of content often seen on the Web. For instance, forum sites, auction sites, search engines, online shops, and the like, do not fit the document metaphor well, and are not covered by XHTML2.</p>
<p>[HTML5] aims to extend HTML so that it is also suitable in these contexts.</p>
<p>XHTML2 and [HTML5] use different namespaces and therefore can both be implemented in the same XML processor.</p>
</blockquote>
|
<p>From what I was able to find in a quick google search, I would suggest that these are indeed competing standards. Both are attempting to advance web technology but are following different paths to do so. </p>
<p>For a pretty thorough treatment of the matter you might look at these two links:</p>
<p><a href="http://xhtml.com/en/future/x-html-5-versus-xhtml-2/" rel="nofollow noreferrer"><a href="http://xhtml.com/en/future/x-html-5-versus-xhtml-2/" rel="nofollow noreferrer">http://xhtml.com/en/future/x-html-5-versus-xhtml-2/</a></a></p>
<p><a href="http://www.cmswire.com/cms/industry-news/setting-the-standards-html-5-vs-xhtml-2-002032.php" rel="nofollow noreferrer"><a href="http://www.cmswire.com/cms/industry-news/setting-the-standards-html-5-vs-xhtml-2-002032.php" rel="nofollow noreferrer">http://www.cmswire.com/cms/industry-news/setting-the-standards-html-5-vs-xhtml-2-002032.php</a></a></p>
| 17,484
|
<p>I have some data of the form</p>
<pre><code>Key ID Link
1 MASTER 123
2 AA 123
3 AA 123
4 BB 123
5 MASTER 456
6 CC 456
</code></pre>
<p>I would like to be able to select in the same select all linked items matching the selection criteria, plus the linked master. For example, if I have an ID of 'AA', I want the rows with ID = 'AA' to be returned, plus the row with ID = 'MASTER' and a link of 123:</p>
<pre><code>1 MASTER 123
2 AA 123
3 AA 123
</code></pre>
<p>I'm using Oracle 10.2g, so if any special Oracle syntax will make this easier, then that would be ok.</p>
|
<p>Here's one method.</p>
<pre><code>SELECT DISTINCT key, id, link
FROM the_table
START WITH id = 'AA'
CONNECT BY id = 'MASTER' and link = PRIOR link and 'AA' = PRIOR ID
</code></pre>
|
<p>SELECT * FROM table_name WHERE ID=your_id UNION ALL SELECT * FROM table_name WHERE ID='MASTER' AND link = (SELECT link FROM table_name WHERE ID=your_id)</p>
<p>That should answer to the question I understood ;)</p>
| 38,739
|
<p><a href="https://rads.stackoverflow.com/amzn/click/com/020161622X" rel="noreferrer" rel="nofollow noreferrer">The Pragmatic Programmer</a> advocates the use of code generators.
Do you create code generators on your projects? If yes, what do you use them for?</p>
|
<p>Code generators if used widely without correct argumentation make code less understandable and decrease maintainability (the same with dynamic SQL by the way). Personally I'm using it with some of ORM tools, because their usage here mostly obvious and sometimes for things like searcher-parser algorithms and grammatic analyzers which are not designed to be maintained "by hands" lately. Cheers.</p>
|
<p>Yes I've had to maintain a few. CORBA or some other object communication style of interface is probably the general thing that I think of first. You have object definitions that are provided to you by the interface you are going to talk over but you still have to build those objects up in code. Building and running a code generator is a fairly routine way of doing that. This can become a fairly lengthy compile just to support some legacy communication channel, and since there is a large tendency to put wrappers around CORBA to make it simpler, well things just get worse.</p>
<p>In general if you have a large amount of structures, or just rapidly changing structures that you need to use, but you can't handle the performance hit of building objects through metadata, then your into writing a code generator.</p>
| 13,837
|
<p>I want to have a text box that the user can type in that shows an Ajax-populated list of my model's names, and then when the user selects one I want the HTML to save the model's ID, and use that when the form is submitted.</p>
<p>I've been poking at the auto_complete plugin that got excised in Rails 2, but it seems to have no inkling that this might be useful. There's a <a href="http://railscasts.com/episodes/102-auto-complete-association" rel="nofollow noreferrer">Railscast episode</a> that covers using that plugin, but it doesn't touch on this topic. The comments <a href="http://railscasts.com/episodes/102-auto-complete-association#comment_37039" rel="nofollow noreferrer">point out that it could be an issue</a>, and <a href="http://model-ac.rubyforge.org/" rel="nofollow noreferrer">point to <code>model_auto_completer</code> as a possible solution</a>, which seems to work if the viewed items are simple strings, but the inserted text includes lots of junk spaces if (as I would like to do) you include a picture into the list items, <a href="http://model-ac.rubyforge.org/classes/ModelAutoCompleterHelper.html#M000003" rel="nofollow noreferrer">despite what the documentation says</a>.</p>
<p>I could probably hack <code>model_auto_completer</code> into shape, and I may still end up doing so, but I am eager to find out if there are better options out there.</p>
|
<p>I rolled my own. The process is a little convoluted, but...</p>
<p>I just made a text_field on the form with an observer. When you start typing into the text field, the observer sends the search string and the controller returns a list of objects (maximum of 10).</p>
<p>The objects are then sent to render via a partial which fills out the dynamic autocomplete search results. The partial actually populates link_to_remote lines that post back to the controller again. The link_to_remote sends the id of the user selection and then some RJS cleans up the search, fills in the name in the text field, and then places the selected id into a hidden form field.</p>
<p>Phew... I couldn't find a plugin to do this at the time, so I rolled my own, I hope all that makes sense.</p>
|
<p>I rolled my own. The process is a little convoluted, but...</p>
<p>I just made a text_field on the form with an observer. When you start typing into the text field, the observer sends the search string and the controller returns a list of objects (maximum of 10).</p>
<p>The objects are then sent to render via a partial which fills out the dynamic autocomplete search results. The partial actually populates link_to_remote lines that post back to the controller again. The link_to_remote sends the id of the user selection and then some RJS cleans up the search, fills in the name in the text field, and then places the selected id into a hidden form field.</p>
<p>Phew... I couldn't find a plugin to do this at the time, so I rolled my own, I hope all that makes sense.</p>
| 10,674
|
<p>I've got what I think is a simple question. I've seen examples both ways. The question is - "why can't I place my annotations on the field?". Let me give you an example....</p>
<pre><code>@Entity
@Table(name="widget")
public class Widget {
private Integer id;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public Integer getId() { return this.id; }
public Integer setId(Integer Id) { this.id = id;}
}
</code></pre>
<p>The above code works fine (assuming there's not a typo in there). When the annotation is placed on the getter of the property everything is perfect.</p>
<p>However, that seems awkward to me. In my mind it's cleaner to place the annotation on the field, like so --</p>
<pre><code>@Entity
@Table(name="widget")
public class Widget {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
public Integer getId() { return this.id; }
public Integer setId(Integer Id) { this.id = id;}
}
</code></pre>
<p>I've seen examples of both ways. However, when I run this second example I get the following...</p>
<pre>
java.lang.NullPointerException
at com.widget.util.hibernate.HibernateSessionFactory$ThreadLocalSession.initialValue(HibernateSessionFactory.java:25)
at com.widget.util.hibernate.HibernateSessionFactory$ThreadLocalSession.initialValue(HibernateSessionFactory.java:1)
at java.lang.ThreadLocal$ThreadLocalMap.getAfterMiss(Unknown Source)
at java.lang.ThreadLocal$ThreadLocalMap.get(Unknown Source)
at java.lang.ThreadLocal$ThreadLocalMap.access$000(Unknown Source)
at java.lang.ThreadLocal.get(Unknown Source)
at com.widget.util.hibernate.HibernateSessionFactory.get(HibernateSessionFactory.java:33)
at com.widget.db.dao.AbstractDao.(AbstractDao.java:12)
at com.widget.db.dao.WidgetDao.(WidgetDao.java:9)
at com.widget.db.dao.test.WidgetDaoTest.findById(WidgetDaoTest.java:17)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
...
</pre>
<p>Here's the skeleton of <code>HibernateSessionFactory</code> (line 25 is marked) ....</p>
<pre><code>protected Session initialValue() {
SessionFactory sessionFactory = null;
try {
Configuration cfg = new AnnotationConfiguration().configure();
String url = System.getProperty("jdbc.url");
if (url != null) {
cfg.setProperty("hibernate.connection.url", url);
}
sessionFactory = cfg.buildSessionFactory();
}
catch (Exception e) {
}
Session session = sessionFactory.openSession(); // LINE 25
return session;
}
</code></pre>
<p>Anyone have an idea what's going on here?</p>
|
<p>From a performance and design perspective, using annotations on getters is a better idea than member variables, because the getter setters are called using reflection if placed on the field, than a method. Also if you plan to use validation and other features of hibernate, you'll have all the annotations at one place, rather than scattering them all over the place.</p>
<p>My recommendation go with methods not member variables.</p>
<p>From the documentation</p>
<blockquote>
<p>Depending on whether you annotate fields or methods, the access type used by Hibernate will be field or property. The EJB3 spec requires that you declare annotations on the element type that will be accessed, i.e. the getter method if you use property access, the field if you use field access. Mixing EJB3 annotations in both fields and methods should be avoided. Hibernate will guess the access type from the position of @Id or @EmbeddedId.</p>
</blockquote>
|
<p>Does it work if you do the following:</p>
<pre><code>@Entity
@Table(name="widget")
public class Widget {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
public Integer getId() { return this.id; }
public Integer setId(Integer Id) { this.id = id;}
}
</code></pre>
| 39,352
|
<p>For the last couple of months I have been writing an intranet site for my college with lots of reports for staff about students. It is all going well but once a week (ish) I am having to go to IT get them to log into IIS stop the application pool, clear out the website folder, clear out the temporary asp.NET cache and replace the website with the new one. Not a big job but I would prefer to do it myself as and when I want.</p>
<p>I don't know much about ASP.NET deployment and IIS is there a way for me to update the website myself (keeping the system live if possible)? Last time I looked at this I think I found the files were locked within the website directory.</p>
<p>What do the different publish options achieve?</p>
|
<p>Why are you stopping the app pool and clearing the temp files? It works just fine of you overwrite the files in the website itself.</p>
<p>The only thing I do is go into the bin directory and clear out all the randomly named .dll files.</p>
<p>Visual Studio also has it's own deployment option, which you can just give a UNC path and it will delete the old files and copy up the new version of the site. It even throws up an app_offline.html for you.</p>
|
<p>I always update my website during scheduled maintenance, usually outside work hours. So, evening or weekend are the best time to shutdown for a short laps of time the services, and update the website. Schedule that maintenance so everyone know their will be a downtime.</p>
| 19,400
|
<p>Is there a way that I can get a full crash dump when my application crashes suddenly? </p>
<p>The problem is that I suspect that it's due to unmanaged code that kills the .net framework itself, and because of that, unless there's a debugger attached to the application at the moment of the crash, the application doesn't even gets a chance to handle the crash.</p>
<p>I can't attach a debugger and wait, because the crash happens randomly and we have many installed locations, so I'm wondering if it's possible to do this without attaching a debugger.</p>
<p>Edit: I'm aware of Microsoft Debugging SDK, and I also just found out about DebugDiag. I'd like to do this without having to attach to the application each time, as it's usually in the middle of a sale and I don't have time to attach the debugger and explore the stack trace. DebugDiag does seem to let me setup a rule for this, but it seems to only work on already running processes, rather than waiting for some process to launch.</p>
|
<p>You can use <a href="http://support.microsoft.com/default.aspx/kb/286350" rel="nofollow noreferrer">adplus -crash</a> or <a href="http://support.microsoft.com/kb/241215" rel="nofollow noreferrer">userdump.exe</a>.</p>
|
<p>debugdiag is fully <a href="http://blogs.iis.net/sukesh/archive/2006/06/02/ddintro.aspx" rel="nofollow noreferrer">scriptable</a>. When I was having problems like this, we would have it scan for certain process names, and attach automatically. </p>
| 33,229
|
<p>I am having problems submitting forms which contain UTF-8 strings with Ajax. I am developing a <a href="http://en.wikipedia.org/wiki/Apache_Struts" rel="noreferrer">Struts</a> web application which runs in a <a href="http://en.wikipedia.org/wiki/Apache_Tomcat" rel="noreferrer">Tomcat</a> server. This is the environment I set up to work with UTF-8:</p>
<ul>
<li><p>I have added the attributes <code>URIEncoding="UTF-8" useBodyEncodingForURI="true"</code> into the <code>Connector</code> tag to Tomcat's <code>conf/server.xml</code> file.</p></li>
<li><p>I have a <code>utf-8_general_ci</code> database</p></li>
<li><p>I am using the next filter to ensure my request and responses are encoded in UTF-8</p>
<pre><code>package filters;
import java.io.IOException;
import javax.servlet.*;
public class UTF8Filter implements Filter {
public void destroy() {}
public void doFilter(ServletRequest request,ServletResponse response, FilterChain chain)
throws IOException, ServletException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
}
}
</code></pre></li>
<li><p>I use this filter in WEB-INF/web.xml</p></li>
<li><p>I am using the next code for my JSON responses:</p>
<pre><code>public static void populateWithJSON(HttpServletResponse response,JSONObject json)
{
String CONTENT_TYPE="text/x-json;charset=UTF-8";
response.setContentType(CONTENT_TYPE);
response.setHeader("Cache-Control", "no-cache");
try {
response.getWriter().write(json.toString());
} catch (IOException e) {
throw new ApplicationException("Application Exception raised in RetrievedStories", e);
}
}
</code></pre></li>
</ul>
<p>Everything seems to work fine (content coming from the database is displayed properly, and I am able to submit forms which are stored in UTF-8 in the database). The problem is that I am <strong>not able to submit forms with Ajax</strong>. I use jQuery, and I thought the problem was the lack of contentType field in the Ajax request. But I was wrong. I have a really simple form to submit comments which contains of an id and a body. The body field can be in different languages such as Spanish, German, or whatever.</p>
<p>If I submit my form with body textarea containing <code>contraseña</code>, <a href="http://en.wikipedia.org/wiki/Firebug_%28software%29" rel="noreferrer">Firebug</a> shows me:</p>
<blockquote>
<h3>Request Headers</h3>
<ul>
<li><strong><em>Host</em></strong> localhost:8080</li>
<li><strong><em>Accept-Charset</em></strong> ISO-8859-1, utf-8;q=0.7;*q=0.7</li>
<li><strong><em>Content-Type</em></strong> application/x-www-form-urlencoded; charset UTF-8</li>
</ul>
</blockquote>
<p>If I execute <em>Copy Location with parameters</em> in Firebug, the encoding seems already wrong:</p>
<pre><code>http://localhost:8080/Cerepedia/corporate/postStoryComment.do?&body=contrase%C3%B1a&id=88
</code></pre>
<p>This is my jQuery code:</p>
<pre><code>function addComment() {
var comment_body = $("#postCommentForm textarea").val();
var item_id = $("#postCommentForm input:hidden").val();
var url = rooturl+"corporate/postStoryComment.do?";
$.post(url, { id: item_id, body: comment_body } ,
function(data){
/* Do stuff with the answer */
}, "json"); }
</code></pre>
<p>A submission of a form with jQuery is causing the next error server side (note I am using <a href="http://en.wikipedia.org/wiki/Hibernate_%28Java%29" rel="noreferrer">Hibernate</a>).</p>
<pre><code>javax.servlet.ServletException: org.hibernate.exception.GenericJDBCException: Could not execute JDBC batch update
at org.apache.struts.action.RequestProcessor.processException(RequestProcessor.java:520)
at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:427)
at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:228)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913)
at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:462)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.cerebra.cerepedia.security.AuthorizationFilter.doFilter(AuthorizationFilter.java:78)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.cerebra.cerepedia.hibernate.HibernateSessionRequestFilter.doFilter(HibernateSessionRequestFilter.java:30)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at filters.UTF8Filter.doFilter(UTF8Filter.java:14)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:581)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Unknown Source)
Caused by: org.hibernate.exception.GenericJDBCException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103)
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:249)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:235)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:139)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
at com.cerebra.cerepedia.item.dao.ItemDAOHibernate.addComment(ItemDAOHibernate.java:505)
at com.cerebra.cerepedia.item.ItemManagerPOJOImpl.addComment(ItemManagerPOJOImpl.java:164)
at com.cerebra.cerepedia.struts.item.ItemAction.addComment(ItemAction.java:126)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:269)
at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:170)
at org.apache.struts.actions.MappingDispatchAction.execute(MappingDispatchAction.java:166)
at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:425)
... 26 more
Caused by: java.sql.BatchUpdateException: Incorrect string value: '\xF1a' for column 'body' at row 1
at com.mysql.jdbc.ServerPreparedStatement.executeBatch(ServerPreparedStatement.java:657)
at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeBatch(NewProxyPreparedStatement.java:1723)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:242)
... 44 more
26-ago-2008 19:54:48 org.apache.catalina.core.StandardWrapperValve invoke
GRAVE: Servlet.service() para servlet action lanzó excepción
java.sql.BatchUpdateException: Incorrect string value: '\xF1a' for column 'body' at row 1
at com.mysql.jdbc.ServerPreparedStatement.executeBatch(ServerPreparedStatement.java:657)
at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeBatch(NewProxyPreparedStatement.java:1723)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:242)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:235)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:139)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
at com.cerebra.cerepedia.item.dao.ItemDAOHibernate.addComment(ItemDAOHibernate.java:505)
at com.cerebra.cerepedia.item.ItemManagerPOJOImpl.addComment(ItemManagerPOJOImpl.java:164)
at com.cerebra.cerepedia.struts.item.ItemAction.addComment(ItemAction.java:126)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:269)
at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:170)
at org.apache.struts.actions.MappingDispatchAction.execute(MappingDispatchAction.java:166)
at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:425)
at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:228)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913)
at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:462)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.cerebra.cerepedia.security.AuthorizationFilter.doFilter(AuthorizationFilter.java:78)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.cerebra.cerepedia.hibernate.HibernateSessionRequestFilter.doFilter(HibernateSessionRequestFilter.java:30)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at filters.UTF8Filter.doFilter(UTF8Filter.java:14)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:581)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Unknown Source)
javax.servlet.ServletException: java.lang.NumberFormatException: null
at org.apache.struts.action.RequestProcessor.processException(RequestProcessor.java:520)
at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:427)
at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:228)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913)
at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:449)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:690)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.cerebra.cerepedia.security.AuthorizationFilter.doFilter(AuthorizationFilter.java:78)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.cerebra.cerepedia.hibernate.HibernateSessionRequestFilter.doFilter(HibernateSessionRequestFilter.java:30)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at filters.UTF8Filter.doFilter(UTF8Filter.java:14)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:581)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NumberFormatException: null
at java.lang.Long.parseLong(Unknown Source)
at java.lang.Long.valueOf(Unknown Source)
at com.cerebra.cerepedia.struts.item.ItemAction.addComment(ItemAction.java:120)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:269)
at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:170)
at org.apache.struts.actions.MappingDispatchAction.execute(MappingDispatchAction.java:166)
at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:425)
... 26 more
26-ago-2008 20:13:25 org.apache.catalina.core.StandardWrapperValve invoke
GRAVE: Servlet.service() para servlet action lanzó excepción
java.lang.NumberFormatException: null
at java.lang.Long.parseLong(Unknown Source)
at java.lang.Long.valueOf(Unknown Source)
at com.cerebra.cerepedia.struts.item.ItemAction.addComment(ItemAction.java:120)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:269)
at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:170)
at org.apache.struts.actions.MappingDispatchAction.execute(MappingDispatchAction.java:166)
at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:425)
at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:228)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913)
at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:449)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:690)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.cerebra.cerepedia.security.AuthorizationFilter.doFilter(AuthorizationFilter.java:78)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.cerebra.cerepedia.hibernate.HibernateSessionRequestFilter.doFilter(HibernateSessionRequestFilter.java:30)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at filters.UTF8Filter.doFilter(UTF8Filter.java:14)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:581)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Unknown Source)
</code></pre>
|
<p>have you tried adding the following before the call :</p>
<pre><code>$.ajaxSetup({
scriptCharset: "utf-8" ,
contentType: "application/json; charset=utf-8"
});
</code></pre>
<p>The options are explained <a href="http://docs.jquery.com/Ajax/jQuery.ajax#toptions" rel="noreferrer">here</a>.</p>
<p>contentType : When sending data to the server, use this content-type. Default is "application/x-www-form-urlencoded", which is fine for most cases.</p>
<p>scriptCharset : Only for requests with 'jsonp' or 'script' dataType and GET type. Forces the request to be interpreted as a certain charset. Only needed for charset differences between the remote and local content.</p>
|
<p>I see this problem a lot.
The meta doesn't work always in your PHP data operations, so just type this at the beginning:</p>
<pre><code><?php header('Content-type: text/html; charset=utf-8'); ?>
</code></pre>
| 4,952
|
<p>I find the .Net FileSystemWatcher class really handy for writing utilities that automatically come to life when files show up in their watched folders. Is there any equivalent to this functionality in the *nix world that would allow me to watch a folder (and possibly all of its subdirectories)?</p>
<p><strong>Edit:</strong> Preferably this will be something that doesn't require kernel patches.</p>
|
<p>That would be <a href="http://www.gnome.org/%7Eveillard/gamin/" rel="noreferrer">Gamin the File Alteration Monitor</a> or <a href="http://en.wikipedia.org/wiki/Inotify" rel="noreferrer">Inotify</a>.</p>
<p>Edit: Mono does have Gamin bindings - in fact, its implementation of FileSystemWatcher uses Gamin. <a href="https://www.mono-project.com/docs/faq/technical/#what-are-the-issues-with-filesystemwatcher" rel="noreferrer">https://www.mono-project.com/docs/faq/technical/#what-are-the-issues-with-filesystemwatcher</a>.</p>
<blockquote>
<p><strong>What are the issues with FileSystemWatcher?</strong></p>
<p>The Mono implementation of FileSystemWatcher has a number of backends, the most optimal one, the one with fewer dependencies is the inotify-backend (available in Mono 1.1.17 and newer versions).</p>
<p>With this backend the kernel provides Mono with updates on any changes to files on the file system but it requires an inotify-enabled kernel, which only newer Linux distributions ship.</p>
<p>In older Linux systems, you must have installed FAM or Gamin (it will work with either one). You might need the -devel packets installed.</p>
<p>For the *BSD family, there’s a Kqueue based implementation that will be used when detected at runtime.</p>
<p>If none of the above work, Mono falls back to polling the directories for changes, which far from optimal.</p>
</blockquote>
|
<p>Yes, dnotify and <a href="http://www-128.ibm.com/developerworks/linux/library/l-inotify.html" rel="nofollow noreferrer">inotify</a>.</p>
<p>I don't know if Mono has these wrapped, but it would be worth checking.</p>
| 41,991
|
<p><a href="https://i.stack.imgur.com/WwWuN.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/WwWuN.jpg" alt="3D printing problem stringing"></a></p>
<p>So these past few days I have been 3D printing again with my Ender 3 with PETG and 0.4 mm nozzle and while I have been using the same setting as usual I am seeing an unusual amount of stringing between the prints. Does anyone know why? If you're wondering regarding the settings here they are, I'm using Cura for slicing, see options:</p>
<p><a href="https://i.stack.imgur.com/ialqzm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ialqzm.png" alt="Quality"></a> <a href="https://i.stack.imgur.com/Tc2Blm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Tc2Blm.png" alt="Shell"></a>
<a href="https://i.stack.imgur.com/3SpNZm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/3SpNZm.png" alt="Temperature"></a> <a href="https://i.stack.imgur.com/6H1M6m.png" rel="noreferrer"><img src="https://i.stack.imgur.com/6H1M6m.png" alt="Retraction"></a>
<a href="https://i.stack.imgur.com/0KMAQm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/0KMAQm.png" alt="Speed"></a> <a href="https://i.stack.imgur.com/xWib6m.png" rel="noreferrer"><img src="https://i.stack.imgur.com/xWib6m.png" alt="Cooling"></a></p>
|
<p>The travel speed of 160 mm/s is a big red flag. PETG is not tolerant of a hot nozzle moving over it at high speeds, especially unretracted (combing). The nozzle will drag material in a stuttering pattern, every so often, marring the surface and pulling what it dug up into strings.</p>
<p>Lower the travel speed to the same as the print speed, and then experiment with whether you can increase it without problems. I would not try going over 80 mm/s and probably not even over 60.</p>
<p>For what it's worth, this <em>sounds like</em> softened/molten PETG is a non-newtonian fluid, where at low stress (slow moving nozzle pushing/pulling) it deforms gracefully, but at high stress (fast moving nozzle) it strongly resists deformation and has a discontinuous breaking point. A quick Googling turned up this article, <a href="https://link.springer.com/article/10.1007/s10924-019-01544-6" rel="nofollow noreferrer">Thermal, Rheological and Mechanical Properties of PETG/rPETG Blends</a>, which might explain what's happening.</p>
|
<p>Petg it stringy material, all I can do is keep it dry to prevent blob. but I live in hot country with high moisture so I decide to keep filament in heat dryer box while print. It help a lot. </p>
| 1,615
|
<p>About two days ago, I started seeing that my hotend was heating up erratically. I first noticed this while printing a part in PETG and the temp jumped to 260 °C. I shut down the printer at that time and first started checking the hardware. I noticed that the E3D V6 thermistor had been tightened too much. I disassembled the entire hotend, cleaned everything and then reassembled everything. I thought to retune the hotend and when I tried tuning it at 240 °C. </p>
<p>This is where the strange behavior occurs. The hotend steadily climbed up till about 200 °C. After that it just went nuts. I started seeing unreal temps such as 646 °C and such. At this point I thought the MEGA might be at fault. I replaced it and the hotend (an E3D V6 clone). This had the screw on glass thermistor. Again the same erratic behavior and unreal temp readings. </p>
<p>What could be wrong here? What am I missing? Can this be the heater cartridge? </p>
|
<p>One of the thermistor wires had come loose from the crimp ferrules. I re-crimped it and it works fine now. </p>
|
<p>This can come from several sources:</p>
<h1>Hardware</h1>
<p>The thermistor or its connections might be damaged, and the fault is only observable when the hotend is hot or moved to a certain area. Start by checking the wiring! You may be able to repair a bad connection easily, but depending what was broken, you may need to replace something. In some cases squishing a thermistor cartridge too much can destroy the internals, so a replacement is needed.</p>
<p>A mainboard failure is more likely to just show a static temperature, and a heater failure would show as maybe not getting past a certain point.</p>
<h1>Firmware</h1>
<p>If it had not worked before or you changed the firmware, the firmware should also be a suspect. The firmware can 'fail' when using the wrong thermistor type/table which can result in a very big offset or bad slope, resulting in wrong or unaccurate readings.</p>
| 844
|
<p>I have a framework that loads a lot of child collections from a non-database source. I recently got a use case where the resource is on network drives, and it is taking forever to get the collections loaded. I still need to support the eager loading scenario, but I now need to add lazy loading.</p>
<p>I had the solution to this bookmarked, but now I can't find that link. Google hasn't returned any usable links so far. The first reaction is to just add a Boolean parameter to the constructor. I know that this is a bad "code smell" and I remember the answer being something different.</p>
<p>Can anybody point me to a resource on how to solve this problem?</p>
<p>MORE INFO:</p>
<p>The collections are vertical, not horizontal. That's why loading in the background will not work in this specific case. That data is stored in a hierarchical structure similar to folders. I've seen some structures go up to 10 levels deep.</p>
|
<p>The solution turned out to be simpler than I thought. I just mixed the modes at different levels. By this I mean that I used eager loading at the topmost horizontal collections, and converted anything else below this to lazy loading.</p>
<p>It works really well. Now the UI, that uses this framework, is very responsive.</p>
|
<p>Yes, a boolean in your constructor would definitely be a bad code smell. However, I would also say that changing your class to support lazy loading is a code smell as well because it violates some of the basic principles of encapsulation (i.e. should your class know or care whether resources are located on network drives or not?).</p>
<p>You should not change your class. Instead, change the code that uses your class so that it retrives data in a background thread instead.</p>
| 40,856
|
<p>I am building a small wpf app in C#. When a button gets clicked a third
party dll function constructs a tree like object. This object is bound
to a treeview. This works fine but takes a bit of time to load. As the
dll function constructs the object it prints progress info to the
console. I want to redirect this into a TextBlock so that the user
gets to see the progress messages. </p>
<p>My window ctor looks like this: </p>
<pre>
InitializeComponent();
StringRedir s = new StringRedir(ref ProgressTextBlock);
Console.SetOut(s);
Console.SetError(s);
this.DataContext = s;
</pre>
<p>xaml: <pre>
<code><</code>TextBlock Text="{Binding Path=Text}" Width="244"
x:Name="ProgressTextBlock" TextWrapping="Wrap" />
<code><</code>TreeView >...<code><</code>/TreeView>
</pre></p>
<p>The StringRedir class is shown below. The problem is the TextBlock for
some reason does not get updated with the messages until the TreeView
gets loaded. Stepping through I see the Text property being updated
but the TextBlock is not getting refreshed. I added a MessageBox.Show
() at the point where Text gets updated and this seems to cause the
window to refresh each time and I am able to see each message. So I
guess I need some way to explicitly refresh the screen...but this
doesnt make sense I thought the databinding would cause a visual
refresh when the property changed. What am I missing here? How do I
get it to refresh? Any advice is appreciated! </p>
<pre><code>public class StringRedir : StringWriter , INotifyPropertyChanged
{
private string text;
private TextBlock local;
public string Text {
get{ return text;}
set{
text = text + value;
OnPropertyChanged("Text");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
public StringRedir(ref TextBlock t)
{
local = t;
Text = "";
}
public override void WriteLine(string x)
{
Text = x +"\n";
//MessageBox.Show("hello");
}
}
</code></pre>
|
<p>You haven't included the code that is loading the data for the <code>TreeView</code>, but I'm guessing it's being done on the UI thread. If so, this will block any UI updates (including changes to the <code>TextBlock</code>) until it has completed.</p>
|
<p>I believe the problem is in the constructor of your StringRedir class. You're passing in ProgessTextBlock, and you're doing this to it:</p>
<pre><code>local.Text = "";
</code></pre>
<p>This is effectively <em>overwriting</em> the previously set value for ProgressTextBlock.Text, which was this:</p>
<pre><code>{Binding Text}
</code></pre>
<p>See what I mean? By explicitly setting a value to the TextBlock's Text property, you've cancelled the binding.</p>
<p>If I'm reading right, it looks like the idea of passing a TextBlock into the StringRedir's ctor is a hangover from before you tried binding directly. I'd ditch that and stick with the binding idea as it's more in the "spirit" of WPF.</p>
| 49,827
|
<p><strong>What mechanisms do you know that prevent your site from being abused by anonymous spammers.</strong></p>
<p>For example, let's say that I have a site where people can vote something. But I <em>don't</em> want someone to spam something all the way to the top. So I found (a) creating an account and only allowed to vote once and (b) CAPTCHA to decrease spam. What other methods do you know and how good do they work?</p>
|
<p>The big thing I've noticed is that whatever you do, you want your system to be unique. You want an attacker to have to tailor their automation program for your specific site, rather than just throw a pre-existing script at it that will work almost anywhere. It doesn't even have to be cryptographically secure; it just has to make your site a little different from the norm.</p>
<p>This doesn't mean you can't or shouldn't use something like a pre-built captcha widget. Absolutely do use one of those as a staring point! It just means you have to customize it somewhere so that something extra happens that is outside the norm and will break any pre-existing script that could normally defeat it.</p>
<p>If your site gets big enough that you have attackers targeting it specifically, then your simple little customization probably won't hold up anymore and you might have do something a little more special and think about real cryptography and all that. But that's one of those things that's a "good" problem to have.</p>
|
<p>stackoverflow has a few features that help with this; I think the single most useful step you can take is disabling the ability of anonymous users and new accounts to vote. This way, no one can sign up for hundreds of accounts and use their one vote to overpower other users. I'd say requiring a few posts or membership for a certain period of time are both decent options.</p>
<p>Some would say you could allow one vote per IP address to help address this, but I've played plenty of games where malicious users with a nigh-infinite number of proxies defied IP address-based security. It's a deterrent, but a savvy user will get around it easily.</p>
| 6,347
|
<p>I have a pretty standard django app, and am wondering how to set the url routing so that I don't have to explicitly map each url to a view. </p>
<p>For example, let's say that I have the following views: <code>Project, Links, Profile, Contact</code>. I'd rather not have my <code>urlpatterns</code> look like this:</p>
<pre><code>(r'^Project/$', 'mysite.app.views.project'),
(r'^Links/$', 'mysite.app.views.links'),
(r'^Profile/$', 'mysite.app.views.profile'),
(r'^Contact/$', 'mysite.app.views.contact'),
</code></pre>
<p>And so on. In <a href="http://www.pylonshq.com" rel="noreferrer">Pylons</a>, it would be as simple as:</p>
<pre><code>map.connect(':controller/:action/:id')
</code></pre>
<p>And it would automatically grab the right controller and function. Is there something similar in Django?</p>
|
<p>In answer to your first question, hopefully, you'll see something in the sys.transmission_queue system view. See
<a href="http://msdn.microsoft.com/en-us/library/ms190336.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms190336.aspx</a> for documentation on that.</p>
<p>If you Google that, you might find some useful troubleshooting resources too.</p>
<p>Dave</p>
|
<p>John,</p>
<p>I've only recently begun looking into the service broker in order to implement asynch messaging between DB instances. I found the following to be quite useful in getting my head around it.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/bb839489(SQL.90).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/bb839489(SQL.90).aspx</a></p>
| 20,300
|
<p>Typically I use <code>E_ALL</code> to see anything that PHP might say about my code to try and improve it.</p>
<p>I just noticed a error constant <code>E_STRICT</code>, but have never used or heard about it, is this a good setting to use for development? The manual says:</p>
<blockquote>
<p>Run-time notices. Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code. </p>
</blockquote>
<p>So I'm wondering if I'm using the best <code>error_reporting</code> level with <code>E_ALL</code> or would that along with <code>E_STRICT</code> be the best? Or is there any other combination I've yet to learn?</p>
|
<p>In PHP 5, the things covered by <code>E_STRICT</code> are not covered by <code>E_ALL</code>, so to get the most information, you need to combine them:</p>
<pre><code> error_reporting(E_ALL | E_STRICT);
</code></pre>
<p>In PHP 5.4, <code>E_STRICT</code> will be included in <code>E_ALL</code>, so you can use just <code>E_ALL</code>.</p>
<p>You can also use</p>
<pre><code>error_reporting(-1);
</code></pre>
<p>which will always enable <em>all</em> errors. Which is more semantically correct as:</p>
<pre><code>error_reporting(~0);
</code></pre>
|
<p>ini_set("display_errors","2");
ERROR_REPORTING(E_ALL);</p>
| 10,047
|
<p>When you execute a SQL query, you have to clean your strings or users can execute malicious SQL on your website.</p>
<p>I usually just have a function escape_string(blah), which:</p>
<ul>
<li>Replaces escapes (<code>\</code>) with double escapes (<code>\\</code>).</li>
<li>Replaces single quotes (<code>'</code>) with an escaped single quote (<code>\'</code>). </li>
</ul>
<p>Is this adequate? Is there a hole in my code? Is there a library which can do this quickly and reliably for me?</p>
<p>I'd like to see graceful solutions in Perl, Java, and PHP.</p>
|
<p>For maximum security, performance, and correctness use prepared statements.
Here's how to do this with lots of examples in different languages, including PHP:</p>
<p><a href="https://stackoverflow.com/questions/1973/what-is-the-best-way-to-avoid-sql-injection-attacks">https://stackoverflow.com/questions/1973/what-is-the-best-way-to-avoid-sql-injection-attacks</a></p>
|
<p>I am not sure if MySQL supports parameterized queries, if so, you should make an effort to go this route. This will ensure the users input can't do anything malicious.</p>
<p>Otherwise some "bad" characters in addition to what you mentioned would be semicolon (;) and comments (-- and /* */).</p>
| 2,478
|
<p>My project is currently using a svn repository which gains several hundred new revisions per day.
The repository resides on a Win2k3-server and is served through Apache/mod_dav_svn. </p>
<p>I now fear that over time the performance will degrade due to too many revisions.<br>
Is this fear reasonable?<br>
We are already planning to upgrade to 1.5, so having thousands of files in one directory will not be a problem in the long term.</p>
<blockquote>
<p>Subversion on stores the delta (differences), between 2 revisions, so this helps saving a LOT of space, specially if you only commit code (text) and no binaries (images and docs).</p>
</blockquote>
<p>Does that mean that in order to check out the revision 10 of the file foo.baz, svn will take revision 1 and then apply the deltas 2-10?</p>
|
<p>What type of repo do you have? FSFS or BDB?</p>
<p>(Let's assume FSFS for now, since that's the default.)</p>
<p>In the case of FSFS, each revision is stored as a diff against the previous. So, you would think that yes, after many revisions, it would be very slow.</p>
<p>However, this isn't the case. FSFS uses what are called "skip deltas" to avoid having to do too many lookups on previous revs.</p>
<p>(So, if you are using an FSFS repo, Brad Wilson's answer is wrong.)</p>
<p>In the case of a BDB repo, the HEAD (latest) revision is full-text, but the earlier revisions are built as a series of diffs against the head. This means the previous revs have to be re-calculated after each commit.</p>
<p>For more info: <a href="http://svn.apache.org/repos/asf/subversion/trunk/notes/skip-deltas" rel="noreferrer">http://svn.apache.org/repos/asf/subversion/trunk/notes/skip-deltas</a></p>
<p>P.S. Our repo is about 20GB, with about 35,000 revisions, and we have not noticed any performance degradation.</p>
|
<p>I am not sure..... I am using SVN with apache on Centos 5.2. Works ok. Revision number was 8230 something like that... And on all client machines Commit was so slow that we had to wait at least 2min for a file that is 1kb. I am talking about 1 file that has no big filesize. </p>
<p>Then I made a new repository. Started from rev. 1. Now works ok. Fast.
used svnadmin create xxxxxx.
did not check if it is FSFS or BDB..... </p>
| 15,541
|
<p>I have a layout similar to this:</p>
<pre><code><div id="..."><img src="..."></div>
</code></pre>
<p>and would like to use a jQuery selector to select the child <code>img</code> inside the <code>div</code> on click.</p>
<p>To get the <code>div</code>, I've got this selector:</p>
<pre><code>$(this)
</code></pre>
<p>How can I get the child <code>img</code> using a selector?</p>
|
<p>The jQuery constructor accepts a 2nd parameter called <a href="http://api.jquery.com/jQuery/#jQuery-selector-context" rel="noreferrer"><code>context</code></a> which can be used to override the context of the selection. </p>
<pre><code>jQuery("img", this);
</code></pre>
<p>Which is the same as using <a href="http://api.jquery.com/find" rel="noreferrer"><code>.find()</code></a> like this:</p>
<pre><code>jQuery(this).find("img");
</code></pre>
<p>If the imgs you desire are <strong>only</strong> direct descendants of the clicked element, you can also use <a href="http://api.jquery.com/children" rel="noreferrer"><code>.children()</code></a>:</p>
<pre><code>jQuery(this).children("img");
</code></pre>
|
<p>You could use</p>
<pre><code> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
$(this).find('img');
</script>
</code></pre>
| 39,439
|
<p>What logging solutions exist for j2me? </p>
<p>I'm specifically interested in easily excluding logging for "release" version, to have a smaller package & memory footprint. </p>
|
<p>If you are using preprocessing and obfuscation with Proguard, then you can have a simple logging class.</p>
<pre><code>public class Log {
public static void debug(final String message) {
//#if !release.build
System.out.println(message);
//#endif
}
}
</code></pre>
<p>Or do logging where ever you need to. Now, if release.build property is set to true, this code will be commented out, that will result in an empty method. Proguard will remove all usages of empty method - In effect release build will have all debug messages removed.</p>
<p>Edit:</p>
<p>Thinking about it on library level (I'm working on mapping J2ME library) I have, probably, found a better solution.</p>
<pre><code>public class Log {
private static boolean showDebug;
public static void debug(final String message) {
if (showDebug) {
System.out.println(message);
}
}
public static void setShowDebug(final boolean show) {
showDebug = show;
}
}
</code></pre>
<p>This way end developer can enable log levels inside library that he/she is interested in. If nothing will be enabled, all logging code will be removed in end product obfuscation. Sweet :)</p>
<p>/JaanusSiim</p>
|
<p>I wrote a bytecode optimizer, and because of the format of class files you can point to the UTF encoding of classname & function which allows you to output logs with MyClass.someFunc() (you can process the signature if you want to get the types) which allows you to do something like the C style debug using <strong>LINE</strong> & <strong>FILE</strong> macros.</p>
| 14,665
|
<p>I'm comparing the results produced when i use the 'Make .exe' compared to when i run the exact same process using the exact same variables though the IDE vb 6 debugger.</p>
<p>I've tried an array of different compiler options but to no avail.</p>
<p>So my question is why would i get a difference between the debugger and the 'Make .exe'?
have you ever come arross something similar and if so did you find a fix?</p>
<p><em>the program takes a large file of counts of cars in a timeperiod and averages them into 15 minute timeperiods for the day over a month for each route.
It elminates certain records depending on if there outside the standard deviation and other statistical algorithms To eliminate values.
its a bit to much code to post unfortunately...</em></p>
|
<p><code>Debug.Assert</code> and <code>Debug.Print</code> Statement are not compiled into the binary. I sometimes use this to detect whether I am in the IDE or a compiled binary:</p>
<pre>
On Error Resume Next
Debug.Print 1/0
If Err=0 then
'Compiled Binary
else
'in the IDE
End if
</pre>
<p>Be careful with statements like this:</p>
<pre><code>Debug.Assert( DoSomeThingImportend() )
</code></pre>
<p>In the compiled version this statement will not be executed.</p>
|
<p>I've found that in some (very rare) cases, there can be differences in compiled and debug code for VB6.</p>
<p>It might be worth trying the 'Compile to P-Code' option - sometimes this gives slightly different results from native code. You'll find it in Project Properties/Compile tab.</p>
<p>It's possible that if you post your algorithm, we'll be able to find more possibilities.</p>
<p>Edit: Since you can't post the algorithm, I'd suggest breaking the algorithm up incrementally and trying to work out where exactly the differences lie.</p>
| 27,304
|
<p>Say I have two tables, a master list of students containing personal info, and a list of student enrollments in classes. The two tables share a common column, which is a string uniquely identifying the student, but it is not the primary key. </p>
<p>Say I want to display all the enrollments on a page, along with some of the personal data from the student (say perhaps hometown). </p>
<p>I understand that it would be a has_many relationship. The master list record has many enrollments. An enrollment belongs to a student.</p>
<pre><code>class Student < ActiveRecord::Base
has_many :enrollments
end
class Enrollment < ActiveRecord::Base
belongs_to :student
end
</code></pre>
<p>Is this the correct relationship between the two, and if so, how do I do a join query against the shared column?</p>
|
<p>Yes ActiveRecord will manage the relationships for you, but you can also specify the join when searching for a condition in the relationship. For example:</p>
<pre><code>User.find(:all, :joins => :phone_numbers, :conditions => { :phone_numbers => {:name => 'business'} })
</code></pre>
<p>Note though using a hash for the conditional declaration is only in Rails 2.2</p>
<p>But most of the time just using the ActiveRecord relationships with <code>has_many</code> should be just fine and as mentioned in above answers you would call the object using as if it was directly on the model... <code>@student.enrollments</code></p>
|
<p>What mwilliams says plus make sure you want a many to many association when you follow the guide.</p>
| 43,873
|
<p>I'm using grep to generate a list of files I need to move:</p>
<pre><code>grep -L -r 'Subject: \[SPAM\]' .
</code></pre>
<p>How can I pass this list to the mv command and move the files somewhere else?</p>
|
<p>If you want to find and move files that do not match your pattern (move files that don't contain <code>'Subject \[SPAM\]'</code> in this example) use:</p>
<pre><code>grep -L -Z -r 'Subject: \[SPAM\]' . | xargs -0 -I{} mv {} DIR
</code></pre>
<p>The -Z means output with zeros (\0) after the filenames (so spaces are not used as delimeters).</p>
<pre><code>xargs -0
</code></pre>
<p>means interpret \0 to be delimiters.</p>
<p>The -L means find files that do not match the pattern. Replace <code>-L</code> with <code>-l</code> if you want to move files that match your pattern.</p>
<p>Then</p>
<pre><code>-I{} mv {} DIR
</code></pre>
<p>means replace <code>{}</code> with the filenames, so you get <code>mv filenames DIR</code>.</p>
|
<p>You can pass the result to the next command by using
grep ... | xargs mv {} destination</p>
<p>Check man xargs for more info.</p>
| 11,737
|
<p>One of our partners recently reported that our software could not contact a remote instance of SQL Express until they started the RPC Locator and SQL Server Browser services. Where would I find a list of services that must be running, on both server and client, to enable remote access to SQL Express and/or SQL Server?</p>
<p>Sadly, the SQL Express documentation does not appear to include this detail.</p>
|
<p>SQL Express always installs as a named instance (servername\sqlexpress) and hence has a dynamic port assigned to it. The SQL Browser service is required for clients to locate the instance. Without the SQL browser, a client won't know what port the service is listening on.</p>
|
<p>Looking at my current installation of SQL Server, I have remote connections enabled and working and both RPC Locator and SQL Server Browser services are disabled on the machine.</p>
<p>The key is that you have to enable remote connections properly in the Surface Area Configuration Wizard.</p>
| 25,593
|
<p>I am developing an iOS application, and trying to zip the file I have created in the application, is there any built in function able to do this?</p>
|
<p>As Alex pointed out, I responded to <a href="https://stackoverflow.com/questions/230984/compression-api-on-the-iphone">this question</a> by pointing out the <a href="http://www.cocoadev.com/index.pl?NSDataCategory" rel="nofollow noreferrer">NSData category</a> contributed by users of the Cocoadev wiki. That category includes methods for dealing with zipped and gzipped data in an NSData instance (that could be read from a Zip file or written to one). This should be all you need to implement the file zipping you describe, as long as you can feed your file data into an NSData instance.</p>
<p>For an example of this category in action, please see the source code for my iPhone application, <a href="http://www.sunsetlakesoftware.com/2008/10/02/molecules-source-code-now-available" rel="nofollow noreferrer">Molecules</a>. I only use the method to extract data from a gzipped file (in SLSMolecule+PDB.m), but you should be able to get the basic concepts from that.</p>
|
<p>first you download Objective-zip example from <a href="http://code.google.com/p/objective-zip/downloads/list" rel="nofollow">http://code.google.com/p/objective-zip/downloads/list</a></p>
<blockquote>
<p>in this example Find and copy three folder Objective-Zip, MiniZip and ZLib drag in to your project</p>
<p>import two class in you .m class
"ZipFile.h" and
"ZipWriteStream.h"</p>
<p>create method of zip my code is :-</p>
</blockquote>
<pre><code>-(IBAction)Zip{
self.fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory , NSUserDomainMask, YES);
NSString *ZipLibrary = [paths objectAtIndex:0];
NSString *fullPathToFile = [ZipLibrary stringByAppendingPathComponent:@"backUp.zip"];
//[self.fileManager createDirectoryAtPath:fullPathToFile attributes:nil];
//self.documentsDir = [paths objectAtIndex:0];
ZipFile *zipFile = [[ZipFile alloc]initWithFileName:fullPathToFile mode:ZipFileModeCreate];
NSError *error = nil;
self.fileManager = [NSFileManager defaultManager];
NSArray *paths1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
self.documentsDir = [paths1 objectAtIndex:0];
NSArray *files = [[NSFileManager defaultManager]contentsOfDirectoryAtPath:self.documentsDir error:&error];
//for(NSString *filename in files){
for(int i = 0;i<files.count;i++){
id myArrayElement = [files objectAtIndex:i];
if([myArrayElement rangeOfString:@".png" ].location !=NSNotFound){
NSLog(@"add %@", myArrayElement);
NSString *path = [self.documentsDir stringByAppendingPathComponent:myArrayElement];
NSDictionary *attributes = [[NSFileManager defaultManager]attributesOfItemAtPath:path error:&error];
NSDate *Date = [attributes objectForKey:NSFileCreationDate];
ZipWriteStream *streem = [zipFile writeFileInZipWithName:myArrayElement fileDate:Date compressionLevel:ZipCompressionLevelBest];
NSData *data = [NSData dataWithContentsOfFile:path];
// NSLog(@"%d",data);
[streem writeData:data];
[streem finishedWriting];
}else if([myArrayElement rangeOfString:@".txt" ].location !=NSNotFound)
{
NSString *path = [self.documentsDir stringByAppendingPathComponent:myArrayElement];
NSDictionary *attributes = [[NSFileManager defaultManager]attributesOfItemAtPath:path error:&error];
NSDate *Date = [attributes objectForKey:NSFileCreationDate];
ZipWriteStream *streem = [zipFile writeFileInZipWithName:myArrayElement fileDate:Date compressionLevel:ZipCompressionLevelBest];
NSData *data = [NSData dataWithContentsOfFile:path];
// NSLog(@"%d",data);
[streem writeData:data];
[streem finishedWriting];
}
}
[self testcsv];
[zipFile close];
}
</code></pre>
<p>your documents directory saved item .png and .txt files zipping in Library folder with backup.zip
i hope this is helps </p>
| 36,409
|
<p>Is there a CSS editor which automatically expands one-line declarations as multi-line declarations on focus ? To clarify my thought, see example below:</p>
<p>Original CSS:</p>
<pre><code>div#main { color: orange; margin: 1em 0; border: 1px solid black; }
</code></pre>
<p>But when focusing on it, editor automatically expands it to:</p>
<pre><code>div#main {
color: orange;
margin: 1em 0;
border: 1px solid black;
}
</code></pre>
<p>And when it looses focus, editor again it automatically compresses it to one-line declaration.</p>
<p>Thanks.</p>
|
<p>If you are using Visual Studio you should be able to do a close approximation of this:</p>
<ol>
<li>You can change how CSS is formatted
via the Tools -> Options menu.</li>
<li>Check 'Show all settings' if it is unchecked.</li>
<li>Go to Text Editor -> CSS -> Format and pick the semi-expanded option</li>
<li>Ok you changes.</li>
<li>Then <kbd>ctrl+A</kbd>, <kbd>ctrl+K</kbd>, <kbd>ctrl+D</kbd> should re-format your document</li>
<li>When you are finished editing just go back to the options and pick the compact CSS format then <kbd>ctrl+A</kbd>,<kbd>ctrl+K</kbd>,<kbd>ctrl+D</kbd> to re-format again.</li>
</ol>
<p>Hope this helps.</p>
|
<p>Sorry. I don't know of any IDEs that explicitly do that.</p>
<p>But, there are quite a few external options:</p>
<ul>
<li><a href="http://csstidy.sourceforge.net/" rel="nofollow noreferrer">CSSTidy</a> (download)</li>
<li><a href="http://www.cleancss.com/" rel="nofollow noreferrer">Clean CSS</a> (in-browser)</li>
<li><a href="http://floele.flyspray.org/csstidy//css_optimiser.php" rel="nofollow noreferrer">CSS Optimiser</a> (in-browser)</li>
<li><a href="http://www.google.com/search?q=css+(tidy+OR+beautify)" rel="nofollow noreferrer">others...</a> (Google Search)</li>
</ul>
| 19,465
|
<p>How do you think, is it a good idea to have such an enum:</p>
<pre><code>enum AvailableSpace {
Percent10,
Percent20,
SqF500,
SqF600
}
</code></pre>
<p>The question is about the semantics of the values names, i.e. both percentage and square feet. I really believe that it's not a good idea, but I could not find and guidelines, etc. in support of this.</p>
<p>EDIT: This will be used to determine a state of an entity - i.e. as a read only property to describe a state of an object. If we know the total space (i.e. the object itself knows it), we have the option to convert internally, so we either have only percentage, or square feet, or both. The argument is, that "both" is not a good idea.</p>
<p>The above is an example of course, but the real problem is that some data providers send us totals (sq.f.), and others percentage, and my goal is to unify the UI. I'm free to make some approximations, so the exact values will be adapted based on how accurate we want to present the information.</p>
<p>The question is only about the semantics of the value names, not the content - i.e. if it is a good idea to put percentage in an (potential) int enum.</p>
|
<p><strong>The answer</strong>: No, it is not a good idea to use enums for representing values. Especially values in two semantically distinct scales. You should not use enums for values.</p>
<p><strong>The reason</strong>: What's the relation between the enum values from the two scales, like Percent10 and SqF600? How do you expand the list of values you can represent within your code? How do you do comparison and arithmetic operations on these values?</p>
<p><strong>The suggestion (not asked for, but nevertheless here it is. :-))</strong>: The semantic of what you are trying to do would be better reflected by a struct that contains two fields - one for absolute area and one for percentage available of that absolute area. With such structure you can represent anything you can represent with the enums above. For example, data providers that give you absolute area, are represented with a struct with the area and 100% available. Data providers that give you percentage, are represented with a struct with the percentage they set and the absolute area such that the percentage of that area is the actual available area the data provider wants to report. You get "normalized" representation of the data from both type of providers and you can add couple of operators to enable comparison and arithmetic calculations with instances.</p>
|
<p>If at all possible, I'd rather break your example into two values, where your enum is "Percent" and "SquareFeet" and the second value is the quantifier. Tie these together in a struct.</p>
<p>If the context allows for it, it may be even better to create two wrapper types "Percent" and "SquareFeet" and then create some operator overloads, so you can do things like "new SquareFeet(500) + new Percent(20);" and eliminate the use of enums.</p>
<p><em>Update:</em> Your naming scheme would be appropriate if the values were industry recognized terms, almost to the point of being symbols. For example, it's safe to have an enum that contains values such as "ISO9001" rather than two values (an enum containing "ISO" and an int of 9001). It'd also be appropriate to have an enum like below:</p>
<pre><code>public enum OperatingSystem
{
Windows95,
Windows98,
Windows2000,
WindowsXP,
WindowsVista,
MacOSClassic,
MacOSXTiger,
MacOSXLeopard
}
</code></pre>
<p>If the terms "Percentage10" and "Sqf500" are not terms of art or well defined in a spec, data dictionary, etc. then it's inappropriate to use them as values in an enum.</p>
| 21,742
|
<p>How do I suspend a whole process (like the Process Explorer does when I click Suspend) in C#.</p>
<p>I'm starting the Process with Process.Start, and on a certain event, I want to suspend the process to be able to do some investigation on a "snapshot" of it.</p>
|
<p>Here's my suggestion:</p>
<pre><code> [Flags]
public enum ThreadAccess : int
{
TERMINATE = (0x0001),
SUSPEND_RESUME = (0x0002),
GET_CONTEXT = (0x0008),
SET_CONTEXT = (0x0010),
SET_INFORMATION = (0x0020),
QUERY_INFORMATION = (0x0040),
SET_THREAD_TOKEN = (0x0080),
IMPERSONATE = (0x0100),
DIRECT_IMPERSONATION = (0x0200)
}
[DllImport("kernel32.dll")]
static extern IntPtr OpenThread(ThreadAccess dwDesiredAccess, bool bInheritHandle, uint dwThreadId);
[DllImport("kernel32.dll")]
static extern uint SuspendThread(IntPtr hThread);
[DllImport("kernel32.dll")]
static extern int ResumeThread(IntPtr hThread);
[DllImport("kernel32", CharSet = CharSet.Auto,SetLastError = true)]
static extern bool CloseHandle(IntPtr handle);
private static void SuspendProcess(int pid)
{
var process = Process.GetProcessById(pid); // throws exception if process does not exist
foreach (ProcessThread pT in process.Threads)
{
IntPtr pOpenThread = OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)pT.Id);
if (pOpenThread == IntPtr.Zero)
{
continue;
}
SuspendThread(pOpenThread);
CloseHandle(pOpenThread);
}
}
public static void ResumeProcess(int pid)
{
var process = Process.GetProcessById(pid);
if (process.ProcessName == string.Empty)
return;
foreach (ProcessThread pT in process.Threads)
{
IntPtr pOpenThread = OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)pT.Id);
if (pOpenThread == IntPtr.Zero)
{
continue;
}
var suspendCount = 0;
do
{
suspendCount = ResumeThread(pOpenThread);
} while (suspendCount > 0);
CloseHandle(pOpenThread);
}
}
</code></pre>
|
<p>See this CodeProject article for the win32 basics : <a href="http://www.codeproject.com/KB/threads/pausep.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/threads/pausep.aspx</a>. This sample code makes use of the ToolHelp32 library from the SDK, so I would recommend turning this sample code into an unmanaged C++/CLI library with a simple interface like "SuspendProcess(uint processID).</p>
<p>Process.Start will return you a Process object, from which you can get the process id, and then pass this to your new library based on the above.</p>
<p>Dave</p>
| 9,674
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.