instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>I'm developing a multilanguage software. As far as the application code goes, localizability is not an issue. We can use language specific resources and have all kinds of tools that work well with them.</p>
<p>But what is the best approach in defining a multilanguage database schema? Let's say we have a lot of tables (100 or more), and each table can have multiple columns that can be localized (most of nvarchar columns should be localizable). For instance one of the tables might hold product information:</p>
<pre class="lang-sql prettyprint-override"><code>CREATE TABLE T_PRODUCT (
NAME NVARCHAR(50),
DESCRIPTION NTEXT,
PRICE NUMBER(18, 2)
)
</code></pre>
<p>I can think of three approaches to support multilingual text in NAME and DESCRIPTION columns:</p>
<ol>
<li><p>Separate column for each language</p>
<p>When we add a new language to the system, we must create additional columns to store the translated text, like this:</p>
<pre class="lang-sql prettyprint-override"><code>CREATE TABLE T_PRODUCT (
NAME_EN NVARCHAR(50),
NAME_DE NVARCHAR(50),
NAME_SP NVARCHAR(50),
DESCRIPTION_EN NTEXT,
DESCRIPTION_DE NTEXT,
DESCRIPTION_SP NTEXT,
PRICE NUMBER(18,2)
)
</code></pre></li>
<li><p>Translation table with columns for each language</p>
<p>Instead of storing translated text, only a foreign key to the translations table is stored. The translations table contains a column for each language.</p>
<pre class="lang-sql prettyprint-override"><code>CREATE TABLE T_PRODUCT (
NAME_FK int,
DESCRIPTION_FK int,
PRICE NUMBER(18, 2)
)
CREATE TABLE T_TRANSLATION (
TRANSLATION_ID,
TEXT_EN NTEXT,
TEXT_DE NTEXT,
TEXT_SP NTEXT
)
</code></pre></li>
<li><p>Translation tables with rows for each language</p>
<p>Instead of storing translated text, only a foreign key to the translations table is stored. The translations table contains only a key, and a separate table contains a row for each translation to a language.</p>
<pre class="lang-sql prettyprint-override"><code>CREATE TABLE T_PRODUCT (
NAME_FK int,
DESCRIPTION_FK int,
PRICE NUMBER(18, 2)
)
CREATE TABLE T_TRANSLATION (
TRANSLATION_ID
)
CREATE TABLE T_TRANSLATION_ENTRY (
TRANSLATION_FK,
LANGUAGE_FK,
TRANSLATED_TEXT NTEXT
)
CREATE TABLE T_TRANSLATION_LANGUAGE (
LANGUAGE_ID,
LANGUAGE_CODE CHAR(2)
)
</code></pre></li>
</ol>
<p>There are pros and cons to each solution, and I would like to know what are your experiences with these approaches, what do you recommend and how would you go about designing a multilanguage database schema.</p>
|
<p>What do you think about having a related translation table for each translatable table?</p>
<blockquote>
<p>CREATE TABLE T_PRODUCT (pr_id int, PRICE NUMBER(18, 2))</p>
<p>CREATE TABLE T_PRODUCT_tr (pr_id INT FK, languagecode varchar, pr_name text, pr_descr text)</p>
</blockquote>
<p>This way if you have multiple translatable column it would only require a single join to get it + since you are not autogenerating a translationid it may be easier to import items together with their related translations.</p>
<p>The negative side of this is that if you have a complex language fallback mechanism you may need to implement that for each translation table - if you are relying on some stored procedure to do that. If you do that from the app this will probably not be a problem.</p>
<p>Let me know what you think - I am also about to make a decision on this for our next application.
So far we have used your 3rd type.</p>
|
<p>"Which one is best" is based on the project situation. The first one is easy to select and maintain, and also the performance is best since it don't need to join tables when select entity. If you confirmed that your poject is just only support 2 or 3 languages, and it will not increase, you can use it.</p>
<p>The second one is okey but is hard to understand and maintain. And the performance is worse than first one.</p>
<p>The last one is good at scalability but bad at performance. The T_TRANSLATION_ENTRY table will become larger and larger, it's terrible when you want to retrieve a list of entities from some tables.</p>
| 40,904
|
<p>Where should I put the .html files in a wicket Application?</p>
<p>my current project layout is as follows:</p>
<pre><code>src/myproject
--classes+ duplicated html files
web
--numerous .html files - previewed
web/img
--resource files such as css/png/js files
</code></pre>
<p>i want to avoid putting the html files on dupliate locations. what is a good non-redundant strategy to put the html and resource files?
this is using tomcat so obviously, when deployed the directory structure changes to </p>
<pre><code>img
WEB-INF
WEB-INF/classes/myproject
</code></pre>
<p>and the .html files stay at the toplevel, as well alongside the .class files - which is bad.</p>
<p>of course, the preview function in plain html should have no problems with relative paths </p>
<p>are there any examples for this? do i need special code (such as a IResourceStreamLocator) in my wicketappllication class? </p>
<p>i am using wicket 1.4-rc1.</p>
|
<p><a href="https://stackoverflow.com/questions/273721/should-i-put-html-and-java-files-in-the-same-package-folder-in-apache-wicket">Should I put html and java files in the same package (folder) in Apache Wicket?</a></p>
|
<p>I would suggest using <a href="http://maven.apache.org" rel="nofollow noreferrer">Maven</a> to build your application. Never depend on an IDE to build your application. IDE's might differ between developers. When you want to use a CI server you need to fall back to scripting if you don't use a build system.</p>
<p>Maven also <a href="http://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html" rel="nofollow noreferrer">separates resources from sources</a>.</p>
<p>Although Maven requires some time to get into it is very much worth the effort.</p>
| 45,075
|
<p>I'm working to set up Panda on an Amazon EC2 instance.
I set up my account and tools last night and had no problem using SSH to interact with my own personal instance, but right now I'm not being allowed permission into Panda's EC2 instance.
<a href="http://pandastream.com/docs/getting_started" rel="noreferrer">Getting Started with Panda</a></p>
<p>I'm getting the following error:</p>
<pre><code>@ WARNING: UNPROTECTED PRIVATE KEY FILE! @
Permissions 0644 for '~/.ec2/id_rsa-gsg-keypair' are too open.
It is recommended that your private key files are NOT accessible by others.
This private key will be ignored.
</code></pre>
<p>I've chmoded my keypair to 600 in order to get into my personal instance last night, and experimented at length setting the permissions to 0 and even generating new key strings, but nothing seems to be working.</p>
<p>Any help at all would be a great help!</p>
<hr>
<p>Hm, it seems as though unless permissions are set to 777 on the directory, the ec2-run-instances script is unable to find my keyfiles.
I'm new to SSH so I might be overlooking something.</p>
|
<blockquote>
<p>I've chmoded my keypair to 600 in order to get into my personal instance last night,</p>
</blockquote>
<p>And this is the way it is supposed to be. </p>
<p>From the <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AccessingInstancesLinux.html" rel="noreferrer">EC2 documentation</a> we have <em>"If you're using OpenSSH (or any reasonably paranoid SSH client) then you'll probably need to set the permissions of this file so that it's only readable by you."</em> The Panda documentation you link to links to Amazon's documentation but really doesn't convey how important it all is.</p>
<p>The idea is that the key pair files are like passwords and need to be protected. So, the ssh client you are using requires that those files be secured and that only your account can read them.</p>
<p>Setting the directory to 700 really should be enough, but 777 is not going to hurt as long as the files are 600.</p>
<p>Any problems you are having are client side, so be sure to include local OS information with any follow up questions! </p>
|
<p>Just a note for anyone who stumbles upon this:</p>
<p>If you are trying to SSH with a key that has been shared with you, for example:</p>
<p><code>ssh -i /path/to/keyfile.pem user@some-host</code></p>
<p>Where <code>keyfile.pem</code> is the private/public key shared with you and you're using it to connect, <strong>make sure you save it into <code>~/.ssh/</code> and <code>chmod 777</code>.</strong></p>
<p>Trying to use the file when it was saved elsewhere on my machine was giving the OP's error. Not sure if it is directly related.</p>
| 24,668
|
<p>I have strange problem with sharepoint and ajax functionality. We have an UpdatePanel placed inside webpart. When partial postback occurs, page title gets missing.</p>
<p>We have found that temporary partial solution is to write title element into one line and not use any spaces or controls inside it..not even a literal control.</p>
<p>But we need some way to provide sommon title for all pages, so title would look like this:
My default title - Current page title</p>
<p>Any ideas how to solve this?</p>
|
<p>I don't have a reference to the newsgroup post, but this is a known problem with publishing pages, as drax mentioned. The workaround I have used in the past is to hard code the title on the page - the metadata title being lost is part of the bug. </p>
<p>When hardcoding wasn't possible, I have used javascript to change the page title: document.title = "title fixup here";</p>
<p>Supposedly microsoft plans to fix this problem in the next sharepoint release.</p>
|
<p>this looks like pure sharepoint's problem..also it looks like just sites based on publishing page layout are affected.</p>
<p>I debugged response in firebug and for some reason it returns setting for page title, so response from server contains not just update panel information, but also empty page title.</p>
<p>I debugged our webparts and none of them plays with page title. I would suggest not to use publishing or just not use any controls inside title.</p>
<p>We are currently working on this issue in company i work for, so i'll upload uour findings when we figure out something.</p>
| 42,146
|
<p>I need to set a dependency property on a control (Slider.Value) in my code without it triggering a ValueChanged event (since I set the value, not the user). What is the best way to handle this situation in WPF? </p>
<p>For clarification, what I am trying to do is hook up WPF sliders to a WinForms User Control. Currently in my app I have a ValueChanged event handler that passes the slider value to the WinForms control via a method call. The WinForms control (which is actually a wrapper around a native OpenGL window) needs to be able to dynamically change the slider based on it's internal calculations. To do this I use an abstraction of a slider (ISlider) , I instantiate a WPF-flavor of that slider in my app, and pass a handle to it's base to the WinForms control via a .NET property on the WinForms User Control. All of this is currently working, it's just that when the internal logic decides the slider needs to change, it calls ISlider::SetPos(), which then changes the WPF slider, which then triggers a ValueChanged event on the slider, and the handler for that event extracts the slider's position and passes it in to the WinForms control which originated the event in the first place. The suggestions by ligaz and Alan Le both seem like they should work, but I'm just not sure I'm going about this in the best way.</p>
|
<p>Here's a simply workaround/hack. Add a boolean to keep track whether you changed the setting, let's say "IsChangedByMe". When you change the dependency property in code, set the bool to true. In the ValueChanged event, if IsChangedByMe is true, don't do anything.</p>
|
<p>One possible solution is to derive from Slider and override <em>OnValueChanged(...)</em>. When you did not want to raise the event you should do nothing, otherwise you should call the base implementation.</p>
| 18,628
|
<p>I am writing a Composite control, which contains a listview to display a table of items. Normally when using a ListView in Asp.NET I would define the templates in the code-forward.</p>
<pre><code><asp:ListView runat="server" ID="ArticleList">
<LayoutTemplate>
<div class="ContentContainer">
<div runat="server" id="itemPlaceholder" />
</div>
</LayoutTemplate>
<ItemTemplate>
<div>
<div><%# Eval("Content") %></div>
</div>
</ItemTemplate>
</asp:ListView>
</code></pre>
<p>I assume it's something like:</p>
<pre><code>ListView view = new ListView();
view.LayoutTemplate = .....
view.ItemTemplate = .....
// when do I call these?
view.DataSource = myDataSource;
view.DataBind();
</code></pre>
<p><strong>Update:</strong>
I created 2 templates by implementing the ITemplate interface:</p>
<pre><code>private class LayoutTemplate : ITemplate
{
public void InstantiateIn(Control container)
{
var outer = new HtmlGenericControl("div");
var inner = new HtmlGenericControl("div") { ID = "itemPlaceholder" };
table.Rows.Add(row);
container.Controls.Add(table);
}
}
private class ItemTemplate : ITemplate
{
public void InstantiateIn(Control container)
{
var inner = new HtmlGenericControl("div");
container.Controls.Add(inner);
}
}
</code></pre>
<p>and I can add them using:</p>
<pre><code>dataList.LayoutTemplate = new LayoutTemplate();
dataList.ItemTemplate = new ItemTemplate();
</code></pre>
<p>But then I get stuck, since container.DataItem is null.</p>
|
<p>The trick is to subscribe to the databinding event of the itemplaceholder in the ItemTemplate. </p>
<p>The complete solution:</p>
<pre><code>public class FibonacciControl : CompositeControl
{
public FibonacciControl()
{
// ....
}
protected override void CreateChildControls()
{
base.CreateChildControls();
ListView view = new ListView();
view.LayoutTemplate = new LayoutTemplate();
view.ItemTemplate = new ItemTemplate();
view.DataSource = FibonacciSequence();
view.DataBind();
this.Controls.Add(view);
}
private IEnumerable<int> FibonacciSequence()
{
int i1 = 0;
int i2 = 1;
for (int i = 0; i < Iterations; i++)
{
yield return i1 + i2;
int temp = i1 + i2;
i1 = i2;
i2 = temp;
}
yield break;
}
public int Iterations { get; set; }
private class LayoutTemplate : ITemplate
{
public void InstantiateIn(Control container)
{
var ol = new HtmlGenericControl("ol");
var li = new HtmlGenericControl("li") { ID = "itemPlaceholder" };
ol.Controls.Add(li);
container.Controls.Add(ol);
}
}
private class ItemTemplate : ITemplate
{
public void InstantiateIn(Control container)
{
var li = new HtmlGenericControl("li");
li.DataBinding += DataBinding;
container.Controls.Add(li);
}
public void DataBinding(object sender, EventArgs e)
{
var container = (HtmlGenericControl)sender;
var dataItem = ((ListViewDataItem)container.NamingContainer).DataItem;
container.Controls.Add( new Literal(){Text = dataItem.ToString() });
}
}
}
</code></pre>
|
<p>Setup a class like:</p>
<pre><code>public delegate void InstantiateTemplateDelegate(Control container);
public class GenericTemplateImplementation : ITemplate
{
private InstantiateTemplateDelegate instantiateTemplate;
public void InstantiateIn(Control container)
{
this.instantiateTemplate(container);
}
public GenericTemplateImplementation(InstantiateTemplateDelegate instantiateTemplate)
{
this.instantiateTemplate = instantiateTemplate;
}
}
</code></pre>
<p>And then do the following:</p>
<pre><code> view.LayoutTemplate = new GenericTemplateImplementation(p =>
{
p.Controls.Add(new Label { Text = "Foo" });
});
</code></pre>
| 11,814
|
<p>I was thinking about how to create a program that would only be valid for X period of time, (within a C# app).</p>
<p>What I was thinking was that you would have the current date as a constant inside the program and it would check to see if it is X days older than that. Naturally I do not want to store the date, or the X outside of the program as it can be tampered with.</p>
<p>What I also do not want to manually change this regularly and recompile and deploy it. So is there a way to set a variable to be the current date when it is compiled?</p>
<p>I could have a batch file that would compile it and deploy the new exe to the distribution server.</p>
<p>Thanks</p>
|
<p>Precompilation directives are your key here. You could create a constant in your application and have it set when you compile.</p>
<p>Make sure you obfuscate your code, however. Someone could disassemble it easily and tamper with the constant. Another solution is to have your software "phone home" to register itself. That way, the registration info is stored on your server and not their machine. There are also third party packages that perform the same security as you're looking for, but they are <strong>expensive</strong>!</p>
|
<p>The problem with .Net is that it would be easy to decompile and change the date you want to use has constant. You might need to think to something else.</p>
<p>You could write it in the registry but then the people will edit this value.</p>
<p>They aren't a perfect solution but to have an account that validate with an external (web) server is a good idea.</p>
| 41,509
|
<p>I'm trying to work out a way of passing the web current http context to a service class (or initialising the class with a reference to it). I am doing this to abstract the rest of the app away from needing to know anything about the http context. </p>
<p>I also want the service to be testable using TDD, probably using one of the Mockable frameworks. Hence it would be preferable to use an interface rather than an actual class.</p>
<p>An example of what I'd like to achieve:</p>
<pre><code>class WebInstanceService
{
private IHttpContext _Context;
public WebInstanceService( ... , IHttpContext HttpContext )
{
....
_Context = HttpContext;
}
// Methods...
public string GetInstanceVariable(string VariableName)
{
return _Context.Current.Session[VariableName];
}
}
</code></pre>
<p>One of the main issues I have is that there is no IHttpContext, the .net http context is a subclass of an abstract class which can't be mocked (easily?).</p>
<p>Another issue is that I can't initialise global instances of the class as then the context won't be relevant for most requests. </p>
<p>I could make the class static, and require the Context to be passed to each function as it is called i.e.</p>
<pre><code>public static string GetInstanceVariable(string VariableName, HttpContext Context)
{ ... }
</code></pre>
<p>but this doesn't make the class any easier to test, I still need to create an HttpContext and additionally any non-web-aware services which want to use this class suddenly need to be able to retrieve the Context requiring them to be closely coupled to the web server - the whole reason for wanting to create this class in the first place.</p>
<p>I'm open to ALL suggestions - particularly those which people know facilitate easy tdd testing. <strong>How would people suggest I tackle this problem?</strong></p>
<p>Cheers</p>
|
<p>This is why HttpContextBase and HttpContextWrapper were introduced. You probably want to use HttpContextBase and when passing the real context in, use <code>new HttpContextWrapper( httpContext )</code>, although, I think that what is available to you in the controller is already of type HttpContextBase. I would create one of these in my controller each time rather than trying to reference the current context from the static, global HttpContext.Current instance. If you need it in your view, pass a reference to your strongly typed context in ViewData.</p>
<p>I mock up HttpContextBase frequently in my tests.</p>
<pre><code>class WebInstanceService
{
private HttpContextBase _Context;
public WebInstanceService( ... , HttpContextBase HttpContext )
{
....
_Context = HttpContext;
}
// Methods...
public string GetInstanceVariable(string VariableName)
{
return _Context.Session[VariableName];
}
}
</code></pre>
|
<p>What we do is spin one of these up <a href="http://haacked.com/archive/2007/06/19/unit-tests-web-code-without-a-web-server-using-httpsimulator.aspx" rel="nofollow noreferrer">http://haacked.com/archive/2007/06/19/unit-tests-web-code-without-a-web-server-using-httpsimulator.aspx</a></p>
<p>Easy as pie, just instanciate an HttpSimulator and fill in the values, and HttpContext.Current gets filled up with whatever you specify.</p>
<p>IHttpContext is something that is in MVC, and aparently one day will be in webforms. Hopefully that day will be .net 4</p>
| 43,281
|
<p>What's your opinion for the best possible way to build asp.net multilingual localized web application (only UI localization of string resources). Especially this two things:</p>
<ol>
<li>How to store resources? Xml files, resx files or something else?</li>
<li>How to handle URL's? I don't want to keep language parameter in query string all the time so I need to use URL rewriting maybe?</li>
</ol>
<p>/BR</p>
|
<p>Have you looked into the localization support in ASP.NET? It uses resource assemblies and sets the default resource based on the browser's settings. You can also override the setting by setting the culture and uiculture settings for the thread handling the request.</p>
<p>If you don't like using the resource assemblies (which do require a project rebuild when you want to make changes), you can also create a custom resource provider for ASP.NET (<a href="http://www.leftslipper.com/ShowFaq.aspx?FaqId=9" rel="nofollow noreferrer">this link</a> uses MS Access as an example, you can try to customize it for SQL or some other provider).</p>
<p><a href="http://asp.net" rel="nofollow noreferrer">http://asp.net</a> has some tutorials to get you started, like <a href="http://www.asp.net/learn/videos/video-40.aspx" rel="nofollow noreferrer">this one</a>.</p>
|
<p>Use Data Driven ASP.NET Localization Resource Provider as described in <a href="http://www.west-wind.com/presentations/wwdbresourceprovider/" rel="nofollow">http://www.west-wind.com/presentations/wwdbresourceprovider/</a> </p>
| 32,095
|
<p>Does anyone know a way to find out programatically which physical disk holds a given partition?
Manually, I can find this info using Start->Run->diskmgmt.msc , where I can see that (on my computer) that partitions C: and D: are on disk 1, E: & F: on disk 0.</p>
<p>This is for optimizing some file crunching operations by doing them in parallel if the files are on different physical disks.</p>
|
<p>You can obtain this information using WMI from System.Management namespace by quering <a href="http://msdn.microsoft.com/en-us/library/aa394132(VS.85).aspx" rel="nofollow noreferrer">Win32_DiskDrive</a> class.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms257340(VS.80).aspx" rel="nofollow noreferrer">Here's</a> basic info about WMI in .NET.</p>
|
<p>Are you sure the partition is associated with only one disk? It could be striped/spanned/etc across multiple physical disks.</p>
| 38,459
|
<p>By default, objects (tables, stored procedures, etc) are set up with the dbo owner/schema (I think ms sql 2000 calls it owner, while ms sql 2005 calls it schema)</p>
<p>The owner/schema is really a role or user in the database. I've always left the default of dbo, but I've recently seen some examples in microsoft training books where some of their tables & stored procedures had different owners/schemas. When is it beneficial to do this and why?</p>
|
<p>The use of schemas is exceptionally beneficial when you have security concerns.</p>
<p>If you have multiple applications that access the database, you might not want to give the Logistics department access to Human Resources records. So you put all of your Human Resources tables into an hr schema and only allow access to it for users in the hr role.</p>
<p>Six months down the road, Logistics now needs to know internal expense accounts so they can send all of these palettes of blue pens to the correct location people. You can then create a stored procedure that executes as a user that has permission to view the hr schema as well as the logistics schema. The Logistics users never need to know what's going on in HR and yet they still get their data.</p>
<p>You can also use schemas the way cfeduke has suggested and just use them to group things in the object browser. If you are doing this, just be careful because you might end up creating Person.Address and Company.Address when you really just need a single dbo.Address (I'm not knocking your example, cfeduke, just using it to illustrate that both address tables might be the same or they might be different and that YMMV).</p>
|
<p><a href="http://www.sqlteam.com/article/understanding-the-difference-between-owners-and-schemas-in-sql-server" rel="nofollow noreferrer">This article</a> explains it well, including the changes from SQL Server 2000 to 2005.</p>
| 31,744
|
<p>I have control over the HttpServer but not over the ApplicationServer or the Java Applications sitting there but I need to block direct access to certain pages on those applications. Precisely, I don't want users automating access to forms issuing direct GET/POST HTTP requests to the appropriate servlet. </p>
<p>So, I decided to block users based on the value of <code>HTTP_REFERER</code>. After all, if the user is navigating inside the site, it will have an appropriate <code>HTTP_REFERER</code>. Well, that was what I thought. </p>
<p>I implemented a rewrite rule in the .htaccess file that says: </p>
<pre><code>RewriteEngine on
# Options +FollowSymlinks
RewriteCond %{HTTP_REFERER} !^http://mywebaddress(.cl)?/.* [NC]
RewriteRule (servlet1|servlet2)/.+\?.+ - [F]
</code></pre>
<p>I expected to forbid access to users that didn't navigate the site but issue direct GET requests to the "servlet1" or "servlet2" servlets using querystrings. But my expectations ended abruptly because the regular expression <code>(servlet1|servlet2)/.+\?.+</code> didn't worked at all. </p>
<p>I was really disappointed when I changed that expression to <code>(servlet1|servlet2)/.+</code> and it worked so well that my users were blocked no matter if they navigated the site or not. </p>
<p>So, my question is: How do I can accomplish this thing of not allowing "robots" with direct access to certain pages if I have no access/privileges/time to modify the application?</p>
|
<p>I'm not sure if I can solve this in one go, but we can go back and forth as necessary.</p>
<p>First, I want to repeat what I think you are saying and make sure I'm clear. You want to disallow requests to servlet1 and servlet2 is the request doesn't have the proper referer and it <strong>does</strong> have a query string? I'm not sure I understand (servlet1|servlet2)/.+\?.+ because it looks like you are requiring a file under servlet1 and 2. I think maybe you are combining PATH_INFO (before the "?") with a GET query string (after the "?"). It appears that the PATH_INFO part will work but the GET query test will not. I made a quick test on my server using script1.cgi and script2.cgi and the following rules worked to accomplish what you are asking for. They are obviously edited a little to match my environment:</p>
<pre><code>RewriteCond %{HTTP_REFERER} !^http://(www.)?example.(com|org) [NC]
RewriteCond %{QUERY_STRING} ^.+$
RewriteRule ^(script1|script2)\.cgi - [F]
</code></pre>
<p>The above caught all wrong-referer requests to script1.cgi and script2.cgi that tried to submit data using a query string. However, you can also submit data using a path_info and by posting data. I used this form to protect against any of the three methods being used with incorrect referer:</p>
<pre><code>RewriteCond %{HTTP_REFERER} !^http://(www.)?example.(com|org) [NC]
RewriteCond %{QUERY_STRING} ^.+$ [OR]
RewriteCond %{REQUEST_METHOD} ^POST$ [OR]
RewriteCond %{PATH_INFO} ^.+$
RewriteRule ^(script1|script2)\.cgi - [F]
</code></pre>
<p>Based on the example you were trying to get working, I think this is what you want:</p>
<pre><code>RewriteCond %{HTTP_REFERER} !^http://mywebaddress(.cl)?/.* [NC]
RewriteCond %{QUERY_STRING} ^.+$ [OR]
RewriteCond %{REQUEST_METHOD} ^POST$ [OR]
RewriteCond %{PATH_INFO} ^.+$
RewriteRule (servlet1|servlet2)\b - [F]
</code></pre>
<p>Hopefully this at least gets you closer to your goal. Please let us know how it works, I'm interested in your problem.</p>
<p>(BTW, I agree that referer blocking is poor security, but I also understand that relaity forces imperfect and partial solutions sometimes, which you seem to already acknowledge.)</p>
|
<p>I'm guessing you're trying to prevent screen scraping?</p>
<p>In my honest opinion it's a tough one to solve and trying to fix by checking the value of HTTP_REFERER is just a sticking plaster. Anyone going to the bother of automating submissions is going to be savvy enough to send the correct referer from their 'automaton'.</p>
<p>You could try rate limiting but without actually modifying the app to force some kind of is-this-a-human validation (a CAPTCHA) at some point then you're going to find this hard to prevent.</p>
| 2,560
|
<p>Is there a way to define styles for a combination of classes? For example, I'd like my HTML to look like this, but the output to render in the appropriate color:</p>
<pre><code><span class="red">Red Text</span><br/>
<span class="green">Green Text</span><br/>
<span class="red green">Yellow Text</span><br/>
</code></pre>
<p><strong>Edit:</strong> The above seems to be confusing people when it was just an example; so here is another example:</p>
<pre><code><style>
.style1 { background-color: #fff; }
.style2 { background-color: #eee; }
.style1.highlight { color: red; }
.style2.highlight { color: blue; }
</style>
<ul>
<li class="action style1">Do Action 1</li>
<li class="action style2">Do Action 2</li>
<li class="action style1 highlight">Do Action 1</li>
<li class="action style2 highlight">Do Action 2</li>
</ul>
<script language="javascript" type="text/javascript">
$("li.action").bind("click", function(e) {
e.preventDefault();
// Do some stuff
$(this).addClass("highlight");
$(this).unbind("click");
});
</script>
</code></pre>
<p>Again, this is just an <em>example</em>, so don't get hung up on alternating elements or anything like that. What I'm trying to avoid is having to duplicate the bind function for each different styleN or having to write an elseif structure that checks for each styleN class. Unfortunately this code doesn't work in IE 6 or 7 - the highlighted text for both .style1 and .style2 elements end up being blue.</p>
|
<p>You can select on multiple classes:</p>
<pre><code>span.red.green { color: yellow; }
</code></pre>
<p>That will apply to any span element with red and green classes. Which may not be what you want, since it will also apply to, say:</p>
<pre><code><span class="red green blue">white</span>
</code></pre>
<p>Note that this doesn’t work right in IE 6.</p>
|
<p>maybe something like this</p>
<pre><code>.red
{
color: red;
}
.red_green
{
color: #AS8324;
}
</code></pre>
<p>and you can use your html code</p>
<pre><code><span class="red">Red Text</span><br/>
<span class="green">Green Text</span><br/>
<span class="red_green">Yellow Text</span><br/>
</code></pre>
<p>I don't know this is what you exactly want but this is my approach. I hope it helps.</p>
| 47,039
|
<p>everybody; I have this problem in asp.net, I have a page where I insert and modify data, before saving I make a validation if it passes I save the data but if not I raise an exception and show it, the function goes like this;</p>
<pre><code>protected void btnSave_Click(object sender, EventArgs e)
{
try
{
...
if(ValidData())
//Save
...
else
throw new Exception("Invalid data");
}
catch(Exception ex)
{
// Javascript alert
JSLiteral.Text = Utilities.JSAlert(ex.Message);
}
}
</code></pre>
<p>The problem is that after I raise the exception and fix the data in the page I click again the save button and it saves but before it shows me again the exception message and its annoying. Even when the data is saved I click again and it shows the message from the exception again.</p>
<p>Do you know the answer for this issue?</p>
|
<p>If JSLiteral is a server side control and it's using view state. Then you'd need to clear the state of the control, when the save is succesful. </p>
<p>You could disable the viewstate for the control like JSLiteral.EnableViewState =false;</p>
|
<p>Is the message saved in the viewstate of the literal?</p>
<p>Explicitly set the literal text to nothing if the data is valid.</p>
| 43,899
|
<p>I want to create cursor rsrc files on the Mac from png files. The application that uses the cursors requires it to be in a .rsrc format and I cannot change that. Does anybody know of any way I can create the cursor .rsrc files from png images.</p>
|
<p>You can use <a href="http://www.versiontracker.com/dyn/moreinfo/macosx/23349" rel="nofollow noreferrer" title="Rezilla">Rezilla</a> to edit resource files on Mac OS X, it has a CURS (and crsr) editor among others. It's a PowerPC binary but it runs well under rosetta on intel.</p>
<p>Also, you don't create a CURS resource file, you create a resource file and add as many CURS resources to it as you need. Resource forks are generic and can contain any number/kind of resources.</p>
|
<p>Its been a long time since I've thought about MacOS resource forks. Are you using the classic MacOS (i.e. before MacOS X)?</p>
<p>As I recall, <A HREF="http://developer.apple.com/documentation/macos8/DevTools/ResEditReference/reseditreference.html" rel="nofollow noreferrer">ResEdit</A> was the application most often used to manipulate the resource fork of a classic Mac application. I know it can edit cursor resources, but I don't recall if it can read PNG files. You may need to convert the files to GIF.</p>
<p>ResEdit is a Classic MacOS application. MacOS X prior to 10.5 could run Classic apps in emulation, but in 10.5 this support has been removed. You'd need to find a system either running the classic MacOS directly, or running 10.4 with Classic installed.</p>
| 9,760
|
<p>Im having a problem with a final part of my assignment. We get in a stream of bits, etc etc, in the stream is an integer with the number of 1's in the text portion. I get that integer and its 24 which is correct, now i loop through the text data i get and i try to count all the 1's in there. But my proc is always returning zero.</p>
<p>I was able to make sure it was looping properly and it is.</p>
<p>The text = Hello
which is 16 1's, here is my proc for looping through that text to count the number of ones in it.</p>
<pre><code>sub AX,AX
sub SI,SI
mov bx,[bp+6] ;get message offset
@@mainLoop:
mov cx,8
mov dh,80h
cmp byte ptr [bx + si],0
je @@endChecker
@@innerLoop:
test byte ptr [bx + si],dh
jz @@zeroFound
inc AX
@@zeroFound:
shr bh,1
loop @@innerLoop
@@continue:
inc si
jmp @@mainLoop
</code></pre>
<p>the rest of the proc is just push/pops. What im wanting this to actually do is use TEST to compare 100000000 to a byte, if its a 1 inc AX else shift right the mask by 1 and loop a whole byte, than inc to next byte and do again.</p>
|
<p>'shr bh,1' should probably be 'shr dh,1', no?</p>
|
<p>Just to give you an alternative and shorter implementation of your inner-loop:</p>
<pre><code> mov cx, 8
mov dh, byte ptr [bx+si]
@@innerLoop:
add dh, dh
adc ax, 0
loop @@innerLoop
</code></pre>
<p>Here we don't test the bits at all. Instead the add dh, dh shifts the topmost bit into the carry and also does the same as shl dh,1 in one instruction.</p>
<p>The addc ax,0 just adds the carry to AX.</p>
| 28,750
|
<p>I have a following xslt code :</p>
<pre><code><xsl:template match="table_terms_and_abbr">
<informaltable frame='none' colsep='none' rowsep='none'>
<tgroup cols='2' align='left'>
<colspec colnum="1" colwidth='1*'/>
<colspec colnum="2" colwidth='1*'/>
<xsl:apply-templates/>
</tgroup>
</informaltable>
</xsl:template>
</code></pre>
<p>and the following xml that it's processing : </p>
<pre><code><table_terms_and_abbr>
<tblrow_hdr>Name ,, Description</tblrow_hdr>
<tbody>
<tblrow_bold_first> BOT ,, &j_bot;</tblrow_bold_first>
...
</tbody>
</table_terms_and_abbr>
</code></pre>
<p>Now i want to improve the xslt by moving following lines inside the <code>table_terms_and_abbr</code>:</p>
<pre><code><tblrow_hdr>Name ,, Description</tblrow_hdr>
<tbody>
</tbody>
</code></pre>
<p>So i will have something like : </p>
<pre><code><xsl:template match="table_terms_and_abbr">
<informaltable frame='none' colsep='none' rowsep='none'>
<tgroup cols='2' align='left'>
<colspec colnum="1" colwidth='1*'/>
<colspec colnum="2" colwidth='1*'/>
<xsl:call-template name="tblrow_hdr">
BOT ,, &j_bot; * ???? *
</xsl:call-template>
<tbody>
<xsl:apply-templates/>
</tbody>
</tgroup>
</informaltable>
</xsl:template>
</code></pre>
<p>The line marked with * ???? * does not work. I using saxon9 (xslt 2.0 stylesheet) on linux platform and got this error: </p>
<p><em>XTSE0010: No character data is allowed within xsl:call-template</em></p>
<p>I know how to pass the attributes to the template i.e: </p>
<pre><code><xsl:with-param name="is_make_first_bold" select = "1" as="xs:integer"/>
</code></pre>
<p>but how to pass free text ? </p>
<p>The idea is move to the template all static data and in xml only use variable data i.e </p>
<pre><code><table_terms_and_abbr>
<tblrow_bold_first> BOT ,, &j_bot;</tblrow_bold_first>
...
</table_terms_and_abbr>
</code></pre>
<p><strong>More Info</strong><br>
My requirement was to create a simplified syntax for defining repeatable tables for our DocBook documentation. For that i created a general named template <code>tblrow</code> that will split the line delimited by ",," to separate entities and will create a list of entries in the table row.<br>
Each entry can be a simple string, an ENTITY or another template.
Since the parameter numbers are undefined (the tables can have different number of cells) i can't use a standard parameters for the templates and used delimited string. If i want to have one of the table entries to contain a link to some place in the document i can't use the parameters again since i can't pass xref template as a parameter.<br>
The main reason not to change the <code>tblrow</code> template is that it's working :) and it's kind of complex. It's took me ages to achieve this and I'm not completely understand how it's working :). </p>
<p>Now on top of this i have a few variables that can control the displayed output like <code>tblrow_hdr</code> that will underline and bold the text in each entry. Since <code>tblrow_hdr</code> is common for all <code>table_terms_and_abbr</code> tables it just sounds logical to me not having this in xml rather put the call to the <code>tblrow_hdr</code> inside the <code>table_terms_and_abbr</code> template and here i stuck. </p>
|
<blockquote>
<p>I know how to pass the attributes to the template i.e:</p>
<pre><code><xsl:with-param name="is_make_first_bold" select = "1" as="xs:integer"/>
</code></pre>
<p>but how to pass free text ? </p>
</blockquote>
<p>Pass the text as the content of an <code>xsl:with-param</code> element.</p>
<p><a href="http://www.w3.org/TR/xslt#section-Passing-Parameters-to-Templates" rel="nofollow noreferrer">XSL Transformations 11.6 Passing Parameters to Templates</a></p>
<pre><code><xsl:with-param
name = qname
select = expression>
<!-- Content: template -->
</xsl:with-param>
</code></pre>
<p>Parameters are passed to templates using the <code>xsl:with-param</code> element. The required <code>name</code> attribute specifies the name of the parameter (the variable the value of whose binding is to be replaced). The value of the name attribute is a <a href="http://www.w3.org/TR/REC-xml-names#NT-QName" rel="nofollow noreferrer">QName</a>, which is expanded as described in <a href="http://www.w3.org/TR/xslt#qname" rel="nofollow noreferrer">[2.4 Qualified Names]</a>. 'xsl:with-param' is allowed within both <code>xsl:call-template</code> and <code>xsl:apply-templates</code>. The value of the parameter is specified in the same way as for <code>xsl:variable</code> and <code>xsl:param</code>. The current node and current node list used for computing the value specified by <code>xsl:with-param</code> element is the same as that used for the <code>xsl:apply-templates</code> or <code>xsl:call-template</code> element within which it occurs. It is not an error to pass a parameter <em>x</em> to a template that does not have an <code>xsl:param</code> element for <em>x</em>; the parameter is simply ignored.</p>
<p>This example defines a named template for a numbered-block with an argument to control the format of the number.</p>
<pre><code><xsl:template name="numbered-block">
<xsl:param name="format">1. </xsl:param>
<fo:block>
<xsl:number format="{$format}"/>
<xsl:apply-templates/>
</fo:block>
</code></pre>
<h2> </h2>
<pre><code><xsl:template match="ol//ol/li">
<xsl:call-template name="numbered-block">
<xsl:with-param name="format">a. </xsl:with-param>
</xsl:call-template>
</xsl:template>
</code></pre>
|
<p>You can pass the additional string data as a parameter:</p>
<p> <xsl:with-param name="pNeededText" select="'--123Abc'"/></p>
<p>and in the called template define this parameter:</p>
<p> <xsl:param name="pNeededText" as="xs:string"></p>
<p>Or, you could define a <strong>global <code><xsl:variable/></code> or <code><xsl:param/></code></strong> and reference it directly in the called template. </p>
| 38,303
|
<p>Simple question:</p>
<ul>
<li>What Python GUI API's are out there and what are the advantages of any given API?</li>
</ul>
<p>I'm not looking for a religious war here, I'm just wanting to get a good handle on all that is out there in terms of Python GUI APIs.</p>
|
<p><a href="http://wiki.python.org/moin/GuiProgramming" rel="noreferrer">Here's a good list.</a></p>
|
<p>I've been working with <a href="http://www.wxpython.org" rel="nofollow noreferrer">wxPython</a> for a few years now and I like it quite a bit. The best thing about wxPython is that the UI feels native on the different platforms it runs on (excellent on Windows and Linux though not as good on OS/X).</p>
<p>The API lacks some consistency, but you quickly get used to it.</p>
<p>You can check out <a href="http://www.testuff.com" rel="nofollow noreferrer">Testuff</a> (shameless plug, as it's my own product) to get a feeling of what can be done with wxPython (although I must say, with quite a bit of effort).</p>
| 11,955
|
<p>I'm interested in reading about the various ways other developers and architects deal with the customization of certain areas of their applications for certain sites. Call outs to customer implemented pre and post processing, events doing the same, allowing business logic methods to be overridden, using strategies with pluggable modules, data configurable processes, e.g. rule engines, scripting, etc. </p>
<p>The list could go on, but I'm asking who used what and what the pros and cons are of each of these approaches, as well as what other approaches there are.</p>
<p>This assumes we don't create a customer specific code branch to accommodate these customizations. </p>
|
<p>MS is working on two different frameworks for this in .NET: the Managed Extensibility Framework and System.Addin. </p>
<p>Probably the most commonly used way applications expose extensibility is through Dependency Injection/Inversion of Control mixed with runtime type resolution. That means, you let an external entity "inject" the implementation of an interface at runtime instead of binding to a specific implementation at compile time. Your code doesn't care if your IRepository is written by your company or by a 3rd party. By coding against interfaces and using DI/IOC frameworks <a href="http://blog.ashmind.com/index.php/2008/08/19/comparing-net-di-ioc-frameworks-part-1/" rel="nofollow noreferrer">(this link provides a great overview of .NET frameworks)</a> you allow your application to be easily customizable.</p>
|
<p>For the products I work with, customizations that are built either by the Services group for a given customer, or sometimes by the customers themselves, get shared to the rest of the team (for stuff we've made) and often get "productized" in later releases.</p>
<p>We support a [nearly] full-access API which can be used to do [almost] anything the GUIs can do, but in an automated fashion. </p>
<p>We encourage customers to write custom scripts and then share them back with us. Growing the available uses of a product through extensions, whether they be officially supported, or remain community tools, helps to engender goodwill amongst your customer base.</p>
<p>For customizations we build, the initial work, while billed to a specific customer, can then be implemented rapidly elsewhere, allowing current and future users mroe flexibility when using the product.</p>
| 33,239
|
<p>We determined in a <a href="https://stackoverflow.com/questions/303810/variable-dynamic-option-lists-in-html-select-using-ie">previous question</a> that many features of HTML SELECTs are not supported in IE. Is there an alternative widget that you would recommend from your experience that meets the following requirements?</p>
<ol>
<li>Respects the <code>contentEditable</code> property (does not allow selection changes if true)</li>
<li>Respects the <code>disabled</code> property of individual OPTIONs (shows them "grayed out" or with strike-through font, and makes them un-selectable)</li>
<li>Supports Option Groups (<code>OPTGROUP</code> elements)</li>
<li>Supports <code>style</code> options such as <code>border</code> and <code>margin</code> in the <code>SELECT</code> and all sub-elements</li>
<li>Supports dynamic add and delete of <code>OPTION</code> and <code>OPTGROUP</code> elements</li>
<li>Supports the above in IE version 6 and above</li>
</ol>
<p>EDIT: As noted by @Joel Coehoorn, items 3 and 5 above are currently supported in IE. They are included here to make sure they are not overlooked in a replacement widget.</p>
|
<p>At last check IE6+ does support #3 and #5, and you can (mis)use OPTGROUP to work around most of the other items.</p>
<p>You can do this by having an optgroup with no options inside it, like this:</p>
<pre><code><optgroup label="--"></optgroup>
</code></pre>
<p>You can make the label anything you want, but the point is that you'll end up with an item that looks like a normal option, but cannot be selected. That opens to the door to all kinds of fun:</p>
<ul>
<li>You can disable specific items by adding them as optgroups</li>
<li>You can prevent selection changes by encoded all options but the current one as optgroups (use some other text key to indicate they are disabled, if you need to)</li>
<li>You can use blank, --, or &mdash; labels to indicated simple separators rather than whole groups.</li>
</ul>
<p>That accounts for most of #1 & #2 in your list, anyway- at least the functional points.</p>
<p>The reason for "(mis)use" is because this won't pass most html validators. However, the trick does work on all major browsers.</p>
|
<p>I am writing such a widget. I plan to implement optgroup in my next version, which will be in a few days hopefully, since ive been making good progress.</p>
<p><a href="http://programmingdrunk.com/current-projects/dropdownReplacement/" rel="nofollow noreferrer">demo page</a></p>
<p><a href="https://code.google.com/p/dogself-jquery/source/browse/trunk/jquery.dropdownReplacement/" rel="nofollow noreferrer">svn</a></p>
| 39,376
|
<p>Evil or not evil?</p>
<pre><code>public static void Raise(this EventHandler handler, object sender, EventArgs args)
{
if (handler != null)
{
handler(sender, args);
}
}
// Usage:
MyButtonClicked.Raise(this, EventArgs.Empty);
// This works too! Evil?
EventHandler handler = null;
handler.Raise(this, EVentArgs.Empty);
</code></pre>
<p>Note that due to the nature of extension methods, MyButtonClicked.Raise will not throw a NullReferenceException if MyButtonClicked is null. (E.g. there are no listeners to MyButtonClicked event).</p>
<p>Evil or not?</p>
|
<p>Not evil. I wish events worked this way by default. Can someone explain why an event with no subscribers is null?</p>
|
<p>Throwing an exception when there are no handlers is not really preferable by the most. If it does not have an handlers it is better to be empty rather than null.</p>
| 30,823
|
<p>I want to set up a Subversion server installation on Windows Server 2003 64-bit and I'm considering using <a href="http://www.visualsvn.com/server/" rel="noreferrer">VisualSVN Server</a>. Does this work OK in a 64-bit environment? Are there any issues or gotchas I should be aware of before installing the software?</p>
<p>Many thanks!</p>
|
<p>Ive been using VisualSVN Server on W2K3 x64 on one of our MS SQL 2005 boxes with no problems at all for over a month now. I followed the <a href="http://www.visualsvn.com/server/doc/server-config/" rel="nofollow noreferrer">installation guide</a> and have had no issue at all with either the server code or the integrated Apache server. </p>
|
<p>I have a lot of experience with SVN servers on windows.</p>
<p>VisualSVN works fine.</p>
<p>However it is x86. If you want your server to run as 64bit process you can do the following(Maybe you can create a hack to work with VisualSVN - Didn't try yet):</p>
<blockquote>
<p><strong>Update1: This is an obsolete method. There is no need to download this anymore.</strong><br>
Download from here the x64 server process:
<a href="http://nightlybuilds.tortoisesvn.net/latest/x64/full/svnserve.exe" rel="nofollow">http://nightlybuilds.tortoisesvn.net/latest/x64/full/svnserve.exe</a></p>
</blockquote>
<p>Now let install the server as a service (That is also what VisualSVN does).</p>
<p>InstallService.bat</p>
<pre><code>sc create svnserver binpath= "C:\Program Files\TortoiseSVN\bin\svnserve.exe --service -r D:\SvnRepositories" displayname= "Subversion" depend= Tcpip start= auto
pause
</code></pre>
<p>keep the spaces as shown.</p>
<p>If you will ever want to remove it make sure to stop it through services.msc and then run:</p>
<p>UninstallService.bat</p>
<pre><code>sc delete svnserver
pause
</code></pre>
<p>If you are running under Vista/7/2008 You will need to run as administrator.</p>
<p>Hope this helps</p>
| 29,640
|
<p>I have a table which contains 3 nvarchar(255) columns and a combination of these 3 columns must be unique. Normally I would create a Unique constraint, but in this case, I am hitting the 900 byte limit. Since I have to support SQL Server 2000, I can not use Include columns to get around this situation.</p>
|
<p>If I understand you correctly, you could use a trigger and on the Insert or Update check to see if the combination of the values is unique prior to making the change. You could also do the same via a stored procedure.</p>
|
<p>You could hash the 3 columns, using MD5 or SHA1, and create a unqiue constraint on the hashed value.</p>
<p>How easy it is to implement depends on where you INSERTs/UPDATEs come from.</p>
<p>If they only come from your application, then it should be relatively easy to implement.</p>
<p>If they come from multiple sources you can look into implementing the hash in T-SQL. A quick Google search turned up the following implementation of MD5 in T-SQL: <a href="http://binaryworld.net/Main/CodeDetail.aspx?CodeId=3600" rel="nofollow noreferrer">http://binaryworld.net/Main/CodeDetail.aspx?CodeId=3600</a>. On SQL2005, you can use the built-in hash function: <a href="http://msdn.microsoft.com/en-us/library/ms174415.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms174415.aspx</a>.</p>
<p>Note that MD5 is no longer considered "secure", though it should be sufficient for this scenario. It runs quicker and is easier to implement than SHA1.</p>
| 24,204
|
<p>I've heard that there are some things one cannot do as a computer programmer, but I don't know what they are. One thing that occurred to me recently was: wouldn't it be nice to have a class that could make a copy of the source of the program it runs, modify that program and add a method to the class that it is, and then run the copy of the program and terminate itself. Is it possible for code to write code?</p>
|
<p>Start by looking at <a href="http://en.wikipedia.org/wiki/Quines" rel="nofollow noreferrer">quines</a>, then at Macro-Assemblers and then <a href="http://www.google.com/search?q=lex+yacc" rel="nofollow noreferrer">lex & yacc</a>, and <a href="http://www.google.com/search?q=flex+bison" rel="nofollow noreferrer">flex & bison</a>. Then consider <a href="http://en.wikipedia.org/wiki/Self-modifying_code" rel="nofollow noreferrer">self-modifying code</a>.</p>
<p>Here's a quine (formatted, use the output as the new input):</p>
<pre><code>#include<stdio.h>
main()
{
char *a = "main(){char *a = %c%s%c; int b = '%c'; printf(a,b,a,b,b);}";
int b = '"';
printf(a,b,a,b,b);
}
</code></pre>
<p>Now if you're just looking for things programmers can't do look for the opposite of np-complete.</p>
|
<p>This is one of the fundamental questions of Artificial Intelligence. Personally I hope it is not possible - otherwise soon I'll be out of a job!!! :)</p>
| 31,230
|
<p>I have the following markup, and I want to make the <code>All</code> radio button checked.</p>
<pre><code><ul>
<li><input type="radio" value="All" name="Foo"/>All</li>
<li><input type="radio" value="New" name="Foo"/>New</li>
<li><input type="radio" value="Removed" name="Foo"/>Removed</li>
<li><input type="radio" value="Updated" name="Foo"/>Updated</li>
</ul>
</code></pre>
<p>I'd like to match via attribute, but I need to match on 2 attributes, <code>@name='Foo'</code> and <code>@value='All'</code>.</p>
<p>Something like this:</p>
<pre><code>$("input[@name='Foo' @value='all']").attr('checked','checked');
</code></pre>
<p>Can someone show how this can be done?</p>
|
<p>The following HTML file shows how you can do this:</p>
<pre><code><html>
<head>
<script type="text/javascript" src="jquery-1.2.6.pack.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("a").click(function(event){
$("input[name='Foo'][value='All']").attr('checked','checked');
event.preventDefault();
});
});
</script>
</head>
<body>
<ul>
<li><input type="radio" value="All" name="Foo" />All</li>
<li><input type="radio" value="New" name="Foo" />New</li>
<li><input type="radio" value="Removed" name="Foo" />Removed</li>
<li><input type="radio" value="Updated" name="Foo" />Updated</li>
</ul>
<a href="" >Click here</a>
</body>
</html>
</code></pre>
<p>When you click on the link, the desired radio button is selected. The important line is the one setting the <code>checked</code> attribute.</p>
|
<p>I was beating my head against a wall similar to this and just want to point out that in jQuery 1.3 the syntax used in the accepted answer is the ONLY syntax that will work. The questioner uses the @ syntax for the expression which does not work at all in jQuery. Hopefully this helps the next guy to come across this question via Google =p</p>
<p>To be clear, you have to use </p>
<pre><code>jQuery('input[name=field1][val=checked]')
</code></pre>
<p>and not </p>
<pre><code>jQuery('input[@name=field1][@val=checked]')
</code></pre>
| 18,871
|
<p>Currently we have a project with a standard subversion repository layout of:</p>
<p>./trunk<br>
./branches<br>
./tags</p>
<p>However, as we're moving down the road of OSGi and a modular project, we've ended up with:</p>
<p>./trunk/bundle/main<br>
./trunk/bundle/modulea<br>
./trunk/bundle/moduleb
./tags/bundle/main-1.0.0<br>
./tags/bundle/main-1.0.1<br>
./tags/bundle/modulea-1.0.0</p>
<p>The 'build' is still quite monolithic in that it builds all modules in sequence, though I'm starting to wonder if we should refactor the build/repository to something more like:</p>
<p>./bundle/main/trunk<br>
./bundle/main/tags/main-1.0.0<br>
./bundle/main/tags/main-1.0.1<br>
./bundle/modulea/trunk<br>
./bundle/modulea/tags/modulea-1.0.0 </p>
<p>In this pattern I would imagine each module building itself, and storing its binary in a repository (maven, ivy, or another path of the subversion repository itself).</p>
<p>Are there guidelines or 'best-practices' over project layouts once one goes modular?</p>
|
<p>The Subversion book contains two sections on this:</p>
<ul>
<li><a href="http://svnbook.red-bean.com/en/1.4/svn.branchmerge.maint.html#svn.branchmerge.maint.layout" rel="nofollow noreferrer">Repository Layout</a></li>
<li><a href="http://svnbook.red-bean.com/en/1.4/svn.reposadmin.planning.html#svn.reposadmin.projects.chooselayout" rel="nofollow noreferrer">Planning Your Repository Organization</a></li>
</ul>
<p>A blog entry on the subject: <a href="http://blogs.collab.net/subversion/subversion_repo" rel="nofollow noreferrer">"Subversion Repository Layout"</a></p>
<p>The short answer, though: while your mileage will vary (every situation is individual), your <code>/bundle/<project>/(trunk|tags|branches)</code> scheme is rather common and will likely work well for you.</p>
|
<p>I've answered a similar question in a StackOverflow <a href="https://stackoverflow.com/questions/16829/structure-of-projects-in-version-control#16915">Version Control Structure question</a>. It actually fits even better here since we do heavy OSGi development and have lots of bundles. I must echo Anders Sandvig comments: keep trunk/tags/branches on the root level since you will only branch a limited set of modules. It also does not interfere with modules building individually.</p>
<p>I won't copy the answer I made before but it is entirely relevant to this question.</p>
| 3,519
|
<p>My Visual Studio (2008) Editor has stopped to underline Errors (this nifty wavy red lines). I can't really tell when, but it can be related to the installation of .Net Framework 3.5 SP 1 or the MVC Beta (which I guess is unlikely). Furthermore have I installed and uninstalled both CodeRush and Resharper for evaluation purposes (decided not to keep either one of them).</p>
<p>Does anyone know the problem and how to restore this functionality again?</p>
|
<p>Have you checked <kbd>Tools</kbd>→<kbd>Options...</kbd>→<kbd>Text Editor</kbd>→<kbd>C#</kbd>→<kbd>Advanced</kbd>→<kbd>Underline errors in the editor</kbd>?</p>
<p>I usually like to reset my settings after messing around with plugins, as they tend to mess with settings: <kbd>Tools</kbd>→<kbd>Import and Export Settings...</kbd>→<kbd>Reset all settings</kbd>.</p>
|
<p>Just go to settings and search for errors and <a href="https://i.stack.imgur.com/vS9eO.png" rel="nofollow noreferrer">Image in Error Squiggles</a>. You can see the Error squiggles (Modified: Workspace - Right now you can't see it because I modified it). Just click on modified and you will see the disabled option. If by mistake you disabled it, just enable it and you can see the red line errors again in your code.</p>
| 33,599
|
<p><a href="https://e3d-online.com/blogs/news/are-abrasives-killing-your-nozzle" rel="nofollow noreferrer">E3D-Online</a> and <a href="http://makezine.com/2015/09/11/carbon-fiber-filament-ruins-nozzles/" rel="nofollow noreferrer">Make Magazine</a> have written about the potential damage printing carbon fiber and glow in the dark filaments can do to your printer's nozzle.</p>
<p>What I can't seem to find is what clues or warning signs to be on the look out for if your nozzle has taken a significant amount of wear. I've printed a few hundred grams of glow filament personally and have not noticed any change in print quality.</p>
<p>E3D says you may have "unpredictable erratic printing" with a worn nozzle. Can anyone explain or provide examples of what this actually means and when a replacement is necessary?</p>
|
<p>I believe the little experiment made by E3D - the same link you provide - answers your question very well. Several points about wear can be found in this article. After printing only 250 grams of ColorFabb XT-CF20 (carbon fiber filament):</p>
<ul>
<li>The nozzle diameter had increased markedly</li>
<li>The inner walls of the orifice (opening) showed deep sharp ridges and grooves</li>
<li>The tip of the nozzle had become critically rounded, and shortened</li>
</ul>
<p>All of these symptoms were found repeatedly for standard brass nozzles.</p>
<p>In particular, I believe the last of these symptoms may be the one most easily identifiable without accurate measuring equipment (and without observing print quality).</p>
<p>With regards to reduction in print quality, these symptoms could be simulated by:</p>
<ul>
<li>Setting the nozzle diameter too big in your slicer</li>
<li>Leveling your bed too high (the rounded tip will also reduce the length of the tip)</li>
<li>Printing with a partial clog that interruptus normal filament flow (due to the grooves and ridges)</li>
</ul>
<p>Exactly what this will look like on your printed part is hard to predict, but I would assume you could see blobs, under-extrusion, poor layer adhesion, as well as an irregular surface finish of your top layers.</p>
|
<p>You can check for shortened nozzle length using a set of feeler gauges to measure the gap from bed to nozzle. <a href="https://en.wikipedia.org/wiki/Feeler_gauge" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Feeler_gauge</a></p>
| 163
|
<p>I have some design diagrams only on paper. Scanning them to bitmaps is easy, but I've had no luck getting useful vectors out of them. I've tried vectorizers in programs like gimp, and a few online services. Generally, I end up with enormous numbers of spurious vectors (from dust, dotted lines, text on the diagram, slightly variations in scanning contrast, etc).</p>
<p>What tools and/or techniques can I use to get a more useful vector result, that I can then modify in a normal CAD tool without spending absurd amounts of time cleaning it all up first?</p>
|
<p>There is the capable but somewhat expensive <a href="http://www.scan2cad.com/" rel="nofollow" title="Scan2CAD">Scan2CAD</a>.</p>
<p>Otherwise, if you're happy with outlines and not centre lines, scan b&w, aggressively clean up macules, mask off text, and then vectorize in potrace, autotrace, etc. Alternatively, load the bitmap at the correct resolution into a drawing package as a raster layer and draw the lines/objects you want over it. This avoids the horrors of dotted lines.</p>
<p>Both ways are quite a bit of work, sadly.</p>
|
<p>I would recommend using something like <a href="http://www.getpaint.net/index.html" rel="nofollow noreferrer">Paint.NET</a> to "fix" the images before attempting to convert them to CAD.</p>
<p>To my knowledge, most of the Image-to-CAD applications are going to use the grayscale intensity of each pixel to get the Z-axis value. So, you can help this process by pre-filtering the image into grayscale and playing with the contrast until you get enough distinction between the features you want to stand out in your CAD model or print. Here's a quick example using a sample image:</p>
<p>Poor Contrast
<a href="https://i.stack.imgur.com/JuyOg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JuyOg.png" alt="Poor Contrast"></a></p>
<p>Better Contrast
<a href="https://i.stack.imgur.com/yEjjk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yEjjk.png" alt="Better Contrast"></a></p>
<p>Whichever program you use will generally have an easier time detecting the edges of the flower pedals in the second image the further towards the center it goes.</p>
<p>GIMP has <a href="https://www.gimp.org/tutorials/Color2BW/" rel="nofollow noreferrer">greyscale</a> and <a href="https://www.gimp.org/tutorials/ContrastMask/" rel="nofollow noreferrer">contrast</a> tools as well.</p>
| 221
|
<p>I am printing a mechanical part for my printer. </p>
<p>It's a new mount for my extruders and I have been attempting to use BVOH as a support filament so that when my print is done it will cut down on the need to finish the part and possible mistakes. </p>
<p>My problem is I can get the BVOH to adhere to the bed with no problem and no warping of any kind, but I can't get the ASA to adhere to the BVOH supports. I run the BVOH at 220 °C and the ASA at 250 °C with my fan at 10 % and I am using a Flashforge Creator Pro printer which is mostly enclosed. </p>
<p>Does anyone know of a way to get the ASA to adhere to the BVOH?</p>
|
<p>Can you tell by looking at the de-adhesion what isn't sticking? </p>
<p>It may be that printing the ASA at higher temperature is melting the BVOH enough that it doesn't stick, being molten. If so, then it may be possible to print the first layer of ASA at a cooler temperature, slower if necessary to still succeed at extrusion, with fans blowing. Then, print the next layer of ASA at a higher temperature, also with fans flowing.</p>
<p>A test might be to print the BVOH, then a layer of ASA, and stop. Let it cool and test the adhesion. If it sticks under these conditions, then a better command of the temperature profile may offer a way forward.</p>
|
<p>Here's how I got it to work. I set the heat bed to 110°C and disabled the underlayer of the raft layer. I set the BVOH and the ASA to 235°C after the 4th layer I set the heatbed to 90°C and after the 6th layer I set the bed down to 60°C so that the BVOH hardened and adhered to the bed making sure that nothing curled or moved. After the print finished it took 24 hours for my BVOH to fully dissolve but thats probably because I set my support to 100% infill. Either way I got a perfect ASA extruder mount</p>
| 1,306
|
<p>I have problem with return statment >.< I want to store all magazine names into</p>
<pre><code>ArrayList<String> ListNameMagazine = new ArrayList<String>();
</code></pre>
<p>I have a DB; in the DB there is a table <code>name_magazine</code> and the data in <code>name_magazine</code> is</p>
<blockquote>
<p>Magazine1</p>
<p>Magazine2</p>
<p>Magazine3</p>
<p>Magazine4</p>
</blockquote>
<p>This my main:</p>
<pre><code> ShowData Show = new ShowData();
int HowManyMagazine = Show.HowManyMagazine(1); // to make sure there is how many Magazine name in my database
//System.out.print(HowManyMagazine); //i want to make sure the data is out.
String nmeMagazine = null; // this variable for get data from return statement
// i want to store in ListNameMagazine
ArrayList<String> ListNameMagazine = new ArrayList<String>();
for (int numbeer = 0;numbeer <= HowManyMagazine ; numbeer++)
{
//Store in 1 variable String, because if arrayList it's error
nmeMagazine = Show.getResult("Select Name_Magazine from Magazine");
// Store again in array list
ListNameMagazine.add(nmeMagazine);
}
for (String s : ListNameMagazine)
{
System.out.println(s); // show the data
}
</code></pre>
<p>This is my return statement:</p>
<pre><code>public String getResult(String sql)
throws SQLException
{
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData resultsetmetadata = rs.getMetaData();
//String just_try = null;
while (rs.next()) {
System.out.println("Result:"+rs.getString(1));
//just_try = rs.getString(1);
//return just_try;
}
return null; //return just_try;
}
</code></pre>
<p>The problem is in return statement.</p>
<p>When the comment ( // ) I erase and the last return null; I delete. It become like here:</p>
<pre><code>public String getResult(String sql)
throws SQLException
{
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData resultsetmetadata = rs.getMetaData();
String just_try = null;
while (rs.next()) {
//System.out.println("Result:"+rs.getString(1));
just_try = rs.getString(1);
return just_try;
}
return just_try;
}
</code></pre>
<p>When I show the data using this statement.</p>
<pre><code>for (String s : ListNameMagazine)
{
System.out.println(s); // show the data
}
</code></pre>
<p>the result only</p>
<blockquote>
<p>Magazine4</p>
<p>Magazine4</p>
<p>Magazine4</p>
<p>Magazine4</p>
</blockquote>
<p>@.@ I have confuse where the miss @.@</p>
<p>but when I show data in return statement like this</p>
<pre><code>public String getResult(String sql)
throws SQLException
{
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData resultsetmetadata = rs.getMetaData();
String just_try = null;
while (rs.next()) {
System.out.println("Result:"+rs.getString(1));
//just_try = rs.getString(1);
//return just_try;
}
return null;
}
</code></pre>
<p>The data show what I want. I know I only miss in somewhere but I don't know where that @.@. I hope you guys can found it .THX</p>
|
<p>Your problem is that <strong>return</strong> returns only one thing, and it will <em>return immediately and the function will exit</em>! You are retuning the name of a magazine <strong>just_try</strong>.</p>
<pre><code>while (rs.next()) {
//System.out.println("Result:"+rs.getString(1));
just_try = rs.getString(1);
return just_try;
}
</code></pre>
<p>So, you start iterating through <strong>rs</strong>, and you get the name:</p>
<pre><code>just_try = rs.getString(1);
</code></pre>
<p>And then you tell the code to return just_try.</p>
<pre><code>return just_try;
</code></pre>
<p>At this point just_try will be returned and the function will exit! I think your problem is that you are expecting the function to keep going, and to keep returning values to the code that calls it, but this is not the way it works.</p>
<p>I suspect what you want to do is something like this:</p>
<pre><code>ArrayList<String> ListNameMagazine;
ListNameMagazine = Show.getResult("Select Name_Magazine from Magazine");
</code></pre>
<p>then in the function getResult:</p>
<pre><code>public ArrayList<String> getResult(String sql) throws SQLException {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData resultsetmetadata = rs.getMetaData();
ArrayList<String> returnArrayList = new ArrayList<String>();
while (rs.next()) {
returnArrayList.add(rs.getString(1));
}
return returnArrayList;
}
</code></pre>
|
<p>xan: Your method returns a String, while you try to return a list.</p>
<p>The signature must be changed to </p>
<pre><code>public List<String> getResult(String sql) throws SQLException;
</code></pre>
| 42,594
|
<p>I need to activate a JButton ActionListener within a JDialog so I can do some unit testing using JUnit.</p>
<p>Basically I have this:</p>
<pre><code> public class MyDialog extends JDialog {
public static int APPLY_OPTION= 1;
protected int buttonpressed;
protected JButton okButton;
public MyDialog(Frame f) {
super(f);
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttonpressed= APPLY_OPTION;
}
} );
public int getButtonPressed() {
return buttonpressed;
}
}
</code></pre>
<p>then I have my JUnit file:</p>
<pre><code>public class testMyDialog {
@Test
public void testGetButtonPressed() {
MyDialog fc= new MyDialog(null);
fc.okButton.???????? //how do I activate the ActionListener?
assertEquals(MyDialog.APPLY_OPTION, fc.getButtonPressed());
}
}
</code></pre>
<p>This may sound redundant to do in a unit test, but the actual class is a lot more complicated than that...</p>
|
<p><code>AbstractButton.doClick</code></p>
<p>Your tests might run faster if you use the form that takes an argument and give it a shorter delay. The call blocks for the delay.</p>
|
<p>I created a getter for the JButton and used the doClick. Example:</p>
<pre><code>@Test
@DisplayName("ActionListener test")
void testActionListener(){
HelpWindow helpWindow = new HelpWindow("menu");
assertDoesNotThrow(() -> helpWindow.getReturnButton().doClick());
}
</code></pre>
| 42,648
|
<p>We are currently using unit tests to test our project. We have the majority of functionality covered but I think our tests are too brittle. </p>
<p>I was wondering if there are any specific things we can be doing to make the unit tests more flexible so they don't break for the wrong reasons.</p>
<p>A couple answers have mentioned being careful of mocking too much... So what are legitimate reasons for mocking? I think that may be one of our main problems, but when your application is mostly a dynamic, database-driven site, how do you get away from mocking?</p>
|
<p>This is a somewhat simplistic answer, but shows the right mindset:</p>
<ul>
<li>A test should break if the behaviour changes in a way that you care about.</li>
<li>A test should continue to work if the behaviour changes in a way that you don't care about.</li>
</ul>
<p>So as far as is possible - without going <em>hugely</em> out of your way - make sure you're testing the "end result" of the method without caring how it got there. One thing to watch out for is mocking - it's incredibly useful, but can easily make your tests brittle.</p>
|
<blockquote>
<p>So what are legitimate reasons for
mocking? I think that may be one of
our main problems, but when your
application is mostly a dynamic,
database-driven site, how do you get
away from mocking?</p>
</blockquote>
<p>Reasons for mocking an object comprise</p>
<ul>
<li>object is or uses an external resource such as database, network, file system</li>
<li>object is a GUI</li>
<li>object is not [yet] available</li>
<li>object behavior is not deterministic</li>
<li>object is expensive to setup</li>
</ul>
| 34,372
|
<p>This is a bit of a lazyweb question but you get the rep so :-)</p>
<p>I have a Java class that returns instances of itself to allow chaining
(e.g. ClassObject.doStuff().doStuff())</p>
<p>For instance:</p>
<pre><code>public class Chainer
{
public Chainer doStuff()
{
/* Do stuff ... */
return this;
}
}
</code></pre>
<p>I would like to extend this class. Is there a way, perhaps using generics, to extend this class without having to overwrite each method signature?</p>
<p>E.g. not:</p>
<pre><code>public class ChainerExtender extends Chainer
{
public ChainerExtender doStuff()
{
super.doStuff();
return this;
}
}
</code></pre>
<p>I have tried:</p>
<pre><code>public class Chainer
{
public <A extends Chainer> A doStuff()
{
/* Do stuff ... */
return (A)this;
}
}
public class ChainerExtender extends Chainer
{
public <A extends Chainer> A doStuff()
{
/* Do stuff ... */
return super.doStuff();
}
}
</code></pre>
<p>But this didn't work giving the error:</p>
<pre><code>type parameters of <A>A cannot be determined;
no unique maximal instance exists for type variable A with upper bounds A,Chainer
</code></pre>
<p>Am I forced to have class declarations like:</p>
<pre><code>public class Chainer<T extends Chainer<T>> {}
public class ChainerExtender extends Chainer<ChainerExtender>
</code></pre>
<p>As per <a href="https://stackoverflow.com/questions/153994/generic-type-args-which-specificy-the-extending-class">this question</a>?</p>
|
<p>Have you tried the straight-forward</p>
<pre><code>public class Chainer
{
public Chainer doStuff()
{
/* Do stuff ... */
return this;
}
}
public class ChainerExtender extends Chainer
{
@Override
public ChainerExtender doStuff()
{
/* Do stuff ... */
super.doStuff();
return this;
}
}
</code></pre>
<p>With Java 5, you can declare overriding methods to have co-variant return types, which means just what this says: a subclass can have an overriding method signature with a more specific return type.</p>
|
<p>Could you just post a complete example leading to the error message you see ?</p>
<p>I just compiled and execute the following without a hitch:</p>
<pre><code>public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
ChainerExtender c = new ChainerExtender();
c.doStuff().doStuff();
}
public static class Chainer
{
public <A extends Chainer> A doStuff()
{
/* Do stuff ... */
System.out.println("Chainer");
return (A)this;
}
}
public static class ChainerExtender extends Chainer
{
/**
* @see test.Test.Chainer#doStuff()
*/
@Override
public <A extends Chainer> A doStuff()
{
System.out.println("ChainerExtender");
return super.doStuff();
}
}
}
</code></pre>
<p>Gives:</p>
<pre><code>ChainerExtender
Chainer
ChainerExtender
Chainer
</code></pre>
<p>I have have misunderstood this issue, please downvote and comment.</p>
| 28,290
|
<p>This was something originally discussed during a presentation given by Charles Brian Quinn of the <a href="http://www.bignerdranch.com/" rel="noreferrer">Big Nerd Ranch</a> at <a href="http://www.actsasconference.com" rel="noreferrer">acts_as_conference</a>. He was discussing what he had learned from instructing a Ruby on Rails Bootcamp to many people both new to programming and new to Rails.</p>
<p>One particular slide that stood out was along the lines of <strong>never using foo and bar as examples when trying to teach someone to program</strong>. His reasoning was very simple.</p>
<p>Which is easier to understand?</p>
<pre><code>baz = foo + bar
</code></pre>
<p>or</p>
<pre><code>answer = first_number + second_number
</code></pre>
<p>It's happened many times myself when explaining something and I immediately jump to the go to foo bar placeholders but then realize my mistake and make the example make a lot more sense by using a real world scenario. </p>
<p>This is especially applicable when trying to teach someone who has had no programming exposure and you end up needing explain foo and bar before explaining what you're actually trying to teach.</p>
<p>However, using foo and bar for experienced programmers seems OK, though I personally think, along with Charles, that it's something that needs to change.</p>
<p>A quick SO search for "foo" returns over 20 pages of results with foo being used in more ways that I can comprehend. And in some cases where I'm reading a question on a particular language and I'm doing so to help understand that language better. If applicable variable names are used instead of foo and bar, it makes it much easier to understand and interpret the problem. So for seasoned developers, the construct seems a bit flawed as well.</p>
<p>Is this a habit that will ever be able to be kicked? Why do you choose to foo bar or to not foo bar?</p>
|
<p>It strictly depends on what are you trying to teach. Sometimes, when showing a programming example, you have to declare a few things just for the snippet to be "complete", and those few things are not the core of what you are showing. </p>
<p>For example, if you want to show how to throw an exception, I believe it is ok to present a snippet like</p>
<pre><code>public void foo() {
// Do some things
if (errorCondition) {
throw new Exception("Error message");
}
}
</code></pre>
<p>Since the point in it is showing exceptions, there is no point in caring about the method name, so foo is "legal" in this context, or at least for me.</p>
<p>What I would not accept (in this same example) would be</p>
<pre><code>public void foo() {
// Do some things
if (bar) {
throw new Exception(baz);
}
}
</code></pre>
<p>as it is obscuring what you are trying to teach.</p>
|
<p>I am new to programming, and more or less self taught. I read a lot of example code online and at the beginning found myself replacing foo and bar &c. with more relevant names, such as the firstnumber and secondnumber examples above.</p>
<p>I now prefer x,y,z,i... because foo and bar seem to spark linguistic impulses in my mind and can distract me from the routine, and I've developed, somewhat, the ability to hold a whole bunch of different variables in my head and remember what they are. But I would still definitely recommend using relevant naming when teaching someone else, especially when explaining code to someone that doesn't program but needs to understand how the program works.</p>
| 29,027
|
<p>Pretty simple scenario. I have a web service that receives a byte array that is to be saved as a particular file type on disk. What is the most efficient way to do this in C#?</p>
|
<p>That would be <a href="http://msdn.microsoft.com/en-us/library/system.io.file.writeallbytes.aspx" rel="noreferrer"><code>File.WriteAllBytes()</code></a>.</p>
|
<p>Perhaps the System.IO.BinaryWriter and BinaryReader classes would help.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.io.binarywriter.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.io.binarywriter.aspx</a></p>
<p>"Writes primitive types in binary to a stream and supports writing strings in a specific encoding."</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.io.binaryreader.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.io.binaryreader.aspx</a></p>
<p>"Reads primitive data types as binary values in a specific encoding."</p>
| 15,656
|
<p>On my Monoprice Mini Select v2 there is poor adhesion when the print head goes to put down a new layer on the bed as seen in the photo. Does anyone have a fix for this?</p>
<p><a href="https://i.stack.imgur.com/NVbXE.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NVbXE.jpg" alt="enter image description here"></a></p>
|
<p>You could try a higher bed temp, but also check to make sure bed is levelled all round as this can sometimes cause this to happen </p>
|
<p>Things you need to check or do: </p>
<ol>
<li>Use adhesion layers </li>
<li>Set lower speeds at first layer.</li>
<li>Increase bed temperature (try 5 degrees steps)</li>
<li>Clean the bed</li>
<li>Check if the bed is completely leveled up. </li>
<li>Increase the thickness of the first layer. </li>
</ol>
| 1,634
|
<p>I am trying to enable Full-text indexing in SQL Server 2005 Express. I am running this on my laptop with Vista Ultimate.</p>
<p>I understand that the standard version of SQL Server Express does not have full-text indexing. I have already downloaded and installed "Microsoft SQL Server 2005 Express Edition with Advanced Services Service Pack 2" (<a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=5B5528B9-13E1-4DB9-A3FC-82116D598C3D&displaylang=en" rel="noreferrer">download</a>).</p>
<p>I have also ensured that both the "SQL Server (instance)" and "SQL Server FullText Search (instance)" services are running on the same account which is "Network Service".</p>
<p>I have also selected the option to "Use full-text indexing" in the Database Properties > Files area.</p>
<p>I can run the sql query "SELECT fulltextserviceproperty('IsFulltextInstalled');" and return 1.</p>
<p>The problem I am having is that when I have my table open in design view and select "Manage FullText Index"; the full-text index window displays the message... </p>
<blockquote>
<p>"Creation of the full-text index is not available. Check that you have the correct permissions or that full-text catalogs are defined."</p>
</blockquote>
<p>Any ideas on what to check or where to go next?</p>
|
<pre><code>sp_fulltext_database 'enable'
CREATE FULLTEXT CATALOG [myFullText]
WITH ACCENT_SENSITIVITY = ON
CREATE FULLTEXT INDEX ON [dbo].[tblName] KEY INDEX [PK_something] ON [myFullText] WITH CHANGE_TRACKING AUTO
ALTER FULLTEXT INDEX ON [dbo].[otherTable] ADD ([Text])
ALTER FULLTEXT INDEX ON [dbo].[teyOtherTable] ENABLE
</code></pre>
|
<p>Use sql server management studio.</p>
<p>Login as admin to your windows account.</p>
<p>Then select database and right click on database in sql server management studio and select Define Full Text Index and you are guided throughout the process by management studio.</p>
| 2,607
|
<p>I am planning on getting a 3D printer soon and I was just wondering, what do you do with 3D prints that either failed or were prototypes that you no longer want?<br>
I tried looking online but the closest I got was effects on environment, turning prints back into filament, or restarting a failed print half-way, none of which were the information I was looking for. </p>
<p>The solution should be somewhat eco and just keeping unwanted prints in a box somewhere isn't a very good solution either.<br>
Finishing off failed prints isn't totally applicable because it wouldn't apply to prototype prints that you don't want to keep.</p>
<p>Is there anywhere to send failed 3D prints for professional recycling, or are there any recommendations for properly disposing 3D prints? </p>
<p>In case this is of any use, the printer I am planning to get uses filament that can be made of PLA, ABS, Nylon, and possibly other materials. The printer is this one specifically (<a href="https://www.kickstarter.com/projects/101hero/101hero-the-world-first-us49-3d-printer">https://www.kickstarter.com/projects/101hero/101hero-the-world-first-us49-3d-printer</a>) from KickStarter.</p>
|
<p>The "obvious" answer is re-grinding the prints and making more filament. Unfortunately, this isn't yet a very economical or simple operation. A decent filament extruder capable of holding acceptable diameter tolerances is around $1000, and even then they can be pretty fidgety to operate. You have to have a LOT of volume throughput in your filament extruder for regrinding to be an economical proposition. </p>
<p>Some of the reasons why recycling prints into filament can be difficult:</p>
<ul>
<li>Most plastics will degrade to some extent each time they are extruded. (Both by the 3d printer and by the filament extruder.) PLA will thermally degrade with extended exposure to heat. PET will hydrolyze and break down if not meticulously dried to remove moisture prior to heating to the melting temp. (PETG seems to be less prone to hydrolysis damage than plastic bottle PET, but it still happens to a limited degree.) ABS holds up to extrusion conditions better than most, which is part of why it's favored for injection molding, but there's still the potential to affect properties by depleting additives or cooking out plasticizers. <strong>In practice, this means regrinds generally need to be mixed with fresh pellets at some ratio.</strong> That dilutes the degraded or additive-depleted polymer with good material so you can maintain the material properties and performance. </li>
<li>If you print a variety of different colors, and don't want all your recycled filament to mix and end up a muddy brownish color, it can be difficult to manage the color sorting and matching. Most people don't want different colors along the length of a spool, either. So the regrind has to be mixed evenly in with virgin pellets and a suitable amount of masterbatch colorant to get a reasonable color output. You're not going to run off a new spool with 95% virgin pellets just to recycle a 50 gram failed print, are you? Likewise for material matching. Mixing materials is a bad idea. <strong>If you only print white PLA, this is all pretty easy to manage. But if you print a variety of colors and materials, you've got to set up a material tracking, sorting, and storage operation.</strong> You <em>can</em> do it... it's just a hassle. </li>
<li>Diameter control is difficult. 3D printers need a fairly tight diameter control for reliable performance and good quality. This is really the key challenge in any filament extrusion process. Extruded polymers like to change shape as they extrude and cool due to molecular alignment effects. You can't just push molten plastic out a 1.75mm nozzle -- "die swell" will make the extrudate bulge to a larger diameter immediately upon exiting the nozzle. Then you have to actually <em>pull</em> on the soft filament as it cools to carefully draw it down to the right diameter. The way the filament extruder measures diameter and controls tension is the key to getting acceptable results. Most hobbyist/desktop filament extruders have not succeeded at this. </li>
</ul>
<p>Those are just the major issues. Filament extrusion is a complex subject with a lot of depth. For a home user of 3d printers, making filament basically becomes a whole second hobby. In my opinion, it only really makes sense in a commercial production printing environment where paid technicians can run the extruder(s) and a very large print throughput makes the pellets+regrind economics much more favorable than just buying new filament. </p>
<p>Reducing and reusing are preferable to recycling. Making your printer more reliable and gaining experience with calibration/configuration will reduce the volume of waste produced. </p>
<p>There are also some productive uses that let you reuse unwanted prints as-is or "downcycle" them for productive uses. </p>
<ul>
<li>I personally keep a box of failed prints (and calibration prints and
no-longer-needed prototypes) as showpieces for people who want to
learn about 3D printing, and as toys for my nieces and nephews. I strongly recommend doing your calibration prints with a "toy" calibration model like <a href="http://www.thingiverse.com/thing:763622" rel="noreferrer">Benchy</a> or <a href="http://www.thingiverse.com/thing:1090268" rel="noreferrer">CaliBlocks</a>. 3D printing is still new enough that people will happily take dozens of Benchies off your hands for the novelty value.</li>
<li>Failed and unwanted prints can also be used around the workshop for shims, sacrificial
cushions when clamping or hammering or drilling, or as scrap for experimenting
with adhesives or post-processing techniques.</li>
<li>ABS scraps are good for making ABS-slurry as a print bed adhesion treatment
layer, or for solvent-painting and filling gaps in other prints. Unfortunately, most other filaments do not have such convenient and safe solvents.</li>
<li>Some people have experimented with putting piles of scrap prints on a cookie sheet in an oven and melting them into multicolor cutting boards. There's a lot you can do with this sort of heavy remelt plate if you get creative. (I personally wouldn't use cheap Asian filaments for food contact though, they often have unpleasant contaminants.)</li>
</ul>
|
<p>If you have a few friends you could pitch in and use a recycling service like <a href="https://www.terracycle.com/en-US/zero_waste_boxes/3d-printing-materials" rel="nofollow noreferrer">Terracycle</a> where you can send your failed prints, rafts and scraps. No affiliation with Terracycle, it's just a service that I found and am considering.</p>
| 304
|
<p>I want to write a program that would print every combination of a set of variables to a text file, creating a word list. Each answer should be written on a separate line and write all of the results for 1 digit, 2 digits, and 3 digits to a single text file.</p>
<p>Is there a simple way I can write a python program that can accomplish this? Here is an example of the output I am expecting when printing all the binary number combinations possible for 1, 2, and 3 digits:</p>
<pre><code>Output:
0
1
00
01
10
11
000
001
010
011
100
101
110
111
</code></pre>
|
<p>A naïve solution which solves the problem and is general enough for any application you might have is this:</p>
<pre><code>def combinations(words, length):
if length == 0:
return []
result = [[word] for word in words]
while length > 1:
new_result = []
for combo in result:
new_result.extend(combo + [word] for word in words)
result = new_result[:]
length -= 1
return result
</code></pre>
<p>Basically, this gradually builds up a tree in memory of all the combinations, and then returns them. It is memory-intensive, however, and so is impractical for large-scale combinations.</p>
<p>Another solution for the problem is, indeed, to use counting, but then to transform the numbers generated into a list of words from the wordlist. To do so, we first need a function (called <code>number_to_list()</code>):</p>
<pre><code>def number_to_list(number, words):
list_out = []
while number:
list_out = [number % len(words)] + list_out
number = number // len(words)
return [words[n] for n in list_out]
</code></pre>
<p>This is, in fact, a system for converting decimal numbers to other bases. We then write the counting function; this is relatively simple, and will make up the core of the application:</p>
<pre><code>def combinations(words, length):
numbers = xrange(len(words)**length)
for number in numbers:
combo = number_to_list(number, words)
if len(combo) < length:
combo = [words[0]] * (length - len(combo)) + combo
yield combo
</code></pre>
<p>This is a Python generator; making it a generator allows it to use up less RAM. There is a little work to be done after turning the number into a list of words; this is because these lists will need padding so that they are at the requested length. It would be used like this:</p>
<pre><code>>>> list(combinations('01', 3))
[['0', '0', '0'], ['0', '0', '1'],
['0', '1', '0'], ['0', '1', '1'],
['1', '0', '0'], ['1', '0', '1'],
['1', '1', '0'], ['1', '1', '1']]
</code></pre>
<p>As you can see, you get back a list of lists. Each of these sub-lists contains a sequence of the original words; you might then do something like <code>map(''.join, list(combinations('01', 3)))</code> to retrieve the following result:</p>
<pre><code>['000', '001', '010', '011', '100', '101', '110', '111']
</code></pre>
<p>You could then write this to disk; a better idea, however, would be to use the built-in optimizations that generators have and do something like this:</p>
<pre><code>fileout = open('filename.txt', 'w')
fileout.writelines(
''.join(combo) for combo in combinations('01', 3))
fileout.close()
</code></pre>
<p>This will only use as much RAM as necessary (enough to store one combination). I hope this helps.</p>
|
<p>It shouldn't be too hard in most languages. Does the following pseudo-code help?</p>
<pre><code>for(int i=0; i < 2^digits; i++)
{
WriteLine(ToBinaryString(i));
}
</code></pre>
| 29,896
|
<p>So I made some timers for a quiz. The thing is, I just realized when I put </p>
<pre><code>javascript: alert("blah");
</code></pre>
<p>in the address, the popup alert box <strong>pauses</strong> my timer. Which is very unwanted in a quiz.</p>
<p>I don't think there is any way to stop this behaviour... but I'll ask anyway.</p>
<p>If there is not, mind suggesting what should I do?</p>
|
<p>Apparently the preview rendering differs from the posted rendering. This paragraph is here to make sure the next two lines show up as code.</p>
<pre><code>// Preserve native alert() if you need it for something special
window.nativeAlert = window.alert;
window.alert = function(msg) {
// Do something with msg here. I always write mine to console.log,
// but then I have rarely found a use for a real modal dialog,
// and most can be handled by the browser (like window.onbeforeunload).
};
</code></pre>
|
<p>The server session could be set to expire at say 1 hour. The javascript could be used as only a display tool for the user to know how much time is left. If he decides to cheat by pausing the timer, then he might be suprised when posting his test that his session has timed out.</p>
| 24,116
|
<p>Using NHibernate from C# and only HQL (not SQL) in a way that is compatible with MS SQL Server 2005/2008 (and preferably Oracle).</p>
<p>Is there a way to write the order by clause so that nulls will sort at the end of the query results while the non-null results will be sorted in ascending order?</p>
<p>Based on the answer to the question referenced by nickf the answer is:</p>
<pre><code>select x from MyClass x order by case when x.MyProperty is null then 1 else 0 end, x.MyProperty
</code></pre>
|
<p>The point is to separate algorithms into classes that can be plugged in at runtime. For instance, let's say you have an application that includes a clock. There are many different ways that you can draw a clock, but for the most part the underlying functionality is the same. So you can create a clock display interface:</p>
<pre><code>class IClockDisplay
{
public:
virtual void Display( int hour, int minute, int second ) = 0;
};
</code></pre>
<p>Then you have your Clock class that is hooked up to a timer and updates the clock display once per second. So you would have something like:</p>
<pre><code>class Clock
{
protected:
IClockDisplay* mDisplay;
int mHour;
int mMinute;
int mSecond;
public:
Clock( IClockDisplay* display )
{
mDisplay = display;
}
void Start(); // initiate the timer
void OnTimer()
{
mDisplay->Display( mHour, mMinute, mSecond );
}
void ChangeDisplay( IClockDisplay* display )
{
mDisplay = display;
}
};
</code></pre>
<p>Then at runtime you instantiate your clock with the proper display class. i.e. you could have ClockDisplayDigital, ClockDisplayAnalog, ClockDisplayMartian all implementing the IClockDisplay interface.</p>
<p>So you can later add any type of new clock display by creating a new class without having to mess with your Clock class, and without having to override methods which can be messy to maintain and debug.</p>
|
<p>Strategy pattern works on simple idea i.e. "Favor Composition over Inheritance" so that strategy/algorithm can be changed at run time. To illustrate let's take an example where in we need to encrypt different messages based on its type e.g. MailMessage, ChatMessage etc.</p>
<pre><code>class CEncryptor
{
virtual void encrypt () = 0;
virtual void decrypt () = 0;
};
class CMessage
{
private:
shared_ptr<CEncryptor> m_pcEncryptor;
public:
virtual void send() = 0;
virtual void receive() = 0;
void setEncryptor(cost shared_ptr<Encryptor>& arg_pcEncryptor)
{
m_pcEncryptor = arg_pcEncryptor;
}
void performEncryption()
{
m_pcEncryptor->encrypt();
}
};
</code></pre>
<p>Now at runtime you can instantiate different Messages inherited from CMessage (like CMailMessage:public CMessage) with different encryptors (like CDESEncryptor:public CEncryptor)</p>
<pre><code>CMessage *ptr = new CMailMessage();
ptr->setEncryptor(new CDESEncrypto());
ptr->performEncryption();
</code></pre>
| 20,709
|
<pre><code><xsl:for-each select="./node [position() &lt;= (count(*) div 2)]">
<li>foo</li>
</xsl:for-each>
<xsl:for-each select="./node [count(*) div 2 &lt; position()]">
<li>bar</li>
</xsl:for-each>
</code></pre>
<p>My list has 12 nodes, but the second list is always 8 and the first is always 4. What's wrong with my selects?</p>
|
<p>When you do <code>count(*)</code>, the current node is the <code>node</code> element being processed. You want either <code>count(current()/node)</code> or <code>last()</code> (preferable), or just calculate the midpoint to a variable for better performance and clearer code:</p>
<pre><code><xsl:variable name="nodes" select="node"/>
<xsl:variable name="mid" select="count($nodes) div 2"/>
<xsl:for-each select="$nodes[position() &lt;= $mid]">
<li>foo</li>
</xsl:for-each>
<xsl:for-each select="$nodes[$mid &lt; position()]">
<li>bar</li>
</xsl:for-each>
</code></pre>
|
<p>I'm not at all sure, but it seems to me that <code>count(*)</code> is not doing what you think it is. That counts the number of children of the current node, not the size of the current node list. Could you print it out to check that it's 8 or 9 instead of 12?</p>
<p>Use <code>last()</code> to get the context size.</p>
| 5,425
|
<p>How do you set the Windows time zone on the local machine programmatically in C#? Using an interactive tool is not an option because the remote units have no user interface or users. The remote machine is running .NET 2.0 and Windows XP Embedded and a local app that communicates with a central server (via web service) for automated direction of its tasks. We can deliver a command to synch to a certain time/zone combination, but what code can be put in the local app to accomplish the change? The equipment is not imaged for specific locations before installation, so in order to use any equipment at any location, we have to be able to synch this information.</p>
|
<p><a href="http://msdn.microsoft.com/en-us/library/ms724944.aspx" rel="nofollow noreferrer">SetTimeZoneInformation</a> should do what you need. You'll need to use <a href="http://pinvoke.net/default.aspx/kernel32/SetTimeZoneInformation.html" rel="nofollow noreferrer">P/Invoke</a> to get at it.</p>
<p>Note also that you'll need to possess and enable the SE_TIME_ZONE_NAME privilege.</p>
|
<p>Try this...</p>
<p>First, you need to find, in the registry, the <strong>key</strong> that represents the zone you want ("Central Standard Time" is an example). Those are located here:</p>
<blockquote>
<p>HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\Current Version\Time Zones</p>
</blockquote>
<p>So, with that in mind, create a batch file, "SetTimeZone.bat" with the following line in it:</p>
<blockquote>
<p>RunDLL32 shell32.dll,Control_RunDLL %SystemRoot%\system32\TIMEDATE.cpl,,/Z %1</p>
</blockquote>
<p>From C#, call:</p>
<blockquote>
<p>System.Diagnostics.Process.Start("SetTimeZone.bat", "The key of the time zone you want to set");</p>
</blockquote>
| 5,272
|
<p>I have an XML reader on this XML string:</p>
<pre><code><?xml version="1.0" encoding="UTF-8" ?>
<story id="1224488641nL21535800" date="20 Oct 2008" time="07:44">
<title>PRESS DIGEST - PORTUGAL - Oct 20</title>
<text>
<p> LISBON, Oct 20 (Reuters) - Following are some of the main
stories in Portuguese newspapers on Monday. Reuters has not
verified these stories and does not vouch for their accuracy. </p>
<p>More HTML stuff here</p>
</text>
</story>
</code></pre>
<p>I created an XSD and a corresponding class for deserialization.</p>
<pre><code>[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public class story {
[System.Xml.Serialization.XmlAttributeAttribute()]
public string id;
[System.Xml.Serialization.XmlAttributeAttribute()]
public string date;
[System.Xml.Serialization.XmlAttributeAttribute()]
public string time;
public string title;
public string text;
}
</code></pre>
<p>I then create an instance of the class using the <code>Deserialize</code> method of XmlSerializer.</p>
<pre><code>XmlSerializer ser = new XmlSerializer(typeof(story));
return (story)ser.Deserialize(xr);
</code></pre>
<p>Now, the <code>text</code> member of <code>story</code> is always null. How do I change my <code>story</code> class so that the XML is parsed as expected?</p>
<p><strong>EDIT:</strong> </p>
<p>Using an XmlText does not work and I have no control over the XML I'm parsing.</p>
|
<p>I found a <em>very</em> unsatisfactory solution.</p>
<p>Change the class like this (ugh!)</p>
<pre><code>// ...
[XmlElement("HACK - this should never match anything")]
public string text;
// ...
</code></pre>
<p>And change the calling code like this (yuck!)</p>
<pre><code>XmlSerializer ser = new XmlSerializer(typeof(story));
string text = string.Empty;
ser.UnknownElement += delegate(object sender, XmlElementEventArgs e) {
if (e.Element.Name != "text")
throw new XmlException(
string.Format(CultureInfo.InvariantCulture,
"Unknown element '{0}' cannot be deserialized.",
e.Element.Name));
text += e.Element.InnerXml;
};
story result = (story)ser.Deserialize(xr);
result.text = text;
return result;
</code></pre>
<p>This is a really bad way of doing it because it breaks <em>encapsulation</em>. Is there a better way of doing it?</p>
|
<p>Looks to me that the XML is incorrect.
Since you use HTML tags within the text tag the HTML tags are interpreted as XML.
You should use CDATA to correctly interpret the data or escape < and >.</p>
| 26,807
|
<p>Problem, there's no method:</p>
<pre><code>bool ChangePassword(string newPassword);
</code></pre>
<p>You have to know the current password (which is probably hashed and forgotten).</p>
|
<p>This is an easy one that I wasted too much time on. Hopefully this post saves someone else the pain of slapping their forehead as hard as I did.</p>
<p>Solution, reset the password randomly and pass that into the change method.</p>
<pre><code>MembershipUser u = Membership.GetUser();
u.ChangePassword(u.ResetPassword(), "myAwesomePassword");
</code></pre>
|
<p>You are not able to change the password if the requiresQuestionAndAnswer="true"</p>
<p>I got the work around for this </p>
<p>Created two membership providers in web.config </p>
<p>
</p>
<p>i am using the AspNetSqlMembershipProviderReset provider for reseting the password since it has the requiresQuestionAndAnswer= false where as AspNetSqlMembershipProvider is the default provider used.</p>
<p>i wrote the following code to reset the password for the user.</p>
<p>public bool ResetUserPassword(String psUserName, String psNewPassword)
{
try
{
// Get Membership user details using secound membership provider with required question answer set to false.</p>
<pre><code> MembershipUser currentUser = Membership.Providers["AspNetSqlMembershipProviderReset"].GetUser(psUserName,false);
//Reset the user password.
String vsResetPassword = currentUser.ResetPassword();
//Change the User password with the required password
currentUser.ChangePassword(vsResetPassword, psNewPassword);
//Changed the comments to to force the user to change the password on next login attempt
currentUser.Comment = "CHANGEPASS";
//Check if the user is locked out and if yes unlock the user
if (currentUser.IsLockedOut == true)
{
currentUser.UnlockUser();
}
Membership.Providers["AspNetSqlMembershipProviderReset"].UpdateUser(currentUser); return true;
}
catch (Exception ex)
{
throw ex;
return false;
}
}
</code></pre>
| 36,545
|
<p>On occasion, I find myself wanting to search the text of changelist descriptions in Perforce. There doesn't appear to be a way to do this in P4V. I can do it by redirecting the output of the changes command to a file...</p>
<pre><code>p4 changes -l > p4changes.txt
</code></pre>
<p>...(the -l switch tells it to dump the full text of the changelist descriptions) and then searching the file, but this is rather cumbersome. Has anyone found a better way?</p>
|
<p>When the submitted changelist pane has focus, a CTRL+F lets you do an arbitrary text search, which includes changelist descriptions.</p>
<p>The only limitation is that it searches just those changelists that have been fetched from the server, so you may need to up the number retrieved. This is done via the "Number of changelists, jobs, branch mappings or labels to fetch at a time" setting which can be found by navigating to Edit->Preferences->Server Data.</p>
|
<p>If you still love your command line, you can write a small perl script that:</p>
<ul>
<li>changes the record separator $/ to
double newline "\n\n" so it filters
the input into full records of the
ztagged p4 output. </li>
<li>scans
the '/^... desc/..//' part with
regular expressions from the args.</li>
</ul>
<p>usage would be something like 'p4 -ztag changes -l | yourperlfilter.pl searchterm1 searchterm2'</p>
<p>if that worked ok, you could <a href="http://markmail.org/message/ipcpb4ddbqhdmt43" rel="nofollow noreferrer">integrate it into the p4win tools menu</a>.</p>
| 16,236
|
<p>I am working on localization for an app where custom patterns are used to format the date-time.</p>
<p>one example is:
dd-MM HH:mm</p>
<p>I need to get localized versions of this custom format for dates, so that I get the date using numbers, and the time, basically using the local order (dd MM or MM dd) and the local seperator for both date and time.</p>
<p>This is fairly trivial, as long as I am using the default formatting, but as soon as I stray from these, the formatting becomes hardcoded.</p>
<p>Any ideas?</p>
<p>Thanks, Jonas</p>
<p>edit:
I have the cultureInfo objects, the problem is that when I do a DateTime.ToString("ES-es"), I get too much info - I need only month+day, but with the default ToString, I get year+month+day</p>
<p>Edit again:
I see how I can change the ShortDate pattern for each CultureInfo object I use. However, I also need the default ShortDate pattern in some situations, so changing that would, unfortunately, leave me with another, equivalent problem.</p>
<p>Final edit: in case anyone cares. I never did find a solution, so I ended up coding a static function that checks the current CultureInfo, and returns the correctly formatted date, sans year.</p>
|
<p>Look at the DateTimeFormatInfo class (CultureInfo.DateTimeFormat property), in particular the properties DateSeparator, TimeSeparator, ShortDatePattern.</p>
|
<p>The <a href="http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.aspx" rel="nofollow noreferrer">CultureInfo</a> class would be a good place to start looking.</p>
| 40,459
|
<p>One problem I have with open-source is not often the product or documentation, but the level of community involvement and support. Response time for some questions on official forums can take more than a week, which can honestly make a big difference when choosing a platform for commercial services use. However, I find that evaluating the community beforehand is very difficult. How do I know what are the most common issues, and whether or not people are getting support for them? How do I know what problems I personally might encounter based upon my project, which would require some level of community support? Do you have a formula for performing this evaluation?</p>
|
<p>I've usually found that relying on community support for anything mission critical is asking for trouble. So I usually stay away from open source unless it's something that I'm confident we can support in-house or there is a commercial support service available for it.</p>
|
<p>The only real way to evaluate the community is to try it, participate in the community. Most communities will have good support networks available in one manner or another. Also many individuals are starting to offer support services for the various frameworks as well, for those looking for a more dedicated resource for problem resolution.</p>
<p>But I find the best way is to just get in there, ask a few questions, poke around at the resources, and really see what is there.</p>
| 22,274
|
<p>I've got a problem here with an MSI deployment that I'm working on (using <a href="http://en.wikipedia.org/wiki/InstallShield" rel="nofollow noreferrer">InstallShield</a>). We have a program running in the background that needs to run per-user, and it needs to start automatically without user intervention.</p>
<p>The problem is with <a href="http://en.wikipedia.org/wiki/Group_Policy#Operation" rel="nofollow noreferrer">Group Policy Object</a>/<a href="http://en.wikipedia.org/wiki/Active_Directory" rel="nofollow noreferrer">Active Directory</a> (GPO/AD) deployment the application is started in the SYSTEM context before anyone is logged in rather than as the user who is about to log in. The application can only run once per user, and it seems that the SYSTEM process prevents the USER process from starting. This means the PCs need to be rebooted twice before the software can be deployed to the users. How do we to stop this?</p>
<p>Basically the current workflow is: </p>
<ol>
<li>Installation/upgrade runs... kill background application</li>
<li>Install new files</li>
<li>Startup background application</li>
</ol>
<p>This works for published applications and interactive <a href="http://en.wikipedia.org/wiki/Windows_Installer" rel="nofollow noreferrer">MSI</a> installations - it's only 'assigned' applications that seem to have the problem. As step 3 happens in the SYSTEM context rather than the user context :(</p>
<p>Ideally, I'd have the development team patch the EXE file to prevent launching in the SYSTEM context, but that's a release cycle away, and I'm looking for an installer-based solution for the interim.</p>
<p>(I don't know Installscript... So I'm guessing <a href="http://en.wikipedia.org/wiki/VBScript" rel="nofollow noreferrer">VBScript</a> is probably the way to go if there's no native InstallShield stuff I can use.)</p>
|
<p>You can use the <a href="http://msdn.microsoft.com/en-us/library/aa369780(VS.85).aspx" rel="noreferrer">LogonUser</a> property of Windows Installer as a condition to the action launching the EXE.</p>
|
<p>AHA! I knew there had to be a cleaner solution... the code I was working on was starting to look something like this:</p>
<pre class="lang-vb prettyprint-override"><code>On Error Resume Next
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colProcessList = objWMIService.ExecQuery _
("Select * from Win32_Process Where Name = 'BackgroundProcess.exe'")
For Each objProcess in colProcessList
colProperties = objProcess.GetOwner(strNameOfUser,strUserDomain)
If strNameOfUser = "SYSTEM" Then
objProcess.Terminate()
End If
Next
</code></pre>
| 4,953
|
<p>I am trying to implement AJAX in my Google App Engine application, and so I am looking for a good AJAX framework that will help me. Anyone has any idea?</p>
<p>I am thinking about Google Web Toolkit, how good it is in terms of creating AJAX for Google App Engine?</p>
|
<p>As Google Web Toolkit is a <a href="http://code.google.com/support/bin/answer.py?answer=54830&topic=10208" rel="nofollow noreferrer">subset of Java</a> it works best when you Java at the backend too. Since Google App Engine is currently <a href="http://code.google.com/appengine/kb/general.html#language" rel="nofollow noreferrer">Python only</a> I think you'd have to do a lot of messing about to get your server and client to talk nicely to each other.</p>
<p>jQuery seems to be the most popular JavaScript library option in the <a href="http://www.djangosnippets.org/tags/ajax/?page=1" rel="nofollow noreferrer">AJAX Tag at DjangoSnippets.com</a>.</p>
<p><strong>Edit:</strong> The above is only true of Google App Engine applications written in Python. As Google App Engine now supports Java, GWT could now be a good choice for writing an AJAX front end. <a href="http://code.google.com/webtoolkit/doc/latest/tutorial/appengine.html" rel="nofollow noreferrer">Google even have a tutorial showing you how to do it.</a></p>
|
<p>If you want to be able to invoke method calls from JavaScript to Python, <a href="http://json-rpc.org/wiki/python-json-rpc" rel="nofollow noreferrer">JSON-RPC</a> works well with Google App Engine. See Google's article, "<a href="http://code.google.com/appengine/articles/rpc.html" rel="nofollow noreferrer">Using AJAX to Enable Client RPC Requests</a>", for details.</p>
| 7,757
|
<p>Is it possible to define a spring-managed EJB3 hibernate listener?</p>
<p>I have this definition in my <strong>persistence.xml</strong>:</p>
<pre><code><properties>
<property name="hibernate.ejb.interceptor"
value="my.class.HibernateAuditInterceptor" />
<property name="hibernate.ejb.event.post-update"
value="my.class.HibernateAuditTrailEventListener" />
</properties>
</code></pre>
<p>But I would like to manage <code>HibernateAuditInterceptor</code> and <code>HibernateAuditTrailEventListener</code> with spring, so I can do some bean injection (ex: session-scoped bean) within these classes. Is this possible?</p>
|
<p><a href="http://blog.krecan.net/2009/01/24/spring-managed-hibernate-interceptor-in-jpa/" rel="nofollow noreferrer">http://blog.krecan.net/2009/01/24/spring-managed-hibernate-interceptor-in-jpa/</a></p>
|
<p>The problem is that those properties are just strings. Even if you define your SessionFactory as a Spring bean, any properties you pass to it through the hibernateProperties setter are just strings:</p>
<pre><code><bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource"ref="myDataSource"/>
<property name="mappingResources">
<list>
<value>whatever.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.ejb.interceptor= my.class.HibernateAuditInterceptor
</value>
<value>
hibernate.ejb.event.post-update=my.class.HibernateAuditTrailEventListener
</value>
</property>
</bean>
</code></pre>
<p>So I don't think you can do that.</p>
| 32,248
|
<p>I have a couple old services that I want to completely uninstall. How can I do this?</p>
|
<p>Use the <em>SC</em> command, like this (you need to be on a command prompt to execute the commands in this post):</p>
<pre><code>SC STOP shortservicename
SC DELETE shortservicename
</code></pre>
<hr>
<p><strong>Note:</strong> You need to run the command prompt as an administrator, not just logged in as the administrator, but also with administrative rights. If you get errors above about not having the necessary access rights to stop and/or delete the service, run the command prompt as an administrator. You can do this by searching for the command prompt on your start menu and then right-clicking and selecting "Run as administrator". <strong>Note to PowerShell users:</strong> <code>sc</code> is aliased to <code>set-content</code>. So <code>sc delete service</code> will actually create a file called <code>delete</code> with the content <code>service</code>. To do this in Powershell, use <code>sc.exe delete service</code> instead</p>
<hr>
<p>If you need to find the short service name of a service, use the following command to generate a text file containing a list of services and their statuses:</p>
<pre><code>SC QUERY state= all >"C:\Service List.txt"
</code></pre>
<p>For a more concise list, execute this command:</p>
<pre><code>SC QUERY state= all | FIND "_NAME"
</code></pre>
<p>The short service name will be listed just above the display name, like this:</p>
<pre><code>SERVICE_NAME: MyService
DISPLAY_NAME: My Special Service
</code></pre>
<p>And thus to delete that service:</p>
<pre><code>SC STOP MyService
SC DELETE MyService
</code></pre>
|
<p>For me my service that I created had to be uninstalled in Control Panel > Programs and Features</p>
| 10,169
|
<p>For reasons unknown, the VB6 compiler often likes to reorder the contents of .vbp files and the control descriptor block at the top of .frm files (The code that describes the properties of controls on the form. Code that you don't see in the IDE but you do see in a text editor and <em>when doing diffs against the previous revision in version control</em>.). This is monumentally annoying and very distracting when comparing revisions of a file.</p>
<p>Is there a way to prevent this?</p>
|
<p>I don't think there's much you can do about this. I've noticed the same problem: the IDE likes to rearrange things for seemingly no apparent reason. Some things I've noticed:</p>
<ul>
<li><p>When you use the SSTab control, VB
likes to rearrange properties for
tabs, especially the TabEnabled
property.</p></li>
<li><p>For project files, it randomly
rearranges the order in which files
appear and I think I remember seeing
cases where similar file types are
not always grouped together and end
up mixed in with the project
properties. You don't have
much control over this, unless you run all your VBP's through some type of sanitizer that groups like files together (forms in one group, modules in another group, etc.) and sorts them alphabetically or something, so that they remain consistent. One possible way to handle this could be to write an IDE add-on that automatically does this everytime you save changes to a project file, or come up with some batch process that will just recurse over your source directories and clean up all the VBP's in one go.</p></li>
<li><p>The IDE seems to randomly change the
case of things; this seems to happen
frequently to project references.
Sometimes they are output in lower
case, and other times they are
output in upper case. You can get
around this by choosing "Ignore
Case" when you diff files in
SourceSafe.</p></li>
<li><p>Control coordinates, such
Top, Left, Height, and Width, can differ between
two revisions of the same form. This is due
to different developers using
different screen resolutions and/or
different screen DPI settings while working on the same form.
If you aren't doing this already, I
highly recommend that you get
everyone to develop using the same
resolution and same DPI setting.
The differing values are caused by rounding errors that
occur when logical screen
coordinates at different resolutions/DPI settings
are converted to twips, the default
coordinate space that VB uses for
laying out forms. Additionally, while I'm on the topic, make
sure everyone has their display set to 96dpi,
because if you develop VB forms at
120dpi, there is a really really good
chance they won't display correctly
on a display set to 96dpi.</p></li>
<li><p>There are probably other things I
can't remember right now...</p></li>
</ul>
<p>As for the order of controls being changed in form files, this is normal, and you usually don't want to try rearrange the order of controls by hand if it happens to change from one revision of the form to the next. The order that the controls appear in a form file determines their Z-order on the form. If the order of the controls changes in the .frm file, this will change their relative Z-order on the form, which could lead to unintended results in how your forms are displayed.</p>
|
<p>I have noticed that re-opening the form and saving again often restores a consistent order.</p>
| 20,242
|
<p>I've been writing a little application that will let people upload & download files to me. I've added a web service to this applciation to provide the upload/download functionality that way but I'm not too sure on how well my implementation is going to cope with large files.</p>
<p>At the moment the definitions of the upload & download methods look like this (written using Apache CXF):</p>
<pre><code>boolean uploadFile(@WebParam(name = "username") String username,
@WebParam(name = "password") String password,
@WebParam(name = "filename") String filename,
@WebParam(name = "fileContents") byte[] fileContents)
throws UploadException, LoginException;
byte[] downloadFile(@WebParam(name = "username") String username,
@WebParam(name = "password") String password,
@WebParam(name = "filename") String filename) throws DownloadException,
LoginException;
</code></pre>
<p>So the file gets uploaded and downloaded as a byte array. But if I have a file of some stupid size (e.g. 1GB) surely this will try and put all that information into memory and crash my service.</p>
<p>So my question is - is it possible to return some kind of stream instead? I would imagine this isn't going to be terribly OS independent though. Although I know the theory behind web services, the practical side is something that I still need to pick up a bit of information on.</p>
<p>Cheers for any input,
Lee</p>
|
<p><a href="https://stackoverflow.com/q/132618/16800">Stephen Denne</a> has a Metro implementation that satisfies your requirement. My answer is provided below after a short explination as to why that is the case.</p>
<p>Most Web Service implementations that are built using HTTP as the message protocol are REST compliant, in that they only allow simple send-receive patterns and nothing more. This greatly improves interoperability, as all the various platforms can understand this simple architecture (for instance a Java web service talking to a .NET web service).</p>
<p>If you want to maintain this you could provide chunking.</p>
<pre><code>boolean uploadFile(String username, String password, String fileName, int currentChunk, int totalChunks, byte[] chunk);
</code></pre>
<p>This would require some footwork in cases where you don't get the chunks in the right order (Or you can just require the chunks come in the right order), but it would probably be pretty easy to implement.</p>
|
<p>One way to do it is to add a <strong>uploadFileChunk</strong>(byte[] chunkData, int size, int offset, int totalSize) method (or something like that) that uploads parts of the file and the servers writes it the to disk. </p>
| 16,076
|
<p>What are the best continuous integration frameworks/projects for Perl and why?</p>
|
<p>The only one I've seen in action is <a href="http://sourceforge.net/projects/smolder" rel="noreferrer">Smolder</a> (it is used for <a href="http://smolder.plusthree.com/app/public_projects/report_details/5562" rel="noreferrer">parrot</a>). It is TAP based and therefore integrates well with standard perl testing structures. See also this <a href="http://www.slideshare.net/mpeters/smolder-introduction" rel="noreferrer">presentation</a>.</p>
|
<p>Pjam - is a new <a href="https://github.com/thaljef/Pinto" rel="nofollow">pinto</a> based build server for perl applications. This is the perl specific build server,
because of using <strong>pinto</strong> under the hood it gives you very control on your builds:</p>
<ul>
<li>comparing builds</li>
<li>roll back project to given build</li>
<li>see changes for the next build</li>
<li>etc. </li>
</ul>
<p>It's ruby on rails applications - see more on <a href="https://github.com/melezhik/pjam-on-rails" rel="nofollow">https://github.com/melezhik/pjam-on-rails</a>. The author. </p>
| 12,728
|
<p>Does anyone know how to transform a enum value to a human readable value?</p>
<p>For example:</p>
<blockquote>
<p>ThisIsValueA should be "This is Value A".</p>
</blockquote>
|
<p>Converting this from a vb code snippet that a certain Ian Horwill left at a <a href="http://secretgeek.net/progr_purga.asp" rel="noreferrer">blog post long ago</a>... i've since used this in production successfully.</p>
<pre><code> /// <summary>
/// Add spaces to separate the capitalized words in the string,
/// i.e. insert a space before each uppercase letter that is
/// either preceded by a lowercase letter or followed by a
/// lowercase letter (but not for the first char in string).
/// This keeps groups of uppercase letters - e.g. acronyms - together.
/// </summary>
/// <param name="pascalCaseString">A string in PascalCase</param>
/// <returns></returns>
public static string Wordify(string pascalCaseString)
{
Regex r = new Regex("(?<=[a-z])(?<x>[A-Z])|(?<=.)(?<x>[A-Z])(?=[a-z])");
return r.Replace(pascalCaseString, " ${x}");
}
</code></pre>
<p>(requires, 'using System.Text.RegularExpressions;')</p>
<p>Thus:</p>
<pre><code>Console.WriteLine(Wordify(ThisIsValueA.ToString()));
</code></pre>
<p>Would return, </p>
<pre><code>"This Is Value A".
</code></pre>
<p>It's much simpler, and less redundant than providing Description attributes.</p>
<p>Attributes are useful here only if you need to provide a layer of indirection (which the question didn't ask for).</p>
|
<p>I found it best to define your enum values with an under score so ThisIsValueA would be This_Is_Value_A then you can just do a enumValue.toString().Replace("_"," ") where enumValue is your varible.</p>
| 3,455
|
<p>I have two medium-sized web applications that I'm merging into one. They are both localized with <code>GetText</code> and have large amout of common strings, so merging them manually would be extremely annoying. What is the fastest way to merge the two <code>PO</code> files?</p>
|
<p><code>msgcat</code> is meant for just this thing: it concatenates and merges PO files. <code>msgmerge</code> is for merging PO files with an updated POT file.</p>
|
<p>"WinMerge" can be very helpful</p>
| 46,416
|
<p>I have a long running process in VB6 that I want to finish before executing the next line of code. How can I do that? Built-in function? Can I control how long to wait?</p>
<p>Trivial example:</p>
<pre><code>Call ExternalLongRunningProcess
Call DoOtherStuff
</code></pre>
<p>How do I delay 'DoOtherStuff'?</p>
|
<p>VB.Net: I would use a <a href="http://msdn.microsoft.com/en-us/library/kzy257t0.aspx" rel="noreferrer">WaitOne</a> event handle.</p>
<p>VB 6.0: I've seen a DoEvents Loop.</p>
<pre><code>Do
If isSomeCheckCondition() Then Exit Do
DoEvents
Loop
</code></pre>
<p>Finally, You could just sleep:</p>
<pre><code>Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Sleep 10000
</code></pre>
|
<p><code>System.Threading.Thread.Sleep(500)</code></p>
| 12,075
|
<p>I'm currently performing a migration operation from a legacy database. I need to perform migration of millions of originating rows, breaking the original content apart into multiple destination parent / child rows. </p>
<p>As it's not a simple 1 to 1 migration and the the resulting rows are parent / children row based on identity generated keys, what's the best mechanism for performing the migration? </p>
<p>I'm assuming that I can't use bulk insert as the identity values for the child rows cannot be determined at the point of generating the script content? The only solution I can currently think of is to set the identity explicitly and then have a predetermined starting point for the import.</p>
<p>If anyone else has any input I'd appreciate the feedback.</p>
|
<p>This is my standard approach:</p>
<ul>
<li>create your new data model</li>
<li>pull the data into the new DB unchanged</li>
<li>write (and run) a SQL script to perform the migration</li>
<li>test</li>
<li>(optional) drop the tables with the legacy data</li>
</ul>
<p>You can get a long way towards migrating the data with plain SQL. For the case you described, you might not need to deal with a single Cursor to get it across. </p>
<p>Running the process in Query Analyzer (or an analog in your dbms), you'll have the advantage that you can wrap everything in a Transaction so that you can roll back if anything goes wacky along the way. Write it in little bits and test it in chunks, on your dev database. Once everything is working correctly, set the script loose on your production database.</p>
<p>Sorted.</p>
|
<p>Thanks for the suggestion but I'd prefer to produce a programmatic solution. I'm currently using Nant / CruiseControl to automate the tests and need something I can recreate on the fly based on the current live legacy content.</p>
| 31,071
|
<p>I am aware that you can lock an object in c# using lock but can you give up the lock and wait for something else to notify you that it's changed like you can in java with wait and notify?</p>
<p>It seems to me that synchronised and lock in java and c# respectively are synonomous.</p>
|
<p>The equivalent functionality (including the normal locking) is in the <a href="http://msdn.microsoft.com/en-us/library/system.threading.monitor.aspx" rel="noreferrer">Monitor</a> class. </p>
<pre><code>foo.notify() => Monitor.Pulse(foo)
foo.notifyAll() => Monitor.PulseAll(foo)
foo.wait() => Monitor.Wait(foo)
</code></pre>
<p>The <code>lock</code> statement in C# is equivalent to calling <code>Monitor.Enter</code> and <code>Monitor.Exit</code> with an appropriate try/finally block.</p>
<p>See <a href="http://pobox.com/~skeet/csharp/threads" rel="noreferrer">my threading tutorial</a> or <a href="http://www.albahari.com/threading/" rel="noreferrer">Joe Albahari's one</a> for more details.</p>
|
<p>I think Wait Handles may work for you. See if <a href="http://msdn.microsoft.com/en-us/library/ms173179.aspx" rel="nofollow noreferrer">this</a> helps.</p>
| 25,683
|
<p>A lambda expression which takes a function (of one argument) and a number, and applies the function to twice the number.</p>
|
<p>Applying the function to twice the number:</p>
<pre><code>(lambda (f x) (f (* 2 x)))
</code></pre>
<p>Applying the function to the number twice (which is what you may have intended to ask):</p>
<pre><code>(lambda (f x) (f (f x)))
</code></pre>
|
<p>Here is another way to approach it:</p>
<p>Write a Contract, Purpose, and Header:</p>
<pre><code>;; apply-double : function -> number -> any
;; to apply a given function to double a given number
(define (apply-double fun num) ...)
</code></pre>
<p>Write some Tests:</p>
<pre><code>(= (apply-double identity 10) 20)
(= (apply-double - 15) -30)
(= (apply-double / 7) 1/14)
</code></pre>
<p>Define the function:</p>
<pre><code>(define (apply-double fun num)
(fun (* 2 num)))
</code></pre>
<p>This is an abbreviation of the recipe here: <a href="http://www.htdp.org/2003-09-26/Book/" rel="nofollow noreferrer">http://www.htdp.org/2003-09-26/Book/</a></p>
| 28,260
|
<p>I would like to know which dependency described in my pom.xml brings a transitive dependency in my target directory.</p>
<p>To be more precise, I have the library "poi-2.5.1-final-20040804.jar" in my WEB-INF/lib directory and I would like to know which dependency in my pom.xml brings that.</p>
|
<p>To add to @David Crow, here's <a href="http://maven.apache.org/plugins/maven-dependency-plugin/examples/filtering-the-dependency-tree.html" rel="noreferrer">a dependency:tree example</a> from the Maven site:</p>
<pre><code>mvn dependency:tree -Dincludes=velocity:velocity
</code></pre>
<p>might output</p>
<pre><code>[INFO] [dependency:tree]
[INFO] org.apache.maven.plugins:maven-dependency-plugin:maven-plugin:2.0-alpha-5-SNAPSHOT
[INFO] \- org.apache.maven.doxia:doxia-site-renderer:jar:1.0-alpha-8:compile
[INFO] \- org.codehaus.plexus:plexus-velocity:jar:1.1.3:compile
[INFO] \- velocity:velocity:jar:1.4:compile
</code></pre>
|
<p>The dependency information is also included in the Project Information/Dependencies report if you have maven generate a site for the project, using mvn site.</p>
| 5,432
|
<p>If you want to create a custom attribute for MS test (say [Repeat(3)]
how would you do that?</p>
|
<p>I don't think you will like the answer: there is no supported way. However, there is a codeplex project <a href="http://www.codeplex.com/MSTestExtensions" rel="nofollow noreferrer">MSTestExtensions</a> implementing a work around and a <a href="http://callumhibbert.blogspot.com/2008/01/extending-mstest.html" rel="nofollow noreferrer">blog post</a> about how MSTestExtensions works. (Using ContextBoundObject)</p>
|
<p>looking more, here is one possible place to start:
<a href="http://blog.dotnetwiki.org/IntroducingYUnitAMicroscopicUnitTestFrameworkForTeamTest.aspx" rel="nofollow noreferrer">Peli's blog</a></p>
<p>I'm still looking for other good resources or examples.</p>
| 13,977
|
<p>When overriding the MembershipProvider and calling it directly, is there a way to fill the NameValueCollection config parameter of the Initialize method without manually looking through the config file for the settings? </p>
<p>Obviously this Initialize is being called by asp.net and the config is being filled somewhere. I have implemented my own MembershipProvider and it works fine through the build in controls.
I would like to create a new instance of my provider and make a call to it directly, but I don't really want to parse the .config for the MembershipProvider, it's connection string name and then the connection string if it's already being done somewhere.</p>
|
<p>tvanfosson- Thanks for the help. (if I had the 15 points necessary I would vote you up) </p>
<p>From your link I was able to figure it out. It turns out the second parameter to the Initialize proceedure was the list of parameters from the provider and could be reached in the following way:</p>
<pre><code>string configPath = "~/web.config";
Configuration config = WebConfigurationManager.OpenWebConfiguration(configPath);
MembershipSection section = (MembershipSection)config.GetSection("system.web/membership");
ProviderSettingsCollection settings = section.Providers;
NameValueCollection membershipParams = settings[section.DefaultProvider].Parameters;
Initialize(section.DefaultProvider, membershipParams);
</code></pre>
|
<p>In any case you shouldn't create instance of MembershipProvider. It is creating and initializating by standard asp.net infrastructure. You can access to it by code like this one:</p>
<p>var customerMembership = Membership.Provider; </p>
| 29,000
|
<p>I switched locally from subversion 1.4 to 1.5, our server still runs 1.4. Since then every merge takes ages to perform. What took only a couple of seconds is now in the area of 5-10 minutes (or more). There is no difference between the command line client and tortoise (so we talk about the windows versions).</p>
<p>Has anybody else this strange phenomenon?</p>
|
<p>Upgrading to 1.5.3 (when it is out) will significantly speed up your merges.</p>
|
<p>We've had problems when trying to add large numbers of files to repositories through the client which I assume created orphaned processes on the server when we killed the crashed client. We had to kill the server processes too and restart the subversion service (we run SVN as a windows service). Our SVN machine is dedicated so we actually just rebooted the box and everything went back to normal.</p>
| 2,876
|
<p>We are looking to improve our marketing email list by preventing fake emails from entering in the first place. We want to confirm that an email address exists (and that there is actually a mailbox for that email address). </p>
<p>Does anyone know of any services or components to validate an email address? </p>
|
<p>It would be quite trivial to do this yourself.</p>
<ol>
<li><p>Create a webform where the user can type in their email address. You could protect it with a captcha to prevent bots from hitting it.</p></li>
<li><p>On submission, save the email address to a database along with a GUID, DateTime timestamp and IsActivated bit. The GUID uniquely identifies this subscription. The timestamp states an expiry time that the email address must be confirmed by.</p></li>
<li><p>Send an email to the email address with a URL in it like.</p>
<p><a href="http://www.example.com/validate.aspx?g=GUID-GOES-HERE" rel="nofollow noreferrer">http://www.example.com/validate.aspx?g=GUID-GOES-HERE</a></p></li>
<li><p>If user receives the email in their inbox & clicks the validation link before the timestamp for that GUID/Email expires, then you activate their account.</p></li>
<li><p>At regular intervals you could have a job remove rows from the table that have never been activated where the activation window has expired.</p></li>
</ol>
|
<p>There are several levels of email validation and I've got source to do them all. However, I despise your line of business and would never share them with you...</p>
<p>Just to clarify - I don't despise you, Jeff... Just your line of business.</p>
| 36,201
|
<p>I remember from C days that we were encouraged to use</p>
<pre><code>i > -1
</code></pre>
<p>instead of</p>
<pre><code>i >= 0
</code></pre>
<p>because of performance.</p>
<p>Does this still apply in the C# .NET world? What are the performance implications of using one over the other with today's compilers? i.e. Is the compiler clever enough to optimize these for you?</p>
<p>(As an aside try and type the question "use >= or >" into the question field on Stack Overflow and see what happens.)</p>
|
<p>No, there are no performance issues associated with comparison operators. And any good compiler would optimize something this trivial anyway.</p>
<p>I'm not sure where you got the suggestion to use "i > -1" rather than "i >= 0". On the x86 architecture, it makes no difference which you use: either case takes exactly two instructions... one to compare and one to jump:</p>
<pre><code> ;; if (i > -1) {
cmp eax, -1
jle else
then:
...
else:
;; if (i >= 0) {
cmp eax, 0
jl else
then:
...
else:
</code></pre>
<p>On most RISC architectures that I know, "i >= 0" may actually be faster since there is usually a dedicated zero register, and "i > -1" may require loading a constant. For example, MIPS only has a < instruction (no <=). Here is how the two constructs would be (naively!) expressed in MIPS assembly language:</p>
<pre><code> // if (i >= 0) { (assuming i is in register %t0)
stl $t1, $0, $t0 // in C: t1 = (0 < t0)
beq $t1, $0, else // jump if t1 == 0, that is if t0 >= 0
nop
then:
...
else:
// if (i > -1) { (assuming i is in register %t0)
addi $t2, $0, -1 // in C: t2 = -1
stl $t1, $t2, $t0 // in C: t1 = (t2 < t0) = (-1 < t0)
bne $t1, $0, else // jump if t1 != 0, that is if t0 > -1
nop
then:
...
else:
</code></pre>
<p>So in the naive, general case, it will actually be one instruction faster to do "i >= 0" on MIPS. Of course, RISC code is so heavily optimizable that a compiler would likely change either of these instruction sequences almost beyond recognition :-)</p>
<p>So... the short answer is no no no, no difference.</p>
|
<p>For greater than zero, it must make two checks. It checks if the negative bit is off and it checks if the zero bit is off.</p>
<p>For greater than or equal to zero, it only has to check if the negative bit is off, because we don't care if the zero bit is on or off.</p>
| 28,613
|
<p>There's a feature that I'd like to see in issue tracking software that just doesn't seem to be all that common, and that is the ability to divide a ticket (bug, feature request, etc) into sub-tasks and view them in a hierarchical fashion, perhaps with some kind of progress bar style report of progress on a particular ticket and its child tickets.</p>
<p>My thinking is that this would be useful for both developers and project managers: project managers like to have a fairly broad overview of what is going on, whereas developers need to drill down to the details, and very often need to divide a task into sub-tasks. This would also come in handy if someone put two issues into one ticket.</p>
<p>Does anyone know of an issue tracker which does this? So far the ones I've looked at (Trac, FogzBugz, and Basecamp) all have a flat organisation of tickets, so they're either useful for the developers or for the project managers but not for both. <a href="http://www.assembla.com/" rel="noreferrer">Assembla</a> does allow a ticket to have child tickets (and multiple parent tickets) but it doesn't do a very good job of usability on this specific feature.</p>
<p>If there is such an issue tracker, has anyone used it for both developers and project managers, and if so, how much success did you have with it? Alternatively, is there a better approach that can be usable by both categories of users?</p>
<p>(<strong>Update:</strong> This is <em>not</em> a subjective "what is your favourite bug tracking software" question. I am asking about bug trackers with a specific feature for a specific purpose, so please don't post your favourite bug tracker if it doesn't do what I've asked for. The only arguably subjective element is how well it works for this particular purpose.)</p>
|
<p><a href="http://www.atlassian.com/software/jira/" rel="noreferrer">JIRA</a></p>
<p><img src="https://i.stack.imgur.com/J8my8.png" alt="subtasks"></p>
|
<p><strong>JIRA integrated with Pivotal Tracker.</strong></p>
<p><em>JIRA</em> allows for tickets. It gives JQL filter ability for search. Gives ability to share tickets between groups. Gives ability for workflow diagrams, history, transitions, comments, etc. Gives ability to view reporters, assignees, implementers. For each ticket there's ability to add Comments, Attachments, Attach Screenshots, Link, Clone, Resolve Issue. JIRA provides a very nice layout of the current ticket state.</p>
<p><em>Pivotal Tracker</em> allows "velocity" management of project for Agile Development. Useful for PMs and developers. Provides graphs, charts. Provides ability to integrate JIRA's tickets into its project. Provides a dashboard with projects. Provides real-time velocity graphs. Provides a number of views within each project including Current, Ice Box, My Work. Each JIRA ticket can be a "Story" in PT. Each story goes through Start, Finish, Deliver, Accept/Reject, and Rejected stages for SDLC. Each story gives ability to Add Task, Comments, Attachments, and Upload Files.</p>
<p><strong>JIRA workflow</strong> <img src="https://i.stack.imgur.com/tQxBy.png" alt="enter image description here"></p>
<p><strong>Pivotal Tracker workflow</strong> </p>
<p><img src="https://i.stack.imgur.com/8V1Kw.jpg" alt="enter image description here"></p>
| 16,968
|
<p>I want to find (not generate) 2 text strings such that, after removing all non letters and ucasing, one string can be translated to the other by simple substitution.</p>
<p>The motivation for this comes from a project I known of that is testing methods for attacking cyphers via probability distributions. I'd like to find a large, coherent plain text that, once encrypted with a simple substitution cypher, can be decrypted to something else that is also coherent.</p>
<p>This ends up as 2 parts, find the longest such strings in a corpus, and get that corpus.</p>
<hr>
<p>The first part seems to me to be amiable to some sort of attack with a B-tree keyed off the string after a substitution that makes the sequence of first occurrences sequential.</p>
<pre><code>HELLOWORLDTHISISIT
1233454637819a9b98
</code></pre>
<p>A little optimization based on knowing the maximum value and length of the string based on each depth of the tree and the rest is just coding.</p>
<hr>
<p>The Other part would be quite a bit more involved; how to generate a large corpus of text to search? some kind of internet spider would seem to be the ideal approach as it would have access to the largest amount of text but how to strip it to just the text?</p>
<p>The question is; Any ideas on how to do this better?</p>
<hr>
<p>Edit: the cipher that was being used is an insanely basic 26 letter substitution cipher.</p>
<p>p.s. this is more a thought experiment then a probable real project for me. </p>
|
<p>There are 26! different substitution ciphers. That works out to a bit over 88 bits of choice:</p>
<pre><code>>>> math.log(factorial(26), 2)
88.381953327016262
</code></pre>
<p>The entropy of English text is something like 2 bits per character at least. So it seems to me you can't reasonably expect to find passages of more than 45-50 characters that are accidentally equivalent under substitution.</p>
<p>For the large corpus, there's the Gutenberg Project and Wikipedia, for a start. You can download an dump of all the English Wikipedia's XML files from their website.</p>
|
<p>I think you're asking a bit much to generate a substitution that is also "coherent". That is an AI problem for the encryption algorithm to figure out what text is coherent. Also, the longer your text is the more complicated it will be to create a "coherent" result... quickly approaching a point where you need a "key" as long as the text you are encrypting. Thus defeating the purpose of encrypting it at all. </p>
| 45,115
|
<p>Folks,</p>
<p>I am pulling all my Flash (pure AS3 project, not Flash CS3) content from a Drupal back-end for SEO purposes. This works great, except the HTML rendering built into the TextField object leaves a lot to be desired. Could anyone recommend any libraries that would allow me to display HTML elements? At this stage, commercial or open-source libraries are welcome.</p>
<p>Thanks,
Marcus</p>
|
<p>you might also want to try:
<a href="http://code.google.com/p/htmlwrapper/" rel="nofollow noreferrer">http://code.google.com/p/htmlwrapper/</a></p>
<p>I haven't used it but it looks like it does what you want.</p>
|
<p>Try using this Flex iFrame, which is modeled after it's HTML iframe counterpart. I haven't used this solution in my Flex applications yet, but it looks promising.</p>
<p><a href="http://deitte.com/archives/2006/08/finally_updated.htm" rel="nofollow noreferrer">http://deitte.com/archives/2006/08/finally_updated.htm</a></p>
<p>However, please note that this same author now recommends <b>against</b> using this.</p>
<p>As always, your mileage may vary,
Randy Stegbauer</p>
| 32,531
|
<p>I typically use URL rewriting to pass content IDs to my website, so this</p>
<pre><code> Foo.1.aspx
</code></pre>
<p>rewrites to</p>
<pre><code> Foo.aspx?id=1
</code></pre>
<p>For a specific application I need to pass in multiple IDs to a single page, so I've rewritten things to accept this:</p>
<pre><code> Foo.1,2,3,4,5.aspx
</code></pre>
<p>This works fine in Cassini (the built-in ad hoc web server for Visual Studio) but gives me "Internet Explorer cannot display the webpage" when I try it on a live server running IIS. Is this an IIS limitation? Should I just use dashes or underscores instead of commas?</p>
|
<p>Commas are allowed in the filename part of a URL, but are reserved characters in the domain*, as far as I know.</p>
<p>What version of IE are you using? I've come across the odd report of IE5.5 truncating URLs on a comma (<a href="http://kb.adobe.com/selfservice/viewContent.do?externalId=326072" rel="noreferrer">link here</a>, but have tested URLs with commas in IE7 and it seems to be OK, so if there was an IE bug, it doesn't seem to be there any more - could it be an IIS issue?</p>
<p>I'm wondering if the page error is due to a rule failure with the <code>mod_rewrite</code> - can you post the rule which is matching multiple ids and passing them off to your <code>Foo.aspx</code>? Is there any chance that it's only matching <code>Foo.N,N</code>, and failing on more commas?</p>
<p><hr>
* From the <a href="http://www.ietf.org/rfc/rfc2396.txt" rel="noreferrer">URI RFC</a>:</p>
<blockquote>
<p>2.2. Reserved Characters</p>
<p>Many URI include components consisting of or delimited by, certain
special characters. These characters are called "reserved", since
their usage within the URI component is limited to their reserved
purpose. If the data for a URI component would conflict with the
reserved purpose, then the conflicting data must be escaped before
forming the URI.</p>
<pre><code> reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
"$" | ","
</code></pre>
<p>The "reserved" syntax class above refers to those characters that are
allowed within a URI, but which may not be allowed within a
particular component of the generic URI syntax</p>
</blockquote>
|
<p>The right way to <em>accept</em> multiple ids is like this:</p>
<pre><code>Foo.aspx?id=1;id=2;id=3;id=4;id=5
</code></pre>
<p>Note that's just what the target is. When re-writing urls, you can set your own rules to a certain extent for what you want the source to look like.</p>
<p>I had to learn this on StackOverflow, too. See this question:<br>
<a href="https://stackoverflow.com/questions/63463/split-out-ints-from-string">Split out ints from string</a></p>
| 24,199
|
<p>Could somebody please point me in the right direction for learning how to do networking in C#/.net 3.5? Code samples and explanations are welcome. Basically I am looking for how to do asynchronous/multithreaded server/client models.</p>
<p>I am fairly comfortable with the basics in how to accomplish this in C++ with WinSock but though all of my research cannot seem to grasp this concept in C#.</p>
<p>Thanks for any assistance you can provide :)</p>
|
<p>If WCF meets your needs, it's worth looking at. <a href="http://www.zeroc.com" rel="noreferrer">ZeroC </a> and other alternative higher level libraries exist. Otherwise there are several different ways to work closer to the socket level if that's what you need.</p>
<h3>TcpClient/UdpClient</h3>
<p>These provide a relatively thin wrapper around the underlying sockets. It essentially provides a Stream over the socket. You can use the async methods on the NetworkStream (BeginRead, etc.). I don't like this one as the wrapper doesn't provide that much and it tends to be a little more awkward than using the socket directly.</p>
<h3>Socket - Select</h3>
<p>This provides the classic Select technique for multiplexing multiple socket IO onto a single thread. Not recommended any longer.</p>
<h3>Socket - APM Style</h3>
<p>The Asynchronous Programming Model (AKA IAsyncResult, Begin/End Style) for sockets is the primary technique for using sockets asynchronously. And there are several variants. Essentially, you call an async method (e.g., BeginReceive) and do one of the following:</p>
<ol>
<li>Poll for completion on the returned IAsyncResult (hardly used).</li>
<li>Use the WaitHandle from the IAsyncResult to wait for the method to complete.</li>
<li>Pass the BeginXXX method a callback method that will be executed when the method completes.</li>
</ol>
<p>The best way is #3 as it is the usually the most convenient. When in doubt, use this method.</p>
<p>Some links:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/magazine/cc300760.aspx" rel="noreferrer">MSDN Magazine Article on Sockets</a></li>
<li><a href="http://msdn.microsoft.com/en-us/magazine/cc163467.aspx" rel="noreferrer">A Jeffery Richter Article on the Asynchronous Programming Model</a></li>
</ul>
<h3>.NET 3.5 High Performance Sockets</h3>
<p>.NET 3.5 introduced a new model for async sockets that uses events. It uses the "simplified" async model (e.g., Socket.SendAsync). Instead of giving a callback, you subscribe to an event for completion and instead of an IAsyncResult, you get SocketAsyncEventArgs. The idea is that you can reuse the SocketAsyncEventArgs and pre-allocate memory for socket IO. In high performance scenarios this can be much more efficient that using the APM style. In addition, if you do pre-allocate the memory, you get a stable memory footprint, reduced garbage collection, memory holes from pinning etc. Note that worrying about this should only be a consideration in the most high performance scenarios.</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/magazine/cc163356.aspx" rel="noreferrer">MSDN Magazine: Get Connected With The .NET Framework 3.5</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.socketasynceventargs.aspx" rel="noreferrer">MSDN Information with technique for pre-allocating memory</a></li>
</ul>
<h3>Summary</h3>
<p>For most cases use the callback method of the APM style unless you prefer the style of the SocketAsyncEventArgs / Async method. If you've used CompletionPorts in WinSock, you should know that both of these methods use CompletionPorts under the hood.</p>
|
<p>It depends on what you want to focus on. </p>
<p>If you want to focus on functionality and leave the plumbing to the framework, then start with Windows Communication Foundation. </p>
<p>If you're looking to build your own plumbing, then use <code>System.Net.Sockets.Socket</code> class. </p>
| 25,875
|
<p>I'm trying to make semantic urls for search pages, but if someone use a search finished in dot, the .net engine return a 404. </p>
<p>The request don't even get to the routing engine, so i think its something related to security or something like that. </p>
<p>For example, the stackoverflow routes also don't work in these case:
<a href="https://stackoverflow.com/questions/tagged/etc."><a href="https://stackoverflow.com/questions/tagged/etc">https://stackoverflow.com/questions/tagged/etc</a>.</a></p>
|
<p>If you are using .NET 4.0 and IIS 7+, you can set this flag in the system.web section of your web.config and it will be allowed:</p>
<pre><code><httpRuntime relaxedUrlToFileSystemMapping="true" />
</code></pre>
<p>I've tested it and it works. <a href="http://haacked.com/archive/2010/04/29/allowing-reserved-filenames-in-URLs.aspx" rel="noreferrer">Haack</a> has an explanation of it. </p>
|
<p>In windows, file names cannot end with a '.'
I think all problems stem from there, ie IIS doesn't know what to do with it, so it never gets as far as the ASP.NET error handler and gets handles by the default IIS 404 page.</p>
<p>Most search engines (<a href="http://www.google.com/support/bin/answer.py?hl=en&answer=430" rel="nofollow noreferrer">well Google anyway</a>) exclude punctuation from queries, and I think yours should too.</p>
<p>EDIT:
It falls over because it has no file type, even the Microsoft site falls over look <a href="http://www.microsoft.com/en/us/fallover." rel="nofollow noreferrer"><a href="http://www.microsoft.com/en/us/fallover" rel="nofollow noreferrer">http://www.microsoft.com/en/us/fallover</a>.</a> but you can modify the default error files (live somewhere like C:\WINDOWS\help\iisHelp\common) or change it completely.</p>
<p>Check this one out: <a href="http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/80cb8d8d-8fd8-4af5-bb3b-4d11fff3ab9c.mspx?mfr=true" rel="nofollow noreferrer">Configuring Custom Error Messages (IIS 6.0)</a></p>
| 37,592
|
<p>Kindly point towards theory/material to read for understanding colors and what makes a good color combinations. Mind it that I am not interested in say "Color combinations for web application" etc. More of the lines of say "Colors and humans".</p>
<p>Material free to read is what i am looking for.</p>
<p>Thanks</p>
|
<p>In addition to the links I'd like to post my way of selecting pleasant colors:</p>
<ol>
<li><p><em>NEVER</em> ever use pure colors. Even if you want a pure color, don't!. If you want a strong bright green for example don't use 00ff00. Use something like 10e013 instead.</p></li>
<li><p>If you have one color that you like, and you want another one that fits to the first open a graphic program. Go to the color picker, type in your color and then switch to HSV mode. Then adjust either one of Hue, Saturation or Lightness. Don't modify two or all parameters, just one. That makes sure the color you choose is perceptually related to the color you've started with.</p></li>
<li><p>If you have no idea what color to start with get a classic masterpiece of painting from the net. Blur it a bit and then pick some nice colors from it. If you use some common sense it's hard not to end with pleasant colors this way.</p></li>
</ol>
<p>Just to give you an example: I've just picked these colors:</p>
<p><img src="https://torus.untergrund.net/misc/colors.png" alt="alt text"></p>
<p>From this painting:</p>
<p><a href="http://www.cs.nthu.edu.tw/~sheu/Images/Monet.jpg" rel="nofollow noreferrer">http://www.cs.nthu.edu.tw/~sheu/Images/Monet.jpg</a></p>
<p>I know - it's not exaclty what you've asked for, but I learned these tricks the hard way.</p>
|
<p>Some theory here:</p>
<p><a href="http://www.worqx.com/color/index.htm" rel="nofollow noreferrer">http://www.worqx.com/color/index.htm</a></p>
| 49,019
|
<p>I have a project to build a voting desktop application for a class in Java. While security isn't the focus of the project, I would like to be as realistic as I can. What are some of the primary tools to integrate security into a Java application.</p>
<p>Edit: I'm not primarily worried about physical security, we are simply building an application not a whole system. I want to ensure votes are recorded correctly and not able to be changed or read by someone else.</p>
|
<p>It really depends on what kind of security you are looking to integrate. Do you want security to ensure that the user isn't running any debuggers or such to flip bits in your application to change the votes? Do you want to ensure that the user doesn't install logging software to keep track of who voted for who? Do you want to ensure that the person who is supposed to be voting is actually voting? Security is a very broad subject, and it's hard to give an answer without knowing what exactly you are looking for.</p>
|
<p>I believe that physical security is more important for voting booth system rather than you know, code security.<br>
These machine by their very nature shouldn't be connected to any kind of public networks, especially not the the internet. But having a good physical security to prevent any sort of physical tampering is very important.</p>
| 4,900
|
<p>Having programmed through emacs and vi for years and years at this point, I have heard that using an IDE is a very good way of becoming more efficient.</p>
<p>To that end, I have decided to try using Eclipse for a lot of coding and seeing how I get on.</p>
<p>Are there any suggestions for easing the transition over to an IDE. Obviously, some will think none of this is worth the bother, but I think with Eclipse allowing emacs-style key bindings and having code completion and in-built debugging, I reckon it is well worth trying to move over to a more feature-rich environment for the bulk of my development worth.</p>
<p>So what suggestions do you have for easing the transition?</p>
|
<p>Eclipse is the best IDE I've used, even considering its quite large footprint and sluggishness on slow computers (like my work machine... Pentium III!).</p>
<p>Rather than trying to 'ease the transition', I think it's better to jump right in and let yourself be overwhelmed by the bells and whistles and truly useful refactorings etc.</p>
<p>Here are some of the most useful things I would consciously use as soon as possible:</p>
<ul>
<li>ctrl-shift-t finds and opens a class via incremental search on the name</li>
<li>ctrl-shift-o automatically generates import statements (and deletes redundant ones)</li>
<li>F3 on an identifier to jump to its definition, and alt-left/right like in web browsers to go back/forward in navigation history</li>
<li><p>The "Quick fix" tool, which has a large amount of context-sensitive refactorings and such. Some examples:</p>
<pre><code>String messageXml = in.read();
Message response = messageParser.parse(messageXml);
return response;</code></pre></li>
</ul>
<p>If you put the text cursor on the argument to parse(...) and press ctrl+1, Eclipse will suggest "Inline local variable". If you do that, then repeat with the cursor over the return variable 'response', the end result will be:</p>
<pre><code>return messageParser.parse(in.read());
</code></pre>
<p>There are many, many little rules like this which the quick fix tool will suggest and apply to help refactor your code (including the exact opposite, "extract to local variable/field/constant", which can be invaluable).
You can write code that calls a method you haven't written yet - going to the line which now displays an error and using quick fix will offer to create a method matching the parameters inferred from your usage. Similarly so for variables.
All these small refactorings and shortcuts save a lot of time and are much more quickly picked up than you'd expect. Whenever you're about to rearrange code, experiment with quick fix to see if it suggests something useful.</p>
<p>There's also a nice bag of tricks directly available in the menus, like generating getters/setters, extracting interfaces and the like. Jump in and try everything out!</p>
|
<p>Read the doc...
And see what shortcuts/keybindings equivalents are with your familiar ones. Learn the new ones... </p>
| 12,344
|
<p>I would like to check which type of RAM my computer uses before I order an upgrade. I'm fairly sure its DDR2 but I would like to double check this.</p>
<p>Is there any way to check this in Windows XP without opening the case up and looking? </p>
<p><em>EDIT</em>
The content police seem to have gotten the wrong end of the stick, I was looking for a piece of software or a command that would allow me to check this. I feel that this makes this question perfectly valid for StackOverflow and of interest to other programmers. </p>
|
<p><a href="http://www.cpuid.com/cpuz.php" rel="noreferrer">CPU-Z</a> can tell you. On the SPD tab you can view the DIMM specific information</p>
|
<p>Find out the motherboard/chipset from the device manager, google it, know what it takes.</p>
<p>As Greg Hewgill says, you'd need to script that some how (to make this a valid question on SO) - but you'd have to do that part yourself =)</p>
| 17,864
|
<p>A colleague is looking to generate UML class diagrams from heaps of Python source code.
He's primarily interested in the inheritance relationships, and mildly interested in compositional relationships, and doesn't care much about class attributes that are just Python primitives.</p>
<p>The source code is pretty straightforward and not tremendously evil--it doesn't do any fancy metaclass magic, for example. (It's mostly from the days of Python 1.5.2, with some sprinklings of "modern" 2.3ish stuff.) </p>
<p>What's the best existing solution to recommend?</p>
|
<p>You may have heard of <a href="http://www.pylint.org/" rel="noreferrer">Pylint</a> that helps statically checking Python code. Few people know that it comes with a tool named <a href="http://www.logilab.org/blogentry/6883" rel="noreferrer">Pyreverse</a> that draws UML diagrams from the Python code it reads. Pyreverse uses Graphviz as a backend.</p>
<p>It is used like this:</p>
<pre class="lang-none prettyprint-override"><code>pyreverse -o png -p yourpackage .
</code></pre>
<p>where the <code>.</code> can also be a single file.</p>
|
<p>If you use Eclipse, maybe <a href="http://sourceforge.net/projects/eclipse-pyuml" rel="nofollow noreferrer">PyUML</a>. Haven't used it, though.</p>
| 32,512
|
<p>First, I know there are methods off of the generic <code>List<></code> class already in the framework do iterate over the <code>List<></code>.</p>
<p>But as an example, what is the correct syntax to write a ForEach method to iterate over each object of a <code>List<></code>, and do a <code>Console.WriteLine(object.ToString())</code> on each object.
Something that takes the <code>List<></code> as the first argument and the lambda expression as the second argument.</p>
<p>Most of the examples I have seen are done as extension methods or involve LINQ. I'm looking for a plain-old method example.</p>
|
<pre><code>public void Each<T>(IEnumerable<T> items, Action<T> action)
{
foreach (var item in items)
action(item);
}
</code></pre>
<p>... and call it thusly:</p>
<pre><code>Each(myList, i => Console.WriteLine(i));
</code></pre>
|
<p>You can traverse each string in the list and even you can search in the whole generic using a single statement this makes searching easier.</p>
<pre><code>public static void main(string[] args)
{
List names = new List();
names.Add(“Saurabh”);
names.Add("Garima");
names.Add(“Vivek”);
names.Add(“Sandeep”);
string stringResult = names.Find( name => name.Equals(“Garima”));
}
</code></pre>
| 44,046
|
<p>As the question says, how do I add a new option to a DropDownList using jQuery?</p>
<p>Thanks</p>
|
<p>Without using any extra plugins,</p>
<pre><code>var myOptions = {
val1 : 'text1',
val2 : 'text2'
};
var mySelect = $('#mySelect');
$.each(myOptions, function(val, text) {
mySelect.append(
$('<option></option>').val(val).html(text)
);
});
</code></pre>
<p>If you had lots of options, or this code needed to be run very frequently, then you should look into using a <a href="https://developer.mozilla.org/en/DOM/document.createDocumentFragment" rel="noreferrer">DocumentFragment</a> instead of modifying the DOM many times unnecessarily. For only a handful of options, I'd say it's not worth it though.</p>
<p>------------------------------- Added --------------------------------</p>
<p><code>DocumentFragment</code> is good option for speed enhancement, but we cannot create option element using <code>document.createElement('option')</code> since IE6 and IE7 are not supporting it.</p>
<p>What we can do is, create a new select element and then append all options. Once loop is finished, append it to actual DOM object.</p>
<pre><code>var myOptions = {
val1 : 'text1',
val2 : 'text2'
};
var _select = $('<select>');
$.each(myOptions, function(val, text) {
_select.append(
$('<option></option>').val(val).html(text)
);
});
$('#mySelect').append(_select.html());
</code></pre>
<p>This way we'll modify DOM for only one time!</p>
|
<p>try this Function: </p>
<pre><code>function addtoselect(param,value){
$('#mySelectBox').append('&lt;option value='+value+'&gt;'+param+'&lt;/option&gt;');
}
</code></pre>
| 40,955
|
<p>I have this situation.
I have a real stored in a varbinary field in a sql 2005 database.
As I can't convert a varbinary to a real in sql 2005, I'm trying to do that in vb.net.</p>
<p>That field gets stored as a byte() array in a DataTable.</p>
<p>Now I would like to read that byte() into a double, or decimal variable.
But I don't have much of a clue on how to do that...</p>
|
<p>It really depends on how it's stored, but <a href="http://msdn.microsoft.com/en-us/library/system.bitconverter.todouble.aspx" rel="nofollow noreferrer">BitConverter.ToDouble</a> may be your friend. That's assuming it's in IEE754 format. Where are you getting the data from in the first place?</p>
|
<pre><code>Public Function GetDateFromBytes(ByRef value() As Byte, _
ByRef startindex As Int32) As Date
'create a aray of Ints
Dim IntValues() As Int32 = {BitConverter.ToInt32(value, startindex), _
BitConverter.ToInt32(value, (startindex + 7)), _
BitConverter.ToInt32(value, startindex + 15), _
BitConverter.ToInt32(value, startindex + 31)}
Return Date.FromBinary(New Decimal(IntValues))
End Function
</code></pre>
| 28,576
|
<p>What's the best way to return a random line in a text file using C? It has to use the standard I/O library (<code><stdio.h></code>) because it's for Nintendo DS homebrew.</p>
<p><strong>Clarifications:</strong></p>
<ul>
<li>Using a header in the file to store the number of lines won't work for what I want to do.</li>
<li>I want it to be as random as possible (the best being if each line has an equal probability of being chosen as every other line.)</li>
<li>The file will never change while the program is being run. (It's the DS, so no multi-tasking.)</li>
</ul>
|
<p>Read each line, and use a random number to choose whether to keep that line or ignore it. For the first line, you want odds of 1:1 to keep; for the second, you want odds of 1:2, etc.</p>
<pre><code>count = 0;
while (fgets(line, length, stream) != NULL)
{
count++;
if ((rand() * count) / RAND_MAX == 0)
strcpy(keptline, line);
}
</code></pre>
<p>I haven't verified that this has the proper random qualities, but it seems right at first glance.
<hr>
It has been pointed out that integer overflow would quickly become a problem with the way the comparison is coded, and I had independently reached the same conclusion myself. There are probably many ways to fix it, but this is the first that comes to mind:</p>
<pre><code>if ((rand() / (float)RAND_MAX) <= (1.0 / count))
</code></pre>
|
<p>Use a combination of Adam's random offset into the file approach and Mark's probability approach. Adam's method can get you randomly to a section of the file. Then you use Mark's approach to avoid preferring the larger strings. Mark's algorithm will prefer the first few strings from wherever it starts,</p>
| 28,744
|
<p>We are working on an <a href="http://en.wikipedia.org/wiki/S60_%28software_platform%29" rel="noreferrer">S60</a> version and this platform has a nice Python API..</p>
<p>However, there is nothing official about Python on Android, but since <a href="http://en.wikipedia.org/wiki/Jython" rel="noreferrer">Jython</a> exists, is there a way to let the snake and the robot work together??</p>
|
<p>One way is to use <a href="http://kivy.org/" rel="noreferrer">Kivy</a>:</p>
<blockquote>
<p>Open source Python library for rapid development of applications
that make use of innovative user interfaces, such as multi-touch apps.</p>
</blockquote>
<p></p>
<blockquote>
<p>Kivy runs on Linux, Windows, OS X, Android and iOS. You can run the same [python] code on all supported platforms.</p>
</blockquote>
<p><a href="https://play.google.com/store/apps/details?id=org.kivy.showcase" rel="noreferrer">Kivy Showcase app</a> </p>
|
<p>One more option seems to be <a href="http://pyqt.sourceforge.net/Docs/pyqtdeploy/index.html" rel="noreferrer">pyqtdeploy</a> which citing the docs is:</p>
<blockquote>
<p>a tool that, in conjunction with other tools provided with Qt, enables
the deployment of PyQt4 and PyQt5 applications written with Python
v2.7 or Python v3.3 or later. It supports deployment to desktop
platforms (Linux, Windows and OS X) and to mobile platforms (iOS and
Android).</p>
</blockquote>
<p>According to <a href="https://stackoverflow.com/questions/24239684/deploying-pyqt5-application-to-android-via-pyqtdeploy-and-qt5">Deploying PyQt5 application to Android via pyqtdeploy and Qt5</a> it is actively developed, although it is difficult to find examples of working Android apps or tutorial on how to cross-compile all the required libraries to Android. It is an interesting project to keep in mind though!</p>
| 12,723
|
<p>Is it possible to have transport security without authentication? I'm well aware of it's flaws but atm I can't install a certificate a the client side.
It seems I can set WSHttpBinding.SecurityMode to Transport and the ClientCredentialType to HttpClientCredentialType.None, but when I try to call the service I get this exception:</p>
<p>An error occurred while making the HTTP request to <a href="https://[MyService]" rel="nofollow noreferrer">https://[MyService]</a>. This could be due to the fact that the server certificate is not configured properly with HTTP.SYS in the HTTPS case. This could also be caused by a mismatch of the security binding between the client and the server.</p>
<p>I don't think it's a mismatch of the security binding between the client and the server because I'm using a proxy generated by svcutil.</p>
<p>Why's it looking for a server certificate if I've set the ClientCredentialType to None?</p>
|
<p>You can have HTTPS communication without authentication, but you cannot have HTTPS communication without certificates, since HTTPS encryption uses certificates.</p>
<p>There are a few things to check:</p>
<ol>
<li>Can you access the WSDL or another resource on the site over HTTPS in a browser?</li>
<li>Do you get any warnings about the certificate when doing so? </li>
</ol>
<p>If you can't access the WSDL or another resource on the site over HTTPS, then HTTPS isn't configured on the server.</p>
<p>If you get warnings about the certificate, then you don't have a certificate that the client will trust. There are three options here; one is to get a valid certificate from somewhere like <a href="http://en.wikipedia.org/wiki/Verisign" rel="nofollow noreferrer">Verisign</a> that will be trusted, the other is to install the certificate in a trusted part of the user's store (which you can't do as you mentioned), and the final is to turn off the cerificate revocation in the client's WCF configuration.</p>
|
<p>I had the error you describe even though the security mode was set to transport and client credential type was set to none.</p>
<p>This was due to the fact that my web service URLs had been created by the Visual Studio 2010 service reference creator as <em><a href="http://www.myservice.com:80/myservice.asmx" rel="nofollow">http://www.myservice.com:80/myservice.asmx</a></em> with a specific port 80. When I changed this to <em><a href="http://www.myservice.com/myservice.asmx" rel="nofollow">http://www.myservice.com/myservice.asmx</a></em> the binding worked correctly.</p>
| 23,005
|
<p>I've been trying to come up with a way to create a 3 column web design where the center column has a constant width and is always centered. The columns to the left and right are variable. This is trivial in tables, but not correct semantically. </p>
<p>I haven't been able to get this working properly in all current browsers. Any tips on this?</p>
|
<p>Use <a href="http://matthewjamestaylor.com/blog/perfect-3-column.htm" rel="nofollow noreferrer">this technique</a>, and simply specify a fixed width for the centre column.</p>
|
<p>I think you'd need to start off with initial (fixed) widths for both sidebar columns and then, when the page loads, use javascript to get the window width and calculate the new width of the sidebars.</p>
<p>sidebar width = (window width - center column width) / 2</p>
<p>You could then reapply the javascript if the window is resized.</p>
| 9,875
|
<p>I have a series of datetime objects and would like to calculate the average delta between them.</p>
<p>For example, if the input was <code>(2008-10-01 12:15:00, 2008-10-01 12:25:00, 2008-10-01 12:35:00)</code>, then the average delta would be exactly 00:10:00, or 10 minutes.</p>
<p>Any suggestions on how to calculate this using Python?</p>
|
<p>As far as algorithms go, that's an easy one. Just find the max and min datetimes, take the difference, and divide by the number of datetimes you looked at.</p>
<p>If you have an array a of datetimes, you can do:</p>
<pre><code>mx = max(a)
mn = min(a)
avg = (mx-mn)/(len(a)-1)
</code></pre>
<p>to get back the average difference.</p>
<p>EDIT: fixed the off-by-one error</p>
|
<p>small clarification</p>
<pre><code>from datetime import timedelta
def avg(a):
numdeltas = len(a) - 1
sumdeltas = timedelta(seconds=0)
i = 1
while i < len(a):
delta = abs(a[i] - a[i-1])
try:
sumdeltas += delta
except:
raise
i += 1
avg = sumdeltas / numdeltas
return avg
</code></pre>
| 21,680
|
<p>Is there any Excel report framework available? We need to export some of the reports into Excel format. Our application is java application hence anything supporting java would be great. I have tried Apache POI API, however that is not good enough. Any framework based on Windows API would be better.</p>
|
<p><a href="http://www.microsoft.com/sql/technologies/reporting/default.mspx" rel="nofollow noreferrer">SQL Server Reporting Services</a> has options to export to Excel.</p>
|
<p>Try <a href="http://xlsgen.arstdesign.com/" rel="nofollow noreferrer">xlsgen</a>, supports Java (but can only run under Windows).</p>
| 11,651
|
<p>Does anyone know any resources (books/websites/whatever) related to parsing. I'm not so much interested in specific technologies such as yacc, XML or regular expressions, but something more general about best practices, stream vs. pull, error reporting and recovery, gotchas to look out for etc.</p>
|
<p>There a nice book on parsing techniques <a href="http://www.cs.vu.nl/~dick/PTAPG.html" rel="nofollow noreferrer">Parsing Techniques, a Practical Guige</a>. You should be able to find some interesting bits. There is complete chapter on error handling.</p>
|
<p>This may not be exactly what you meant, but a very good, and slightly relevant, book;
<a href="http://www.pragprog.com/titles/gwd/data-crunching" rel="nofollow noreferrer">Data Crunching: Solve Everyday Problems using Java, Python, and More</a></p>
| 48,163
|
<p>I have a very specific html table construct that seems to reveal a Gecko bug.</p>
<p>Here's a distilled version of the problem. Observe the following table in a gecko-based browser (FF, for example): (you'll have to copy and paste this into a new file)</p>
<pre><code><style>
table.example{
border-collapse:collapse;
}
table.example td {
border:1px solid red;
}
</style>
<table class="example">
<thead>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td rowspan="3">3</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td rowspan="2">2</td>
</tr>
<tr>
<td>1</td>
<td>3</td>
</tr>
</tbody>
</table>
</code></pre>
<p>There's a line missing over the "3" in the bottom-right cell -- view it in any other browser and the line will appear as expected. Interestingly, ditch the thead section of the table and look what we get:</p>
<pre><code><style>
table.example{
border-collapse:collapse;
}
table.example td {
border:1px solid red;
}
</style>
<table class="example">
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td rowspan="3">3</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td rowspan="2">2</td>
</tr>
<tr>
<td>1</td>
<td>3</td>
</tr>
</tbody>
</table>
</code></pre>
<p>Doing that makes it work. Has anyone seen this? I suppose I'll just get rid of my thead section for now as a workaround though it makes the table rather less accessible.</p>
|
<p>Strange... definitely a painting bug. If you right-click to get the context menu to appear over <em>part</em> of where the line should be, then when you dismiss the context menu, the line has been redrawn underneath.</p>
<p>Edit: Workaround - if you put <code>style="border-color: ...;"</code> on the <code><td rowspan="3"></code> you can get the border to appear, but it has to be a <em>different</em> colour - just use one that's as close to the others as possible. For example, if the table is #ff0000 use #ff0001</p>
|
<p>i have also found this bug but it's not on my PC but another. If i resize the browser window after a certain resolution the lines will disappear. once i maximise the window the all pop back.
you can fix this permanently by setting border-collapse:separate; this gives each boreder of each cell its own width. It's not what i want to do but it works.</p>
<p>It can also be caused by using border-collapse:collapse; then setting aligning borders to 1px and then 0px. Because it collapses the borders it seems to prioritise the 0px over the 1px width.</p>
<p>either way it's firefox only and it's yet another reason to move away from it.</p>
| 33,462
|
<p>I wrote a Java program to add and retrieve data from an MS Access. At present it goes sequentially through ~200K insert queries in ~3 minutes, which I think is slow. I plan to rewrite it using threads with 3-4 threads handling different parts of the hundred thousands records. I have a compound question:</p>
<ul>
<li><p>Will this help speed up the program because of the divided workload or would it be the same because the threads still have to access the database sequentially? </p></li>
<li><p>What strategy do you think would speed up this process (except for query optimization which I already did in addition to using Java's preparedStatement)</p></li>
</ul>
|
<p>First, don't use Access. Move your data anywhere else -- SQL/Server -- MySQL -- anything. The DB engine inside access (called Jet) is pitifully slow. It's not a real database; it's for personal projects that involve small amounts of data. It doesn't scale at all.</p>
<p>Second, threads rarely help.</p>
<p>The JDBC-to-Database connection is a process-wide resource. All threads share the one connection. </p>
<p>"But wait," you say, "I'll create a unique Connection object in each thread."</p>
<p>Noble, but <em>sometimes</em> doomed to failure. Why? Operating System processing between your JVM and the database may involve a socket that's a single, process-wide resource, shared by all your threads.</p>
<p>If you have a single OS-level I/O resource that's shared across all threads, you won't see much improvement. In this case, the ODBC connection is one bottleneck. And MS-Access is the other.</p>
|
<p>On modern multi-core machines, using multiple threads to populate a database can make a difference. It depends on the database and its hardware. Try it and see.</p>
| 14,494
|
<p>I am using VirtualPc 2007 more and more, the one annoyance is "Alt-Tab".</p>
<p>What I want is to be able to use alt-tab to iterate through all of the applications in the host pc and virtual(s) as if they were one long list. Is there a setting or program to do this?</p>
|
<p>No. If the VPC is in full screen mode, alt+tab works only within the context of the VPC. If the VPC Screen is not focused, you will get the collection of applications that are in the Host (including the instance of VPC)</p>
|
<p>Sadly, no. This is possible in Parallels on the Mac, in what they call "Coherence" mode. But Virtual PC does not support that kind of integration.</p>
| 10,805
|
<p>How do you track outbound links for your web site, since the request is logged on the destination server, not yours? </p>
|
<p>You can add a quick JQuery script to the page that will track external links and can either redirect them to a file on your server that will track the link and then forward to it, or add an ajax request that will submit on click for external links, and track them that way.</p>
<p>See:</p>
<ul>
<li><a href="http://www.prodevtips.com/2008/08/19/tracking-clicks-with-jquery-and-google-analytics/" rel="nofollow noreferrer">http://www.prodevtips.com/2008/08/19/tracking-clicks-with-jquery-and-google-analytics/</a></li>
<li><a href="https://web.archive.org/web/20090214024330/http://www.justskins.com/development/how-to-track-clicks-on-outgoing-links/132" rel="nofollow noreferrer">https://web.archive.org/web/20090214024330/http://www.justskins.com/development/how-to-track-clicks-on-outgoing-links/132</a></li>
</ul>
|
<p>Some newer options that work without any hacks as explained in <a href="https://css-tricks.com/send-an-http-request-on-page-exit/" rel="nofollow noreferrer">https://css-tricks.com/send-an-http-request-on-page-exit/</a> are <code>Fetch</code> with the <code>keepalive</code>-flag or <code>navigator.sendBeacon</code>.</p>
<p><code>keepalive</code> is not yet (Aug. 2022) supported by Firefox (<a href="https://caniuse.com/mdn-api_request_keepalive" rel="nofollow noreferrer">Can I Use</a>), but <code>navigator.sendBeacon</code> works in all modern browsers (<a href="https://caniuse.com/beacon" rel="nofollow noreferrer">Can I Use</a>).</p>
<pre><code>// normal fetch, not guaranteed to work
someLink.addEventListener('click', function(event){
fetch('http://www.testing.local/?origin=classic-fetch');
});
// fetch + keep alive (not working in Firefox as of 103, Aug. 2022)
someLink.addEventListener('click', function(event){
fetch('http://www.testing.local/?origin=fetch-keep-alive', {
keepalive: true
});
});
// navigator.sendBeacon (all modern browsers)
someLink.addEventListener('click', function(event){
navigator.sendBeacon('http://www.testing.local/?origin=beacon');
});
</code></pre>
| 24,355
|
<p>Generate the Fibonacci sequence in the fewest amount of characters possible. Any language is OK, except for one that you define with one operator, <code>f</code>, which prints the Fibonacci numbers.</p>
<p>Starting point: <strong><s>25</s> 14 characters</strong> in <strong>Haskell</strong>:</p>
<p><s> <code>f=0:1:zipWith(+)f(tail f)</code> </s></p>
<pre><code>f=0:scanl(+)1f
</code></pre>
|
<h1>RePeNt, <strike>9</strike>, 8 chars</h1>
<pre><code>1↓[2?+1]
</code></pre>
<p>Or 10 chars with printing:</p>
<pre><code>1↓[2?+↓£1]
</code></pre>
<p>Run using:</p>
<pre><code>RePeNt "1↓[2?+1]"
</code></pre>
<p>RePeNt is a stack based toy language I wrote (and am still improving) in which all operators/functions/blocks/loops use Reverse Polish Notation (RPN).</p>
<pre><code>Command Explanation Stack
------- ----------- -----
1 Push a 1 onto the stack 1
↓ Push last stack value 1 1
[ Start a do-while loop 1 1
2? Push a two, then pop the 2 and copy the last 2 stack 1 1 1 1
items onto the stack
+ Add on the stack 1 1 2
↓£ Push last stack value then print it 1 1 2
1 Push a 1 onto the stack 1 1 2 1
] Pop value (1 in this case), if it is a 0 exit the loop 1 1 2
otherwise go back to the loop start.
</code></pre>
<p>The answer is on the stack which builds itself up like:</p>
<pre><code>1 1
1 1 2
1 1 2 3
1 1 2 3 5
</code></pre>
<p>It never terminates (it has the eqivilent of a C#/JAVA <code>do { } while(true)</code> loop) because the sequence will never terminate, but a terminating solution can be written thus:</p>
<pre><code>N_1↓nI{2?+}
</code></pre>
<p>which is 12 chars.</p>
<p>I wonder if anyone will ever read this :(</p>
|
<p><strong>Euphoria: 44 characters</strong></p>
<pre><code>object f=1&1 loop do f&=f[$]+f[$-1]until 0
</code></pre>
<p>Keeps on generating until RAM or doubles run out.</p>
| 28,816
|
<p>If I have a vector of pairs:</p>
<pre><code>std::vector<std::pair<int, int> > vec;
</code></pre>
<p>Is there and easy way to sort the list in <strong>increasing</strong> order based on the second element of the pair?</p>
<p>I know I can write a little function object that will do the work, but is there a way to use existing parts of the <em>STL</em> and <code>std::less</code> to do the work directly?</p>
<p>EDIT: I understand that I can write a separate function or class to pass to the third argument to sort. The question is whether or not I can build it out of standard stuff. I'd really something that looks like:</p>
<pre><code>std::sort(vec.begin(), vec.end(), std::something_magic<int, int, std::less>());
</code></pre>
|
<p><strong>EDIT</strong>: using c++14, the best solution is very easy to write thanks to lambdas that can now have parameters of type <code>auto</code>. <strong>This is my current favorite solution</strong></p>
<pre><code>std::sort(v.begin(), v.end(), [](auto &left, auto &right) {
return left.second < right.second;
});
</code></pre>
<hr />
<p><strong>ORIGINAL ANSWER</strong>:</p>
<p>Just use a custom comparator (it's an optional 3rd argument to <code>std::sort</code>)</p>
<pre><code>struct sort_pred {
bool operator()(const std::pair<int,int> &left, const std::pair<int,int> &right) {
return left.second < right.second;
}
};
std::sort(v.begin(), v.end(), sort_pred());
</code></pre>
<p>If you're using a C++11 compiler, you can write the same using lambdas:</p>
<pre><code>std::sort(v.begin(), v.end(), [](const std::pair<int,int> &left, const std::pair<int,int> &right) {
return left.second < right.second;
});
</code></pre>
<p><strong>EDIT</strong>: in response to your edits to your question, here's some thoughts ...
if you <strong>really</strong> wanna be creative and be able to reuse this concept a lot, just make a template:</p>
<pre><code>template <class T1, class T2, class Pred = std::less<T2> >
struct sort_pair_second {
bool operator()(const std::pair<T1,T2>&left, const std::pair<T1,T2>&right) {
Pred p;
return p(left.second, right.second);
}
};
</code></pre>
<p>then you can do this too:</p>
<pre><code>std::sort(v.begin(), v.end(), sort_pair_second<int, int>());
</code></pre>
<p>or even</p>
<pre><code>std::sort(v.begin(), v.end(), sort_pair_second<int, int, std::greater<int> >());
</code></pre>
<p>Though to be honest, this is all a bit overkill, just write the 3 line function and be done with it :-P</p>
|
<p>Try swapping the elements of the pairs so you can use <code>std::sort()</code> as normal.</p>
| 35,375
|
<p>I'm designing a user interface for a large touchscreen device running Linux. What would be the best toolkit/developer kit/SDK to use? The only requirement is that its able to run on a semi-low performace device, and that there is a Linux version.</p>
<p>Nice-to-haves would be build in support for effects/animations and a modern look-and-feel, but they are not necessary.</p>
<p>I'm looking at Adobe Flex/AIR already, but I'm not sure if the device will meet the minimum specs.</p>
|
<p>Try QTopia (<a href="http://trolltech.com/products/qtopia" rel="nofollow noreferrer">http://trolltech.com/products/qtopia</a>)
It's from the same stable as the popular Qt desktop toolkit.</p>
|
<p>QTopia is indeed a good option; others are <a href="http://www.directfb.org/" rel="nofollow noreferrer">DirectFB</a>, and of course X11 generally running <a href="http://matchbox-project.org/" rel="nofollow noreferrer">Matchbox</a>.</p>
| 10,346
|
<p>I've got a Monoprice Mini Select (15365) and it takes FOREVER for me to manually spin the dial to get the printhead to raise all the way up so that I can perform maintenance (clear blockages in the nozzle or apply new tape to the bed, etc).</p>
<p>So, I was thinking about writing a snippet of gcode that I could just run which would contain the commands necessary to do that for me. I'm a n00b to 3D printing, but I'm an old programmer so I figured it would be too hard. However, before running this code on my printer, I wanted to get some experts to double check me to make sure I'm not going to hurt anything. :)</p>
<p>Here is what I have, please let me know if I've done anything wrong or if you have any suggestions.</p>
<pre><code>; Move print head to center and top to prepare for cleaning/maintenance
M107 ; fan off
G28 ; home all axes
G21 ; set units to millimeters
G90 ; use absolute coordinates
; full dimensions of the print area are 120mm x 120mm x 120mm
G0 X60 Y60 Z119 ; move to center X,Y and just below the max height
M84 ; disable motors
</code></pre>
<p>I grabbed a few lines from gcode generated by Slic3r and used the gcode wiki entry to understand each of the commands and fill in the extra ones I needed.</p>
|
<p>Yes, on machines which will execute "standard" gcode, this will do what you request. Some good resources are <a href="http://reprap.org/wiki/G-code">http://reprap.org/wiki/G-code</a> and <a href="https://en.wikipedia.org/wiki/G-code">https://en.wikipedia.org/wiki/G-code</a></p>
|
<p>It really depends on whether you currently have something half printed on the bed when you need to do maintenance.
For example, you may have a blockage mid-print or need to reprime the nozzle. </p>
<p>So with that in mind, personally I would separate the line that does the move into two different lines. </p>
<p>Move vertically first, then in X Y. Otherwise, the print head may move diagonally and hit your object. This is because the head will move all three axes at once.</p>
<p>Otherwise looks good.</p>
<p>Edit: Another suggestion is that if you use repetier host to control the printer it will be easier to return to the print in-progress automatically.</p>
<p>Also take a look at the S parameter, for moves it can control how fast the move is.</p>
| 494
|
<p>My table has the following schema:</p>
<p>id, parent_id, text</p>
<p>Given the following data I would like to return an xml hierarchy:</p>
<p>Data: (1,null,'x'), (2,1,'y'), (3,1,'z'), (4,2,'a')</p>
<p>XML:<br>
[row text="x"]<br>
[row text="y"]<br>
[row text="a"/]<br>
[/row]<br>
[row text="z"/]<br>
[/row] </p>
<hr>
<p>Added: the hierachy has no maximum depth</p>
|
<p>If you have a finite depth the there's a quickie that looks like this:</p>
<pre><code>SELECT T.*, T2.*, T3.* /*, ...*/ FROM myTable T
INNER JOIN myTable T2 ON T2.parent_id=T.id
INNER JOIN myTable T3 ON T3.parent_id=T2.id
/* ... */
WHERE T.parent_id IS NULL
FOR XML AUTO
</code></pre>
<p>I'm not sure but it might be possible to devise a similar result using <a href="http://msdn.microsoft.com/en-us/library/ms186243.aspx" rel="nofollow noreferrer">recursive queries</a>. Of course, it's much easier (and probably makes more sense) in the application level.</p>
|
<p>This requires a "transitive closure". You need to process the data recursively to find all children under a given parent.</p>
<p>Roughly the algorithm looks like this.</p>
<pre><code>for top in cursor( nodes where each parent==null ):
build_tree( top )
def build_tree( parent ):
emit opening tag
for child in cursor( nodes where parent == parent ):
build_tree( child )
emit closing tag
</code></pre>
<p>Note that some SQL interpreters may have trouble with the recursion -- they may not open a fresh, new cursor as necessary. Each cursor, however, must be distinct, since you will have as many open cursors as your tree has levels.</p>
| 33,252
|
<h2>Intro:</h2>
<p>I successfully implemented a WCF Service hosted in a Windows Service a few days ago. The community here at StackOverflow helped me with <a href="https://stackoverflow.com/questions/167852/wsdl-url-for-a-wcf-service-basichttpbinding-hosted-inside-a-windows-service">the WSDL exposure here</a>. I thank you once again. However recently I found out that there is another potential client for this service this time located on the same machine as the service and this lead me to think I should add another endpoint with the namedPipesBinding.</p>
<p>Named pipes seem to be the best solution for intra-machine communication as far as I am concerned. <strong>Please</strong> correct me if this is wrong.</p>
<h2>Problem:</h2>
<p>I need to expose another endpoint for the same service/contract but this time using a netNamedPipeBinding. However I really don't understand how do I can then add a service reference from a client. Foolishly after adding </p>
<pre><code><endpoint address="net.pipe://localhost/OfficeService"
binding="netNamedPipeBinding"
contract="netBridge.Development.OfficeService.IWordService"
bindingConfiguration="localBinding" />
</code></pre>
<p>I have tried to add a service reference in a Windows Forms Application located on the same machine typing the net.pipe://.... url. It didn't work. I must mention I have removed the mex (MetaData Exchange) endpoint earlier because I considered it not necessary.</p>
<ol>
<li>Is this mex endpoint necessary for named pipes endpoint binding discovery?</li>
<li>How should I add a service reference in the client app to the named pipe endpoint?</li>
</ol>
|
<p>Your endpoint looks fine, although I'm curious about what's in localBinding...</p>
<p>Sounds like the easiest option is to just change the endpoint configuration on the named pipes client to match your service endpoint. The client shouldn't care as long as it's the only endpoint in the clients config file. Otherwise you'll have to add names to your endpoints and have the client pick a specific one when you new-up the proxy object.</p>
<p>Good luck!</p>
|
<p>the mex endpoint is necessary during development as it provides an http location where the wsdl is built. the wsdl describes to the client how to communicate with the server through named pipes, or TCP/IP, or anything else. once the client app has built the proxy to the named pipes binding and set up the configuration, the mex endpoint is no longer necessary. hence, the mex endpoint can be removed prior to deployment through the environments if desired. </p>
| 22,363
|
<p>I have been having an issue with certain portions of the walls of certain prints becoming separated from the rest of the model. It happens with smooth vertical edges. </p>
<p>Specifically, this model, <a href="https://www.thingiverse.com/thing:2517008" rel="nofollow noreferrer"> ID Badge Holder</a>, on the edges where the lanyard would be attached. And on several places on this model, <a href="https://www.thingiverse.com/thing:2253220" rel="nofollow noreferrer">Cat Necklace</a>. </p>
<p>Here is the resulting issue: </p>
<p><a href="https://i.stack.imgur.com/VU11w.jpg" rel="nofollow noreferrer" title="Detached print wall"><img src="https://i.stack.imgur.com/VU11w.jpg" alt="Detached print wall" title="Detached print wall"></a></p>
<p>I am quite new to 3D printing, so I'm sure this is an easy fix, I just don't know about it yet. </p>
<p>I am printing with a Monoprice Select Mini V2, using Hatchbox PLA, and the default slicing settings inside Cura. I don't have problems with any of the D&D figures I've printed, or some of the other thicker square pieces I've printed. I know I've got kind of a bargain printer; if it's just a quality issue I have to learn to live with, no problem. But if an expert knows of some slicer settings to tweak for these kinds of prints with flat vertical walls, I'd love to give it a try.</p>
|
<p>I have faced the same issue if it concerns just gaps between the walls (to the point you could put a nail in between the outer and inner perimeters, so clearly the perimeters were not bonding), for me this was fixed with proper tension of the belts of my Prusa i3 clone, and for my other (CoreXY) printer reducing the friction of the X-Y system. Both help position the head better for proper wall adhesion.</p>
<p>Now that you have posted a picture of your product I do not think the above is applicable to you. Your print looks as if it has an under-extrusion problem as the lines on the faces are clearly not touching, you see the diagonals of the layers beneath. This under-extrusion also may contribute to the vertical wall bonding problems you mention. To fight under-extrusion you need to check a few things:</p>
<ol>
<li>Be sure the slicer has the actual filament diameter as mentioned on the box, or measured at various points (if it varies, take the mean value).</li>
<li>Check your extruder setup to see whether you have play or friction preventing filament to extrude freely.</li>
<li>Also check whether your extruder gear is not loose, re-tighten the grub screw.</li>
<li>Final step is calibration. You want to be certain that when you demand 100 mm of filament to extrude, you actually extrude 100 mm. Put a mark on the filament and extrude 100 mm using a tool like Pronterface or Repetier-host. If this is off you should readjust the steps per mm in the firmware (if you are able to do so), or increase the extrusion multiplier or flow in your slicer.</li>
</ol>
<p>Please look <a href="https://www.simplify3d.com/support/print-quality-troubleshooting/#not-extruding-enough-plastic" rel="noreferrer">here</a> or <a href="https://rigid.ink/blogs/news/under-extrusion-problems-or-clicking-sounds-heres-why-and-how-to-fix-it" rel="noreferrer">here</a> for more information.</p>
|
<p>When printing someone else's model, your print is at the mercy of their design. Designing for multiple printers is hard work, and even if something is printable on 90% of printers, you may be in the 10%. Sometimes designs use walls too thin for other printers. On this design, the lanyard wall looks a bit thin but workable. My own card holder has a thicker wall at that junction: <a href="https://github.com/firepick1/taz-shield/blob/master/STL/Cardholder.stl" rel="nofollow noreferrer">https://github.com/firepick1/taz-shield/blob/master/STL/Cardholder.stl</a></p>
<p>Vertical walls are the weakest part of 3D printing. Walls are made up of overlapping filament strands. They'll come apart if your printer belts are loose and the strands don't align (tighten belt if there is play). They'll come apart if you print too fast and the contact area is too thin (slow down for better contact and more accurate motion). They'll come apart if filament head temp is too low and the strands don't fuse (bump it up by 5C and try again).</p>
<p>Slicing software normally takes are of all this for you, but it's good to understand what happens on the print bed because your slicing software will often have options that you will need to tweak for your specific printer.</p>
| 919
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.