instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>I'm inspired by the <a href="https://stackoverflow.com/questions/153074/tool-to-visualise-code-flow-cc">C/C++</a> question for a code flow visualization tool.</p>
<p>Is there such a thing for Java servlets or applications?</p>
|
<p>Maybe <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>H</kbd> in Eclipse / IntelliJ IDEA ? (albo present in NB somewhere)
Or "data flow from/to" in IntelliJ IDEA?</p>
|
<p>In UML 2 there are two basic categories of diagrams: structure diagrams and behavior diagrams. Every UML diagram belongs to one these two diagram categories. The purpose of structure diagrams is to show the static structure of the system being modeled. They include the class, component, and or object diagrams. Behavioral diagrams, on the other hand, show the dynamic behavior between the objects in the system, including things like their methods, collaborations, and activities. Example behavior diagrams are activity, use case, and sequence diagrams.</p>
<p>Here, my understanding is that the OP is asking for a tool to visualize <strong>code flow</strong> (this is the title of the question), i.e. dynamic behavior. A perfect diagram for this would be the sequence diagram. </p>
<p>But, AFAIK, neither UML reverse engineering tools nor Doxygen can figure out such diagrams from sources. These tools know how to generate structure diagrams (e.g. class diagram), but not behavior diagrams (this would require execution). So these tools doesn't answer the question (even for C++).</p>
<p>IMO, to visualize the code flow, you'll have to look at the call hierarchy as someone pointed out.</p>
| 18,517
|
<p>I have an ASP.NET program where i am downloading a file from web using DownloadFile method of webClient Class and the do some modifications on it. then i am Saving it to another folder with a unique name.When I am getting this error</p>
<blockquote>
<p>The process cannot access the file 'D:\RD\dotnet\abc\abcimageupload\images\TempStorage\tempImage.jpg' because it is being used by another process</p>
</blockquote>
<p>Can anyone tell me how to solve this.</p>
|
<p>Generally, I think your code should looking something like this.</p>
<pre><code>WebClient wc = new WebClient();
wc.DownloadFile("http://stackoverflow.com/Content/Img/stackoverflow-logo-250.png", "Foo.png");
FileStream fooStream;
using (fooStream = new FileStream("foo.png", FileMode.Open))
{
// do stuff
}
File.Move("foo.png", "foo2.png");
</code></pre>
|
<p>Are you explicitly closing the file stream after you make your changes?</p>
| 41,541
|
<p>I have an MSBuild project where within it I have a task that calls multiple projects where I set BuildInParallel = "true"</p>
<p>Example:</p>
<p></p>
<pre><code> <Message Text="MSBuild project list = @(ProjList)" />
<!-- Compile in parallel -->
<MSBuild Projects="@(ProjList)"
Targets="Build"
Properties="Configuration=$(Configuration)"
BuildInParallel="true" />
</code></pre>
<p></p>
<p>These sub-projects actually invoke a command-line tool to do the actual 'building' - call it compile.exe. Doing crude profiling (thank you taskmgr.exe) of the build process has the following results:</p>
<p>based on the /m setting - I see that exact number of MSBuild.exe processes started which is expected of course - the total available concurrent build processes.</p>
<p>However what I expect to see is around that many number of processes of compile.exe. Basically each MSBuild process will just turn around and invoke compile.exe. What I see is that a number of compile.exe's are started, then they slowly finish until I just see one sole compile.exe still around. The tasks that each compile.exe take a different amount of time, so it's expected that one of them takes a lot longer than the others.</p>
<p>However no other compile.exe's are spawned until the first 'batch' of them are finished. In other words if I have /m:4 - I will see 4 compile.exe's until all finish, then another 4 will be spawned.</p>
<p>This isn't exactly completely parallel to me. Has anyone else seen this behavior. Am I just misunderstanding something?</p>
|
<p>The <a href="http://www.developerfusion.com/tools/convert/vb-to-csharp/" rel="noreferrer">Developer Fusion VB.Net to C# converter</a> says that the equivalent C# code is:</p>
<pre><code>System.Random rnd = new System.Random();
IEnumerable<int> numbers = Enumerable.Range(1, 100).OrderBy(r => rnd.Next());
</code></pre>
<p>For future reference, they also have a <a href="http://www.developerfusion.com/tools/convert/csharp-to-vb/" rel="noreferrer">C# to VB.Net converter</a>. There are <a href="http://www.dotnetspider.com/convert/Vb-To-Csharp.aspx" rel="noreferrer">several other tools</a> available for this as well.</p>
|
<p>Best I can do off the top of my head without access to Visual Studio (crosses fingers):</p>
<pre><code>System.Random rnd = New System.Random();
IEnumerable<int> numbers = Enumerable.Range(1, 100).OrderBy(rnd => rnd.Next);
</code></pre>
| 31,794
|
<p>I have a pair of Sun web servers (iws6) sitting behind a load balancer. It likes to know if the web servers are up and continually asks for /alive.html.
That is fine but how do I not log that in my access log?</p>
<p>Failing that, how could I have the archiver strip out that accesses when it roles the file over?</p>
<p>I would prefer something more elegant that cron calling grep -v alive.html</p>
|
<p>You can give Apache rules about what logs to suppress. Maybe IWS has something similar?</p>
<p><a href="http://httpd.apache.org/docs/1.3/logs.html#conditional" rel="nofollow noreferrer">http://httpd.apache.org/docs/1.3/logs.html#conditional</a> </p>
|
<p>Logs are usually one line per entry so that you can grep for what you want. The idea is to have everything in the file, but to use grep in order to read the parts you care about. Grep for everything but load balancer stuff when you read them.</p>
| 13,049
|
<p>I'm using Fedex's web services and getting an annoying error right up front before I can actually get anywhere.</p>
<p>There was an error in serializing body of message addressValidationRequest1: 'Unable to generate a temporary class (result=1).
error CS0030: Cannot convert type 'FedEx.InterOp.AddressValidationServiceReference.ParsedElement[]' to 'FedEx.InterOp.AddressValidationServiceReference.ParsedElement'
error CS0029: Cannot implicitly convert type 'FedEx.InterOp.AddressValidationServiceReference.ParsedElement' to 'FedEx.InterOp.AddressValidationServiceReference.ParsedElement[]'
'. Please see InnerException for more details.</p>
<p>I'm using .NET 3.5 and get a horrible named class generated for me (I'm not sure why it isn't just AddressValidationService):</p>
<p><code>AddressValidationPortTypeClient addressValidationService = new ...;</code></p>
<p>on this class I make my web service call:</p>
<p><code>addressValidationService.addressValidation(request);</code></p>
<p>This is when I get this error.</p>
<p>The only references I can find to this error come from ancient 1.1 projects. In my case my DLL has references to System.Web and System.Web.Services which seemed to be an issue back then.</p>
|
<p>You only need change the [][], not the single [].</p>
<p>In Reference.cs change </p>
<pre><code>private ParsedElement[][] parsedStreetLineField;
to
private ParsedElement[] parsedStreetLineField;
and
public ParsedElement[][] ParsedStreetLine {
to
public ParsedElement[] ParsedStreetLine {
</code></pre>
|
<p>Turns out Fedex's own documentation covers this specifically!</p>
<p><strong>I am using wsdl.exe from Microsoft to generate code and I get an error CS0029: Cannot implicitly convert type 'fedexreq.ParsedElement' to 'fedexreq.ParsedElement[]'.</strong></p>
<p>This is an error generated by Web Services Description Language Tool (Wsdl.exe) to generate the client information. When you publish a schema that contains nested nodes that have the maxOccurs attribute set to the "unbounded" value, the Wsdl.exe tool creates multidimensional arrays in the generated code file. Therefore, the generated code contains incorrect types for the nested nodes. To solve modify the generated code by removing the bracket ([]) array characters from the data type delectation statements. For more information see <a href="http://support.microsoft.com/kb/326790/en-us" rel="noreferrer">http://support.microsoft.com/kb/326790/en-us</a> and <a href="http://support.microsoft.com/kb/891386" rel="noreferrer">http://support.microsoft.com/kb/891386</a> </p>
| 44,942
|
<p>When do we use client side reporting and when do we use server side reporting?</p>
<p>Which reporting is best practice (client/server)?</p>
<p>This pertains to SSRS reporting.</p>
|
<p>Well... client side reporting you'd use if you've got something like a winforms client that you can't guarantee will have constant access to the data source. It might have a set of data cached on the client side which you need to report on even if the connection to the server is unavailable.</p>
<p>Server side reporting you'd use in the scenario where you either need to simplify the report distribution and deployment as you just deploy the reports to one place and everyone can access them. This has the downfall of always requiring a connection be available to the server</p>
|
<p>It depends what you call "server" in this case. As you mention SSRS I am assuming you consider the database (SQL Server) as the server.</p>
<p>It all depends on the application/project structure and requirements. If you have a database that contains also the business logic (store procedures) and you simply want to query data and display/export it, then SSRS is handy.</p>
<p>However if you have a web application with your persistence layer (database) that simply stores information and ensures the information is consistent, but then your business logic is for example in a Web API (i.e: a RESTful API project) that queries/maintains the database data (CRUD) and adds some logic and then responses to HTTP requests with the results/information requested (i.e: with JSON) to a rich front-end, then I would add reporting functionality at client-side (front end) with for example a Javascript library executed in the browser that is able to display the retrieved data in whichever way, it is able to export it to a DOC, Excel, Email it, etc.</p>
<p>Separation of concerns for a typical Web Application:</p>
<ul>
<li>persistence layer (Database) to store information and guarantee consistency</li>
<li>business layer (Back end RESTful API) to do all the smart things on the resources, calculations, authentication, authorization for each HTTP request.</li>
<li>Rich front-end (Javascript + HTML + CSS) to interact with the user and request/display information to the back-end. <strong>As part of the concern of displaying information</strong>, this front-end would also generate reports.</li>
</ul>
| 16,623
|
<p>I am building a web application using .NET 3.5 (ASP.NET, SQL Server, C#, WCF, WF, etc) and I have run into a major design dilemma. This is a uni project btw, but it is 100% up to me what I develop.</p>
<p>I need to design a system whereby I can take an image and automatically crop a certain object within it, without user input. So for example, cut out the car in a picture of a road. I've given this a lot of thought, and I can't see any feasible method. I guess this thread is to discuss the issues and feasibility of achieving this goal. Eventually, I would get the dimensions of a car (or whatever it may be), and then pass this into a 3d modelling app (custom) as parameters, to render a 3d model. This last step is a lot more feasible. It's the cropping issue which is an issue. I have thought of all sorts of ideas, like getting the colour of the car and then the outline around that colour. So if the car (example) is yellow, when there is a yellow pixel in the image, trace around it. But this would fail if there are two yellow cars in a photo.</p>
<p>Ideally, I would like the system to be completely automated. But I guess I can't have everything my way. Also, my skills are in what I mentioned above (.NET 3.5, SQL Server, AJAX, web design) as opposed to C++ but I would be open to any solution just to see the feasibility.</p>
<p>I also found this patent: <a href="http://www.patentstorm.us/patents/7034848.html" rel="nofollow noreferrer">US Patent 7034848 - System and method for automatically cropping graphical images</a></p>
<p>Thanks</p>
|
<p>This is one of the problems that needed to be solved to finish the <a href="http://www.darpagrandchallenge.com/" rel="nofollow noreferrer">DARPA Grand Challenge</a>. Google video has a <a href="http://video.google.com/videoplay?docid=8594517128412883394" rel="nofollow noreferrer">great presentation by the project lead from the winning team</a>, where he talks about how they went about their solution, and how some of the other teams approached it. The relevant portion starts around 19:30 of the video, but it's a great talk, and the whole thing is worth a watch. Hopefully it gives you a good starting point for solving your problem.</p>
|
<p>If I'm reading this right... This is where AI shines.</p>
<p>I think the "simplest" solution would be to use a neural-network based image recognition algorithm. Unless you know that the car will look the <em>exact</em> same in each picture, then that's pretty much the only way.</p>
<p>If it IS the exact same, then you can just search for the pixel pattern, and get the bounding rectangle, and just set the image border to the inner boundary of the rectangle.</p>
| 26,424
|
<p>I have a form, when I click on submit button, I want to communicate with the server and get something from the server to be displayed on the same page. Everything must be done in AJAX manner. How to do it in Google App Engine? If possible, I want to do it in JQuery.</p>
<p>Edit: The example in <a href="http://groups.google.com.my/group/google-appengine/browse_thread/thread/36dc8759dab4cc28?hl=en#" rel="nofollow noreferrer">code.google.com/appengine/articles/rpc.html</a> doesn't work on form. </p>
<hr>
<p>Edit: The rpc procedure <a href="http://groups.google.com.my/group/google-appengine/browse_thread/thread/36dc8759dab4cc28?hl=en#" rel="nofollow noreferrer">doesn't work for form</a>. </p>
|
<p>You can use <a href="http://www.malsup.com/jquery/form/" rel="noreferrer">jquery Form plugin</a> to submit forms using ajax. Works very well.</p>
<pre><code>$('#myFormId').submit(function() {
// submit the form
$(this).ajaxSubmit();
return false;
});
</code></pre>
|
<p>I'd add that in Firebug, you should see your ajax call pop up in the console. If you're getting the exception when you open that address, there's something up with your Python code. Maybe you're not correctly mapping your urls?</p>
| 26,014
|
<p>Is it "acceptable" to have an <strong>ASP.Net 2.0</strong> application without the BLL (Business Logic Layer) as the following?</p>
<ol>
<li>SQL Server Data Storage & Stored Procedures</li>
<li>Data Link Layer (Strongly Typed Table Adapters) connecting to Stored Procs</li>
<li>Presentation Layer ASPX Pages with Code behind and ObjectDataSource for connection straight to the DLL</li>
</ol>
<p>Is a BLL always preferable, even if business logic is entirely validatable in the presentation's code behind? What are the potential drawbacks for not using a BLL?</p>
|
<p>It's acceptable as long as you understand the consequences. The main reason you'd have a BLL is to re-use that logic elsewhere throughout your application.</p>
<p>If you have all that validation logic in the presentation code, you're really making it difficult to re-use elsewhere within your application.</p>
|
<p>If the application is a general one, then the business logic layer can be used in complete other applications too. Like, I normally use my CMS related BLL classes in other applications.</p>
| 2,634
|
<p>I would like to put a link to a webpage in an alert dialog box so that I can give a more detailed description of how to fix the error that makes the dialog box get created. </p>
<p>How can I make the dialog box show something like this:</p>
<pre><code>There was an error. Go to this page to fix it.
wwww.TheWebPageToFix.com
</code></pre>
<p>Thanks.</p>
|
<p>You could try asking them if they wish to visit via window.prompt:</p>
<pre><code>if(window.prompt('Do you wish to visit the following website?','http://www.google.ca'))
location.href='http://www.google.ca/';
</code></pre>
<p>Also, Internet Explorer supports modal dialogs so you could try showing one of those:</p>
<pre><code>if (window.showModalDialog)
window.showModalDialog("mypage.html","popup","dialogWidth:255px;dialogHeight:250px");
else
window.open("mypage.html","name","height=255,width=250,toolbar=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,modal=yes");
</code></pre>
|
<p>Or use window.open and put the <a href="http://qa.techinterviews.com/q/20060809080754AAs7gKM" rel="nofollow noreferrer">link there</a>.</p>
| 8,141
|
<p>Typically I develop my websites on trunk, then merge changes to a testing branch where they are put on a 'beta' website, and then finally they are merged onto a live branch and put onto the live website.</p>
<p>With a Facebook application things are a bit tricky. As you can't view a Facebook application through a normal web browser (it has to go through the Facebook servers) you can't easily give each developer their own version of the website to work with and test.</p>
<p>I have not come across anything about the best way to develop and test a Facebook application while continuing to have a stable live website that users can use. My question is this, what is the best practice for organising the development and testing of a Facebook application?</p>
|
<p>The way I and my partner did it was we each made our own private Facebook applications, that pointed to our IP address where we worked on it. Since we worked in the same place, we each picked a different port, and had our router forward that port to our local IP address. It was kinda slow to refresh a page, but it worked very nicely.</p>
|
<p>Another solution is NGROK</p>
<p><a href="https://ngrok.com/" rel="nofollow">https://ngrok.com/</a></p>
<p>It opens a public tunnel to your local app</p>
<p>Example on my rails application by simply typing</p>
<pre><code>./ngrok 3000
</code></pre>
<p>I get</p>
<pre><code>http://630066fe.ngrok.com -> 127.0.0.1:3000
</code></pre>
| 6,038
|
<p>There are 3 parts to the page. </p>
<ol>
<li><p>Header, which has unknown content at design time as it is populated with text at runtime. All the text must be displayed, no scroll bars.( I think <code>height: 100%</code> does this) </p></li>
<li><p>Content, the content should fill the page below the bottom of the header to the top of the footer. if there is more text in the content that can be shown, then scroll bars should be available. </p></li>
<li><p>Footer. Footer should be <code>25px</code> high and always sit at the bottom of the viewport. </p></li>
</ol>
<p>The window is a popup and it should never have window scroll bars, it can be resized but no scrollbars. The contents scroll bars should be the only one available. </p>
<p>The content area should resize when resizing the window, but the footer stay the same, ie fixed to the bottom. </p>
<p>The widths would all be <code>100%</code></p>
|
<p>GUID technically stands for globally unique identifier. What it is, actually, is a 128 bit structure that is <em>unlikely</em> to ever repeat or create a collision. If you do the maths, the domain of values is in the <a href="https://en.wikipedia.org/wiki/Names_of_large_numbers#Standard_dictionary_numbers" rel="noreferrer">undecillions</a>.</p>
<p>Use guids when you have multiple independent systems or clients generating ID's that need to be unique. </p>
<p>For example, if I have 5 client apps creating and inserting transactional data into a table that has a unique constraint on the ID, then use guids. This prevents having to force a client to request an issued ID from the server first.</p>
<p>This is also great for object factories and systems that have numerous object types stored in different tables where you don't want any 2 objects to have the same ID. This makes caching and scavenging schemas much easier to implement.</p>
|
<p>To actually see what it looks like on a windows computer, go to cmd or powershell.</p>
<ol>
<li><p>Powershell => <code>[guid]::NewGuid()</code></p>
</li>
<li><p>CMD => <code>powershell [guid]::NewGuid()</code></p>
</li>
</ol>
<p><a href="https://i.stack.imgur.com/LMEoD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LMEoD.png" alt="enter image description here" /></a></p>
| 48,595
|
<p>Given an HTML link like</p>
<pre><code><a href="urltxt" class="someclass" close="true">texttxt</a>
</code></pre>
<p>how can I isolate the url and the text? </p>
<p><strong>Updates</strong></p>
<p>I'm using Beautiful Soup, and am unable to figure out how to do that. </p>
<p>I did </p>
<pre><code>soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url))
links = soup.findAll('a')
for link in links:
print "link content:", link.content," and attr:",link.attrs
</code></pre>
<p>i get </p>
<pre><code>*link content: None and attr: [(u'href', u'_redirectGeneric.asp?genericURL=/root /support.asp')]* ...
...
</code></pre>
<p>Why am i missing the content? </p>
<p>edit: elaborated on 'stuck' as advised :)</p>
|
<p>Use <a href="http://crummy.com/software/BeautifulSoup" rel="noreferrer">Beautiful Soup</a>. Doing it yourself is harder than it looks, you'll be better off using a tried and tested module.</p>
<p><strong>EDIT:</strong></p>
<p>I think you want:</p>
<pre><code>soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url).read())
</code></pre>
<p>By the way, it's a bad idea to try opening the URL there, as if it goes wrong it could get ugly.</p>
<p><strong>EDIT 2:</strong></p>
<p>This should show you all the links in a page:</p>
<pre><code>import urlparse, urllib
from BeautifulSoup import BeautifulSoup
url = "http://www.example.com/index.html"
source = urllib.urlopen(url).read()
soup = BeautifulSoup(source)
for item in soup.fetchall('a'):
try:
link = urlparse.urlparse(item['href'].lower())
except:
# Not a valid link
pass
else:
print link
</code></pre>
|
<p>Though I suppose the others <em>might</em> be correct in pointing you to using Beautiful Soup, they <em>might</em> not, and using an external library might be massively over-the-top for your purposes. Here's a regex which will do what you ask.</p>
<pre><code>/<a\s+[^>]*?href="([^"]*)".*?>(.*?)<\/a>/
</code></pre>
<p>Here's what it matches:</p>
<pre><code>'<a href="url" close="true">text</a>'
// Parts: "url", "text"
'<a href="url" close="true">text<span>something</span></a>'
// Parts: "url", "text<span>something</span>"
</code></pre>
<p>If you wanted to get <em>just</em> the text (eg: "textsomething" in the second example above), I'd just run another regex over it to strip anything between pointed brackets.</p>
| 36,321
|
<p>Something else perhaps?
I am already using nHibernate, but I get occasional issues where a lazy initialized proxy object won't actually initialize. I'm thinking of trying something else. The site has user accounts, user posts and photos, and filtering of those to certain location names and title/description matches. Not to mention voting, rating, and marking as a favorite. All of these cause various amounts of db load.</p>
|
<p>SubSonic is currently used in all our webform applications with great success. In a matter of minutes your entire database can be generated from scratch ready to use in your application. Rob Conery, SubSonic creator, has some great webcasts up detailing the process to get SubSonic bits setup in a web application as well as some cool demos to get you started. Check out the <a href="http://subsonicproject.com/download/" rel="nofollow noreferrer">SubSonic Project</a>.</p>
|
<p>LINQ is a great choice. It is used here on Stackoverflow, and on my current project we are using LINQ for our data access. </p>
| 22,875
|
<p>My web application has a login page that submits authentication credentials via an AJAX call. If the user enters the correct username and password, everything is fine, but if not, the following happens:</p>
<ol>
<li>The web server determines that although the request included a well-formed Authorization header, the credentials in the header do not successfully authenticate.</li>
<li>The web server returns a 401 status code and includes one or more WWW-Authenticate headers listing the supported authentication types.</li>
<li>The browser detects that the response to my call on the XMLHttpRequest object is a 401 and the response includes WWW-Authenticate headers. It then pops up an authentication dialog asking, again, for the username and password.</li>
</ol>
<p>This is all fine up until step 3. I don't want the dialog to pop up, I want want to handle the 401 response in my AJAX callback function. (For example, by displaying an error message on the login page.) I want the user to re-enter their username and password, of course, but I want them to see my friendly, reassuring login form, not the browser's ugly, default authentication dialog.</p>
<p>Incidentally, I have no control over the server, so having it return a custom status code (i.e., something other than a 401) is not an option.</p>
<p>Is there any way I can suppress the authentication dialog? In particular, can I suppress the Authentication Required dialog in Firefox 2 or later? Is there any way to suppress the Connect to <em>[host]</em> dialog in IE 6 and later?</p>
<hr>
<p><strong>Edit</strong><br>
<em>Additional information from the author (Sept. 18):</em><br>
I should add that the real problem with the browser's authentication dialog popping up is that it give insufficient information to the user.</p>
<p>The user has just entered a username and password via the form on the login page, he believes he has typed them both correctly, and he has clicked the submit button or hit enter. His expectation is that he will be taken to the next page or perhaps told that he has entered his information incorrectly and should try again. However, he is instead presented with an unexpected dialog box.</p>
<p>The dialog makes no acknowledgment of the fact he just <em>did</em> enter a username and password. It does not clearly state that there was a problem and that he should try again. Instead, the dialog box presents the user with cryptic information like "The site says: '<em>[realm]</em>'." Where <em>[realm]</em> is a short realm name that only a programmer could love.</p>
<p>Web broswer designers take note: no one would ask how to suppress the authentication dialog if the dialog itself were simply more user-friendly. The <em>entire</em> reason that I am doing a login form is that our product management team rightly considers the browsers' authentication dialogs to be awful.</p>
|
<p>I encountered the same issue here, and the backend engineer at my company implemented a behavior that is apparently considered a good practice : when a call to a URL returns a 401, if the client has set the header <code>X-Requested-With: XMLHttpRequest</code>, the server drops the <code>www-authenticate</code> header in its response. </p>
<p>The side effect is that the default authentication popup does not appear.</p>
<p>Make sure that your API call has the <code>X-Requested-With</code> header set to <code>XMLHttpRequest</code>. If so there is nothing to do except changing the server behavior according to this good practice...</p>
|
<p>For those unsing C# here's <code>ActionAttribute</code> that returns <code>400</code> instead of <code>401</code>, and 'swallows' Basic auth dialog.</p>
<pre><code>public class NoBasicAuthDialogAuthorizeAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
base.HandleUnauthorizedRequest(filterContext);
filterContext.Result = new HttpStatusCodeResult(400);
}
}
</code></pre>
<p>use like following:</p>
<pre><code>[NoBasicAuthDialogAuthorize(Roles = "A-Team")]
public ActionResult CarType()
{
// your code goes here
}
</code></pre>
<p>Hope this saves you some time.</p>
| 11,160
|
<p>Why does this happen (circled in red), and how can I fix it? It is making my prints come out horrible.</p>
<p>Not shown in the picture, but the option "Coasting" was Enabled:</p>
<ul>
<li>Coasting Volume 0.064 mm<sup>3</sup></li>
<li>Minimum Volume Before Coasting: 0.8</li>
<li>Coasting Speed 90%</li>
</ul>
<hr>
<p><a href="https://i.stack.imgur.com/a4sB6.jpg" rel="nofollow noreferrer" title="Rendered G-code view of a sliced model"><img src="https://i.stack.imgur.com/a4sB6.jpg" alt="Rendered G-code view of a sliced model" title="Rendered G-code view of a sliced model"></a></p>
|
<p>If you enable the option "Coasting", the extruder will follow the extrusion path at the end of switching to the next layer or the next section, but will not deposit any material as it uses the build up pressure in the nozzle to deposit the final bits. This shows up in your G-code representation by empty (non-depositing) gaps (in reality, when fine-tuned correctly, will be filled).</p>
<p><em>E.g. sliced without "Coasting" enabled:</em>
<a href="https://i.stack.imgur.com/1YJCg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1YJCg.png" alt="Print without enabling the coasting option"></a></p>
<p><em>E.g. sliced with "Coasting" enabled:</em>
<a href="https://i.stack.imgur.com/SAtyB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SAtyB.png" alt="enter image description here"></a></p>
|
<p>I have had a similar thing happen when slicing a large piece that has - in real life - walls of about 2 cm. By scaling it down to 1.5%, this become less than the wall thickness, and the wall was simply omitted by CURA.</p>
<p>In my experience, a model showing gaps <em>can</em> have in these locations a thickness less than 1 wall.</p>
| 951
|
<p>I am trying to make a copy of a database to a new database on the same server. The server is my local computer running SQL 2008 Express under Windows XP.
Doing this should be quite easy using the SMO.Transfer class and it almost works!</p>
<p>My code is as follows (somewhat simplified):</p>
<pre><code>Server server = new Server("server");
Database sourceDatabase = server.Databases["source database"];
Database newDatbase = new Database(server, "new name");
newDatbase.Create();
Transfer transfer = new Transfer(sourceDatabase);
transfer.CopyAllObjects = true;
transfer.Options.WithDependencies = true;
transfer.DestinationDatabase = newDatbase.Name;
transfer.CopySchema = true;
transfer.CopyData = true;
StringCollection transferScript = transfer.ScriptTransfer();
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand switchDatabase = new SqlCommand("USE " + newDatbase.Name, conn))
{
switchDatabase.ExecuteNonQuery();
}
foreach (string scriptLine in transferScript)
{
using (SqlCommand scriptCmd = new SqlCommand(scriptLine, conn, transaction))
{
int res = scriptCmd.ExecuteNonQuery();
}
}
}
</code></pre>
<p>What I do here is to first create a new database, then generate a copy script using the <code>Transfer</code> class and finally running the script in the new database. </p>
<p>This works fine for copying the structure, but the <code>CopyData</code> option doesn't work!</p>
<p>Are there any undocumented limits to the <code>CopyData</code> option? The documentation only says that the option specifies whether data is copied. </p>
<p>I tried using the <code>TransferData()</code> method to copy the databse without using a script but then I get an exception that says "Failed to connect to server" with an inner exception that says "A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)"</p>
<p>I also tried to enable Named Pipes on the server, but that doesn't help. </p>
<p>Edit:
I found a solution that works by making a backup and then restoring it to a new database. It's quite clumsy though, and slower than it should be, so I'm still looking for a better solution.</p>
|
<p>Well, after contacting Microsft Support I got it working properly, but it is slow and more or less useless. Doing a backup and then a restore is much faster and I will be using it as long as the new copy should live on the same server as the original. </p>
<p>The working code is as follows:</p>
<pre><code>ServerConnection conn = new ServerConnection("rune\\sql2008");
Server server = new Server(conn);
Database newdb = new Database(server, "new database");
newdb.Create();
Transfer transfer = new Transfer(server.Databases["source database"]);
transfer.CopyAllObjects = true;
transfer.CopyAllUsers = true;
transfer.Options.WithDependencies = true;
transfer.DestinationDatabase = newdb.Name;
transfer.DestinationServer = server.Name;
transfer.DestinationLoginSecure = true;
transfer.CopySchema = true;
transfer.CopyData = true;
transfer.Options.ContinueScriptingOnError = true;
transfer.TransferData();
</code></pre>
<p>The trick was to set the DestinationDatabase property. This must be set even if the target is that same as the source. In addition I had to connect to the server as a named instance instead of using the other connection options.</p>
|
<p>Here is my solution:</p>
<ol>
<li>I have a Database named is Olddatabase</li>
<li><p>I backup it to E:\databackup\Old.bak</p></li>
<li><p>If you want to create a Duplicate Database from Olddatabase in the same server with name NewDatabase</p></li>
</ol>
<p>3.1 You can use command in query tool : EXEC OldDatabase.dbo.sp_helpfile;
to determinat path of OldDatabase is stored in case you want to save NewDatabase in the same folder. </p>
<p>or You can save NewDatabase in new Path which you want</p>
<ol>
<li><p>use this command in Query tool</p>
<p>RESTORE DATABASE NewDatabase FROM DISK = 'E:\databackup\Old.bak'
WITH MOVE 'OldDatabase' TO 'E:\New path (or the same path)\NewDatabase_Data.mdf',
MOVE 'OldDatabase_log' TO 'E:\New path (or the same path)\NewDatabase_Log.ldf';</p></li>
</ol>
<p>Note: you can Use these command obove in c# with : Create a Store procedure in sql which include Above commands. And you can call the store procedure in C #</p>
| 33,676
|
<p>How can I make a major upgrade to an installation set (MSI) built with <a href="http://en.wikipedia.org/wiki/WiX" rel="noreferrer">WiX</a> install into the same folder as the original installation?</p>
<p>The installation is correctly detected as an upgrade, but the directory selection screen is still shown and with the default value (not necessarily the current installation folder).</p>
<p>Do I have to do manual work like saving the installation folder in a registry key upon first installing and then read this key upon upgrade? If so, is there any example?</p>
<p>Or is there some easier way to achieve this in <a href="http://en.wikipedia.org/wiki/Windows_Installer" rel="noreferrer">MSI</a> or WiX?</p>
<p>As reference, I my current WiX file is below:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2003/01/wi">
<Product Id="a2298d1d-ba60-4c4d-92e3-a77413f54a53"
Name="MyCompany Integration Framework 1.0.0"
Language="1033"
Version="1.0.0"
Manufacturer="MyCompany"
UpgradeCode="9071eacc-9b5a-48e3-bb90-8064d2b2c45d">
<!-- Package information -->
<Package Keywords="Installer"
Id="e85e6190-1cd4-49f5-8924-9da5fcb8aee8"
Description="Installs MyCompany Integration Framework 1.0.0"
Comments="Installs MyCompany Integration Framework 1.0.0"
InstallerVersion="100"
Compressed="yes" />
<Upgrade Id='9071eacc-9b5a-48e3-bb90-8064d2b2c45d'>
<UpgradeVersion Property="PATCHFOUND"
OnlyDetect="no"
Minimum="0.0.1"
IncludeMinimum="yes"
Maximum="1.0.0"
IncludeMaximum="yes"/>
</Upgrade>
<!-- Useless but necessary... -->
<Media Id="1" Cabinet="MyCompany.cab" EmbedCab="yes" />
<!-- Precondition: .NET 2 must be installed -->
<Condition Message='This setup requires the .NET Framework 2 or higher.'>
<![CDATA[MsiNetAssemblySupport >= "2.0.50727"]]>
</Condition>
<Directory Id="TARGETDIR"
Name="SourceDir">
<Directory Id="MyCompany"
Name="MyCompany">
<Directory Id="INSTALLDIR"
Name="Integrat"
LongName="MyCompany Integration Framework">
<Component Id="MyCompanyDllComponent"
Guid="4f362043-03a0-472d-a84f-896522ce7d2b"
DiskId="1">
<File Id="MyCompanyIntegrationDll"
Name="IbIntegr.dll"
src="..\Build\MyCompany.Integration.dll"
Vital="yes"
LongName="MyCompany.Integration.dll" />
<File Id="MyCompanyServiceModelDll"
Name="IbSerMod.dll"
src="..\Build\MyCompany.ServiceModel.dll"
Vital="yes"
LongName="MyCompany.ServiceModel.dll" />
</Component>
<!-- More components -->
</Directory>
</Directory>
</Directory>
<Feature Id="MyCompanyProductFeature"
Title='MyCompany Integration Framework'
Description='The complete package'
Display='expand'
Level="1"
InstallDefault='local'
ConfigurableDirectory="INSTALLDIR">
<ComponentRef Id="MyCompanyDllComponent" />
</Feature>
<!-- Task scheduler application. It has to be used as a property -->
<Property Id="finaltaskexe"
Value="MyCompany.Integration.Host.exe" />
<Property Id="WIXUI_INSTALLDIR"
Value="INSTALLDIR" />
<InstallExecuteSequence>
<!-- command must be executed: MyCompany.Integration.Host.exe /INITIALCONFIG parameters.xml -->
<Custom Action='PropertyAssign'
After='InstallFinalize'>NOT Installed AND NOT PATCHFOUND</Custom>
<Custom Action='LaunchFile'
After='InstallFinalize'>NOT Installed AND NOT PATCHFOUND</Custom>
<RemoveExistingProducts Before='CostInitialize' />
</InstallExecuteSequence>
<!-- execute comand -->
<CustomAction Id='PropertyAssign'
Property='PathProperty'
Value='[INSTALLDIR][finaltaskexe]' />
<CustomAction Id='LaunchFile'
Property='PathProperty'
ExeCommand='/INITIALCONFIG "[INSTALLDIR]parameters.xml"'
Return='asyncNoWait' />
<!-- User interface information -->
<UIRef Id="WixUI_InstallDir" />
<UIRef Id="WixUI_ErrorProgressText" />
</Product>
</Wix>
</code></pre>
|
<p>There's an example in the WiX tutorial: <a href="https://www.firegiant.com/wix/tutorial/getting-started/where-to-install/" rel="nofollow noreferrer">https://www.firegiant.com/wix/tutorial/getting-started/where-to-install/</a></p>
<pre><code><Property Id="INSTALLDIR">
<RegistrySearch Id='AcmeFoobarRegistry' Type='raw'
Root='HKLM' Key='Software\Acme\Foobar 1.0' Name='InstallDir' />
</Property>
</code></pre>
<p>Of course, you've got to set the registry key as part of the install too. Stick this inside a component that's part of the original install:</p>
<pre><code><RegistryKey
Key="Software\Software\Acme\Foobar 1.0"
Root="HKLM">
<RegistryValue Id="FoobarRegInstallDir"
Type="string"
Name="InstallDir"
Value="[INSTALLDIR]" />
</RegistryKey>
</code></pre>
|
<p>You don't really need to separate RegistryKey from RegistryValue in a simple case like this. Also, using HKMU instead of HKLM takes care of it whether you're doing a machine or user install.</p>
<pre><code><RegistryValue
Root="HKMU"
Key="Software\[Manufacturer]\[ProductName]"
Name="InstallDir"
Type="string"
Value="[INSTALLDIR]"
KeyPath="yes" />
</code></pre>
| 7,983
|
<p>I have a need to create a "transactional" process using an external API that does not support COM+ or .NET transactions (Sharepoint to be exact)</p>
<p>What I need to do is to be able to perform a number of processes in a sequence, but any failure in that sequence means that I will have to manually undo all of the previous steps. In my case there are only 2 types of step, both af which are fairly easy to undo/roll back.</p>
<p>Does anyony have any suggestions for design patterns or structures that could be usefull for this ?</p>
|
<p>If your changes are done to the SharePoint object model, you can use the fact that changes are not committed until you call the <code>Update()</code> method of the modified object, such as <code>SPList.Update()</code> or <code>SPWeb.Update()</code>.</p>
<p>Otherwise, I would use the <em>Command</em> Design Pattern. Chapter 6 in <a href="https://rads.stackoverflow.com/amzn/click/com/0596007124" rel="nofollow noreferrer" rel="nofollow noreferrer">Head First Design Patterns</a> even has an example that implements the undo functionality.</p>
|
<p>You might want to have a look at the Compensating Resource Manager:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/8xkdw05k(VS.80).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/8xkdw05k(VS.80).aspx</a></p>
| 4,217
|
<p>I'm considering the following: I have some data stream which I'd like to protect as secure as possible -- does it make any sense to apply let's say AES with some IV, then Blowfish with some IV and finally again AES with some IV?</p>
<p>The encryption / decryption process will be hidden (even protected against debugging) so it wont be easy to guess which crypto method and what IVs were used (however, I'm aware of the fact the power of this crypto chain can't be depend on this fact since every protection against debugging is breakable after some time).</p>
<p>I have computer power for this (that amount of data isn't that big) so the question only is if it's worth of implementation. For example, TripleDES worked very similarly, using three IVs and encrypt/decrypt/encrypt scheme so it probably isn't total nonsense. Another question is how much I decrease the security when I use the same IV for 1st and 3rd part or even the same IV for all three parts?</p>
<p>I welcome any hints on this subject</p>
|
<p>I'm not sure about this specific combination, but it's generally a bad idea to mix things like this unless that specific combination has been extensively researched. It's possible the mathematical transformations would actually counteract one another and the end result would be easier to hack. A single pass of either AES or Blowfish should be more than sufficient.</p>
<p>UPDATE: From my comment below…</p>
<p>Using TripleDES as an example: think of how much time and effort from the world's best cryptographers went into creating that combination (note that DoubleDES had a vulnerability), and the best they could do is 112 bits of security despite 192 bits of key.</p>
<p>UPDATE 2: I have to agree with Diomidis that AES is <em>extremely</em> unlikely to be the weak link in your system. Virtually every other aspect of your system is more likely to be compromised than AES.</p>
<p>UPDATE 3: Depending on what you're doing with the stream, you may want to just use <a href="http://en.wikipedia.org/wiki/Secure_Sockets_Layer" rel="noreferrer">TLS</a> (the successor to SSL). I recommend <a href="http://www.schneier.com/book-practical.html" rel="noreferrer">Practical Cryptography</a> for more details—it does a pretty good job of addressing a lot of the concerns you'll need to address. Among other things, it discusses <a href="http://en.wikipedia.org/wiki/Stream_cipher" rel="noreferrer">stream ciphers</a>, which may or may not be more appropriate than AES (since AES is a <a href="http://en.wikipedia.org/wiki/Block_cipher" rel="noreferrer">block cipher</a> and you specifically mentioned that you had a data stream to encrypt).</p>
|
<p>I agree with what has been said above. Multiple stages of encryption won't buy you much. If you are using a 'secure' algorithm then it is practically impossible to break. Using AES in some standard streaming mode. See <a href="http://csrc.nist.gov/groups/ST/toolkit/index.html" rel="nofollow noreferrer">http://csrc.nist.gov/groups/ST/toolkit/index.html</a> for accepted ciphers and modes. Anything recommended on that site should be sufficiently secure when used properly. If you want to be extra secure, use AES 256, although 128 should still be sufficient anyway. The greatest risks are not attacks against the algorithm itself, but rather attacks against key management, or side channel attacks (which may or may not be a risk depending on the application and usage). If you're application is vulnerable to key management attacks or to side channel attacks then it really doesn't matter how many levels of encryption you apply. This is where I would focus your efforts.</p>
| 14,613
|
<p>I set up a simple event handler as mentioned <a href="https://stackoverflow.com/questions/49510/how-do-you-set-your-cocoa-application-as-the-default-web-browser">here</a>, but it appears that the selector isn't called. I put the code in my AppDelegate class and wired up the delegate in IB. Tried putting in some NSLog()s and breakpoints in the selector I expect to be called, but none of it is hit. The URL scheme works inasmuch as it launches my app, but it doesn't do anything after that. Can anyone advise how to troubleshoot this? Thanks!</p>
|
<p>Well, I can't help but notice that you're <code>-init</code> method is mis-declared. If should have return type <code>id</code> and have a <code>return self;</code> at the end. </p>
<pre><code>- (id)init
{
self = [super init];
if (self) {
[[NSAppleEventManager sharedAppleEventManager] setEventHandler:self andSelector:@selector(getUrl:withReplyEvent:) forEventClass:kInternetEventClass andEventID:kAEGetURL];
}
return self;
}
</code></pre>
<p>With those fixes, I was able to paste those two routines into a test AppController class and have it print out the URLs (with a custom scheme) that I typed into Safari. I'd put a breakpoint on that -init method and step through it to make absolutely sure that -setEventHandler: method is getting called.</p>
|
<p>The big question is: Where are you calling NSAppleEventManager's -setEventHandler:...? You need to call this before your app finishes launching if you want to catch a URL that started your app. If your app delegate is created in your MainMenu.nib, then either its -init or -awakeFromNib methods will work, but, for example, -applicationDidFinishLaunching: won't. </p>
<p>Also, make sure that the selector you provide to -setEventHandler: is exactly the same as your method name, paying particular attention to capitalization and the proper number of colons.</p>
<p>Obviously, if you posted your app delegate's relevant code, it would be quite helpful.</p>
| 43,815
|
<p>I've played around with GTK, TK, wxPython, Cocoa, curses and others. They are are fairly horrible to use.. GTK/TK/wx/curses all seem to basically be direct-ports of the appropriate C libraries, and Cocoa basically mandates using both PyObjC and Interface Builder, both of which I dislike..</p>
<p>The Shoes GUI library for Ruby is great.. It's very sensibly designed, and very "rubyish", and borrows some nice-to-use things from web development (like using hex colours codes, or <code>:color => rgb(128,0,0)</code>)</p>
<p>As the title says: are there any nice, "Pythonic" GUI toolkits?</p>
|
<p>Have you looked at <a href="http://qt.io" rel="nofollow noreferrer">Qt</a>/<a href="http://www.riverbankcomputing.co.uk/software/pyqt/intro" rel="nofollow noreferrer">PyQt</a>? Although PyQt <em>is</em> a direct port from the C++ library, I find it much more pythonic and nice to program with compared to the others you listed. It also has very good documentation.</p>
<p><a href="http://dabodev.com/" rel="nofollow noreferrer">Dabo</a> has a nice ui library implemented on top of wxPython. It's a framework intended mostly for database-centric applications, but the ui library can be used separately. </p>
<p>There are/were several other attempts to create a very pythonic gui as a layer on top of PyGtk or wxPython, such as <a href="http://wiki.wxpython.org/Wax" rel="nofollow noreferrer">wax</a> and <a href="http://www.cosc.canterbury.ac.nz/greg.ewing/python_gui/" rel="nofollow noreferrer">PyGui</a>, which seem to be "stuck" at various degrees of being complete.</p>
<p>Also, an exhaustive list of Python GUI toolkits can be found <a href="http://wiki.python.org/moin/GuiProgramming" rel="nofollow noreferrer">here</a>.</p>
|
<p>I've used <a href="http://glade.gnome.org/" rel="nofollow noreferrer">Glade</a> with some success, though I didn't manage to wrap my head around creating anything really complex. It has a nice GUI builder and stores the forms as xml files that are loaded dynamically. Kind of like XAML afiak.</p>
| 5,652
|
<p>I assumed that the C# margin property had a meaning like in CSS - the spacing around the outside of the control. But Margin values seem to be ignored to matter what values I enter.</p>
<p>Then I read on the SDK: </p>
<blockquote>
<p>Setting the Margin property on a
docked control has no effect on the
distance of the control from the the
edges of its container.</p>
</blockquote>
<p>Given that I'm placing controls on forms, and perhaps docking them, what does the Margin property get me?</p>
|
<p>The margin property is used by whatever layout engine your control host (Panel, for example) is using, in whatever way that layout engine sees fit. However, it is best used for spacing just as you assume. Just read the documentation for that specific layout engine.</p>
<p>It can be very handy when using a FlowLayoutPanel or TableLayoutPanel, for example - to either reduce the default padding or space things out a bit. Obviously, if you write a custom layout provider, you can use Margin however you see fit.</p>
|
<p>Control.Margin property could be also useful at design time if you do not use layout container, but rather place controls manually.</p>
<p>It affects the distance between manually dragged controls at which <a href="https://stackoverflow.com/questions/1376622/change-spacing-of-snaplines-in-visual-studio#answer-15649647">snaplines appear</a>.</p>
<p>E.g. for default margin value of 3 for text box you would have this snaplines:</p>
<p><a href="https://i.stack.imgur.com/HR89v.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HR89v.png" alt="enter image description here"></a></p>
<p>And for margin of 10 - these (label has margin of 3 in both cases):</p>
<p><a href="https://i.stack.imgur.com/rlKfs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rlKfs.png" alt="enter image description here"></a></p>
<p>So if you have some strict guidelines for you UI then you just set the margins as you need and drag controls to the snaplines.</p>
| 10,143
|
<p>I've been reading up on this subject for a while. Suddenly the day has come where this solution is a necessity, not just a dream.</p>
<p>Through my reading, I've seen the popular differences being (file based, memcached, shared memory (mm), sql table, and custom).</p>
<p>The original idea we thought of was using a ZFS or AFS mounted on each of the application servers (LAMP boxes), and pointing the <code>session.save_path</code> php.ini setting to a directory from that mounted path.</p>
<p>I'd like to hear of success stories.</p>
|
<p>John Campbell's answer here should help</p>
<p><a href="https://stackoverflow.com/questions/76712">What is the best way to handle sessions for a PHP site on multiple hosts?</a></p>
<p>The point he makes about NOT using only Memcached is important.</p>
<p>Also, as I mentioned in that question, you may want to consider the session clustering that comes with Zend Platform - but there are significant licensing costs associated with that solution.</p>
|
<p>I think storing your sessions in a database (like MySQL or PostgreSQL) will involve the least headaches, especially if you already have a DB for whatever it is your app does.</p>
<p>Memcached may also help, since it can store data across multiple machines, but I don't have any experience with it.</p>
| 28,001
|
<p>Like any responsible developer, I'd like to make sure that the sites I produce are accessible to the widest possible audience, and that includes the significant fraction of the population with some form of colour blindness.</p>
<p>There are many websites which offer to filter a URL you feed it, either by rendering a picture or by filtering all content. However, both approaches seem to fail when rendering even moderately complex layouts, so I'd be interested in finding a client-side approach.</p>
<p>The ideal solution would be a system filter over the whole screen that can be used to test any program. The next best thing would be a browser plugin.</p>
|
<p>I came across <a href="http://colororacle.org/" rel="noreferrer">Color Oracle</a> and thought it might help. Here is the short description:</p>
<blockquote>
<p>Color Oracle is a colorblindness simulator for Windows, Mac and Linux. It takes the guesswork out of designing for color blindness by showing you in real time what people with common color vision impairments will see. </p>
</blockquote>
|
<p>I found <a href="http://www.coloursimulations.com/" rel="nofollow noreferrer">Colour Simulations</a> easy to use on Windows 10. This software can apply a color-blind filter to a part of the screen or the whole screen. And what's great is it allows me to interact with my PC normally as if it doesn't exist in fullscreen mode. It runs quite slow in my 4K screen using an integrated graphics card, though.</p>
| 24,872
|
<p>I've been developing a few JSF applications lately and am disturbed with the inconsistency in the web component APIs. </p>
<p>I've noticed that there is extremely unpredictable behavior when calling .getValue() or .getSubmittedValue() on a JSF component object in server side code. Sometimes when I call .getValue() on a drop down list box, I've noticed that I get the value as it was BEFORE I selected my value (so the value from the last page refresh), of which .getSubmittedValue() gets me the correct value, as such:</p>
<pre><code>UIInput name = new UIInput(); // This is the control I have in a bean.
public void submit(ActionEvent ae)
{
someMethod(name.getValue().toString()); // Retrieves the "old" value
someMethod(name.getSubmittedValue().toString()); // Retrieves the correct value
}
</code></pre>
<p>Also, I've noticed that calling .getSubmittedValue() on a form field sometimes results in a null pointer exception because that value has not been instantiated in the component object, in which case when I call .getValue() in that circumstance I get the correct value, for example:</p>
<pre><code>HtmlInputText name = new HtmlInputText(); // This is the control I have in a bean.
public void submit(ActionEvent ae)
{
someMethod(name.getValue().toString()); // Retrieves the correct value
someMethod(name.getSubmittedValue().toString()); // Throws NullPointerException
}
</code></pre>
<p>Is this just a "quirk" of the JSF framework, or am I just using the API <strong>COMPLETELY</strong> incorrectly?? Any insight into these two methods would be greatly appreciated. Cheers.</p>
|
<p>Since this is the #1 result in Google for searching on getValue vs. getSubmittedValue I'd just like to add that the difference between these is critical in validation (i.e. when writing a custom validator)</p>
<p>To quote the API documentation for getSubmittedValue():</p>
<blockquote>
<p>This is non-null only between decode
and validate phases, or when
validation for the component has not
succeeded. Once conversion and
validation has succeeded, the
(converted) value is stored in the
local "value" property of this
component, and the submitted value is
reset to null.</p>
</blockquote>
<p>Source: <a href="http://myfaces.apache.org/core11/myfaces-api/apidocs/javax/faces/component/UIInput.html#getSubmittedValue()" rel="noreferrer"><a href="http://myfaces.apache.org/core11/myfaces-api/apidocs/javax/faces/component/UIInput.html#getSubmittedValue()" rel="noreferrer">http://myfaces.apache.org/core11/myfaces-api/apidocs/javax/faces/component/UIInput.html#getSubmittedValue()</a></a></p>
<p>This means that if the validation/conversion has taken place for the binding you are trying to access, you should call getValue() otherwise you'll have to call getSubmittedValue() and deal with parsing it yourself. The order in which these occur seems to be dictated by the order they appear in the UI, but I don't think that's guaranteed. Even if it is, you shouldn't count on that as changing field in your UI shouldn't break your code.</p>
<p>You can detect if the validation/conversion has been done by just looking at what isLocalValueSet() returns. If it returns true, then the valdation/conversion has been done, so you should call getValue(). Otherwise you'll need to call getSubmittedValue() and that'll give you the raw input the user entered and you'll likely want to parse it into something more meaningful.</p>
<p>For example, a calendar object would return a Date object when getValue() was called, but a String object when getSubmittedValue() was called. It's up to your converter to parse the string into a Date so it can be validated.</p>
<p>It'd be great if the JSF spec had a method which would do this for us, but AFAIK it doesn't. If certain dates need to be before other dates, and some are only required in certain circumstances, one will need to write several validators to handle this. So it can easily become an issue. This is similar to the fact that you can't do any kind of validation on a blank field, which means you can't make that field conditionally required. If validation was run on all fields, even blank ones, a custom validator could be written to throw an exception if it should be required and is not. There are some things with JSF which are just a pain; unless/until they're fixed, we just have to deal with them.</p>
<p><p>To speak to the specifics of the issue in the original post: the difference here is where you're at in the life cycle. The <code>submit</code> method seems like an action listener for a button, which puts it at the end of the life cycle; actions and action listeners are triggered in the "Invoke Application" phase which comes prior to the render response, but after validation. If you're going to program in JSF, you should learn and understand the life cycle. It's worth the time.</p>
|
<p>I work on xpages which are based on JSF so.. it could be the same...</p>
<p>Anyway, getSubmittedValue(); always returns what you see in firebug/chrome develepers network tab. That is value within sent packet. I have it shown (chrome) in headers tab, in form data section, named $$xspsubmitvalue.</p>
<p>On the other hand, getValue() is component specific. <-- not 100% sure here.</p>
| 32,502
|
<p>Is there a way to turn off the automatic selection of the first row in the built-in DataGrid in Silverlight?</p>
<p>We build a lot of functionality based off the user selecting a row in a data grid. The automatic firing of SelectionChanged when databinding or sorting is really causing us issues. We have tried to put some guards around the selection, but can't seem get all problems covered.</p>
<p>For example, if you have DataGrid in a tab of a TabControl that is not shown when loading the screen and the DataGrid has a binding to a property of the DataContext that is a list of objects. The grid is not databound until the tab is shown. Is there an event telling us that the grid is databinding? Shouldn't the default behavior of databinding be not to select a row?</p>
<p>Thanks
Mike</p>
|
<p>Have you tried setting a boolean field (ex. bool dataGridFirstLoad) which you set to false in your User Control's constructor.</p>
<p>Then on the SelectionChanged event of the DataGrid, check if dataGridFirstLoad is false. If false set to true and set the SelectedItem to null.</p>
<p>Hope this helps.</p>
|
<p>The code below should do it (set JustRefreshed to true whenever you update/refresh the grid):</p>
<pre><code> int LastSelectedIndex = -1;
bool JustRefreshed = false;
private void dataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (JustRefreshed)
{
JustRefreshed = false;
dataGrid.SelectedIndex = LastSelectedIndex;
return;
}
if (e.AddedItems.Count > 0)
{
LastSelectedIndex = dataGrid.SelectedIndex;
}
//Your logic comes here...
}
}
</code></pre>
| 38,301
|
<p>I'm migrating a TSQL stored procedure to PL/SQL and have encountered a problem - the lack of a CONTINUE keyword in Oracle 10g.</p>
<p>I've read that Oracle 11g has this as a new feature, but upgrading is not an option unfortunately.</p>
<p>Is there any alternative to CONTINUE in 10g? I don't believe it's practical to restructure the logic of the SP as a work-around, because I have an outer loop, an IF, then a nested IF, then the CONTINUE at the end of a statement block within that IF.</p>
<p>Any help would be greatly appreciated, cheers.</p>
|
<p>You can simulate a continue using <a href="http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/controlstructures.htm#BCGFGDAA" rel="noreferrer">goto and labels</a>.</p>
<pre><code>DECLARE
done BOOLEAN;
BEGIN
FOR i IN 1..50 LOOP
IF done THEN
GOTO end_loop;
END IF;
<<end_loop>> -- not allowed unless an executable statement follows
NULL; -- add NULL statement to avoid error
END LOOP; -- raises an error without the previous NULL
END;
</code></pre>
|
<p>In Oracle there is a similar statement called EXIT that either exits a loop or a function/procedure (if there is no loop to exit from). You can add a WHEN to check for some condition.</p>
<p>You could rewrite the above example as follows:</p>
<pre><code>DECLARE
done BOOLEAN;
BEGIN
FOR i IN 1..50 LOOP
EXIT WHEN done;
END LOOP;
END;
</code></pre>
<p>This may not be enough if you want to exit from deep down some nested loops and logic, but is a lot clearer than a couple of GOTOs and NULLs.</p>
| 21,419
|
<p>I'm considering Altova MapForce (or something similar) to produce either XSLT and/or a Java or C# class to do the translation. Today, we pull data right out of the database and manually build an XML string that we post to a webservice. </p>
<p>Should it be db -> (internal)XML -> XSLT -> (External)XML? What do you folks do out there in the wide world?</p>
|
<p>I would use one of the out-of-the-box XML serialization classes to do your internal XML generation, and then use XSLT to transform to the external XML. You might generate a schema as well to enforce that the translation code (whatever will drive your XSLT translation) continues to get the XML it is expecting for translation in case of changes to the object breaks things.</p>
<p>There are a number of XSLT editors on the market that will help you do the mappings, but I prefer to just use a regular XML editor.</p>
|
<p>What database are you using? Oracle has some nice XML mapping tools. There are some Java binding tools (one is <a href="http://java.sun.com/developer/technicalArticles/WebServices/jaxb" rel="nofollow noreferrer">http://java.sun.com/developer/technicalArticles/WebServices/jaxb</a>). However, if you have the luxory consider using Ruby which has nice built-in "to_xml" methods.</p>
| 10,501
|
<p>I have a function which gets a key from the user and generates a Hashtable (on a pattern specified by the key). After creating a Hashtable, I would like to populate a JTable so that each each column represents a key and every rows represents the values associated with the key. I tried everything but couldn't get this work. I'm not creating the table from within the constructor as I need to get input from the user.</p>
|
<p>See <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#data" rel="nofollow noreferrer">How to Use Tables: Creating a Table Model</a>.</p>
<blockquote>
<p>The JTable constructor used by
SimpleTableDemo creates its table
model with code like this:</p>
</blockquote>
<pre><code>new AbstractTableModel() {
public String getColumnName(int col) {
return columnNames[col].toString();
}
public int getRowCount() { return rowData.length; }
public int getColumnCount() { return columnNames.length; }
public Object getValueAt(int row, int col) {
return rowData[row][col];
}
public boolean isCellEditable(int row, int col)
{ return true; }
public void setValueAt(Object value, int row, int col) {
rowData[row][col] = value;
fireTableCellUpdated(row, col);
}
}
</code></pre>
<p>You basically have to wrap your hashtable in the above manner. Here's an example.</p>
<pre><code>package eed3si9n.hashtabletable;
import java.awt.BorderLayout;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.JButton;
import java.awt.Dimension;
public class MainForm extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel jContentPane = null; // @jve:decl-index=0:visual-constraint="23,38"
private JScrollPane m_scrollPane = null;
private JTable m_table = null;
private Hashtable<String, String> m_hash = null;
private JButton m_btnAdd = null;
/**
* This is the default constructor
*/
public MainForm() {
super();
initialize();
m_hash = new Hashtable<String, String>();
m_hash.put("Dog", "Bow");
}
private void onButtonPressed() {
m_hash.put("Cow", "Moo");
m_table.revalidate();
}
/**
* This method initializes this
*
* @return void
*/
private void initialize() {
this.setSize(409, 290);
this.setTitle("JFrame");
this.setContentPane(getJContentPane());
}
/**
* This method initializes jContentPane
*
* @return javax.swing.JPanel
*/
private JPanel getJContentPane() {
if (jContentPane == null) {
jContentPane = new JPanel();
jContentPane.setLayout(new BorderLayout());
jContentPane.setSize(new Dimension(500, 500));
jContentPane.setPreferredSize(new Dimension(500, 500));
jContentPane.add(getM_scrollPane(), BorderLayout.NORTH);
jContentPane.add(getM_btnAdd(), BorderLayout.SOUTH);
}
return jContentPane;
}
/**
* This method initializes m_scrollPane
*
* @return javax.swing.JScrollPane
*/
private JScrollPane getM_scrollPane() {
if (m_scrollPane == null) {
m_scrollPane = new JScrollPane();
m_scrollPane.setViewportView(getM_table());
}
return m_scrollPane;
}
/**
* This method initializes m_table
*
* @return javax.swing.JTable
*/
private JTable getM_table() {
if (m_table == null) {
m_table = new JTable();
m_table.setModel(new AbstractTableModel(){
private static final long serialVersionUID = 1L;
public int getColumnCount() {
return 2;
}
public int getRowCount() {
return m_hash.size();
}
public String getColumnName(int column) {
if (column == 0) {
return "Animal";
} else {
return "Sound";
}
}
public Object getValueAt(int rowIndex, int columnIndex) {
if (columnIndex == 0) {
return getKey(rowIndex);
} else {
return m_hash.get(getKey(rowIndex));
} // if-else
}
private String getKey(int a_index) {
String retval = "";
Enumeration<String> e = m_hash.keys();
for (int i = 0; i < a_index + 1; i++) {
retval = e.nextElement();
} // for
return retval;
}
});
}
return m_table;
}
/**
* This method initializes m_btnAdd
*
* @return javax.swing.JButton
*/
private JButton getM_btnAdd() {
if (m_btnAdd == null) {
m_btnAdd = new JButton();
m_btnAdd.setPreferredSize(new Dimension(34, 30));
m_btnAdd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
onButtonPressed();
}
});
}
return m_btnAdd;
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
MainForm frame = new MainForm();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setVisible(true);
}
});
}
} // @jve:decl-index=0:visual-constraint="10,10"
</code></pre>
|
<p>Firstly, avoid <code>Hashtable</code>, go straight for <code>Map</code>. In this case there two potential standard implementations you mights want: <code>LinkedHashMap</code> can retain the order that the entries were added; <code>TreeMap</code>, a <code>SortedMap</code>/<code>NavigableMap</code>, will sort the results (order of which can be determined by a <code>Comparator</code>. Alternatively you might want a form of <code>Map</code> that fire events or also provides a <code>TableModel</code>.</p>
<p>If you want a one time conversion from the <code>Map</code> to table, then it's pretty straightforward.</p>
<pre><code>public static TableModel toTableModel(Map<?,?> map) {
DefaultTableModel model = new DefaultTableModel(
new Object[] { "Key", "Value" }, 0
);
for (Map.Entry<?,?> entry : map) {
model.addRow(new Object[] { entry.getKey(), entry.getValue() });
}
return model;
}
</code></pre>
<p>Then just create the <code>JTable</code> with this pre-populated model.</p>
<p>(Disclaimer: I've not tested or so much as compiled this code.)</p>
<p>To keep the <code>Map</code> and <code>TableModel</code> synchronized is more code. Generally it's best to avoid duplicating state whereever possible. Write a class that exposes itself as both a <code>Map</code> and a <code>TableModel</code>. You could go more disjoint by having a <code>Map</code> that fires events and a <code>TableModel</code> that adapts the <code>Map</code> (although note that <code>Map</code> does not have random access based on index, so you'll need to be iether clever or slow for large maps).</p>
<p>Going the other way, a simpler approach would be to add the data straight to a <code>DefaultTableModel</code> and not using a <code>Map</code> at all.</p>
| 37,293
|
<p>When working with window handles, is it <em>good</em> enough to use the plain <strong>IntPtr</strong> or should I subclass <strong>SafeHandle</strong>?</p>
<p>Are there any significant pros/cons?</p>
<p>Thanks.</p>
|
<p>That depends :)</p>
<p>If the handle is returned in such a way that you must eventually call a version of ::CloseHandle on them then you should always subclass SafeHandle. SafeHandle makes the strongest guarantee possible in the .Net Framework that a handle will be freed. Not freeing an IntPtr will lead to a resource leak. Enough resource leaks will eventually lead to a program crash. </p>
<p>If the handle doesn't need to be freed then passing around IntPtr is sufficient. </p>
|
<p>That depends :)</p>
<p>If the handle is returned in such a way that you must eventually call a version of ::CloseHandle on them then you should always subclass SafeHandle. SafeHandle makes the strongest guarantee possible in the .Net Framework that a handle will be freed. Not freeing an IntPtr will lead to a resource leak. Enough resource leaks will eventually lead to a program crash. </p>
<p>If the handle doesn't need to be freed then passing around IntPtr is sufficient. </p>
| 37,631
|
<p>I am looking for ways to keep track of simultaneous users within an application. I cannot use IIS logs due to a load balancer that abstracts the users IP address. I am looking for a .NET code based solution or a configuration item, possibly with health monitoring to be able to track the "true" simultaneous user count.</p>
<p>I know that I can monitor the number of sessions, but that isn't really an ideal method to show, as it can be bloated based on the number of sessions with users abandoning their session.</p>
|
<p>There is a similiar question here: <a href="https://stackoverflow.com/questions/259105/tools-and-methods-for-live-monitoring-aspnet-web-applications">Tools and methods for live-monitoring ASP.NET web applications?</a></p>
<p>I found an advanced logging tool for debugging and monitoring .NET applications: <a href="http://www.gurock.com/products/smartinspect/" rel="nofollow noreferrer">SmartInspect</a>. But I don't know if it meets your requirements.</p>
|
<p>You just want to know the number of active users at a particular time? An easy option that omits inactive users as well as most bots would be to register the user as active through a JavaScript AJAX call on page load along with their SessionID. You can then purge old records from the log as you see fit. *Be careful of how you build your table's performance for read/write optimizations. ... just an idea off the top of my head.</p>
| 48,191
|
<p>So I have a User model that :has_many other models like Documents, Videos, Posts and the like. My question arises when I execute a "do" block from the User model like so:</p>
<pre><code>has_many :posts do
def recent
find(:all, :order => 'created_at desc', :limit => 12)
end
end
</code></pre>
<p>This just lets me call something like user.posts.recent to find only those posts associated with the User. With this in place, how can I still add a :dependent => :destroy or :dependent => :delete_all to this association? Everything I have tried so far has errored out on me.</p>
|
<p>It looks like you should take a look at using <a href="http://railscasts.com/episodes/108" rel="nofollow noreferrer">named_scope</a>.</p>
<p>There's no reason why you should have a do block against your association.</p>
<p>You you should turn that recent method into a named scope and you can then tack on :dependent => destroy etc etc.</p>
<p>Good luck!</p>
|
<p>This should work just fine AFAIK:</p>
<pre><code>has_many :posts, :dependent => :destroy do
def recent
find(:all, :order => 'created_at desc', :limit => 12)
end
end
</code></pre>
| 35,729
|
<p>Using 3D printing I'd like to create a text oversized keycap that uses several strong LEDs to make the text light as red or green, depending on status. It's quite similar to what are called annunciators on aircraft:</p>
<p><a href="https://i.stack.imgur.com/6B1lY.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/6B1lY.jpg" alt="Annunciator Panel example without the panels being turned into MX switch keycaps" /></a></p>
<p><a href="https://i.stack.imgur.com/Jce1q.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/Jce1q.jpg" alt="Annunciator removed from a panel where it is separated" /></a></p>
<p>I'd like to create an MX keycap with this ability and size with the backlighting changing from green to red to indicate something is on or off. I understand including the MX connector in the center, but how would I print a black panel and leave the text transparent, or at least transluscent?</p>
|
<p>There are a few possible ways you could go about this:</p>
<ol>
<li>If you have a multi-material printer, you may be able to print with both a transparent or translucent material for the internal structure of the print and an opaque material for the external parts of the print. PET(G) may be suitable for this purpose but is harder to print compared to standard PLA.</li>
<li>You can print the entire print in a translucent material, mask off the lettering at the front and spray paint the rest of the print.</li>
<li>You can create a multi-part print, where one outer 'shell' is printed in opaque filament, and another piece in translucent material, which will mate together after printing.</li>
<li>You can deboss the lettering of your print, and with the letters face down to the bed, print the first layers in an opaque material, and then swap filaments to a translucent material for the rest of the print, spray painting the upper parts of the print to match a uniform color, while leaving the bottom untouched.</li>
</ol>
<p>There are several advantages and disadvantages to each method:</p>
<ol>
<li>Requires that you have a (typically) expensive upgrade installed onto your machine, but would be the most straightforward way to go about this.</li>
<li>Requires precise masking of your letters to make them come out looking nice, but will give you sharper, more defined edges on the lettering.</li>
<li>Will require you to design for tolerances for the two parts, or add glue in the post-processing steps, But could be produced en masse with two printers, one for each material.</li>
<li>Can be a bit fiddly, and will possibly result in an undesired look, with the lettering being debossed into the part, But would be less complex than the other options.</li>
</ol>
<p>Pick whichever method you wish, or try all of them to see which gives you the best results.</p>
|
<p>Cut the letters out of the key, so they print as holes all the way to the light source. Print in black.</p>
<p>fill the holes with clear silicon caulk or leave empty.</p>
| 2,007
|
<p>I am sorry, my question is stupid, but I am not able to answer it, as a java illiterate. I run a tomcat (5) on CentOS5 (for a CAS server), and when I try to open this URL <a href="http://192.168.1.17:8080/cas-server-webapp-3.3.1/login" rel="nofollow noreferrer">http://192.168.1.17:8080/cas-server-webapp-3.3.1/login</a> I get this error : </p>
<p>first error:
java.lang.NoClassDefFoundError: Could not initialize class <strong>org.springframework.webflow.util.RandomGuid</strong></p>
<p>and root error:
org.springframework.web.util.NestedServletException: Handler processing failed; nested exception is java.lang.NoClassDefFoundError: Could not initialize class org.springframework.webflow.util.RandomGuid</p>
<p>$CLASSPATH is empty, and it seems to be a problem, but I don't know what to put in it.</p>
<p>EDIT: Jared is right, my hosts files defined 127.0.0.1 as localhost, and now it work very well!</p>
|
<p>It is important to keep two or three different exceptions strait in our head in this case:</p>
<ol>
<li><p><strong><code>java.lang.ClassNotFoundException</code></strong> This exception indicates that the class was not found on the classpath. This indicates that we were trying to load the class definition, and the class did not exist on the classpath.</p></li>
<li><p><strong><code>java.lang.NoClassDefFoundError</code></strong> This exception indicates that the JVM looked in its internal class definition data structure for the definition of a class and did not find it. This is different than saying that it could not be loaded from the classpath. Usually this indicates that we previously attempted to load a class from the classpath, but it failed for some reason - now we're trying again, but we're not even going to try to load it, because we failed loading it earlier. The earlier failure could be a ClassNotFoundException or an ExceptionInInitializerError (indicating a failure in the static initialization block) or any number of other problems. The point is, a NoClassDefFoundError is not necessarily a classpath problem.</p></li>
</ol>
<p>That being said, another answer poster indicates that the RandomGUID requires a call to InetAddress.getLocalHost(). On many operating systems, this would trigger a host lookup that would use the hosts file (<code>/etc/hosts</code> on *NIX systems, <code>%WINDOWS%/system32/drivers/etc/HOSTS</code> on a Windows system.) </p>
<p>I have seen similar errors quite frequently when that file incorrectly defines the localhost address. <code>127.0.0.1</code> should point to 'localhost' (and probably also <code>localhost.localdomain</code>.) It should <strong>NOT</strong> point to the actual host name of the machine (although for some reason, many older RedHat Linux installers liked to set it incorrectly.)</p>
|
<p>If this appeared suddenly and unlogically to what you've been constructing, try renaming and renaming back classes that are referenced in an error log. This helped me in Netbeans several times.</p>
| 49,114
|
<p>Can you suggest some ways/tips to decrease Resharper memory usage in VS 2008. Working set memory for my VS with 50 projects is around 650mb+ </p>
<p><strong>Edit:</strong> Now that 4.5 is out, this question is no longer relevant.</p>
|
<p>That doesn't sound like a completely unreasonable amount of memory when you've got <em>50</em> projects, Do they really all need to be in the same solution? If so, can you not just get more memory? While there may be ways of decreasing the R# memory use (disable its code analysis?) I suspect it won't make <em>that</em> much difference. I suspect in the end you'll have to accept that a modern IDE with a massive solution requires a powerful machine.</p>
|
<p>650mb+ isn't abnormal, i have solution with 15 projects and 1k files and VS+ReSharper use 500mb (only ReSharper use 153mb)</p>
<p>Try this for show how much memory ReSharper use
ReSharper -> Options -> General -> Show managed memory usage in status bar</p>
| 26,374
|
<p>I quite often see on the Internet various complaints that other peoples examples of currying are not currying, but are actually just partial application.</p>
<p>I've not found a decent explanation of what partial application is, or how it differs from currying. There seems to be a general confusion, with equivalent examples being described as currying in some places, and partial application in others.</p>
<p>Could someone provide me with a definition of both terms, and details of how they differ?</p>
|
<p>Currying is converting a single function of <em>n</em> arguments into <em>n</em> functions with a single argument each. Given the following function:</p>
<pre><code>function f(x,y,z) { z(x(y));}
</code></pre>
<p>When curried, becomes:</p>
<pre><code>function f(x) { lambda(y) { lambda(z) { z(x(y)); } } }
</code></pre>
<p>In order to get the full application of f(x,y,z), you need to do this:</p>
<pre><code>f(x)(y)(z);
</code></pre>
<p>Many functional languages let you write <code>f x y z</code>. If you only call <code>f x y</code> or <em>f(x)(y)</em> then you get a partially-applied function—the return value is a closure of <code>lambda(z){z(x(y))}</code> with passed-in the values of x and y to <code>f(x,y)</code>. </p>
<p>One way to use partial application is to define functions as partial applications of generalized functions, like <strong>fold</strong>:</p>
<pre><code>function fold(combineFunction, accumulator, list) {/* ... */}
function sum = curry(fold)(lambda(accum,e){e+accum}))(0);
function length = curry(fold)(lambda(accum,_){1+accum})(empty-list);
function reverse = curry(fold)(lambda(accum,e){concat(e,accum)})(empty-list);
/* ... */
@list = [1, 2, 3, 4]
sum(list) //returns 10
@f = fold(lambda(accum,e){e+accum}) //f = lambda(accumulator,list) {/*...*/}
f(0,list) //returns 10
@g = f(0) //same as sum
g(list) //returns 10
</code></pre>
|
<p>In writing this, I confused currying and uncurrying. They are inverse transformations on functions. It really doesn't matter what you call which, as long as you get what the transformation and its inverse represent.</p>
<p>Uncurrying isn't defined very clearly (or rather, there are "conflicting" definitions that all capture the spirit of the idea). Basically, it means turning a function that takes multiple arguments into a function that takes a single argument. For example,</p>
<pre><code>(+) :: Int -> Int -> Int
</code></pre>
<p>Now, how do you turn this into a function that takes a single argument? You cheat, of course!</p>
<pre><code>plus :: (Int, Int) -> Int
</code></pre>
<p>Notice that plus now takes a single argument (that is composed of two things). Super!</p>
<p>What's the point of this? Well, if you have a function that takes two arguments, and you have a pair of arguments, it is nice to know that you can apply the function to the arguments, and still get what you expect. And, in fact, the plumbing to do it already exists, so that you don't have to do things like explicit pattern matching. All you have to do is:</p>
<pre><code>(uncurry (+)) (1,2)
</code></pre>
<p>So what is partial function application? It is a different way to turn a function in two arguments into a function with one argument. It works differently though. Again, let's take (+) as an example. How might we turn it into a function that takes a single Int as an argument? We cheat!</p>
<pre><code>((+) 0) :: Int -> Int
</code></pre>
<p>That's the function that adds zero to any Int.</p>
<pre><code>((+) 1) :: Int -> Int
</code></pre>
<p>adds 1 to any Int. Etc. In each of these cases, (+) is "partially applied".</p>
| 26,812
|
<p>I am working on modifying an existing spell check plugin for TinyMCE. </p>
<p>This is what is supposed to happen:
1. User hits "space" and the spell check runs.
2. If the word is spelled wrong the word gets wrapped with a span and gets a red underline</p>
<p>what I find happening is that when the user hits space bar the word does get spell checked but the cursor pops back to the end of the word just typed (instead of to where the space is) (you can see this in action at <a href="http://mail.solidhouse.com/webmail2/test.html" rel="nofollow noreferrer">http://mail.solidhouse.com/webmail2/test.html</a>)</p>
<p>here is my pseudcode:
var b = this.editor.selection.getBookmark();
//for each node
node.nodeValue.replace(r5, '$1$2');
this.editor.selection.moveToBookmark(b);</p>
<p>what I am suspecting is that moveToBookmark keeps the cursor within the element but I have no idea what to do to remedy this.</p>
<p>(I have tried incrementing b.start and b.end but that did not work)</p>
<p>I know this is hard to explain. Any thoughts on this are greatly appreciated. </p>
|
<p>try incrementing the bookmark start/end by 2 instead of 1 if you haven't already. since the underline adds a tag around the mispelled words, that's an additional 2 places that need to be accounted for in the bookmark: 1 for each side of the span.</p>
|
<p>Can you get yourself out of the element by grabbing its parent?</p>
<pre><code>this.parentNode.moveToBookmark(b);
</code></pre>
<p>Or something like that.</p>
| 37,058
|
<p>If I check out a tagged version of my source code without creating a branch, Git indicates that I'm not associated with any branch at all. It's happy to let me make changes and check them in though. Where do those changes go? If I switch back to 'master' they disappear (overwritten by what was in master) and I can't seem to find them again. What gives? If Git lets me commit changes against what's essentially an anonymous branch, surely I can get them back?</p>
|
<p>Because your <strong>commit isn't on any branch</strong>, you can't see it in the working directory unless you checkout that specific commit, using its SHA1. You can find the commit by looking at the <code>reflog</code> which tracks changes in what you have checked out from the repo. If your tag was <code>XXX</code> you'll see something like:</p>
<pre><code>$ git reflog
7a30fd7... HEAD@{0}: checkout: moving from master to XXX
ddf751d... HEAD@{1}: checkout: moving from 96c3b0300ccf16b64efc260c21c85ba9030f2e3a to master
96c3b03... HEAD@{2}: commit: example commit on tag XXX, not on any branch
7a30fd7... HEAD@{3}: checkout: moving from master to XXX
</code></pre>
<p>That tells you the SHA1 that you would have to <code>checkout</code> in order to see your commit in the working directory. </p>
<pre><code>$ git checkout 96c3b03
Note: moving to "96c3b03" which isn't a local branch
If you want to create a new branch from this checkout, you may do so
(now or later) by using -b with the checkout command again. Example:
git checkout -b <new_branch_name>
HEAD is now at 96c3b03... example commit on tag XXX, not on any branch
$ git checkout -b newbranch
$ git branch #lists all branches
feature1
master
* newbranch
</code></pre>
<p>This all seemed a little weird to me at first, until I realized that git <code>checkout</code> places all the project files <em>as of a particular commit</em> into my file system (working directory). In effect, the working directory acts as a browser on the local Git repository. So your changes haven't been overwritten <em>in the repository</em>, they're just not being shown in your working directory when you've checked out the master.</p>
|
<p>To answer the second question you'd use git reset --hard yourtagname </p>
<p>As for what would happen you essentially forked your branch at the tagname and stayed on the same branch. Your commits in the old fork are still there... they're just hard to see. You might have to use the reflog to find the old fork. </p>
| 47,786
|
<p>I've been a PHP developer for many years now, with many tools under my belt; tools that I've either developed myself, or free-to-use solutions that I have learned to trust.</p>
<p>I looked into CodeIgniter recently, and discovered that they have many classes and helper routines to aid with development, yet saw nothing in the examples that I couldn't do just as easily with my own tools. Simple things like DB abstractions, Email helpers, etc. There was some interesting code relating to routes - mapping urls to the right controllers; but even that's not particularly difficult to code yourself if you've ever written an MVC style web app with pretty urls.</p>
<p>Even after looking through some of the other popular frameworks, I still see nothing that would be <strong>that</strong> much of a time-saver. Even looking at the forums, I see people struggling to get the tools to work for them. I do understand how they would be more useful for junior developers, since full system design skills take a while to understand and appreciate fully.</p>
<p>Yet, I'm often told that I should use an off-the-shelf framework to produce my solutions, but I still remain unconvinced. What's the real benefit to someone like myself? Am I just being elitist, or is this a common opinion?</p>
<p>Edit: Looking at some of the answers here, should I perhaps consider packaging up my toolset as its very own framework, writing some documentation and posting tutorials? If I'm hesitant to take on other's frameworks, would opening it up and getting more eyes on it help to improve my own skills/tools?</p>
|
<p>Frameworks have several advantages:</p>
<ul>
<li><p>You don't have to write everything. In your case, this is less of a help because you have your own framework which you have accumulated over the years.</p></li>
<li><p>Frameworks provide standardized and tested ways of doing things. The more users there are of a given framework, the more edge cases that have been encountered and coded for. Your own code may, or may not, be battle hardened in the same way.</p></li>
<li><p>Others can be recruited onto a project with a standard framework and have access to the documentation, examples and experience with that framework. Your own snippets may or may not be fully documented or have examples of use... but isn't much chance that others are comfortable with them initially.</p></li>
</ul>
<p>EDIT: </p>
<p>With regards to your idea of packaging up your own framework, the benefit of cleaning it up for public consumption can be larger than the benefit of getting others to use it.</p>
<p>The reason is simple: you will have to re-evaluate your assumptions about each component, how they fit together and how clear each piece is to understand. Once you publish your framework, your success will be strongly dependent on how easy it is to get up and running with. </p>
<p>Big wins with little effort are essential for adoption (those wins will encourage people to delve further into the framework). Ruby on Rails in an example of a framework that gives such big wins with little effort, and then has hidden layers of features that would have overwhelmed someone just getting started. (The question of the quality of RoR apps is not the point, the point is about adoption speed).</p>
<p>After people adopt a framework, it is about the ease of continued use. Little details like consistent parameter use patterns make all the difference here. If one class has many parameters on every method, while another has setters that are expected to be called before invoking methods, you will lose users because they can't get a "feel" for what is expected in a given case without resorting to the documents.</p>
<p>If both ease-of-adoption and ease-of-living-with issues are addressed properly, you only have to get lucky for people to adopt your framework. If those issues are not addressed properly, even an initial interest in the framework will wane quickly. The reason is that there are <em>many</em> frameworks: you will need to stand out to gain the advantages of having others using your kit (as they rightfully are as wary of <em>your</em> framework as you are of others).</p>
|
<p>Advantages are that it's already written and tested by multiple people therefore less likely to be bug prone. </p>
<p>Disadvantages are that it's not built specifically for your application and therefore will most likely perform worse.</p>
<p>All in all, I can't really see much reason to use one considering you already have your own...although it may be worth releasing that open source so others are able to bug check and recommend improvements.</p>
| 35,235
|
<p>I have a form in which people will be entering dollar values.</p>
<p>Possible inputs:<br>
$999,999,999.99<br>
999,999,999.99<br>
999999999<br>
99,999<br>
$99,999<br></p>
<p>The user can enter a dollar value however they wish. I want to read the inputs as doubles so I can total them.</p>
<p>I tried just typecasting the strings to doubles but that didn't work. Total just equals 50 when it is output:</p>
<pre><code>$string1 = "$50,000";
$string2 = "$50000";
$string3 = "50,000";
$total = (double)$string1 + (double)$string2 + (double)$string3;
echo $total;
</code></pre>
|
<p>A regex won't convert your string into a number. I would suggest that you use a regex to validate the field (confirm that it fits one of your allowed formats), and then just loop over the string, discarding all non-digit and non-period characters. If you don't care about validation, you could skip the first step. The second step will still strip it down to digits and periods only.</p>
<p>By the way, you cannot safely use floats when calculating currency values. You will lose precision, and very possibly end up with totals that do not exactly match the inputs.</p>
<p>Update: Here are two functions you could use to verify your input and to convert it into a decimal-point representation.</p>
<pre><code>function validateCurrency($string)
{
return preg_match('/^\$?(\d{1,3})(,\d{3})*(.\d{2})?$/', $string) ||
preg_match('/^\$?\d+(.\d{2})?$/', $string);
}
function makeCurrency($string)
{
$newstring = "";
$array = str_split($string);
foreach($array as $char)
{
if (($char >= '0' && $char <= '9') || $char == '.')
{
$newstring .= $char;
}
}
return $newstring;
}
</code></pre>
<p>The first function will match the bulk of currency formats you can expect "$99", "99,999.00", etc. It will not match ".00" or "99.", nor will it match most European-style numbers (99.999,00). Use this on your original string to verify that it is a valid currency string.</p>
<p>The second function will just strip out everything except digits and decimal points. Note that by itself it may still return invalid strings (e.g. "", "....", and "abc" come out as "", "....", and ""). Use this to eliminate extraneous commas once the string is validated, or possibly use this by itself if you want to skip validation.</p>
|
<p><a href="http://p2p.wrox.com/topic.asp?TOPIC_ID=3099" rel="nofollow noreferrer">http://p2p.wrox.com/topic.asp?TOPIC_ID=3099</a></p>
<p>goes through it step by step</p>
<p>[edit] typical...the site seems to be down now... :(</p>
| 16,269
|
<p>The SQL-LDR documentation states that you need to do a convetional Path Load:</p>
<blockquote>
<p>When you want to apply SQL functions
to data fields. SQL functions are not
available during a direct path load</p>
</blockquote>
<p>I have TimeStamp data stored in a CSV file that I'm loading with SQL-LDR by describing the fields as such:</p>
<pre><code>STARTTIME "To_TimeStamp(:STARTTIME,'YYYY-MM-DD HH24:MI:SS.FF6')",
COMPLETIONTIME "To_TimeStamp(:COMPLETIONTIME,'YYYY-MM-DD HH24:MI:SS.FF6')"
</code></pre>
<p>So my question is: Can you load timestamp data without a function, or is it the case that you can not do a Direct Path Load when Loading TimeStamp data?</p>
|
<p>As blowdart said, simple IP Address logging is handled by IIS already. Simply right-click on the Website in Internet Information Services (IIS) Manager tool, go to the Web Site tab, and check the Enable Logging box. You can customize what information is logged also. </p>
<p>If you want to restrict the site or even a folder of the site to specific IP's, just go to the IIS Site or Folder properties that you want to protect in the IIS Manager, right click and select Properties. Choose the Directory Security tab. In the middle you should see the "IP Addresses and domain name restrictions. This will be where you can setup which IP's to block or allow.</p>
<p>If you want to do this programatically in the code-behind of ASP.Net, you could use the page preinit event.</p>
|
<p>A little more information please; do you want to log IPs or lock access via IP? Both those functions are built into IIS rather than ASP.NET; so are you looking for how to limit access via IP programatically?</p>
| 13,035
|
<p>Is there a way to change the use of an extruder port on a 3D printer motherboard to move stepper motors (on y axis) on a 3D printer?</p>
<p>This is for a school project, and we have replaced the extruder with a laser for cutting material.</p>
<p>We were tasked with converting a 3D printer into LOM 3D printer, the laser is set using the fan port, however we still need two stepper motors to move material from one side of the printer to the other after each layer of material is cut.</p>
<p><a href="https://i.stack.imgur.com/l40X1.png" rel="nofollow noreferrer" title="Diagram"><img src="https://i.stack.imgur.com/l40X1.png" alt="Diagram" title="Diagram"></a></p>
<p>The mother board we are using is <a href="https://rads.stackoverflow.com/amzn/click/com/B07MXX2RV7" rel="nofollow noreferrer" rel="nofollow noreferrer">WitBot MKS Gen L V1.0 Controller Board Integrated mainboard Compatible Ramps1.4/Mega2560 R3 with A4988 Motor Driver for 3D</a>.</p>
|
<p>This has nothing to do with the infill overlap, the image you've added looks as if the issue is related to non-bonding perimeters (it looks as if it is in between the 2<sup>nd</sup> and the 3<sup>rd</sup> perimeter), hence infill overlap doesn't apply here. If that is the case look into <a href="/q/6067">this question</a>.</p>
<p>I've had this same issue, the problem is that if the perimeters do not touch, this is most probably caused by insufficient filament flow which can be a result of a too high of a print speed (or too low print temperature) of the inner perimeters. This is frequently seen when printing PETG. PETG has a limited print speed, the PETG I use (premium brand) has a maximum speed value of 50 mm/s, your values are for some values over that value. That would be fine for PLA, but high for PETG, the question is not clear on the material used for this print (the hotend temperatures hint to PLA, the bed temperatures are rather high though).</p>
<p>If it is not related to the material being printed, these gaps are also explained if the positioning of the nozzle is not correct, e.g. caused by loose belts. This is supported by the comment on the first layer:</p>
<blockquote>
<p>where the infill on a first layer would often not reach the perimeter shells</p>
</blockquote>
|
<p>I had absolutely the same issue. And after some research I finally found that this is because of wrong pressure advance setting (In case of Marlin - linear advance) in the firmware.
Without pressure advance (linear advance) will be more plastic at the end of the travel rather than at the start. As result the fast full infill will have uneven distribution of the plastic with more plastic close to the perimeters that usually produce rounded corners. The pressure advance makes it better and redistribute plastic flow more even with the speed however if you make this setting too big for your 3d printer and filament then this will result in what you can see on the picture with less plastic at the end of the travel. Basically too big pressure advance parameter will result in less plastic near the perimeters and especially near corners where change in speed happening.</p>
| 1,277
|
<p>I have the following regex that does a great job matching urls: </p>
<pre><code>((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)`
</code></pre>
<p>However, it does not handle urls without a prefix, ie. <strong>stackoverflow.com</strong> or <strong>www.google.com</strong> do not match. Anyone know how I can modify this regex to not care if there is a prefix or not?</p>
<hr>
<p>EDIT: Does my question too vague? Does it need more details?</p>
<hr>
<pre><code>(((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\)))?[\w\d:#@%/;$()~_?\+-=\\\.&]*)
</code></pre>
<p>I added a ()? around the protocols like <strong>Vinko Vrsalovic</strong> suggested, but now the regex will match nearly any string, as long as it has valid URL characters.</p>
<p>My implementation of this is I have a database that I manage the contents, and it has a field that either has plain text, a phone number, a URL or an email address. I was looking for an easy way to validate the input so I can have it properly formatted, ie. creating anchor tags for the url/email, and formatting the phone number how I have the other numbers formatted throughout the site. Any suggestions?</p>
|
<p>The below regex is from the wonderful <a href="http://www.amazon.co.uk/Mastering-Regular-Expressions-Jeffrey-Friedl/dp/0596528124/ref=sr_1_1/279-4458937-3540756?ie=UTF8&s=books&qid=1224694042&sr=8-1" rel="nofollow noreferrer">Mastering Regular Expressions</a> book. If you are not familiar with the <a href="http://www.regular-expressions.info/freespacing.html" rel="nofollow noreferrer">free spacing/comments mode</a>, I suggest you get familiar with it.</p>
<pre><code>\b
# Match the leading part (proto://hostname, or just hostname)
(
# ftp://, http://, or https:// leading part
(ftp|https?)://[-\w]+(\.\w[-\w]*)+
|
# or, try to find a hostname with our more specific sub-expression
(?i: [a-z0-9] (?:[-a-z0-9]*[a-z0-9])? \. )+ # sub domains
# Now ending .com, etc. For these, require lowercase
(?-i: com\b
| edu\b
| biz\b
| gov\b
| in(?:t|fo)\b # .int or .info
| mil\b
| net\b
| org\b
| name\b
| coop\b
| aero\b
| museum\b
| [a-z][a-z]\b # two-letter country codes
)
)
# Allow an optional port number
( : \d+ )?
# The rest of the URL is optional, and begins with / . . .
(
/
# The rest are heuristics for what seems to work well
[^.!,?;"'<>()\[\]{}\s\x7F-\xFF]*
(?:
[.!,?]+ [^.!,?;"'<>()\[\]{}\s\x7F-\xFF]+
)*
)?
</code></pre>
<p>To explain this regex briefly (for a full explanation get the book) - URLs have one or more dot separated parts ending with either a limited list of final bits, or a two letter country code (.uk .fr ...). In addition the parts may have any alphanumeric characters or hyphens '-', but hyphens may not be the first or last character of the parts. Then there may be a port number, and then the rest of it.</p>
<p>To extract this from the website, go to <a href="http://regex.info/listing.cgi?ed=3&p=207" rel="nofollow noreferrer">http://regex.info/listing.cgi?ed=3&p=207</a> It is from page 207 of the 3rd edition.</p>
<p>And the page says "Copyright © 2008 Jeffrey Friedl" so I'm not sure what the conditions for use are exactly, but I would expect that if you own the book you could use it so ... I'm hoping I'm not breaking the rules putting it here.</p>
|
<p>Just use:</p>
<pre><code>.*
</code></pre>
<p>i.e. match everything. </p>
<p>The things you want to match are just hostnames, not URL (technically). </p>
<p>There's no structure you can use to definitively identify hostnames.
Perhaps you could look for things that end in ".com" but then you'll miss any .co.uk, net, .org, etc.</p>
<p>Edit:</p>
<p>In other words: If you remove the requirement that the URL-like things start with a protocol you won't have any thing to match on.
Depending on what you are using the regular expression on:</p>
<ol>
<li>Treat everything as a URL</li>
<li>Keep the requirement for a protocol</li>
<li>Hack checks for common endings for hostnames (e.g. .com .net .org) and accept you'll miss some.</li>
</ol>
| 28,011
|
<p>I need to copy some records from our SQLServer 2005 test server to our live server. It's a flat lookup table, so no foreign keys or other referential integrity to worry about.</p>
<p>I could key-in the records again on the live server, but this is tiresome. I could export the test server records and table data in its entirety into an SQL script and run that, but I don't want to overwrite the records present on the live system, only add to them.</p>
<p>How can I select just the records I want and get them transferred or otherwise into the live server? We don't have Sharepoint, which I understand would allow me to copy them directly between the two instances.</p>
|
<p>If your production SQL server and test SQL server can talk, you could just do in with a SQL insert statement.</p>
<p>first run the following on your test server:</p>
<pre><code>Execute sp_addlinkedserver PRODUCTION_SERVER_NAME
</code></pre>
<p>Then just create the insert statement:</p>
<pre><code>INSERT INTO [PRODUCTION_SERVER_NAME].DATABASE_NAME.dbo.TABLE_NAME (Names_of_Columns_to_be_inserted)
SELECT Names_of_Columns_to_be_inserted
FROM TABLE_NAME
</code></pre>
|
<p>I would just script to sql and run on the other server for quick and dirty transferring. If this is something that you will be doing often and you need to set up a mechanism, SQL Server Integration Services (SSIS) which is similar to the older Data Transformation Services (DTS) are designed for this sort of thing. You develop the solution in a mini-Visual Studio environment and can build very complex solutions for moving and transforming data.</p>
| 18,603
|
<p>What is the highest port number one can use?</p>
|
<p>The port number is an unsigned 16-bit integer, so 65535.</p>
|
<p>It should be 65535.</p>
| 13,831
|
<p>What would be a good tag to use for doing business/making profit with a 3D printer?</p>
|
<p>I'd suggest two different tags:</p>
<ul>
<li><p>[monetization]: For selling, or profiting from printing, or from printing machines</p></li>
<li><p>[financing] (or [costs]): For calculating the cost of materials and machines, including operational expenses.</p></li>
</ul>
|
<p>I would propose something as [business] or [commercial-use] as opposed to [personal-use] to differentiate between these posibilites.</p>
| 11
|
<p>I'm a keyboard junkie. I love having a key sequence to do everything. What are your favorite keyboard shortcuts?</p>
<p>I'll start by naming a couple of mine:</p>
<p>1 - <kbd>Alt</kbd>-<kbd>Space</kbd> to access the windows menu for the current window</p>
<p>2 - <kbd>F2</kbd> to rename a file in Windows Explorer</p>
|
<p><strong><kbd>Win</kbd> + <kbd>1</kbd> .. <kbd>9</kbd></strong> -- Start quick launch shortcut at that index (Windows Vista).</p>
<p><strong><kbd>Ctrl</kbd> + <kbd>Scroll Lock</kbd>, <kbd>Scroll Lock</kbd></strong> -- Crash your computer: <em><a href="http://support.microsoft.com/kb/244139" rel="noreferrer">Windows feature lets you generate a memory dump file by using the keyboard</a></em></p>
<p>@gabr -- <kbd>Win</kbd> + <kbd>D</kbd> is <em>show desktop</em>, <kbd>Win</kbd> + <kbd>M</kbd> minimizes all windows. Hitting <kbd>Win</kbd> + <kbd>D</kbd> twice brings everything back as it has only shown the desktop window in front of the other windows.</p>
|
<p>I don't have favorites among keyboard shortcuts -- they are all utility entities to me...</p>
<p>Except for <kbd><img src="https://farm6.staticflickr.com/5214/5472803412_953823394a_o.jpg" width="15"/></kbd>+<kbd>L</kbd>, which means another coffee break!</p>
| 7,593
|
<p>I have one action I want to perform when a TSpeedButton is pressed and another I want to perform when the same button is "unpressed". I know there's no onunpress event, but is there any easy way for me to get an action to execute when a different button is pressed? </p>
<pre><code>procedure ActionName.ActionNameExecute(Sender: TObject);
begin
PreviousActionName.execute(Sender);
//
end;
</code></pre>
<p>Seems too clunky.</p>
|
<p>Yes, you do. You're defining a self-contained piece of work which the NSOperationQueue will execute on "some" thread, so you're responsible for managing memory in that work piece.</p>
|
<p>yes, you need to.</p>
<pre><code>- (void) main
{
NSAutoreleasePool *thePool = [[NSAutoreleasePool alloc] init];
//your code here
//more code
[thePool release];
}
</code></pre>
<p>if you don't create an autorelease pool, any convinience class-initializer (like [NSString stringWithFormat:]) will leak as these initializers return autoreleased objects.</p>
| 22,297
|
<p>I have a system in which different server processes are handling requests passed as JMS messages from various clients via a JMS broker.</p>
<p>I am trying to identify the source of the messages. Is there a way to get the IP or some identifying information about the origin ?</p>
<p>Clarification: I already have the client deployed by unknown users, so I'm trying to avoid changing message classes... </p>
|
<p>There is an optional JMS header mentioned in the JMS specification called <em>JMSXUserID</em> which which identifies the user sending a message (which the broker validates and ensures is correct to avoid spoofing) which some JMS providers support.</p>
<p>For example here is <a href="http://activemq.apache.org/jmsxuserid.html" rel="nofollow noreferrer">how to enable it in Apache ActiveMQ</a></p>
|
<p>Short answer: NO</p>
| 34,042
|
<p>I have a number of application settings (in user scope) for my custom grid control. Most of them are color settings. I have a form where the user can customize these colors and I want to add a button for reverting to default color settings. How can I read the default settings?</p>
<p>For example:</p>
<ol>
<li>I have a user setting named <code>CellBackgroundColor</code> in <code>Properties.Settings</code>.</li>
<li>At design time I set the value of <code>CellBackgroundColor</code> to <code>Color.White</code> using the IDE.</li>
<li>User sets <code>CellBackgroundColor</code> to <code>Color.Black</code> in my program.</li>
<li>I save the settings with <code>Properties.Settings.Default.Save()</code>.</li>
<li>User clicks on the <code>Restore Default Colors</code> button.</li>
</ol>
<p>Now, <code>Properties.Settings.Default.CellBackgroundColor</code> returns <code>Color.Black</code>. How do I go back to <code>Color.White</code>?</p>
|
<p>@ozgur,</p>
<pre><code>Settings.Default.Properties["property"].DefaultValue // initial value from config file
</code></pre>
<p>Example:</p>
<pre><code>string foo = Settings.Default.Foo; // Foo = "Foo" by default
Settings.Default.Foo = "Boo";
Settings.Default.Save();
string modifiedValue = Settings.Default.Foo; // modifiedValue = "Boo"
string originalValue = Settings.Default.Properties["Foo"].DefaultValue as string; // originalValue = "Foo"
</code></pre>
|
<blockquote>
<p>How do I go back to Color.White?</p>
</blockquote>
<p>Two ways you can do:</p>
<ul>
<li>Save a copy of the settings before the user changes it.</li>
<li>Cache the user modified settings and save it to Properties.Settings before the application closes.</li>
</ul>
| 7,178
|
<p>Does anyone know of a freely available java 1.5 package that provides a list of ISO 3166-1 country codes as a enum or EnumMap? Specifically I need the "ISO 3166-1-alpha-2 code elements", i.e. the 2 character country code like "us", "uk", "de", etc. Creating one is simple enough (although tedious), but if there's a standard one already out there in apache land or the like it would save a little time.</p>
|
<p>Now an implementation of country code (<a href="http://en.wikipedia.org/wiki/ISO_3166-1" rel="nofollow noreferrer">ISO 3166-1</a> <a href="http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2" rel="nofollow noreferrer">alpha-2</a>/<a href="http://en.wikipedia.org/wiki/ISO_3166-1_alpha-3" rel="nofollow noreferrer">alpha-3</a>/<a href="http://en.wikipedia.org/wiki/ISO_3166-1_numeric" rel="nofollow noreferrer">numeric</a>) list as Java enum is available at GitHub under Apache License version 2.0.</p>
<p><strong>Example:</strong></p>
<pre class="lang-java prettyprint-override"><code>CountryCode cc = CountryCode.getByCode("JP");
System.out.println("Country name = " + cc.getName()); // "Japan"
System.out.println("ISO 3166-1 alpha-2 code = " + cc.getAlpha2()); // "JP"
System.out.println("ISO 3166-1 alpha-3 code = " + cc.getAlpha3()); // "JPN"
System.out.println("ISO 3166-1 numeric code = " + cc.getNumeric()); // 392
</code></pre>
<hr />
<p><strong>Last Edit</strong> 2016-Jun-09</p>
<p>CountryCode enum was packaged into com.neovisionaries.i18n with other Java enums, LanguageCode (<a href="http://en.wikipedia.org/wiki/ISO_639-1" rel="nofollow noreferrer">ISO 639-1</a>), LanguageAlpha3Code (<a href="http://en.wikipedia.org/wiki/ISO_639-2" rel="nofollow noreferrer">ISO 639-2</a>), LocaleCode, ScriptCode (<a href="http://en.wikipedia.org/wiki/ISO_15924" rel="nofollow noreferrer">ISO 15924</a>) and CurrencyCode (<a href="http://en.wikipedia.org/wiki/ISO_4217" rel="nofollow noreferrer">ISO 4217</a>) and registered into the Maven Central Repository.</p>
<p><strong>Maven</strong></p>
<pre class="lang-xml prettyprint-override"><code><dependency>
<groupId>com.neovisionaries</groupId>
<artifactId>nv-i18n</artifactId>
<version>1.29</version>
</dependency>
</code></pre>
<p><strong>Gradle</strong></p>
<pre><code>dependencies {
compile 'com.neovisionaries:nv-i18n:1.29'
}
</code></pre>
<p><strong>GitHub</strong></p>
<p><a href="https://github.com/TakahikoKawasaki/nv-i18n" rel="nofollow noreferrer">https://github.com/TakahikoKawasaki/nv-i18n</a></p>
<p><strong>Javadoc</strong></p>
<p><a href="https://takahikokawasaki.github.io/nv-i18n/" rel="nofollow noreferrer">https://takahikokawasaki.github.io/nv-i18n/</a></p>
<p><strong>OSGi</strong></p>
<pre><code>Bundle-SymbolicName: com.neovisionaries.i18n
Export-Package: com.neovisionaries.i18n;version="1.28.0"
</code></pre>
|
<p>This still does not answer the question. I was also looking for a kind of enumerator for this, and did not find anything. Some examples using hashtable here, but represent the same as the built-in get</p>
<p>I would go for a different approach. So I created a script in python to automatically generate the list in Java:</p>
<pre><code>#!/usr/bin/python
f = open("data.txt", 'r')
data = []
cc = {}
for l in f:
t = l.split('\t')
cc = { 'code': str(t[0]).strip(),
'name': str(t[1]).strip()
}
data.append(cc)
f.close()
for c in data:
print """
/**
* Defines the <a href="http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2">ISO_3166-1_alpha-2</a>
* for <b><i>%(name)s</i></b>.
* <p>
* This constant holds the value of <b>{@value}</b>.
*
* @since 1.0
*
*/
public static final String %(code)s = \"%(code)s\";""" % c
</code></pre>
<p>where the data.txt file is a simple copy&paste from Wikipedia table (just remove all extra lines, making sure you have a country code and country name per line).</p>
<p>Then just place this into your static class:</p>
<pre><code>/**
* Holds <a href="http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2">ISO_3166-1_alpha-2</a>
* constant values for all countries.
*
* @since 1.0
*
* </p>
*/
public class CountryCode {
/**
* Constructor defined as <code>private</code> purposefully to ensure this
* class is only used to access its static properties and/or methods.
*/
private CountryCode() { }
/**
* Defines the <a href="http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2">ISO_3166-1_alpha-2</a>
* for <b><i>Andorra</i></b>.
* <p>
* This constant holds the value of <b>{@value}</b>.
*
* @since 1.0
*
*/
public static final String AD = "AD";
//
// and the list goes on! ...
//
}
</code></pre>
| 16,920
|
<p>What is a recommended architecture for providing storage for a dynamic logical database schema?</p>
<p>To clarify: Where a system is required to provide storage for a model whose schema may be extended or altered by its users once in production, what are some good technologies, database models or storage engines that will allow this? </p>
<p>A few possibilities to illustrate:</p>
<ul>
<li>Creating/altering database objects via dynamically generated DML</li>
<li>Creating tables with large numbers of sparse physical columns and using only those required for the 'overlaid' logical schema</li>
<li>Creating a 'long, narrow' table that stores dynamic column values as rows that then need to be pivoted to create a 'short, wide' rowset containing all the values for a specific entity</li>
<li>Using a BigTable/SimpleDB PropertyBag type system</li>
</ul>
<p>Any answers based on real world experience would be greatly appreciated</p>
|
<p>What you are proposing is not new. Plenty of people have tried it... most have found that they chase "infinite" flexibility and instead end up with much, much less than that. It's the "roach motel" of database designs -- data goes in, but it's almost impossible to get it out. Try and conceptualize writing the code for ANY sort of constraint and you'll see what I mean.</p>
<p>The end result typically is a system that is MUCH more difficult to debug, maintain, and full of data consistency problems. This is not <em>always</em> the case, but more often than not, that is how it ends up. Mostly because the programmer(s) don't see this train wreck coming and fail to defensively code against it. Also, often ends up the case that the "infinite" flexibility really isn't that necessary; it's a very bad "smell" when the dev team gets a spec that says "Gosh I have no clue what sort of data they are going to put here, so let 'em put WHATEVER"... and the end users are just fine having pre-defined attribute types that they can use (code up a generic phone #, and let them create any # of them -- this is trivial in a nicely normalized system and maintains flexibility and integrity!)</p>
<p>If you have a very good development team and are <strong>intimately aware</strong> of the problems you'll have to overcome with this design, you can successfully code up a well designed, not terribly buggy system. Most of the time. </p>
<p>Why start out with the odds stacked so much against you, though?</p>
<p>Don't believe me? Google "One True Lookup Table" or "single table design". Some good results:
<a href="http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:10678084117056" rel="noreferrer">http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:10678084117056</a></p>
<p><a href="http://thedailywtf.com/Comments/Tom_Kyte_on_The_Ultimate_Extensibility.aspx?pg=3" rel="noreferrer">http://thedailywtf.com/Comments/Tom_Kyte_on_The_Ultimate_Extensibility.aspx?pg=3</a></p>
<p><a href="http://www.dbazine.com/ofinterest/oi-articles/celko22" rel="noreferrer">http://www.dbazine.com/ofinterest/oi-articles/celko22</a></p>
<p><a href="http://thedailywtf.com/Comments/The_Inner-Platform_Effect.aspx?pg=2" rel="noreferrer">http://thedailywtf.com/Comments/The_Inner-Platform_Effect.aspx?pg=2</a></p>
|
<p>sql already provides a way to change your schema: the ALTER command.</p>
<p>simply have a table that lists the fields that users are not allowed to change, and write a nice interface for ALTER.</p>
| 9,190
|
<p>I was recently trying to explain to a programmer why, in ASP.Net, they should create HTMLControls instead of creating HTML strings to create Web pages.</p>
<p>I know it is a better way of doing things, but I really couldn't give concrete reasons, other than, "This way is better."</p>
<p>If you had to answer this question, what would your answer be?</p>
<p>Why is <pre>Dim divA as New HtmlControls.HtmlGenericControl("div")
Dim ulList1 as New HtmlControls.HtmlGenericControl("ul")
Dim liObj1, liObj2, liObj3 as New HtmlControls.HtmlGenericControl("li")
liObj1.innerText = "List item 1"
liObj2.innerText = "List item 2"
liObj3.innerText = "List item 3"
ulList1.Controls.Add(liObj1)
ulList1.Controls.Add(liObj2)
ulList1.Controls.add(liObj3)
divA.Controls.add(ulList1)</pre></p>
<p>"better" than: </p>
<pre><code>Dim strHTML as String
strHTML = "<div><ul><li>List item 1</li><li>List item 2</li><li>List item 3</li></ul></div>"
</code></pre>
<p>? It doesn't look better. Look at all that code! And, this is a very simplistic example, to save space. I don't think I would ever actually create a list manually like that, but would be iterating through a collection or using a more advanced Web control, but I'm trying to illustrate a point.</p>
|
<p>I don't do either. Instead, I:</p>
<ol>
<li>Create a custom control that encapsulates the desired construct</li>
<li>or (very similar) create a simple class with the properties I want and override the <code>.ToString()</code> method to create the desired HTML.</li>
</ol>
<p>But of your two choices, a couple reasons the former is better are:</p>
<ul>
<li>You can change properties of html controls or add other controls to the tree at later points in the page life cycle</li>
<li>ASP.Net is responsible for rendering the html. You're guaranteed not to have any mistakes that might break xhtml compliance.</li>
</ul>
|
<p>Building up controls like you have is The Single Worst Thing About ASP.NET. An MVC or approach with Partials are a much better(more easily maintained) way to construct HTML.</p>
| 46,519
|
<p>Any other tweaks for making emacs as vim-like as possible would be appreciated as well.</p>
<p>Addendum: The main reason I don't just use vim is that I love how emacs lets you open a file in two different frames [ADDED: sorry, this was confusing: I mean separate <em>windows</em>, which emacs calls "frames"]. It's like making a vertical split but I don't have to have one enormous window.</p>
|
<p>You could run VIM in <a href="http://www.vim.org/htmldoc/remote.html#clientserver" rel="nofollow noreferrer">client server mode</a>, then you could have two windows connecting to one instance, hence removing the need for Emacs.</p>
|
<p>You could always start vim in a shell buffer and resize it so it filled the whole frame?</p>
| 12,371
|
<p>I understand the value of the three-part service/host/client model offered by WCF. But is it just me or does it seem like WCF took something pretty direct and straightforward (the ASMX model) and made a mess out of it? </p>
<p>Is there an alternative to using SvcUtil's command line step back in time to generate the proxy? With ASMX services a test harness was automatically provided; is there a good alternative today with WCF? </p>
<p>I appreciate that the WS* stuff is more tightly integrated with WCF and hope to find some payoff for WCF there, but geeze, otherwise I'm perplexed. </p>
<p>Also, the state of books available for WCF is abysmal at best. Juval Lowy, a superb author, has written a good O'Reilly reference book "Programming WCF Services" but it doesn't do that much (for me anyway) for learning now to use WCF. That book's precursor (and a little better organized, but not much, as a tutorial) is Michele Leroux Bustamante's Learning WCF. It has good spots but is outdated in place and its corresponding Web site is gone. </p>
<p>Do you have good WCF learning references besides just continuing to Google the bejebus out of things?</p>
|
<p>Okay, here we go. First, Michele Leroux Bustamante's book has been updated for VS2008. The website for the book is not gone. It's up right now, and it has tons of great WCF info. On that website she provides updated code compatible with VS2008 for all the examples in her book. If you order from Amazon, you will get the reprint which is updated.</p>
<p>WCF is not <em>only</em> a replacement for ASMX. Sure it can (and does quite well) replace ASMX, but the real benefit is that it allows your services to be self-hosted. Most of the functionality from WSE has been baked in from the start. The framework is <em>highly</em> configurable, and the ability to serve multiple endpoints over multiple protocols is amazing, IMO.</p>
<p>While you can still generate proxy classes from the "Add Service Reference" option, it's not necessary. All you really have to do is copy your ServiceContract interface and tell your code where to find the endpoint for the service, and that's it. You can call methods from the service with very little code. Using this method, you have complete control over the implementation. Regardless of the method you choose to generate a proxy class, Michele shows both and uses both in her <strong>excellent</strong> series of webcasts on the subject.</p>
<p>Michele has tons of great material out there, and I recommend you check out her website(s). Here's some links that were incredibly helpful for me as I was learning WCF. I hope that you'll come to realize how strong WCF really is, and how easy it is to implement. The learning curve is a little bit steep, but the rewards for your time investment are well worth it:</p>
<ul>
<li>Michele's webcasts: <a href="http://www.dasblonde.net/2007/06/24/WCFWebcastSeries.aspx" rel="noreferrer">http://www.dasblonde.net/2007/06/24/WCFWebcastSeries.aspx</a></li>
<li>Michele's book website (alive and updated for VS2008): <a href="http://www.thatindigogirl.com/" rel="noreferrer">http://www.thatindigogirl.com/</a></li>
</ul>
<p>I recommend you watch at least 1 of Michele's webcasts. She is a very effective presenter, and she's obviously incredibly knowledgeable when it comes to WCF. She does a great job of demystifying the inner workings of WCF from the ground up.</p>
|
<p>MSDN? I usually do pretty well with the Library reference itself, and I usually expect to find valuable articles there.</p>
| 7,275
|
<p>I have a team of junior developers and they want to have better understanding and usages of generics. Anyone recommend good tutorial or articles samples that are good places to start.</p>
|
<p>A few links:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/ms379564(vs.80).aspx" rel="noreferrer">An Introduction to C# Generics</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/512aeb7t(VS.80).aspx" rel="noreferrer">Generics (C# Programming Guide)</a></li>
</ul>
<p>Recommended books:</p>
<ul>
<li><a href="https://rads.stackoverflow.com/amzn/click/com/0764559885" rel="noreferrer" rel="nofollow noreferrer">Professional .NET 2.0 Generics</a></li>
<li><a href="https://rads.stackoverflow.com/amzn/click/com/1933988363" rel="noreferrer" rel="nofollow noreferrer">C# in Depth</a> </li>
</ul>
|
<p><a href="http://srtsolutions.com/blogs/billwagner/default.aspx" rel="nofollow noreferrer">Bill Wagner's</a> <a href="https://rads.stackoverflow.com/amzn/click/com/0321485890" rel="nofollow noreferrer" rel="nofollow noreferrer">More Effective C#</a> has some really good content on Generics.</p>
| 37,275
|
<p>I have a class with two methods defined in it.</p>
<pre><code>public class Routines {
public static method1() {
/* set of statements */
}
public static method2() {
/* another set of statements.*/
}
}
</code></pre>
<p>Now I need to call method1() from method2()</p>
<p>Which one the following approaches is better? Or is this qualify as a question?</p>
<pre><code>public static method2() {
method1();
}
</code></pre>
<p>OR</p>
<pre><code>public static method2() {
Routines.method1();
}
</code></pre>
|
<p>While I agree with the existing answers that this is primarily a style issue, it is enough of a style issue that both Eclipse and IntelliJ's code critics will flag "non-static references to static methods" in code that does not use the <code>Classname.method()</code> style.</p>
<p>I made it a habit to emphasize <em>intent</em> by using the classname to qualify references to static targets, <code>this</code> to qualify references to instance targets, and bare names for local references. A modern IDE will use different highlighting for these constructs, so I suppose it is less important these days. I like for the maintainer (often myself) to <em>know</em> what was intended, that yes, I knew that was a <code>static</code> reference.</p>
<p>Yeah, it does make for slightly more verbose code, but I think it is worth the extra characters.</p>
|
<p>I do</p>
<pre><code>public static method2() {
Routines.method1();
}
</code></pre>
<p>No guessing.
It is very clear if I call static method from parent class.
I don't like static import for same reason. </p>
| 45,467
|
<p>We all know how to use <code><ctrl>-R</code> to reverse search through history, but did you know you can use <code><ctrl>-S</code> to forward search if you set <code>stty stop ""</code>? Also, have you ever tried running bind -p to see all of your keyboard shortcuts listed? There are over 455 on Mac OS X by default. </p>
<p>What is your single most favorite obscure trick, keyboard shortcut or shopt configuration using bash?</p>
|
<pre><code>cd -
</code></pre>
<p>It's the command-line equivalent of the back button (takes you to the previous directory you were in).</p>
|
<p>Some useful mencoder commands I found out about when looking for some audio and video editing tools:</p>
<p>from .xxx to .avi</p>
<pre><code>mencoder movie.wmv -o movie.avi -ovc lavc -oac lavc
</code></pre>
<p>Dump sound from a video:</p>
<pre><code>mplayer -ao pcm -vo null -vc dummy -dumpaudio -dumpfile fileout.mp3 filein.avi
</code></pre>
| 9,388
|
<p>I'm using Java for accessing Alfresco content server via it's web service API for importing some content into it. Content should have some NamedValue properties set to UTF-8(cyrillic) string. I keep getting the Sax parser exception:</p>
<pre><code>org.xml.sax.SAXParseException: An invalid XML character (Unicode: 0x1b) was found in the element content of the document.
</code></pre>
<p>The code looks something like this:</p>
<pre><code>NamedValue[] namedValueProperties = new NamedValue[2];
namedValueProperties[0] = Utils.createNamedValue(Constants.PROP_NAME, name );
namedValueProperties[1] = Utils.createNamedValue("{my.custom.model}myProperty", cyrillicString);
CMLCreate create = new CMLCreate("1", parentReference, null, null, null, documentType, namedValueProperties);
CML cml = new CML();
cml.setCreate(new CMLCreate[]{create});
UpdateResult[] results = null;
try {
results = WebServiceFactory.getRepositoryService().update(cml);
} catch (...)
Here comes the "org.xml.sax.SAXParseException"
}
</code></pre>
<p>Does anyone know how to solve this problem?</p>
|
<p>The problem was that <code>alfresco-web-service-client.jar</code> library I used was from 2.9B distribution (I am hitting 2.9B community content server), and dependency libs <code>bcprov-jdk15-136.jar</code> and <code>xmlsec-1.4.0.jar</code> were not adequate (remained old from 2.1 verison). I should have used <code>bcprov-jdk15-137.jar</code> and <code>xmlsec-1.4.1.jar</code> which are deployed along with 2.9B distribution. </p>
|
<p>The easiest way to get around it is I think to escape cyrillicString, for instance with <a href="http://commons.apache.org/lang/api-release/org/apache/commons/lang/StringEscapeUtils.html#escapeXml(java.lang.String)" rel="nofollow noreferrer">escapeXml</a> from Jakarta Commons, or by converting the whole string to XML entities if it's not enough. But in the long run, Alfresco should be fixed, so opening a ticket may be a good choice too.</p>
| 23,122
|
<p>What are some helpful things that ASP.NET MVC developers could suggest that would help us ASP.NET WebForms developers to write better code/web apps?</p>
<p>I'm a WebForms guy but with all the new hype around MVC I'd value some comments on helpful tips, tricks and strategies that might be able to be used in a webforms app.</p>
|
<p>Something that occurred to me a while ago when learning about the new MVC framework, is that WebForms was, I think, an attempt at MVC in many ways. The markup and code-behind comprise View and Controller, and you're left to write your own Model.</p>
<p>This idea goes hand in hand with the important design considerations I gained from learning about MVC. The most important of which is solidifying the core domain of your system as a whole and making sure all common logic is defined at a level that is reusable within this domain. This is your Model, and I like to call the logic that lives at this level Domain Logic (I mix terms, I know). Your Model should be reusable across different applications (a main web/winforms app, winforms apps for utility and configuration, background processing services, web services, etc.). Your applications should stay very specific to their purpose: they consist of Presentation Logic (their views) and Application Logic (their controllers). Anything that crosses the line of needing to be used in other applications is easily classifiable as Domain Logic, and should not be part of the application code for any given application.</p>
<p>I hope that makes sense.</p>
<p>The gist of it is, even if you're not using a pure MVC framework or object model or whatever, this high level look at design can be applied with great effect. Isolate common logic in a domain layer that is reusable across applications and your applications are much easier to write and extend and maintain.</p>
|
<p>I'm also coming from webforms, but have been learning asp.net MVC since around preview 3.</p>
<p>I'm not exactly sure how to bring anything from MVC into webforms, they are two entirely different frameworks. I'm probably too new with it to understand how any of it could be applied to webforms, but right now it seems they have very little in common.</p>
<p>Some of the strengths of MVC are it's rigid structure on how you need to do things and where you put code. It also does away with the form runat=server and I believe does not promote the usage of any of the asp.net server controls (you need to write all the HTML yourself). That is pretty much the definition of webforms right there. MVC pretty much replaces webforms with it's own framework.</p>
<p>If you ever did Classic ASP or PHP, I would call ASP.net MVC a more structured framework for what people might do with those older scripting languages. It's kind of like the FuseBox framework, but even more structured and evolved.</p>
| 34,466
|
<p><strong>Background</strong></p>
<p>We have a web application in which several developers have written several .js files that manipulate the DOM and the problem of duplicate function names has crept into our application.</p>
<p><strong>Question</strong></p>
<p>Can anyone recommend a tool that will warn us when we accidentally write a web page with two javascript functions with the same name? </p>
<p><strong>Example</strong></p>
<p><em>HTML page</em></p>
<pre><code><script language="JavaScript" src="test.js" type="text/javascript"></script>
<script>function foo() {alert('bar');}</script>
</code></pre>
<p><em>test.js</em></p>
<pre><code>function foo() {alert('foo');}
</code></pre>
<p>Since foo() is declared twice in the page, apparently only the one that takes precedence is loaded. </p>
<p>The tools I've used seem to ignore this. Firebug only shows the loaded function. Netbeans will show both functions in navigator (without a warning), but only looks at one file at a time (ie, I can't point it at the HTML file and see it and the .js at the same time.) and web developer extensions allows me to look at everything at once, but no errors or warnings. Firefox's error console also throws no warning or error. Neither does IE.</p>
<p>Thanks!</p>
|
<p>Well, using a parser may not always be ideal as it requires an extra step of copying and pasting your code, and everyone else's, into the parser and even then I'm not sure it would catch what you want. The time tested solution to collaborative Javascript development is to namespace your code. </p>
<pre><code>var myNamespace = function (){
var myPrivateProperty;
var myPrivateFunction = function(){};
return{
myPublicProperty: '',
myPublicFunction: function(){}
}
}();
</code></pre>
<p>This is based on Douglas Crockford's <a href="http://yuiblog.com/blog/2007/06/12/module-pattern/" rel="nofollow noreferrer">module pattern</a>.</p>
<p>Then you can call your public functions this way:</p>
<pre><code> myNamespace.myPublicFunction();
</code></pre>
<p>And your public properties:</p>
<pre><code> myNamespace.myPublicProperty;
</code></pre>
<p>Each developer can develop in their own namespace so as to not step on others' code.</p>
|
<p>My solution would be a simple HTML parser for Java (I just hacked one with regexps; you may want to try <a href="http://java-source.net/open-source/html-parsers/jtidy" rel="nofollow noreferrer">http://java-source.net/open-source/html-parsers/jtidy</a>) and the Apache Rhino library (<a href="http://www.mozilla.org/rhino/doc.html" rel="nofollow noreferrer">http://www.mozilla.org/rhino/doc.html</a>).</p>
<p>It should be possible to overload the parser in Rhino to throw an error if a function is redefined.</p>
<p>I'm using a slightly modified version of env.js (<a href="http://jqueryjs.googlecode.com/svn/trunk/jquery/build/runtest/env.js" rel="nofollow noreferrer">http://jqueryjs.googlecode.com/svn/trunk/jquery/build/runtest/env.js</a>) by John Resig to emulate a browser. This allows me to test JavaScript in JUnit tests. I can fill in forms, submit them, check the layout of the pages, etc.</p>
<p>See my blog for details: <a href="http://blog.pdark.de/2008/11/18/testing-the-impossible-javascript-in-a-web-page/" rel="nofollow noreferrer">http://blog.pdark.de/2008/11/18/testing-the-impossible-javascript-in-a-web-page/</a></p>
| 37,823
|
<p>Here's what I did:</p>
<ol>
<li>I've opened a C++ Builder 6 - project in C++ Builder 2009.</li>
<li>Auto-converted it to a C++ Builder 2009 project.</li>
<li>Told it (<em>C++ Builder 2009</em>) to build everything.</li>
</ol>
<p>Here's what <em>it</em> did:</p>
<ol>
<li>Successfully compiled everything.</li>
<li><p>Failed to complete ILINK32, exiting with </p>
<pre><code>"Error: Unresolved external '_CG_DESC' referenced from MyProjectsFirstFile.obj".
</code></pre></li>
</ol>
|
<p>It looks like a Code Guard error. Try deleting all the object (.obj) files and rebuilding the entire project.</p>
<p>If this still does not work, then turn off the Code Guard option in C++Builder 6 and try importing the project again.</p>
<p>You may also want to try the <a href="https://forums.codegear.com/category.jspa?categoryID=8" rel="nofollow noreferrer">CodeGear/Embarcadero Discussion Forums</a>.</p>
<p>Reference:
<a href="https://forums.codegear.com/thread.jspa?messageID=52470&tstart=0" rel="nofollow noreferrer">https://forums.codegear.com/thread.jspa?messageID=52470&tstart=0</a></p>
|
<p>Never let the IDE auto-upgrade a project from an old version. It never works correctly. Instead, always create a new project fresh and add your existing source files to it as needed.</p>
| 48,998
|
<p>I'm new to windows programming and I'm trying to get notified of all changes to the file system (similar to the information that FileMon from SysInternals displays, but via an API). Is a FindFirstChangeNotification for each (non-network, non-substed) drive my best bet or are there other more suitable C/C++ APIs?</p>
|
<p><code>FindFirstChangeNotification</code> is fine, but for slightly more ultimate power you should be using <code>ReadDirectoryChangesW.</code> (In fact, it's even recommended in the documentation!)</p>
<p>It doesn't require a function pointer, it does require you to manually decode a raw buffer, it uses Unicode file names, but it is generally better and more flexible.</p>
<p>On the other hand, if you want to do what FileMon does, you should probably do what FileMon does and use <a href="http://msdn.microsoft.com/en-us/library/ms790748.aspx" rel="noreferrer">IFS to create and install a file system filter</a>.</p>
|
<p>You can use FileSystemWatcher class. Very efficient but cannot work with Network shared drives.</p>
| 3,733
|
<p>Is it possible to get the originating port from an ActionExecutingContext object? If so, how?</p>
|
<p>Yes, look at ActionExecutingContext.HttpContext.Request.Url.Port;</p>
|
<p>ActionExecutionContext.HttpContextBase.Url.Port should work for you.</p>
| 35,063
|
<p>The bugzilla (perl-based) system has a feature to login automatically by using a http server environment variable. If you fill in the right ID or username, you are automatically logged in.</p>
<p>My server runs Joomla (PHP-based) and has all the information about who is logged in. It runs bugzilla within a sub-frame.</p>
<p>So, how can I set this enviroment value from a PHP script?</p>
<p>To put it in another way, how does the following script return my own-set variable elsewhere in a session from PHP:</p>
<pre><code>#!/usr/bin/perl -wT
print "Content-type: text/html\n\n";
while (($key, $val) = each %ENV) {
print "$key = $val&lt;BR&gt;\n";
}
</code></pre>
|
<p>What you need is the DECIMAL datatype:</p>
<pre><code>declare @val decimal(10,2)
select @val = 10.155
select @val
</code></pre>
<p>When you input values, you can either rely on the built in rounding, or explicitly decide which rounding you want:</p>
<pre><code>select val = round(10.155, 2, 0) -- rounded
select val = round(10.155, 2, 1) -- truncated
</code></pre>
<p>Decimal (10,2) means that ten digits can be used, and that two of them are to be taken as being after the decimal point. i.e. The highest number that decimal(4,2) can contain is 99.99. Trying to set it to 100 will result in arithmetic overflow.</p>
|
<p>Decimal - it is the simplest, however any of mentined will do the job</p>
| 44,204
|
<pre><code>SELECT * FROM (SELECT ROW_NUMBER() OVER (ORDER BY hrl.Frn) as Row,
hrl.unq, hrl.LcnsId, hc.Business,hc.Name,hc.Phone,
hrl.Frn,hrl.CallSign, hrl.gsamarkettypeid,
gmt.[Market Type Code] + ' - ' + gmt.gsamarkettype,
hrl.gsalatitude,hrl.gsalongitude,
rsc.RadioServiceCode + ' - ' + rsc.RadioService,
GrantDt, ExpirationDt, EffectiveDt,
CancellationDt
FROM dbo.sbi_f_HldrRgstrtnLcns hrl
INNER JOIN dbo.sbi_f_HldrCntcts hc on
hc.CallSign = hrl.CallSign
INNER JOIN dbo.sbi_l_radioservicecodes rsc on
rsc.radioservicecodeid = hrl.radioservicecodeid
LEFT OUTER JOIN dbo.sbi_l_GSAMarketTypes gmt on
gmt.GSAMarketTypeId = hrl.GSAMarketTypeId
WHERE hc.Entity_Type = 'L' AND hrl.LicenseStatusId IN (1)
and Row >=1 and Row <= 20) -- The error occurs here,
-- it says incorrect syntax near )
</code></pre>
|
<p>Move your Row criteria into the outer select</p>
<pre><code>SELECT * FROM (SELECT ROW_NUMBER() OVER (ORDER BY hrl.Frn) as Row,
...
WHERE hc.Entity_Type = 'L' AND hrl.LicenseStatusId IN (1)
) T
WHERE T.Row >=1 and T.Row <= 20)
</code></pre>
|
<p>You can't use an alias for a column in a where clause, because the where clause is processed before the Select Clause. </p>
<p>EDITED: </p>
<p>You could also just add the subquery in the where clause</p>
<pre><code>Where ((SELECT ROW_NUMBER() OVER (ORDER BY hrl.Frn)) < 20,
</code></pre>
<p>or without usingt Row_Number at all,</p>
<pre><code>Where (Select Count(*)
From dbo.sbi_f_HldrRgstrtnLcns
Where Frn < hrl.Frn) < 20
</code></pre>
| 46,629
|
<p>I'm investigating SUDS as a SOAP client for python. I want to inspect the methods available from a specified service, and the types required by a specified method.</p>
<p>The aim is to generate a user interface, allowing users to select a method, then fill in values in a dynamically generated form.</p>
<p>I can get some information on a particular method, but am unsure how to parse it:</p>
<pre><code>client = Client(url)
method = client.sd.service.methods['MyMethod']
</code></pre>
<p>I am unable to <strong>programmaticaly</strong> figure out what object type I need to create to be able to call the service</p>
<pre><code>obj = client.factory.create('?')
res = client.service.MyMethod(obj, soapheaders=authen)
</code></pre>
<p>Does anyone have some sample code?</p>
|
<p>Okay, so SUDS does quite a bit of magic.</p>
<p>A <code>suds.client.Client</code>, is built from a WSDL file:</p>
<pre><code>client = suds.client.Client("http://mssoapinterop.org/asmx/simple.asmx?WSDL")
</code></pre>
<p>It downloads the WSDL and creates a definition in <code>client.wsdl</code>. When you call a method using SUDS via <code>client.service.<method></code> it's actually doing a whole lot of recursive resolve magic behind the scenes against that interpreted WSDL. To discover the parameters and types for methods you'll need to introspect this object.</p>
<p>For example:</p>
<pre><code>for method in client.wsdl.services[0].ports[0].methods.values():
print '%s(%s)' % (method.name, ', '.join('%s: %s' % (part.type, part.name) for part in method.soap.input.body.parts))
</code></pre>
<p>This should print something like:</p>
<pre class="lang-py prettyprint-override"><code>echoInteger((u'int', http://www.w3.org/2001/XMLSchema): inputInteger)
echoFloatArray((u'ArrayOfFloat', http://soapinterop.org/): inputFloatArray)
echoVoid()
echoDecimal((u'decimal', http://www.w3.org/2001/XMLSchema): inputDecimal)
echoStructArray((u'ArrayOfSOAPStruct', http://soapinterop.org/xsd): inputStructArray)
echoIntegerArray((u'ArrayOfInt', http://soapinterop.org/): inputIntegerArray)
echoBase64((u'base64Binary', http://www.w3.org/2001/XMLSchema): inputBase64)
echoHexBinary((u'hexBinary', http://www.w3.org/2001/XMLSchema): inputHexBinary)
echoBoolean((u'boolean', http://www.w3.org/2001/XMLSchema): inputBoolean)
echoStringArray((u'ArrayOfString', http://soapinterop.org/): inputStringArray)
echoStruct((u'SOAPStruct', http://soapinterop.org/xsd): inputStruct)
echoDate((u'dateTime', http://www.w3.org/2001/XMLSchema): inputDate)
echoFloat((u'float', http://www.w3.org/2001/XMLSchema): inputFloat)
echoString((u'string', http://www.w3.org/2001/XMLSchema): inputString)
</code></pre>
<p>So the first element of the part's type tuple is probably what you're after:</p>
<pre><code>>>> client.factory.create(u'ArrayOfInt')
(ArrayOfInt){
_arrayType = ""
_offset = ""
_id = ""
_href = ""
_arrayType = ""
}
</code></pre>
<p>Update:</p>
<p>For the Weather service it appears that the "parameters" are a part with an <code>element</code> not a <code>type</code>:</p>
<pre><code>>>> client = suds.client.Client('http://www.webservicex.net/WeatherForecast.asmx?WSDL')
>>> client.wsdl.services[0].ports[0].methods.values()[0].soap.input.body.parts[0].element
(u'GetWeatherByZipCode', http://www.webservicex.net)
>>> client.factory.create(u'GetWeatherByZipCode')
(GetWeatherByZipCode){
ZipCode = None
}
</code></pre>
<p>But this is magic'd into the parameters of the method call (a la <code>client.service.GetWeatherByZipCode("12345")</code>. IIRC this is SOAP RPC binding style? I think there's enough information here to get you started. Hint: the Python command line interface is your friend!</p>
|
<p>i needed an example of using suds with objects.
beside the answers found here, i found a very good <a href="https://webkul.com/blog/python-suds-client/" rel="nofollow noreferrer">article</a>
that answered my question even further.</p>
<p>here is a short summary:</p>
<p>first, print the client to see an overview of it's content.</p>
<pre><code>from suds.client import Client client =
Client("https://wsvc.cdiscount.com/MarketplaceAPIService.svc?wsdl")
print client
</code></pre>
<p>second, create an instance of a type (using it's name including it's prefix ns*.), and print it, to see it's member data.</p>
<pre><code>HeaderMessage = client.factory.create('ns0:HeaderMessage')
print HeaderMessage
</code></pre>
<p>to fill your object's data members, either assign them a scalar value for scalar members, or a dict, to object members.</p>
<pre><code>HeaderMessage.Context = {
"CatalogID": "XXXXX"
"CustomerID": 'XXXXX'
"SiteID": 123
}
</code></pre>
<p>members whose type name start with ArrayOf expect a list of objects of the type mentioned in the rest of the type name.</p>
<pre><code>ArrayOfDomainRights = client.factory.create('ns0:ArrayOfDomainRights')
ArrayOfDomainRights.DomainRights = [XXXXXXXXXXXXX, XXXXXXXXXXXX]
</code></pre>
| 29,943
|
<p>This is a GUI application (actually MFC). I need a command window with the ability to display a prompt like such:</p>
<blockquote>
<p>Name of favorite porn star:</p>
</blockquote>
<p>The user should be able to enter text after the prompt like such:</p>
<blockquote>
<p>Name of favorite porn star: <strong>Raven Riley</strong></p>
</blockquote>
<p>But I need to prevent the user from moving the cursor into the prompt area. Users should also be prevented from backspacing into the prompt in order to prevent the following:</p>
<blockquote>
<p><strong>Rrraven Rrrileeey Ruuuulez!!!</strong> Name of favorite porn star:</p>
</blockquote>
<p>Also need to control text selection and so on. And finally, I should have no problem retrieving only the text the user entered (minus prompt text).</p>
<p>Will it be better to create my own window class from scratch (i.e inherit from CWnd) or should I reuse the Windows EDIT control (i.e. inherit from CEdit)?</p>
<p>A similar command window can be seen in AutoCAD and Visual Studio (in debug mode).</p>
|
<p>I think you'd be better off creating a subclass of CEdit and limiting filtering key-presses. I suppose the hard part is not letting the user move the caret to the prompt area, but you can probably write some code to make sure the caret always get sent back to where it belongs (the input part).</p>
<p>Anyway, if you really, really want to implement your own control (it's not that difficult after all) I recommend you read Jacob Navia's "technical documentation" on how he built the LCC compiler and environment. Actually, it seems the docs are not online anymore, but I'm sure you can get them through his e-mail (jacob@jacob.remcomp.fr).</p>
<p><strong>Edit</strong>: I liked your previous example better. Keep it classy, LOL :)</p>
|
<p>I had a very similar requirement and did exactly what davidg suggested; subclassed a edit control and filtered key presses. This was actually using Qt not MFC but the principle will be exactly the same. </p>
<p>You need to remember to filter keys such as home as well as left and backspace. I just checked to see if the move would move the caret into the prompt and if it did ignored the keypress.</p>
<p>Another thing to watch for is pasting multiline text, you will have to choose whether to just paste the first line or all lines, adding the prompt on all lines after the first. When subclassing the control you get lots of behaviour which won't work exactly as you want it.</p>
| 20,117
|
<p>I have a need to display many numerical values in columns. These values need to be easily editable so I cannot just display them in a table. I am using textboxes to display them. Is there a way for me to right-justify the text displayed in a textbox? It would also be nice if when the user is entering data for it to start displaying what they type from the right.</p>
|
<p>Did you try setting the style:</p>
<pre><code>input {
text-align:right;
}
</code></pre>
<p>Just tested, this works fine (in FF3 at least):</p>
<pre><code><html>
<head>
<title>Blah</title>
<style type="text/css">
input { text-align:right; }
</style>
</head>
<body>
<input type="text" value="2">
</body>
</html>
</code></pre>
<p>You'll probably want to throw a class on these inputs, and use that class as the selector. I would shy away from "rightAligned" or something like that. In a class name, you want to describe what the element's function is, not how it should be rendered. "numeric" might be good, or perhaps the business function of the text boxes.</p>
|
<p>Apply <code>style="text-align: right"</code> to the input tag. This will allow entry to be right-justified, and (at least in Firefox 3, IE 7 and Safari) will even appear to flow from the right.</p>
| 20,169
|
<p>All,</p>
<p>Our application requires data on ISO countries and currencies (where the data must be up to date). We did purchase country/currency data from ISO themselves, however we still needed to perform alot of manual manipulation of the data, as well as write our own tool to read and process the data into our database.</p>
<ol>
<li><p>Are we going about getting this data the wrong way?</p></li>
<li><p>What is the norm in relation to the acquisition of country/currency data? </p></li>
<li><p>Is there any well known providers out there that are offer to provide this data as a service or through some other medium in a usable format?</p></li>
</ol>
<p>Any help will be greatly appreciated.</p>
|
<p>The <a href="http://msdn.microsoft.com/en-us/library/ky2chs3h.aspx" rel="nofollow noreferrer">.NET CultureInfo</a> class provides formatting for currencies (as well as dates, times, numbers, etc). I would never have even considered buying the data from ISO when it's available for free in the .NET runtime.</p>
|
<p>You might be interested by IBM's <a href="http://www.icu-project.org/" rel="nofollow noreferrer" title="International Component for Unicode (ICU)">International Component for Unicode (ICU)</a> library.</p>
<p>Open source, well known, supports "numbers, dates, times and currency amounts" formatting.</p>
<p>Not sure if it helps your case, but this info might be useful for somebody else... :-)</p>
| 30,589
|
<p>Obviously having whitespace in css, aspx and html pages is a great advantage at design time. But is there a way to (a tool that will) clear all the whitespace from all the files and possibly merge javascript and css files in a more optimal way. </p>
<p>I am using asp.net themes so there are quite a lot of separate css files that would be improved through some form of automated combining. I have seen a few http modules but that isn't quite what I want I just want to run something over the published project beofre sending it to the server.</p>
<p>EDIT: Compression at least in IIS is unfortunately not an option, we are currently running it on the same IIS server as a third party web based student management system. It doesn't like compression and the IIS options don't seem to be per application pool. I did apply asp.net compression but the bulk of my extra data seems to be the app_themes which I know would compress well I just don't want to have to manually go through compressing all the css separately.</p>
|
<p><a href="http://nadeausoftware.com/articles/2007/03/don_t_use_html_white_space_removal_speed_web_site" rel="nofollow noreferrer">An empirical study on the effect of removing white space</a> from a not-untypical website (Drupal) showed minimal effects. (site also contains some links to non .net html white space removal tools)</p>
<p>I have gotten magical improvements in page size by aggressively managing viewstate size and using <a href="http://blowery.org/httpcompress/" rel="nofollow noreferrer">Blowery's http compression</a> module.</p>
<p>Another strategy is to do minifiation (merging many css files into one). Telerik has such a component <a href="http://www.telerik.com/help/aspnet-ajax/radstylesheetmanager.html" rel="nofollow noreferrer">RadStyleSheetManager</a>, it works only with style sheets embedded into assemblies.</p>
|
<p>i found this:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/aa719805(VS.71).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa719805(VS.71).aspx</a></p>
<p>greets!</p>
| 45,152
|
<p>i have scenario where i have to provide my own control template for a few WPF controls - i.e. GridViewHeader. when you take a look at control template for GridViewHEader in blend, it is agregated from several other controls, which in some cases are styled for that control only - i.e. this splitter between columns.
those templates, obviously are resources hidden somewhere in system...dll (or somewhwere in themes dll's).
so, my question is - is there a way to reference those predefined templates? so far, i've ended up having my own copies of them in my resources, but i don't like that approach.</p>
<p>here is sample scenario:
i have a GridViewColumnHeader:</p>
<pre><code> <Style TargetType="{x:Type GridViewColumnHeader}" x:Key="gridViewColumnStyle">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="VerticalContentAlignment" Value="Stretch"/>
<Setter Property="Background" Value="{StaticResource GridViewHeaderBackgroundColor}"/>
<Setter Property="BorderBrush" Value="{StaticResource GridViewHeaderForegroundColor}"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Padding" Value="2,0,2,0"/>
<Setter Property="Foreground" Value="{StaticResource GridViewHeaderForegroundColor}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GridViewColumnHeader}">
<Grid SnapsToDevicePixels="true" Tag="Header" Name="Header">
<ContentPresenter Name="HeaderContent" Margin="0,0,0,1" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
<Canvas>
<Thumb x:Name="PART_HeaderGripper" Style="{StaticResource GridViewColumnHeaderGripper}"/>
</Canvas>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="true">
</Trigger>
<Trigger Property="IsPressed" Value="true">
<Setter TargetName="HeaderContent" Property="Margin" Value="1,1,0,0"/>
</Trigger>
<Trigger Property="Height" Value="Auto">
<Setter Property="MinHeight" Value="20"/>
</Trigger>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</code></pre>
<p>so far - nothing interesting, but say, i want to add some extra functionality straight in the template - i'd leave cotnent presenter as is, add my controls next to it and i'd like to leave Thumb with defaults from framework. i've found themes provided by microsoft <a href="http://msdn.microsoft.com/en-us/library/aa358533.aspx" rel="nofollow noreferrer">here</a>:</p>
<p>the theme for Thumb looks like that:</p>
<pre><code><Style x:Key="GridViewColumnHeaderGripper"
TargetType="{x:Type Thumb}">
<Setter Property="Canvas.Right"
Value="-9"/>
<Setter Property="Width"
Value="18"/>
<Setter Property="Height"
Value="{Binding Path=ActualHeight,RelativeSource={RelativeSource TemplatedParent}}"/>
<Setter Property="Padding"
Value="0"/>
<Setter Property="Background"
Value="{StaticResource GridViewColumnHeaderBorderBackground}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Thumb}">
<Border Padding="{TemplateBinding Padding}"
Background="Transparent">
<Rectangle HorizontalAlignment="Center"
Width="1"
Fill="{TemplateBinding Background}"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</code></pre>
<p>so far - i have to copy & paste that style, while i'd prefer to get reference to it from resources.</p>
|
<p>Referencing internal resources that are 100% subject to change isn't serviceable - better to just copy it. </p>
|
<p>It is possible to reference them, but as paulbetts said, its not recommended as they could change. Also consider if what you are doing is truely 'correct'. Can you edit your question to explain why you need to do this exactly?</p>
| 9,478
|
<p>In Sharepoint designer's workflow editor I wish to retrieve the username/name of the work flow initiator (i.e. who kicked it off or triggered the workflow) - this is relatively easy to do using 3rd party products such as Nintex Workflow 2007 (where I would use something like {Common:Initiator}) - but I can't seem to find any way out of the box to do this using share point designer and MOSS 2007.</p>
<p><strong>Update</strong></p>
<p>It does not look like this rather obvious feature is supported OOTB, so I ended up writing a custom activity (as suggested by one of the answers). I have listed the activities code here for reference though I suspect there are probably a few instances of this floating around out there on blogs as it's a pretty trivial solution:</p>
<pre><code>public partial class LookupInitiatorInfo : Activity
{
public static DependencyProperty __ActivationPropertiesProperty =
DependencyProperty.Register("__ActivationProperties",
typeof(Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties),
typeof(LookupInitiatorInfo));
public static DependencyProperty __ContextProperty =
DependencyProperty.Register("__Context", typeof (WorkflowContext),
typeof (LookupInitiatorInfo));
public static DependencyProperty PropertyValueVariableProperty =
DependencyProperty.Register("PropertyValueVariable", typeof (string),
typeof(LookupInitiatorInfo));
public static DependencyProperty UserPropertyProperty =
DependencyProperty.Register("UserProperty", typeof (string),
typeof (LookupInitiatorInfo));
public LookupInitiatorInfo()
{
InitializeComponent();
}
[Description("ActivationProperties")]
[ValidationOption(ValidationOption.Required)]
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties __ActivationProperties
{
get { return ((Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties)(base.GetValue(__ActivationPropertiesProperty))); }
set { base.SetValue(__ActivationPropertiesProperty, value); }
}
[Description("Context")]
[ValidationOption(ValidationOption.Required)]
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public WorkflowContext __Context
{
get { return ((WorkflowContext)(base.GetValue(__ContextProperty))); }
set { base.SetValue(__ContextProperty, value); }
}
[Description("UserProperty")]
[ValidationOption(ValidationOption.Required)]
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public string UserProperty
{
get { return ((string) (base.GetValue(UserPropertyProperty))); }
set { base.SetValue(UserPropertyProperty, value); }
}
[Description("PropertyValueVariable")]
[ValidationOption(ValidationOption.Required)]
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public string PropertyValueVariable
{
get { return ((string) (base.GetValue(PropertyValueVariableProperty))); }
set { base.SetValue(PropertyValueVariableProperty, value); }
}
protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
{
// value values for the UserProperty (in most cases you
// would use LoginName or Name)
//Sid
//ID
//LoginName
//Name
//IsDomainGroup
//Email
//RawSid
//Notes
try
{
string err = string.Empty;
if (__ActivationProperties == null)
{
err = "__ActivationProperties was null";
}
else
{
SPUser user = __ActivationProperties.OriginatorUser;
if (user != null && UserProperty != null)
{
PropertyInfo property = typeof (SPUser).GetProperty(UserProperty);
if (property != null)
{
object value = property.GetValue(user, null);
PropertyValueVariable = (value != null) ? value.ToString() : "";
}
else
{
err = string.Format("no property found with the name \"{0}\"", UserProperty);
}
}
else
{
err = "__ActivationProperties.OriginatorUser was null";
}
}
if (!string.IsNullOrEmpty(err))
Common.LogExceptionToWorkflowHistory(new ArgumentOutOfRangeException(err), executionContext,
WorkflowInstanceId);
}
catch (Exception e)
{
Common.LogExceptionToWorkflowHistory(e, executionContext, WorkflowInstanceId);
}
return ActivityExecutionStatus.Closed;
}
}
</code></pre>
<p>And then wire it up with the following .action xml file:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<WorkflowInfo Language="en-us">
<Actions>
<Action Name="Lookup initiator user property"
ClassName="XXX.ActivityLibrary.LookupInitiatorInfo"
Assembly="XXX.ActivityLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=XXX"
AppliesTo="all"
Category="WormaldWorkflow Custom Actions">
<RuleDesigner Sentence="Lookup initating users property named %1 and store in %2">
<FieldBind Field="UserProperty" DesignerType="TextArea" Id="1" Text="LoginName" />
<FieldBind Field="PropertyValueVariable" DesignerType="ParameterNames" Text="variable" Id="2"/>
</RuleDesigner>
<Parameters>
<Parameter Name="__Context" Type="Microsoft.Sharepoint.WorkflowActions.WorkflowContext, Microsoft.SharePoint.WorkflowActions" Direction="In"/>
<Parameter Name="__ActivationProperties" Type="Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties, Microsoft.SharePoint" Direction="In"/>
<Parameter Name="UserProperty" Type="System.String, mscorlib" Direction="In" />
<Parameter Name="PropertyValueVariable" Type="System.String, mscorlib" Direction="Out" />
</Parameters>
</Action>
</Actions>
</WorkflowInfo>
</code></pre>
|
<p>I don't think this is possible to do in SharePoint Designer out of the box. You could probably write a custom action to get the originator, but I don't believe it is exposed through the SPD workflow interface at all. </p>
<p>The best you could probably do is get the user who created or modified the item in the list, but this wouldn't handle cases where the workflow was manually run.</p>
|
<p>The custom activity solution only work if you are working with moss, if you only have wss 3.0 you can put one step more in your workflow and set a custom comment field with any information, this make the last modified person to change and become the same as the workflow initiator, then you can use the ModifiedBy field to make any decision that you need.</p>
| 15,935
|
<p>Is there a tool or a way to find out how much memory consumed by each DLL or object in .NET?
The more detail it analyzes the better. Thanks.</p>
|
<p>You could try <a href="http://www.microsoft.com/downloads/details.aspx?familyid=a362781c-3870-43be-8926-862b40aa0cd0&displaylang=en" rel="nofollow noreferrer">CLR Profiler</a> which is free, or maybe the trial version of <a href="http://www.red-gate.com/Products/ants_profiler/index.htm" rel="nofollow noreferrer">ANTS Profiler</a>.</p>
|
<p>I always liked the <a href="http://www.jetbrains.com/profiler/index.html" rel="nofollow noreferrer">dot.Trace profiler</a> from Jetbrains (as well as Resharper)</p>
| 13,508
|
<p>How can instantiated classes <strong>access the Document class?</strong></p>
<p>Even after I <strong>name the Document class</strong> using the Properties bar in Flash, attempting to access it from other classes usually fails, saying <em>"attempting to access an undefined property...</em></p>
<p>One solution is always <strong>casting the Document class to itself!</strong> eg.</p>
<pre><code>Main(Main).globalMethod();
</code></pre>
<p>But sometimes even this stellar gotcha fails, and then there's usually no way out, apart from <strong>the obvious!</strong></p>
<pre><code>class Other{
var parentClass:Main;
public function Other(parent:Main){
parentClass = parent; // pointer to the Main class in a local var!
Main(parentClass).globalMethod();
}
}
</code></pre>
|
<p>You can use a singleton for your document class (<code>Main</code>, in your example), which allows you to access the instance from anywhere.</p>
<pre><code>public class Main extends Sprite {
private static var _instance:Main;
public static function get instance():Main { return _instance; }
public function Main() {
_instance = this;
// etc...
}
// etc...
}
</code></pre>
<p>Then you access the <code>Main</code> instance like this:</p>
<pre><code>public class Other {
public function Other() {
Main.instance.usefulInstanceMethod();
}
}
</code></pre>
<p>The document class is a pretty good candidate for the singleton pattern, because generally there should only be instance available.</p>
|
<p>The document class is not inherently a globally accessible object. If you want to call methods that are in the document class, you'll always have to pass a reference from Main to any other classes/objects that want to call its methods. A more object oriented approach would be to dispatch events from your other classes (Other) for the Main class to listen to and call an appropriate method in itself.</p>
<p>If you are unconcerned about keeping a good OOP structure and want to access the document class from a display object that has been added to the display list you could try something like: <code>stage.getChildAt( 0 );</code></p>
| 48,361
|
<p>I have an ASP.NET application that will host multiple tenants (Software-as-a-Service style). Each tenant will have their own domain name (www.mydomain.com, www.yourdomain.com) and their own SSL certificate.</p>
<p><strong>Is there a way to host the application such that all of the tenants are on the same application <em>instance</em>?</strong></p>
<ul>
<li>I know you can have multiple IIS web sites pointing to the same shared location, but that won't work - it's not the same <em>instance</em>. That's different <em>instances</em> of the same <em>application</em>.</li>
<li>I also know you can use SSL host header mapping with wildcard certificates, but that won't work because all of the tenants would need to be subdomains of the same primary domain - yourdomain.commondomain.com, mydomain.commondomain.com. For the solution to be valid, everyone needs to have their own domain name, not be subdomains. (Ideally each tenant could opt to use an EV cert, too, and you can't have wildcard EV certs.)</li>
</ul>
|
<p>The problem is that classic SSL requires the certificate to be presented before the web browser has indicated which host it wants to use. You can therefore only configure one certificate per IP/port combination.</p>
<p>There is an extension to TLS called <a href="http://en.wikipedia.org/wiki/Server_Name_Indication" rel="nofollow noreferrer">Server Name Indication</a> which allows the browser to indicate which logical server it wants to talk to. This feature is <a href="http://www.iis.net/learn/get-started/whats-new-in-iis-8/iis-80-server-name-indication-sni-ssl-scalability" rel="nofollow noreferrer">supported as of IIS 8.0 (Windows Server 2012)</a>.</p>
<p>Wildcards work because the certificate <em>itself</em> says that it is valid for all servers under that domain.</p>
|
<p>You constrained to only IIS - or could putting soft/hard proxies or content-switching hardware also be an option? </p>
<p>Thinking that you could terminate the SSL at a proxy or content-switch - then transform the request into your own internal url.</p>
<p>e.g. foo.com/x and bar.com/y get translated into myapp/x and myapp/y respectively under the hood - passing the original hostname in the request headers.</p>
| 14,365
|
<p>I'm using castle windsor for a pet-project I'm working on. I'm starting to notice that I need to call the IoC container in different places in my code to create new objects. This dependency on the container makes my code harder to maintain.</p>
<p>There are two solutions I've used to solve this problem</p>
<p>I tried to create abstract factories as wrappers around the container that I could inject into parts of my application that need to create objects. This works but has some drawbacks because castle has a hard time injecting it's own container as a dependency. So I have to do that by hand, this kind of defeats the whole purpose of the IoC container.</p>
<p>I have used the main applicationcontroller class to wrap the IoC container and work as a central factory/repository. This was quite succesfull but this class is getting too big and acts like a central god-object, almost every other objects has a reference to it.</p>
<p>Both solutions sort of work but both have their drawbacks. So I'm curious if other people had the same problem and have found better solutions.</p>
<hr>
<p><em>edit</em>
The problem isn't for object A that depends on object B. Here I usually just use constructor injection and everything works. Sometimes I have objects of type A that need to create a variable number of other objects of type B during their lifetime. I'm not sure how to do this.</p>
<p>@Blair Conrad: The maintenance issues are not severe until now. I had some classes depend on the container object calling container.Resolve<>. And I don't want to have my code depending on what I think is infrastructure. I'm still trying things out so I noticed I had to change a lot of code when switching from ninject to castle for this project.</p>
<p>@flowers: Hmm. I like your fists solution. It combines the things that work from both solutions I've tried. I think I was still thinking too much in objects and not enough in interfaces/responsibilities.
I tried purpose built factories but I would like to have them use the container behind the scenes to create the objects and I havn't found out how I can DI the container into objects in a clean way.</p>
|
<p>Please, do not ever ever use static classes like IoC.Container.Resolve or ContainerFactory.GetContainer!</p>
<p>This makes the code more complicated, harder to test to maintain, to reuse and to read. </p>
<p>Normally any single component or a service has only one single point of injection - that's the constructor (with optional properties). And generally your components or service classes should not ever know about the existence of such thing as container. </p>
<p>If your components really need to have dynamic resolution inside (i.e. resolving exception handling policy or workflow, based on the name), then I recommend to consider <a href="http://rabdullin.com/how-to-avoid-tight-ioc-coupling-in-non-deterministic-resolution-scenarios/" rel="noreferrer">lending IoC powers via the highly-specific providers</a></p>
|
<p>That's a really comon problem. Windsor's built in <a href="http://docs.castleproject.org/Windsor.Typed-Factory-Facility-interface-based-factories.ashx" rel="nofollow">Typed Factory Facility</a> will give you the benefits of using a factory, without the mentioned drawbacks.</p>
| 13,490
|
<p>I have a table ("venues") that stores all the possible venues a volunteer can work, each volunteer is assigned to work one venue each.</p>
<p>I want to create a select drop down from the venues table.</p>
<p>Right now I can display the venue each volunteer is assigned, but I want it to display the drop down box, with the venue already selected in the list.</p>
<pre><code><form action="upd.php?id=7">
<select name="venue_id">
<?php //some sort of loop goes here
print '<option value="'.$row['venue_id'].'">'.$row['venue_name'].'</option>';
//end loop here ?>
</select>
<input type="submit" value="submit" name="submit">
</form>
</code></pre>
<p>For example, volunteer with the id of 7, is assigned to venue_id 4</p>
<pre><code><form action="upd.php?id=7">
<select name="venue_id">
<option value="1">Bagpipe Competition</option>
<option value="2">Band Assistance</option>
<option value="3">Beer/Wine Pouring</option>
<option value="4" selected>Brochure Distribution</option>
<option value="5">Childrens Area</option>
<option value="6">Cleanup</option>
<option value="7">Cultural Center Display</option>
<option value="8">Festival Merch</option>
</select>
<input type="submit" value="submit" name="submit">
</form>
Brochure Distribution option will already be selected when it displays the drop down list, because in the volunteers_2009 table, column venue_id is 4.
</code></pre>
<p>I know it will take a form of a for or while loop to pull the list of venues from the venues table</p>
<p>My query is:</p>
<pre><code>$query = "SELECT volunteers_2009.id, volunteers_2009.comments, volunteers_2009.choice1, volunteers_2009.choice2, volunteers_2009.choice3, volunteers_2009.lname, volunteers_2009.fname, volunteers_2009.venue_id, venues.venue_name FROM volunteers_2009 AS volunteers_2009 LEFT OUTER JOIN venues ON (volunteers_2009.venue_id = venues.id) ORDER by $order $sort";
</code></pre>
<p>How do I populate the select drop down box with the venues (<strong>volunteers_2009.venue_id</strong>, <strong>venues.id</strong>) from the venues table and have it pre-select the venue in the list?</p>
|
<pre class="lang-php prettyprint-override"><code>$query = "SELECT volunteers_2009.id, volunteers_2009.comments, volunteers_2009.choice1, volunteers_2009.choice2, volunteers_2009.choice3, volunteers_2009.lname, volunteers_2009.fname, volunteers_2009.venue_id, venues.venue_name FROM volunteers_2009 AS volunteers_2009 LEFT OUTER JOIN venues ON (volunteers_2009.venue_id = venues.id) ORDER by $order $sort";
$res = mysql_query($query);
echo "<select name = 'venue'>";
while (($row = mysql_fetch_row($res)) != null)
{
echo "<option value = '{$row['venue_id']}'";
if ($selected_venue_id == $row['venue_id'])
echo "selected = 'selected'";
echo ">{$row['venue_name']}</option>";
}
echo "</select>";
</code></pre>
|
<pre><code><!DOCTYPE html>
<html>
<head>
<title>table binding</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div id="mydiv" style="width:100px;height:100px;background-color:yellow">
<select id="myselect"></select>
</div>
</body>
</html>
<?php
include('dbconnection.php');
$sql = "SHOW TABLES FROM $dbname";
$result = mysqli_query($conn,$sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysqli_error();
exit;
}
while ($row = mysqli_fetch_row($result)) {
echo "<script>
var z = document.createElement('option');
z.setAttribute('value', '".$row[0]."');
var t = document.createTextNode('".$row[0]."');
z.appendChild(t);
document.getElementById('myselect').appendChild(z);</script>";
}
?>
</code></pre>
| 24,328
|
<p>Most applications only have "Restore, Move, Size, Minimize, Maximize and Close", however <i>MS SQL</i> offers extra options "Help, Customize view". Along those lines, is it possible to add to the right click menu of an application in the task bar? </p>
<p>Note: I'm <b>not</b> referring to an icon in the notification area next to the clock.</p>
|
<p>This is a simpler <a href="http://bytes.com/forum/thread529258.html" rel="nofollow noreferrer">answer</a> I found. I quickly tested it and it works. </p>
<p>My code:</p>
<pre><code> private const int WMTaskbarRClick = 0x0313;
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case WMTaskbarRClick:
{
// Show your own context menu here, i do it like this
// there's a context menu present on my main form so i use it
MessageBox.Show("I see that.");
break;
}
default:
{
base.WndProc(ref m);
break;
}
}
}
</code></pre>
|
<p>The menu on right click of the minimized program or Alt+Space or right click of the window icon in the title bar is called the SysMenu.</p>
<p>Here's an option for WPF:</p>
<pre><code>// License MIT 2019 Mitch Gaffigan
// https://stackoverflow.com/a/58160366/138200
public class SysMenu
{
private readonly Window Window;
private readonly List<MenuItem> Items;
private bool isInitialized;
private IntPtr NextID = (IntPtr)1000;
private int StartPosition = 5;
public SysMenu(Window window)
{
this.Items = new List<MenuItem>();
this.Window = window ?? throw new ArgumentNullException(nameof(window));
this.Window.SourceInitialized += this.Window_SourceInitialized;
}
class MenuItem
{
public IntPtr ID;
public string Text;
public Action OnClick;
}
public void AddSysMenuItem(string text, Action onClick)
{
if (string.IsNullOrWhiteSpace(text))
{
throw new ArgumentNullException(nameof(text));
}
if (onClick == null)
{
throw new ArgumentNullException(nameof(onClick));
}
var thisId = NextID;
NextID += 1;
var newItem = new MenuItem()
{
ID = thisId,
Text = text,
OnClick = onClick
};
Items.Add(newItem);
var thisPosition = StartPosition + Items.Count;
if (isInitialized)
{
var hwndSource = PresentationSource.FromVisual(Window) as HwndSource;
if (hwndSource == null)
{
return;
}
var hSysMenu = GetSystemMenu(hwndSource.Handle, false);
InsertMenu(hSysMenu, thisPosition, MF_BYPOSITION, thisId, text);
}
}
private void Window_SourceInitialized(object sender, EventArgs e)
{
var hwndSource = PresentationSource.FromVisual(Window) as HwndSource;
if (hwndSource == null)
{
return;
}
hwndSource.AddHook(WndProc);
var hSysMenu = GetSystemMenu(hwndSource.Handle, false);
/// Create our new System Menu items just before the Close menu item
InsertMenu(hSysMenu, StartPosition, MF_BYPOSITION | MF_SEPARATOR, IntPtr.Zero, string.Empty);
int pos = StartPosition + 1;
foreach (var item in Items)
{
InsertMenu(hSysMenu, pos, MF_BYPOSITION, item.ID, item.Text);
pos += 1;
}
isInitialized = true;
}
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg == WM_SYSCOMMAND)
{
var item = Items.FirstOrDefault(d => d.ID == wParam);
if (item != null)
{
item.OnClick();
handled = true;
return IntPtr.Zero;
}
}
return IntPtr.Zero;
}
#region Win32
private const Int32 WM_SYSCOMMAND = 0x112;
private const Int32 MF_SEPARATOR = 0x800;
private const Int32 MF_BYPOSITION = 0x400;
private const Int32 MF_STRING = 0x0;
[DllImport("user32.dll")]
private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
[DllImport("user32.dll")]
private static extern bool InsertMenu(IntPtr hMenu, int wPosition, int wFlags, IntPtr wIDNewItem, string lpNewItem);
#endregion
}
</code></pre>
<p>Example of use:</p>
<pre><code>internal partial class MainWindow : Window
{
public MainWindow()
{
var sysMenu = new SysMenu(this);
sysMenu.AddSysMenuItem("Quit", miQuit_Click);
sysMenu.AddSysMenuItem("Show debug tools", miShowDebug_Click);
}
private void miQuit_Click()
{
// "On-Click" logic here
}
private void miShowDebug_Click()
{
// "On-Click" logic here
}
}
</code></pre>
| 18,525
|
<p>I am displaying a list of items using a SAP ABAP column tree model, basically a tree of folder and files, with columns.</p>
<p>I want to load the sub-nodes of folders dynamically, so I'm using the EXPAND_NO_CHILDREN event which is firing correctly.</p>
<p>Unfortunately, after I add the new nodes and items to the tree, the folder is automatically collapsing again, requiring a second click to view the sub-nodes.
Do I need to call a method when handling the event so that the folder stays open, or am I doing something else wrong?</p>
<pre><code>* Set up event handling.
LS_EVENT-EVENTID = CL_ITEM_TREE_CONTROL=>EVENTID_EXPAND_NO_CHILDREN.
LS_EVENT-APPL_EVENT = GC_X.
APPEND LS_EVENT TO LT_EVENTS.
CALL METHOD GO_MODEL->SET_REGISTERED_EVENTS
EXPORTING
EVENTS = LT_EVENTS
EXCEPTIONS
ILLEGAL_EVENT_COMBINATION = 1
UNKNOWN_EVENT = 2.
SET HANDLER GO_APPLICATION->HANDLE_EXPAND_NO_CHILDREN
FOR GO_MODEL.
...
* Add new data to tree.
CALL METHOD GO_MODEL->ADD_NODES
EXPORTING
NODE_TABLE = PTI_NODES[]
EXCEPTIONS
ERROR_IN_NODE_TABLE = 1.
CALL METHOD GO_MODEL->ADD_ITEMS
EXPORTING
ITEM_TABLE = PTI_ITEMS[]
EXCEPTIONS
NODE_NOT_FOUND = 1
ERROR_IN_ITEM_TABLE = 2.
</code></pre>
|
<p>It's been a while since I've played with SAP, but I always found the SAP Library to be particularly helpful when I got stuck...</p>
<p>I managed to come up with this one for you:
<a href="http://help.sap.com/saphelp_nw04/helpdata/en/47/aa7a18c80a11d3a6f90000e83dd863/frameset.htm" rel="nofollow noreferrer">http://help.sap.com/saphelp_nw04/helpdata/en/47/aa7a18c80a11d3a6f90000e83dd863/frameset.htm</a>, specifically: </p>
<blockquote>
<p><em>When you add new nodes to the tree model, set the flag ITEMSINCOM to 'X'.<br />
This informs the tree model that you want to load the items for that node on demand.</em></p>
</blockquote>
<p>Hope it helps?</p>
|
<p>Your code looks fine,</p>
<p>I would use the method <code>ADD_NODES_AND_ITEMS</code> myself if I were to add nodes and items ;)</p>
<p>Beyond that, try to call <code>EXPAND_NODE</code> after you added the items/nodes and see if that helps.</p>
| 2,911
|
<p>For a report in MS Access (2007) I need to put data of some columns on all odd pages and other columns on all even pages. It is for printing out double sided card files onto sheets of paper.</p>
<p>Does somebody have an idea how to do that?</p>
|
<p>Your question is too general. I would suggest you have all columns in all pages, and then add some code to the page header section (or even in the detail section) "On Format" to change the .Visible property of your Detail text boxes depending on the page number.</p>
<p>I think you'll need to have a Text Box in the page header or footer with "=[Page]" as source data in order to know the correct page number. My Access report knowledge might be severely outdated, though.</p>
|
<p>You could alternatively use a pair of queries, printing the first to side A, and the second to side B, perhaps?</p>
| 15,381
|
<p>I am implementing NHibernate into an existing web application. However, we have some other processes that do bulk inserting and updating on the database. How can I make NHibernate aware that changes are occurring on the backend db that were not initiated through NHibernate?</p>
<p>Most of the info that I have read around NHibernate use in asp.net have mentioned storing the Session object in the HttpContext or CallContext. This would then store the session object for the duration of the application lifecycle. This is what I have implemented. I was afraid of the costs of initializing NHibernate on each request. Isn't there a significant performance hit with this approach with initializing the Session object on each request?</p>
<p>Also, would it make more sense to store the SessionFactory in the the HttpContext or CallContext so that the mappings don't have to be regenerated on each request?</p>
|
<p>You shouldn't. NHibernate sessions are there to help you work in an ACID environment, which means that one transaction is not aware of any concurrent transactions. You should be using short sessions which do small sets of actions. You should not be holding sessions open for long periods of time. If you do need long periods of time for working with domain objects, then you should be detaching and then re-attaching the domain objects from and to different sessions.</p>
<p>Once you open a new session, any changes done to the database before the session was opened will be made available through NHibernate.</p>
|
<p>You should not store the Session over multiple requests. Bad, bad idea.</p>
<p>There is little to no overhead with recreating it on every call. It should use database connection pooling - which is where the bulk of the overhead would be.</p>
| 30,727
|
<p>I've just built my first 3D printer. It uses a Bowden setup. </p>
<p>When I try to print the extruder starts fine, but after a few seconds the extruder motor start skipping and the nozzle is jammed. </p>
<p>I tried a cold pull, but it didn't help. I removed the PTFE tube and tried to push the filament with my hand, it works but at the start I need the push harder but after it flows fine. But if I reinstall the Bowden setup, it works fine for a few minutes, but after a few seconds it starts again.</p>
<hr>
<p>Note I am using silver PLA at 200-205 °C. I tried to raise the temperature to 215 °C, but it also jammed, and the filament what after I pushed out was black (it is a new hotend and I never used black filament before), like it was burned (if it is possible).</p>
|
<p>Extruder clogging is, at its root, a matter of too much backpressure at the hotend. There are a number of more specific causes, but it very simply comes down to the fact that the printer cannot feed the filament through the hotend as fast as the extruder is pushing it in.</p>
<p>Things to check, pretty much in the order they should be checked/performed for a brand-new printer:</p>
<ul>
<li><strong>Extruder stepper calibration.</strong> With new printers based on RepRap firmware (Enders, Prusas, pretty much any printer in the \$200-\$400 range these days), one of the first things you have to do after assembly is to calibrate your E-stepper (the motor that drives filament through the extruder). The printer is given commands based on millimeters of movement, including the feeding of filament, and it has to translate those into finite steps of the motors. If those steps don't actually move the extruder or the filament as much as expected, the printer will behave poorly, including clogging. E-stepper calibration is pretty easy, especially on Bowden extruders; you basically disconnect the Bowden tube at either end, load filament through the stepper, cut it off flush with the end of the tube or the coupling, then tell the printer to extrude 100 mm of filament. Cut it off flush again and measure, and if it's not 100 mm, look for a command beginning with <code>M92</code> in your printer configuration (it can be in the settings of your actual printer or a configuration script in your slicer software that gets tacked on to the front of the G-code files generated for use with that printer), and adjust the value you see after the <code>E</code> in that command by multiplying it by 100, then dividing by the millimeters of filament actually extruded in the test. Rinse and repeat until the printer is feeding the amount of fil you tell it to.</li>
<li><strong>Bed height/leveling.</strong> This may not sound like it has anything to do with extruder clogs, but in truth, if your extruder is too close to the print bed at any point during the first layer, it can very easily clog the extruder by not allowing enough material to flow out the nozzle to keep up with what's being fed in. Bed leveling is a key step in print prep, and every printer behaves best with subtle changes to the bed leveling procedure. My guess is that you need to re-level for a slightly higher "zero-Z" above the build plate. If you're using the sheet-of-paper method, either use a thicker piece of paper, or go for less friction as you pass the paper between the nozzle and build plate. </li>
<li><strong>Nozzle diameter settings.</strong> The standard nozzle tip diameter is 0.4 mm, however there are others. Your slicer probably expects the standard diameter as a default, so if you're running a 0.3, 0.2 or 0.1 mm nozzle for finer detail, the slicer has to be told that so it can adjust the filament feed rate. Otherwise it'll be jamming up to 16 times as much filament into that hotend as it should be. This isn't likely to be your problem but it's something to check; most extruder nozzles these days have the tip diameter engraved or pressed into the side of the nozzle, and if yours is unlabeled, try heading to the local music store and buying a single 0.013" guitar string (typically sold as a high E for acoustics). If that wire end easily fits through the extruder nozzle, you have a 0.4 mm, if it does not, it's something smaller.</li>
<li><strong>Extruder clog/obstruction.</strong> That guitar string I mentioned makes a really good extruder cleaner. Just feed it through the extruder tip and gently push it up through the hotend till it pops out the top of the extruder, then feed it back and forth a bit to "floss" the extruder tip, cleaning out any minor carbon buildup. If you can't feed the wire completely through the extruder body from either direction, that's probably your problem, and fixes range anywhere from a little more pressure with the wire, to a narrow drill bit carving out the obstruction, up to removing the entire heat block from the printer, putting it on or in something that won't burn, and blasting it with a soldering torch to burn out the obstruction, followed (after letting it cool) by a bath in some acetone to dissolve any remaining gunk.</li>
<li><strong>Gunked-up extruder hobb.</strong> The toothed wheel attached to the extruder stepper is called the "hobb" (you may hear it called a gear, but it's really not one as it doesn't mesh with another gear). As the printer feeds filament, especially if you've had jamming problems, the hobb's teeth will fill with shavings from the filament it feeds through. This can cause the hobb to slip against the filament, which not only reduces the pressure of the filament being pushed through the extruder, it accelerates the accumulation of gunk on the hobb. A short blast of canned air is usually all you need to clean the hobb; if it still looks pretty caked up, a toothbrush will sort it out. While you're at it, check the idler to be sure it's still spinning freely.</li>
<li><strong>Filament type/brand/age.</strong> You mentioned it's "silver PLA"; the silver stuff I have is actually a "silk PLA" product, that sheathes the PLA in a jacket of another plastic (often PET) for that high-gloss appearance. These kinds of filaments can be very temperamental, as can filaments with glitter or fiber aggregate in them (also common in metallic fil colors). You have to have the printer settings dialed in just right, and some of these products just don't work well at all in some printers. Try getting some very basic, brand-name PLA filament like Hatchbox, ColorFabb, MatterHackers, MakerBot, etc, in a good primary color (avoid black or white; the color saturation affects how easily the stuff extrudes at a given temp), no silk finish or other modification. If that prints well, the suspect becomes the silver fil.</li>
<li><strong>Extruder temperature.</strong> You're printing at 200-205 °C, which is usually good, but if you're getting problems, the first thing to do with PLA is to try printing <em>cooler</em>, not hotter. Case in point, getting PLA too hot can cause it to fully melt and drizzle out (vacating the extruder and causing it to overheat the fil further up, jamming the melt tube), it can gum up (directly clogging the extruder nozzle), and it can carbonize (as you see it doing at 215). If you're already flirting with burning your PLA at 10 degrees hotter, you are probably running too hot. Try backing off to 195 or 190 and see if that helps any.</li>
</ul>
|
<p>It is useful to diagnose your problem if you provide more information, specifically what material you are using and what temperature you are using on your hot end.</p>
<p>Even without the above information, it is likely that the hot end temperature is too low. At a low setting, the filament in the nozzle will soften, perhaps even melt as deeply as needed to be extruded, but as new filament is provided by the extruder motor, it also cools the heater block.</p>
<p>By increasing the temperature, you're ensuring there is sufficient thermal energy to handle the incoming cold material.</p>
<p>It would be useful to increase your nozzle temperature by 5°C for each test. Despite matching your controller's temperature to the manufacturer's specification, you can not be certain that the temperature at the nozzle and heat block are what you have programmed.</p>
| 1,542
|
<p>What's the best way to get user input in a C program where the choices are of a limited number?</p>
<p>Say for example the choices are:</p>
<p>A) Print the list.
B) Add 99 to the end of the list.
C) Delete all duplicates.
5) Reset 5 times.</p>
<p>Entering "A" and then Enter is OK.
Or, just a single keystroke would work as well.</p>
|
<p><code>getchar()</code>, or <code>cgetc()</code>, depending on the platform</p>
|
<p>I have used something simple like the following:</p>
<pre><code>int intput()
{
char input = 0;
int ret_val = 0;
read(0, &input, 1);
switch(input) {
case 'c':
// Do c
break;
case 'p':
// Do p
break;
case 'd':
// Do d
break;
case 'q':
quit = 1;
break;
case '?':
PRINT(ENABLE, "c - connect\n");
PRINT(ENABLE, "p - ping\n");
PRINT(ENABLE, "d - disconnect\n");
PRINT(ENABLE, "q - quit\n");
PRINT(ENABLE, "? - this message\n");
break;
}
return 0;
}
</code></pre>
| 6,424
|
<p>I am dealing with MySQL tables that are essentially results of raytracing simulations on a simulated office room with a single venetian blind. I usually need to retrieve the simulation's result for a unique combination of time and blind's settings. So I end up doing a lot of</p>
<pre><code>SELECT result FROM results WHERE timestamp='2005-05-05 12:30:25' \
AND opening=40 AND slatangle=60
</code></pre>
<p>This looks suspiciously optimizable, since this query should never ever return more than one row. Does it make sense to define an index on the three columns that uniquely identify each row? Or are there other techniques I can use?</p>
|
<p>The answer is most definately a yes. If you define a unique index on timestamp, opening and slatangle MySQL should be able to find your row with very few disc seeks.</p>
<p>You might experiment with creating an index on timestamp, opening, slateangle and result. MySQL may be able to fetch your data from the index without touching the datafile at all.</p>
<p>The MySQL Manual has a <a href="http://dev.mysql.com/doc/refman/5.0/en/query-speed.html" rel="nofollow noreferrer">section about optimzing queries</a>. </p>
|
<p>I wouldn't suggest adding 3 indexes. An index using all three columns may be better and even setting the primary key unique on that combination would be best - only if you're sure that it unique.</p>
| 24,017
|
<p>I am wondering if someone can put a bit of an authoritative reference summary of when the !important declaration in CSS does <strong>not</strong> work to override inline styles.</p>
|
<p>There are many factors involved in determining which styles override one another. The lower a style declaration appears in the <strong>cascade</strong>, and the <strong>more specific</strong> it is in targeting the element, the more it will weigh against other styles.</p>
<p>This is the <a href="http://www.w3.org/TR/CSS2/cascade.html" rel="noreferrer">CSS2 standard</a> for style inheritance:</p>
<blockquote>
<ol>
<li>If the cascade results in a value, use it.</li>
<li>Otherwise, if the property is inherited, use the value of the parent
element, generally the computed value.</li>
<li>Otherwise use the property's initial value. The initial value of
each property is indicated in the
property's definition.</li>
</ol>
</blockquote>
<p>Internally, the browser will <a href="http://www.w3.org/TR/CSS2/cascade.html#specificity" rel="noreferrer">calculate the specificity of a rule</a>, according to the standard. The !important declaration will add weight to the rule, but dynamically assigning a style attribute will often take precedence, because it is usually more-highly specified..</p>
|
<p>I'm pretty sure not all browsers recognise the !important declaration. But can't remember which ones do off the top of my head. Will check and get back to you.</p>
<p>[EDIT]
I can confirm IE6 and earlier do not recognise !important (unless the browser is in standards compliance mode - not the default).</p>
<p>You can use !important to override an inline rule. But also remember that inline rules can be tagged !important as well.</p>
| 23,003
|
<p>Every now and then, I bump into syntax that I've seen before, but never used. This is one of those times.</p>
<p>Can someone explain the purpose of ":this" or ":base" following a C# constructor method?</p>
<p>For example:</p>
<pre><code>public MyClass(SomeArg arg) : this(new SomethingElse(), arg)
{
}
</code></pre>
<p>My gut feeling is that it is used to map a default argument onto another constructor method.</p>
|
<p>You're basically right. <code>this()</code> calls a constructor on the current instance, <code>base()</code> calls the supertype's constructor on current instance. They're generally used to handle constructor overloads so you can add additional options without breaking things out into a separate method.</p>
|
<p>You're right.</p>
<p><strong>: base(...)</strong> calls a constructor of the base class. </p>
<p><strong>: this(...)</strong> calls another constructor of the defining class. Most of the time it works merely as a facade.</p>
| 43,922
|
<p>I am using the following code to check if a variable is not nil and not zero</p>
<pre><code>if(discount != nil && discount != 0)
...
end
</code></pre>
<p>Is there a better way to do this?</p>
|
<pre>
unless discount.nil? || discount == 0
# ...
end
</pre>
|
<p>I believe the following is good enough for ruby code. I don't think I could write a unit test that shows any difference between this and the original.</p>
<pre><code>if discount != 0
end
</code></pre>
| 31,421
|
<p>Good morgning,</p>
<p>I would like to be able to analyze text where I am writting whatever the application I am. Example, If I am here, typing in this TextArea, I would like to be able to get the text, same way if I were in the Subject Textbox in my Outlook.</p>
<p>I have search Google without success, maybe it's because it require Win32API call.</p>
<p>The goal would be to start having fun with multiple algorithm like "Bloom Filter" and Markov Chain.</p>
<p>Is it possible with C# and how to start?</p>
|
<p>CodingTheWheels series on building a poker bot goes into detail on how to capture window events from other applications. Its not exactly what your looking for, but it has some good info.</p>
<p><a href="http://www.codingthewheel.com/archives/how-i-built-a-working-poker-bot" rel="nofollow noreferrer">http://www.codingthewheel.com/archives/how-i-built-a-working-poker-bot</a></p>
|
<p>This tool works perfectly fine even for non-managed processess.</p>
<p><a href="http://www.codeproject.com/KB/cs/RuntimeObjectEditor.aspx" rel="nofollow noreferrer">Runtime Object Editor</a></p>
| 19,612
|
<p>I have a problem with Gridview sorting that is similar to others but I'm binding to a collection object as opposed to a data table.</p>
<p>The existing business rules and data access layers of an application follow the pattern of having an object and, if you need a collection of objects of that type, to have another class inheriting CollectionBase and implementing IBindingList.</p>
<p>For desktop applications, it was easy to databind a gridview to one of these objects and there weren't any problems with turning on column sorting. Everything was 'in state' in the desktop app's presentation layer.</p>
<p>Now that code is being moved to a new web application (ASP.NET 2.0, VB codebehind pages).</p>
<p>I've played around with what I had to do to only have certain columns of the collection show up in the gridview and the gridview looked pretty good. When I turned on 'allow sorting', that's when the problems showed up.</p>
<p>I'm getting the error about not having a .Sorting method, etc. In researching this, I found all sorts of solutions that were easily implemented with dataviews <em>if</em> my source was a data table. But it's not - it's a collection. I tried to "cheap shot" a datasource by converting the collection to an XML memory stream and them trying to .ReadXML back into a dataset but that didn't work [Root element is missing error was as far as I got in the dataset.ReadXml(ioTemp) where ioTemp was the System.IO.MemoryStream used in the xml serializer].</p>
<p>Because of the old desktop apps, I've never had to worry about sorting a collection since the gridview handled it once it was loaded. In fact, it's a 'standard' that the collection's .SortProperty, .SortDirection and .ApplySort all through NotSupportedExceptions (I inherited this code from programmers long gone).</p>
<p>Is there an easy way to convert the collection to a data table or a way to sort the collection without having to go back to the database each time? Object Data Sources won't work becuase of the intricate rules in how the objects are built - the wizards in VS2005 just can't handle what we need to do (grabbing data from several tables conditionally to make an object).</p>
<p>Thanks in advance.</p>
|
<p>Have you considered client side sorting instead? </p>
<p>I have used the jquery tablesorter plugin in the past with ASP Gridviews.</p>
<p><a href="http://tablesorter.com/" rel="nofollow noreferrer">http://tablesorter.com/</a></p>
|
<p>I had a similar issue and i needed to implement IComparable on the objects. Basically to sort a collection of objects you need a way to distinguish their order. The IComparable interface has one method called Compare which allows the .Net framework to work out the order of the objects when you sort them. You need to implement this method yourself to get the sort method to work.</p>
<p><a href="http://www.google.ie/search?hl=en&q=vb.net+implement+icomparable&btnG=Google+Search&meta=" rel="nofollow noreferrer" title="Google results">Google results</a></p>
<p>You don't mention the error message so i cant be sure if this is the case, can you post the error?</p>
<p>EDIT :</p>
<p>In regards to your comment; you can implement multi column sorting, it just requires more work. You can specify the fields to sort the collection by and then use this information within the CompareTo Method.</p>
<p><a href="http://codebetter.com/blogs/david.hayden/archive/2005/02/27/56099.aspx" rel="nofollow noreferrer">Have a look at this</a></p>
| 32,919
|
<p>I've been tasked to develop a web application to cover one of our business functions. It needs to have external access from outside our network. At the same time, it needs to be done fairly quickly. I don't have any experience in extranet applications so I'm not exactly sure what all is involved. Learning about it is taking time. I'd like to get the app working first. </p>
<p>What kind of things should I be considering if I decide to not incorporate external access from the beginning and tack it on later? Is that just doomed from the get go? </p>
<p>Thanks,
Keith</p>
|
<p>You can take many things for granted when you are developing for local network:</p>
<ol>
<li><p>Highspeed network</p></li>
<li><p>Trusted user base </p></li>
<li><p>Same timezone for all users (this makes maintenance jobs easier to schedule among other things)</p></li>
<li><p>Control over which browsers and versions users should use</p></li>
<li><p>Authentication against LAN authentication system or no authentication at all due to trusted nature of user base</p></li>
<li><p>Custom port number on web-server as there is no firewall between users and web-server (though this more of deployment issue)</p></li>
</ol>
<p>You will need to challenge all these assumptions when designing for extra net.
For example you should estimate the slowest client connection you need to support. Oddest or most restricted browsers your users might use. </p>
<p>If you decide to use SSL, do check the performance of your website on the slowest connection from the beginning. I have seen many SSL sites perform terribly on slow connections. </p>
|
<p>to consider:<br>
How are you going to authenticate?<br>
How important is it to not be broken into? </p>
| 23,294
|
<p>I've recently begun evaluating a few project management projects for the company I work for. It's the classic case - growing company looking for the right solution (meaning, free or really cheap). It's a combination shop - Windows, Macs, and Linux on the desktop. The tech savviness, of course, ranges from newbie to unix guru. </p>
<p>I have yet to find anything really close to a total solution. I don't expect to find one, but I am looking for suggestions/guidance/any sort of feedback based on people's experience.</p>
<p>What I'm looking for:</p>
<ul>
<li>web based</li>
<li>methodology independent (not looking for an agile solution, etc.)</li>
<li>free or really cheap</li>
<li>document management</li>
<li>timelines and milestones</li>
<li>task tracking and assigning </li>
<li>reporting</li>
<li>source control</li>
<li>development wiki</li>
</ul>
<p>I've looked at Trac, Projectivity, Basecamp, JIRA, RT, XPlanner, and SharedPlan. I've stayed away from Bugzilla due to previous unhappy experiences with it. None of these things really does everything - some are extendable, but I'd check here before going down that path.</p>
<p>Thanks,</p>
|
<p>Read through Edward Tufte's long-running Ask E.T. topic Project Management Graphics (or Gantt Charts). There is no consensus answer, but a lot of things have been evaluated.</p>
<p><a href="http://www.edwardtufte.com/bboard/q-and-a-fetch-msg?msg_id=000076&topic_id=1&topic=Ask%20E%2eT%2e" rel="nofollow noreferrer" title="Ask E T">link text</a></p>
|
<p>I looked hard at Alfresco and Joomla.</p>
<p>None met my needs because I wanted the ultimate in simplicity. But, you seem to prefer having the kitchen sink included (while keeping it easy to use, I guess), so either one of these might be right for you.</p>
<p>Currently, I'm throwing together my own using Django, keeping only the project-deadline, forum and file-versioning concepts.</p>
| 25,150
|
<p>I see that the SML/NJ includes a queue structure. I can't figure out how to use it. How do I use the additional libraries provided by SML/NJ?</p>
|
<p>The <a href="http://www.smlnj.org/doc/smlnj-lib/Manual/queue.html" rel="nofollow noreferrer"><code>Queue</code> structure</a> is not specified by SML '97, but it is present in SML/NJ's top-level environment.</p>
<pre>
$ sml
Standard ML of New Jersey v110.69 [built: Fri Mar 13 16:02:47 2009]
- Queue.mkQueue ();
[autoloading]
[library $SMLNJ-LIB/Util/smlnj-lib.cm is stable]
[autoloading done]
stdIn:1.1-1.17 Warning: type vars not generalized because of
value restriction are instantiated to dummy types (X1,X2,...)
val it = - : ?.X1 Queue.queue
-
</pre>
<p>You can <code>open</code> a structure. This lets you avoid typing <code>Queue.</code> in front of everything. It's discouraged to do this at the top-level, though, because it pollutes the environment and makes it much less obvious what you're depending on. (Within another structure I'd say it might be acceptable in some situations.)</p>
<pre>
$ sml
Standard ML of New Jersey v110.69 [built: Fri Mar 13 16:02:47 2009]
- open Queue;
[autoloading]
[library $SMLNJ-LIB/Util/smlnj-lib.cm is stable]
[autoloading done]
opening Queue
type 'a queue
exception Dequeue
val mkQueue : unit -> 'a queue
val clear : 'a queue -> unit
val isEmpty : 'a queue -> bool
val enqueue : 'a queue * 'a -> unit
val dequeue : 'a queue -> 'a
val next : 'a queue -> 'a option
val delete : 'a queue * ('a -> bool) -> unit
val head : 'a queue -> 'a
val peek : 'a queue -> 'a option
val length : 'a queue -> int
val contents : 'a queue -> 'a list
val app : ('a -> unit) -> 'a queue -> unit
val map : ('a -> 'b) -> 'a queue -> 'b queue
val foldl : ('a * 'b -> 'b) -> 'b -> 'a queue -> 'b
val foldr : ('a * 'b -> 'b) -> 'b -> 'a queue -> 'b
- mkQueue ();
stdIn:3.1-3.11 Warning: type vars not generalized because of
value restriction are instantiated to dummy types (X1,X2,...)
val it = - : ?.X1 queue
-
</pre>
|
<p>I don't have a complete answer for you but I could point you in the right direction. You should look up using the compilation manager (CM) which is built in to SML/NJ. You can think of it as Make for SML.</p>
<p>To use a library from the SML/NJ library you then add smlnj-lib.cm to the CM description file of your application. Then you can use the declarations such as Queue from that library.</p>
<p>The smlnj website has some documentation about the <a href="http://www.smlnj.org/doc/CM/index.html" rel="nofollow noreferrer">compilation manager</a>.</p>
<p>Hope this at least points you in the right direction.</p>
| 23,856
|
<p>Is using a handrolled POCO queue class using pseudo code</p>
<pre><code>T Dequeue() {
lock(syncRoot) {
if(queue.Empty) Thread.Wait();
}
}
void Enqueue(T item) {
queue.Enqueue(item);
Thread.Notify();
}
</code></pre>
<p>For WCF is request queueing a scalable approach?</p>
|
<p>And also don't forget to add namespaces like below to the web config, I think preview 5 default web.config does not have System.Web.Mvc.Html in it:</p>
<pre><code><namespaces>
<add namespace="System.Web.Mvc"/>
<add namespace="System.Web.Mvc.Ajax"/>
<add namespace="System.Web.Mvc.Html"/>
<add namespace="System.Web.Routing"/>
<add namespace="System.Linq"/>
<add namespace="System.Collections.Generic"/>
</namespaces>
</code></pre>
|
<p>In addition to adding the assembly reference I also had to add the line</p>
<pre><code> <add namespace="System.Web.Mvc.Html"/>"
</code></pre>
<p>to the pages/namespaces section in web.config file.</p>
| 25,992
|
<p>How do you manipulate GUID's when doing Windows programming in C or C++?</p>
|
<p>Under Win32 if you want to manipulate GUID's you can use the UuidXXX() Network/RPC functions:</p>
<ul>
<li><p>UuidCompare()</p></li>
<li><p>UuidCreate()</p></li>
<li><p>UuidCreateNil()</p></li>
<li><p>UuidCreateSequential()</p></li>
<li><p>UuidEqual()</p></li>
<li><p>UuidFromString()</p></li>
<li><p>UuidHash()</p></li>
<li><p>UuidIsNil()</p></li>
<li><p>UuidToString()</p></li>
</ul>
|
<p>I use boost::uuid : <a href="http://www.boost.org/doc/libs/1_43_0/libs/uuid/index.html" rel="nofollow noreferrer">http://www.boost.org/doc/libs/1_43_0/libs/uuid/index.html</a>
That way it is guaranteed to still work if I port my application on another plaftorm.</p>
| 17,012
|
<p>I found in a bug in an old C++ MFC program we have that calculates an offset (in days) for a given date from a fixed base date. We were seeing results that were off by one for some reason, and I tracked it down to where the original programmer had used the CTimeSpan.GetDays() method. According to the <a href="http://msdn.microsoft.com/en-us/library/14zezc9x.aspx" rel="nofollow noreferrer">documentation</a>:</p>
<blockquote>
<p>Note that Daylight Savings Time can cause GetDays to return a potentially surprising result. For example, when DST is in effect, GetDays reports the number of days between April 1 and May 1 as 29, not 30, because one day in April is shortened by an hour and therefore does not count as a complete day.</p>
</blockquote>
<p>My proposed fix is to use <code>(obj.GetTotalHours()+1)/24</code> instead. I think that would cover all the issues since this is a batch job that runs at about the same time every day, but I thought I'd ask the smart people here before implementing it if there might be a better way. </p>
<p>This is just a side issue, but I'm also curious how this would be handled if the program could be run at any time.</p>
|
<p>Your fix works fine to get the number of whole 24-hour periods between two times - as long as the events occur at the same time each day. Otherwise that "+1" in the expression could lead to an off-by-one error.</p>
<p>Sometimes you don't care what time of day the event occured, you just want to know which day. In that case, you need to zero out the hours, minutes, and seconds, then use your formula:</p>
<pre><code>CTime startDay(start.GetYear(), start.GetMonth(), start.GetDay(), 0, 0, 0);
CTime finishDay(finish.GetYear(), finish.GetMonth(), finish.GetDay(), 0, 0, 0);
int days = ((finishDay - startDay).GetTotalHours() + 1) / 24;
</code></pre>
|
<p>A minor change to what Mark suggested and it works without any reliance on rounding: Just add one more parameter of zero to the <code>CTime</code> constructor. This forces both times to be in standard time (not daylight savings). The default value for that parameter is -1 which means "Automatically compute if daylight savings time is in effect."</p>
<pre><code>// Discard hours, minutes, seconds, and daylight savings time
CTime startDay(start.GetYear(), start.GetMonth(), start.GetDay(), 0, 0, 0, 0);
CTime endDay(end.GetYear(), end.GetMonth(), end.GetDay(), 0, 0, 0, 0);
// Get number of days apart
CTimeSpan span = endDay - startDay;
int nDays = span.GetDays();
</code></pre>
<p>Tested and works.</p>
| 30,175
|
<p>I want to log to the console when I'm using un-minimized JavaScript files.</p>
<p>Comments are taken out already when I minimize JavaScript. I'm wondering if there's a way I can write a command that isn't commented out but will still be taken out when I minimize the JavaScript file. </p>
|
<p>I think I'd be pretty upset if a Javascript minimizer changed the behaviour of my code based on some funny/clever/odd code construct. How could you ever be sure that code construct isn't there intentionally?</p>
<p>As has been suggested, have a variable that disables logging. Then as part of your minimize script or batch job, you can swap that variable to its non-logging state using sed (for example) before minimizing.</p>
|
<p>Unless whatever you're using to minimize your JS supports conditional statements I don't think you can do this.</p>
<p>Why not just log things if a certain variable is set? </p>
| 19,300
|
<p>I have nant set up to build my ASP.NET MVC project and it works fine locally. I add nant to a tools folder and add it to version control. TeamCity picks up my changes and starts the build but it fails.</p>
<p>I believe I'm using the latest version of Nant and I have added the .net framework 3.5 to the nant.exe.config. What am I missing on the server and yes the .net framework is installed on the server as the asp.net mvc app does work if I manually build and deploy there? </p>
<p>The build file is as follows:
</p>
<pre><code><target name="compile" description="Compiles using the AutomatedDebug Configuration">
<msbuild project="Tolt.Sims.sln" />
</target>
</code></pre>
<p></p>
<p>Here is the error:</p>
<pre>
BUILD FAILED Failed to initialize the 'Microsoft .NET Framework 2.0' (net-2.0) target framework.
Property evaluation failed. Expression: ${path::combine(sdkInstallRoot, 'bin')} ^^^^^^^^^^^^^^ Property 'sdkInstallRoot' has not been set.
For more information regarding the cause of the build failure, run the build again in debug mode. Try 'nant -help' for more information
</pre>
|
<p>If you're using the beta version of NAnt (which currently is the only way you'll get support for targeting anything greater than the 2.0 framework), you maybe running into a registry problem. A similar problem was <a href="http://www.timbarcz.com/blog/NantSetupForVisualStudio2008AndNet35.aspx" rel="nofollow noreferrer">reported by Tim Barcz</a>. </p>
<p>Things pretty much boiled down to NAntContrib (provider of msbuild task) pointing to the 2.0 version of msbuild. Check out his solution to see if it applies to your scenario.</p>
|
<p>I've run into similar issues with NAnt. I know this isn't the <em>Best</em> solution, but it is one that works if you need to get your project moving. </p>
<p>I've found that installing a development environment (C# Express didn't work for me, but VS 2008 did) on the server makes this issue go away. (Yes, I realize this goes against normal best practices, but it works and lets my scripts run so I can get back to coding.)</p>
<p>Just figured I'd share incase anyone else is in a similar situation..(this has worked for me both with CruiseControl.Net and with Hudson).</p>
| 29,827
|
<p>Some years ago I was told about a study into code reuse. Apparently it was found that, on average, programmers have a 7 minute window when searching for code to reuse. If they don't find code that suits their needs within that window they'll write their own.</p>
<p>This was presented in the context of needing to carefully manage your code for reuse to ensure that you can find what you need within the window.</p>
<p>How do you (individuals and organisations) manage your source to make it easier to reuse?
Do you specifically maintain a reuse library? And if so, how do you index it to maximise your hit rate?</p>
|
<p>A complex question:</p>
<ul>
<li><p>Some parts of the code can be generalized as libraries or APIs. We have a common library which is kept up to date with solutions to common problems. Typically: validation, caching, data access classes, logging, etc...</p></li>
<li><p>Some parts are application specific. They cannot be generalized easily. We convert them in HowTos and give internal presentations. Code is also recycled by use of an easily browsable SCM (in our case SVN).</p></li>
<li><p>We also have tools that generate code that one one hand cannot be recycled, on the other it's always similar (think calling a stored procedure).</p></li>
<li><p>Pair programming is also a useful way to spread knowledge of existing solutions. We use that when possible or appropriate.</p></li>
<li><p>The last technique is tuition. Each coder has a tutor to refer to. Since the tutors are few, there is a lot of sharing between them and this knowledge can be diffused in a top down manner.</p></li>
</ul>
|
<blockquote>
<p>How do you (individuals and organisations) manage your source to make
it easier to reuse? Do you specifically maintain a reuse library? And
if so, how do you index it to maximise your hit rate?</p>
</blockquote>
<p>I don't and I have an admittedly controversial opinion here but I find the idea of maximizing code reuse counter-productive (I'm interpreting "maximizing" as prioritizing it above all other things rather than considering it as having both pros and cons to balance in consideration). I prefer instead to allow a healthy amount of redundant efforts in teams to slide in favor of decoupling and isolating each developer's module better. First before everyone starts disagreeing with me left and right, I think we can agree upon some things:</p>
<ol>
<li>Reusing buggy code that will have you spending hours debugging other people's code is not desirable.</li>
<li>Reusing code that balances such a wide range of disparate needs that it barely satisfies your own needs and requires you to jump through a lot of hoops to ultimately get an awkward and inefficient solution is undesirable.</li>
<li>Reusing code that constantly requires design changes and goes through deprecations of a kind which will require you to rewrite the code using it every 6 months is undesirable if you could have just implemented the solution yourself in half an hour in ways that don't need design changes in the future since it's only serving your precise needs.</li>
<li>A codebase filled with alien-looking code is undesirable over one that uses more of the language and standard library in idiomatic and familiar ways, even if that requires slightly more code.</li>
<li>Developers stepping all over each other's toes because both of them want to make incompatible changes to the same design while fighting and arguing and making changes which cause bugs in each other's implementations is undesirable.</li>
<li>Throwing a boatload of dependencies to immature designs that have not proven themselves (not had thorough test coverage, not had the time to really soundproof the design and make sure it effectively satisfies user-end needs without requiring further design changes) is undesirable.</li>
<li>Having to include/import/link a boatload of libraries and classes/functions with the most complex build script to write something simple is undesirable.</li>
<li>Most of all, reusing code in a way that costs far more time both in the short and long run than not reusing it is undesirable.</li>
</ol>
<p>Hopefully we can at least agree on these points. The problem I've found with maximizing code reuse from overly-enthusiastic colleagues was that it often lead to one or more of the problems above. It wasn't directly the enthusiasm for code reuse that was the fundamental problem but that the priorities were skewed towards code reuse rather than test coverage, soundproofing designs, making sure things are mature enough before we reuse them like crazy, and so forth.</p>
<p>Naturally if all the code we reused worked beautifully, had thorough test coverage, was proven to fulfill the needs of everything using it in ways that were far more productive than not reusing it, and didn't have to go through any design changes for years on end, I would be ecstatic about code reuse. But my experiences often found things falling far short of this ideal in ways where code reuse was arguably becoming the maintenance problem rather than the solution.</p>
<blockquote>
<p>How do you (individuals and organisations) manage your source to make
it easier to reuse? Do you specifically maintain a reuse library? And
if so, how do you index it to maximise your hit rate?</p>
</blockquote>
<p>So, again I don't seek to "maximize" code reuse among proprietary code written internally among the team. I seek to make sure the team doesn't spend enormous amount of time on redundant effort, but I let things slide quite a bit if both the physicists and the rendering guys both implement their own axis-aligned bounding box class, e.g. It's not necessarily even that redundant, since the physicist might use min/max representations which are more efficient for his purpose while the rendering developer might use center/half-size representations. I do try to make sure we reuse as much of the standard library when possible, because that's code reuse of a kind that is practically guaranteed to be solid, ultra well-tested, and not require further design changes (other teams are spending a boatload of their time to make sure of that).</p>
<p>Instead I shift the focus on testing. A module duplicating a little bit of code here and there is totally fine if you ask me if it's working beautifully in ways that make users really happy, has thorough test coverage, and doesn't warrant endless changes. We accept such duplication all the time when we use third party libraries who likely duplicate some code that we also have in our internal codebase. It's not an issue there when the redundancy doesn't lead to redundant maintenance efforts.</p>
<p>So I suggest just relaxing the idea of maximizing code reuse just a little bit. But if you want to make it easy as possible to reuse the really solid, well-tested, non-trivial code, then I've found it far more helpful to organize very singular-purpose libraries, like a "math" library, an "image" processing library, etc. -- instead of trying to fuse them all together into something like "core" or "common". The latter types tend to tempt developers to throw in all kinds of eclectic utility functions which barely benefit the team using them, and mostly it tends to become messy in ways where it starts to become difficult to find anything of interest.</p>
| 17,565
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.