instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>What are the performance, security, or "other" implications of using the following form to declare a new class instance in PHP</p>
<pre><code><?php
$class_name = 'SomeClassName';
$object = new $class_name;
?>
</code></pre>
<p>This is a contrived example, but I've seen this form used in Factories (OOP) to avoid having a big if/switch statement.</p>
<p>Problems that come immediately to mind are </p>
<ol>
<li><s>You lose the ability to pass arguments into a constructor</s> (LIES. Thanks Jeremy)</li>
<li>Smells like eval(), with all the security concerns it brings to the table (but not necessarily the performance concerns?)</li>
</ol>
<p>What other implications are there, or what search engine terms other than "Rank PHP Hackery" can someone use to research this?</p>
|
<p>One of the issues with the resolving at run time is that you make it really hard for the opcode caches (like APC). Still, for now, doing something like you describe in your question is a valid way if you need a certain amount of indirection when instanciating stuff.</p>
<p>As long as you don't do something like</p>
<pre><code>$classname = 'SomeClassName';
for ($x = 0; $x < 100000; $x++){
$object = new $classname;
}
</code></pre>
<p>you are probably fine :-)</p>
<p>(my point being: Dynamically looking up a class here and then doesn't hurt. If you do it often, it will).</p>
<p>Also, be sure that $classname can never be set from the outside - you'd want to have some control over what exact class you will be instantiating.</p>
|
<p>I use dynamic instantiation in my custom framework. My application controller needs to instantiate a sub-controller based on the request, and it would be simply ridiculous to use a gigantic, ever-changing switch statement to manage the loading of those controllers. As a result, I can add controller after controller to my application without having to modify the app controller to call them. As long as my URIs adhere to the conventions of my framework, the app controller can use them without having to know anything until runtime.</p>
<p>I'm using this framework in a production shopping cart application right now, and the performance is quite favorable, too. That being said, I'm only using the dynamic class selection in one or two spots in the whole app. I wonder in what circumstances you would need to use it frequently, and whether or not those situations are ones that are suffering from a programmer's desire to over-abstract the application (I've been guilty of this before).</p>
| 7,037
|
<p>I have a small financial application with PHP as the front end and MySQL as the back end. I have ancient prejudices, and I store money values in MySQL as an integer of cents. My HTML forms allow input of dollar values, like "156.64" and I use PHP to convert that to cents and then I store the cents in the database.</p>
<p>I have a function that both cleans the dollar value from the form, and converts it to cents. I strip leading text, I strip trailing text, I multiply by 100 and convert to an integer. That final step is</p>
<p><code>$cents = (integer) ($dollars * 100);</code></p>
<p>This works fine for almost everything, except for a very few values like '156.64' which consistently converts to 15663 cents. Why does it do this?</p>
<p>If I do this:</p>
<p><code>$cents = (integer) ($dollars * 100 + 0.5);</code></p>
<p>then it consistently works. Why do I need to add that rounding value?</p>
<p>Also, my prejudices about storing money amounts as integers and not floating point values, is that no longer needed? Will modern float calculations produce nicely rounded and accurate money values adequate for keeping 100% accurate accounting?</p>
|
<p>If you want precision, you should store your money values using the <a href="http://dev.mysql.com/doc/refman/5.0/en/numeric-types.html" rel="nofollow noreferrer">DECIMAL</a> data type in MySQL.</p>
|
<p>Instead of using</p>
<p>$cents = (integer) ($dollars * 100);</p>
<p>you may want to try to use:</p>
<p>$cents = bcmul($dollars, 100, 2);</p>
| 23,526
|
<p>I have something here that is really catching me off guard.</p>
<p>I have an ObservableCollection of T that is filled with items. I also have an event handler attached to the CollectionChanged event.</p>
<p>When you <strong>Clear</strong> the collection it causes an CollectionChanged event with e.Action set to NotifyCollectionChangedAction.Reset. Ok, that's normal. But what is weird is that neither e.OldItems or e.NewItems has anything in it. <strong>I would expect e.OldItems to be filled with all items that were removed from the collection.</strong></p>
<p>Has anyone else seen this? And if so, how have they gotten around it?</p>
<p>Some background: I am using the CollectionChanged event to attach and detach from another event and thus if I don't get any items in e.OldItems ... I won't be able to detach from that event.</p>
<p><br></p>
<p><strong>CLARIFICATION:</strong>
I do know that the documentation doesn't <em>outright</em> state that it has to behave this way. But for every other action, it is notifying me of what it has done. So, my assumption is that it would tell me ... in the case of Clear/Reset as well.</p>
<p><br></p>
<p>Below is the sample code if you wish to reproduce it yourself. First off the xaml:</p>
<pre><code><Window
x:Class="ObservableCollection.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1"
Height="300"
Width="300"
>
<StackPanel>
<Button x:Name="addButton" Content="Add" Width="100" Height="25" Margin="10" Click="addButton_Click"/>
<Button x:Name="moveButton" Content="Move" Width="100" Height="25" Margin="10" Click="moveButton_Click"/>
<Button x:Name="removeButton" Content="Remove" Width="100" Height="25" Margin="10" Click="removeButton_Click"/>
<Button x:Name="replaceButton" Content="Replace" Width="100" Height="25" Margin="10" Click="replaceButton_Click"/>
<Button x:Name="resetButton" Content="Reset" Width="100" Height="25" Margin="10" Click="resetButton_Click"/>
</StackPanel>
</Window>
</code></pre>
<p>Next, the code behind:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
namespace ObservableCollection
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
_integerObservableCollection.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(_integerObservableCollection_CollectionChanged);
}
private void _integerObservableCollection_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
case System.Collections.Specialized.NotifyCollectionChangedAction.Add:
break;
case System.Collections.Specialized.NotifyCollectionChangedAction.Move:
break;
case System.Collections.Specialized.NotifyCollectionChangedAction.Remove:
break;
case System.Collections.Specialized.NotifyCollectionChangedAction.Replace:
break;
case System.Collections.Specialized.NotifyCollectionChangedAction.Reset:
break;
default:
break;
}
}
private void addButton_Click(object sender, RoutedEventArgs e)
{
_integerObservableCollection.Add(25);
}
private void moveButton_Click(object sender, RoutedEventArgs e)
{
_integerObservableCollection.Move(0, 19);
}
private void removeButton_Click(object sender, RoutedEventArgs e)
{
_integerObservableCollection.RemoveAt(0);
}
private void replaceButton_Click(object sender, RoutedEventArgs e)
{
_integerObservableCollection[0] = 50;
}
private void resetButton_Click(object sender, RoutedEventArgs e)
{
_integerObservableCollection.Clear();
}
private ObservableCollection<int> _integerObservableCollection = new ObservableCollection<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 };
}
}
</code></pre>
|
<p>It doesn't claim to include the old items, because Reset doesn't mean that the list has been cleared</p>
<p>It means that some dramatic thing has taken place, and the cost of working out the add/removes would most likely exceed the cost of just re-scanning the list from scratch... so that's what you should do.</p>
<p>MSDN suggests an example of the entire collection being re-sorted as a candidate for reset.</p>
<p>To reiterate. <strong>Reset doesn't mean clear</strong>, it means <em>Your assumptions about the list are now invalid. Treat it as if it's an entirely new list</em>. Clear happens to be one instance of this, but there could well be others. </p>
<p>Some examples:<br>
I've had a list like this with a lot of items in it, and it has been databound to a WPF <code>ListView</code> to display on-screen.<br>
If you clear the list and raise the <code>.Reset</code> event, the performance is pretty much instant, but if you instead raise many individual <code>.Remove</code> events, the performance is terrible, as WPF removes the items one by one.
I've also used <code>.Reset</code> in my own code to indicate that the list has been re-sorted, rather than issuing thousands of individual <code>Move</code> operations. As with Clear, there is a large performance hit when when raising many individual events.</p>
|
<p><a href="http://msdn.microsoft.com/en-us/library/system.collections.specialized.notifycollectionchangedaction(VS.95).aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/system.collections.specialized.notifycollectionchangedaction(VS.95).aspx</a></p>
<p>Please read this documentation with your eyes open and your brain turned on.
Microsoft did everything right. You must re-scan your collection when it throws a Reset notification for you. You get a Reset notification because throwing Add/Remove for each item (being removed from and added back to collection) is too expensive.</p>
<p>Orion Edwards is completely right (respect, man). Please think wider when reading the documentation.</p>
| 27,689
|
<p>I have an NHibernate session. In this session, I am performing exactly 1 operation, which is to run this code to get a list:</p>
<pre><code>public IList<Customer> GetCustomerByFirstName(string customerFirstName)
{
return _session.CreateCriteria(typeof(Customer))
.Add(new NHibernate.Expression.EqExpression("FirstName", customerFirstName))
.List<Customer>();
}
</code></pre>
<p>I am calling <code>Session.Flush()</code> at the end of the <code>HttpRequest</code>, and I get a <code>HibernateAdoException</code>. NHibernate is passing an update statement to the db, and causing a foreign key violation. If I don't run the <code>flush</code>, the request completes with no problem. The issue here is that I need the flush in place in case there is a change that occurs within other sessions, since this code is reused in other areas. Is there another configuration setting I might be missing?</p>
<hr>
<p>Here's the code from the exception:</p>
<pre><code>[SQL: UPDATE CUSTOMER SET first_name = ?, last_name = ?, strategy_code_1 = ?, strategy_code_2 = ?, strategy_code_3 = ?, dts_import = ?, account_cycle_code = ?, bucket = ?, collector_code = ?, days_delinquent_count = ?, external_status_code = ?, principal_balance_amount = ?, total_min_pay_due = ?, current_balance = ?, amount_delinquent = ?, current_min_pay_due = ?, bucket_1 = ?, bucket_2 = ?, bucket_3 = ?, bucket_4 = ?, bucket_5 = ?, bucket_6 = ?, bucket_7 = ? WHERE customer_account_id = ?]
</code></pre>
<p>No parameters are showing as being passed.</p>
|
<p>Always be careful with NULLable fields whenever you deal with NHibernate. If your field is NULLable in DB, make sure corresponding .NET class uses Nullable type too. Otherwise, all kinds of weird things will happen. The symptom is usually will be that NHibernate will try to update the record in DB, even though you have not changed any fields since you read the entity from the database.</p>
<p>The following sequence explains why this happens:</p>
<ol>
<li>NHibernate retrieves raw entity's data from DB using ADO.NET</li>
<li>NHibernate constructs the entity and sets its properties</li>
<li>If DB field contained NULL the property will be set to the defaul value for its type:
<ul>
<li>properties of reference types will be set to null</li>
<li>properties of integer and floating point types will be set to 0</li>
<li>properties of boolean type will be set to false</li>
<li>properties of DateTime type will be set to DateTime.MinValue</li>
<li>etc.</li>
</ul></li>
<li>Now, when transaction is committed, NHibernate compares the value of the property to the original field value it read form DB, and since the field contained NULL but the property contains a non-null value, <strong>NHibernate considers the property dirty, and forces an update of the enity.</strong></li>
</ol>
<p>Not only this hurts performance (you get extra round-trip to DB and extra update every time you retrieve the entity) but it also may cause hard to troubleshoot errors with DateTime columns. Indeed, when DateTime property is initialized to its default value it's set to 1/1/0001. When this value is saved to DB, ADO.NET's SqlClient can't convert it to a valid SqlDateTime value since the smallest possible SqlDateTime is 1/1/1753!!!</p>
<p>The easiest fix is to make the class property use Nullable type, in this case "DateTime?". Alternatively, you could implement a custom type mapper by implementing IUserType with its Equals method properly comparing DbNull.Value with whatever default value of your value type. In our case Equals would need to return true when comparing 1/1/0001 with DbNull.Value. Implementing a full-functional IUserType is not really that hard but it does require knowledge of NHibernate trivia so prepare to do some substantial googling if you choose to go that way.</p>
|
<p>I also experienced this problem in NH 2.0.1 when trying to hide the inverse ends of many-to-many bags using access="noop" (hint: this doesn't work). </p>
<p>Converting them to access="field" + adding a field on the class fixed the problem. Pretty hard to track them down though.</p>
| 5,522
|
<p>I need to execute a select and then update some of the rows in the <code>ResultSet</code> in an atomic way.</p>
<p>The code I am using looks like (simplified):</p>
<pre><code>stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
rs = stmt.executeQuery("SELECT ...");
while (rs.next()) {
if (conditions_to_update) {
rs.updateString(...);
rs.updateRow();
}
}
</code></pre>
<ul>
<li>Can I guarantee that the updates are going to be executed atomically ? If not, how could I assure that ?</li>
<li>What happens if any other process has changed the database row that you are updating via <code>updateRow()</code> ? Is there any way to lock the rows in the <code>ResultSet</code> ?</li>
</ul>
|
<p>There's probably a whole heap of technologies and concepts that come into play here, and things start to get fairly sticky when you start considering multi-threaded / multi request applications.</p>
<p>As Iassevk stated, you should look into using <a href="http://java.sun.com/docs/books/tutorial/jdbc/basics/transactions.html" rel="nofollow noreferrer">Transactions</a> to ensure the atomic nature of your updates - a very low-level example would be to do something along the lines of:</p>
<pre><code>...
con.setAutoCommit(false);
try {
while (rs.next()) {
if (conditions_to_update) {
rs.updateString(...);
rs.updateRow();
}
}
con.setAutoCommit(true);
} catch (Exception ex) {
//log the exception and rollback
con.rollback();
} finally {
con.close();
}
</code></pre>
<p>All the updates would then be batched into the same transaction. If any of the updates generated an Exception (such as an invalid value or the connection failing part way through the results), the whole lot would be rolled back. (Finally added because I am a champion of it ;p )</p>
<p>This however, won't address your second issue which is two competing methods trying to update the same table - a race condition. There are, in my mind, two main approaches here - each has it's merits and drawbacks.</p>
<p>The easiest approach would be to <a href="http://dev.mysql.com/doc/refman/5.0/en/lock-tables.html" rel="nofollow noreferrer">Lock the table</a> - this would require minimal code changes but has a pretty big drawback. Working on the assumption that, as with most applications, it's more read that write: locking the table will prevent all other users from viewing the data, with the likelihood the code will hang, waiting for the lock to release before the connection time-out kicks in and throws an exception.</p>
<p>The more complex approach is to ensure that the methods for performing these updates are implemented in a thread-safe manner. To that end:</p>
<ul>
<li>All the updates for this table pass through a single Class</li>
<li>That class implements a Singleton pattern, or exposes the update methods as Static methods</li>
<li>The update methods utilise the <a href="http://java.sun.com/docs/books/tutorial/essential/concurrency/syncmeth.html" rel="nofollow noreferrer">Synchronized</a> keyword to prevent race conditions</li>
</ul>
|
<p>Use transactions.</p>
| 25,978
|
<p>How do you do low low level sockets in C, example: actually sending a SYN.</p>
|
<p>What you actually want is a raw socket ... you can completely control the headers and flags with the raw socket interface, but programming them is much more challenging. Here's a great tutorial to get you started: <a href="http://www.cs.binghamton.edu/~steflik/cs455/rawip.txt" rel="nofollow noreferrer">http://www.cs.binghamton.edu/~steflik/cs455/rawip.txt</a>.</p>
|
<p>I suspect the nmap sources would be an excellent place to look.</p>
| 15,194
|
<p>In C#, when you implement an interface, all members are implicitly public. Wouldn't it be better if we could specify the accessibility modifier (<code>protected</code>, <code>internal</code>, except <code>private</code> of course), or should we just use an abstract class instead?</p>
|
<p>If an interface is internal, all its members will be internal to the assembly. If a nested interface is protected, only the subclasses of the outer class could access that interface.</p>
<p>Internal members for an interface outside of its declaring assembly would be pointless, as would protected members for an interface outside of its declaring outer class.</p>
<p>The point of an interface is to describe a <strong>contract</strong> between a implementing type and users of the interface. Outside callers aren't going to care and shouldn't <strong>have</strong> to care about implementation, which is what internal and protected members are for.</p>
<p>For protected members that are called by a base class, abstract classes are the way to go for specifying a contract between base classes and classes that inherit from them. But in this case, implementation details are usually very relevant, unless it's a degenerate pure abstract class (where <em>all</em> members are abstract) in which case protected members are useless. In that case, go with an interface and save the single base class for implementing types to choose.</p>
|
<p>I'm familiar with Java rather than C#, but why an earth would you want a private member within an interface? It couldn't have any implementation and would be invisible to implementing classes, so would be useless. Interfaces exist to specify behaviour. If you need default behaviour than use an abstract class.</p>
| 3,818
|
<p>How do Window's programmers profile their native C++ code?
On Unix/Linux you have gprof <em>[thanks Evan]</em> & valgrind (I personally used this one, although it's not a real profiler), and recently I'm on Mac and Solaris, which means I moved to dTrace. Now when I've had the need to profile on Windows in the past, like at my previous job, I used Intel's vtune, which is great, however it's commercial, and I don't have a license for private use, so I'm left wondering what's the standard (free is better) tool windows programmers commonly use?</p>
<p>Thanks in advance</p>
|
<p>You should give <a href="http://blogs.msdn.com/pigscanfly/archive/2008/02/09/xperf-a-new-tool-in-the-windows-sdk.aspx" rel="nofollow noreferrer">Xperf</a> a try - it's a new system wide performance tool that can drill down to a particular application and what exactly it's doing inside itself as well as what's it's asking of the OS.</p>
<p>It's freely available on the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=F26B1AA4-741A-433A-9BE5-FA919850BDBF&displaylang=en" rel="nofollow noreferrer">Windows SDK for Windows Server 2008 and .NET Framework 3.5 ISO</a>:</p>
<blockquote>
<ol>
<li>Install the SDK by downloading the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=F26B1AA4-741A-433A-9BE5-FA919850BDBF&displaylang=en" rel="nofollow noreferrer">ISO image</a>, or using the Web based
installer.</li>
<li>Find the xperf MSI in the SDK's "bin" directory. It will be named
xperf_x86.msi, xperf_x64.msi, or
xperf_ia64.msi, depending on the
architecture for which you install the
SDK. </li>
<li>You can then install the xperf tools from the MSI directly, or copy
the xperf MSI file to another location
and install it from there. For
example, you could keep the MSI files
on a USB key.</li>
</ol>
</blockquote>
<p><a href="http://blogs.msdn.com/pigscanfly/archive/2008/02/09/xperf-a-new-tool-in-the-windows-sdk.aspx" rel="nofollow noreferrer">Source: Pigs Can Fly blog on MSDN.com</a></p>
<p>Just verified that the xperf msi will not install except on windows Vista or Windows 2007.</p>
<p>-Adam</p>
|
<p><a href="https://stackoverflow.com/questions/375913/what-can-i-use-to-profile-c-code-in-linux/378024#378024">This link</a> talks about Linux, but I use the same technique in MSVC and in C#.</p>
| 40,858
|
<p>Computer Management -> Services and Applications -> Message Queues</p>
<p>How to delete a message from a specific queue?
It seems to me there was some way but I cannot find it right now.</p>
|
<p>Well, it isn't possible to delete a poison message by MMC. </p>
<p>You can try <a href="http://www.cogin.com/mq/download.php" rel="nofollow noreferrer">QueueExplorer</a> and maybe that will help you out, or you have to programmically to solve your issues</p>
|
<p>In Windows 10 you can empty a queue in Computer Management --> Services and Applications --> Message Queuing by right-clicking the queue and selecting All Tasks --> Purge:</p>
<p><a href="https://i.stack.imgur.com/WON1y.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WON1y.jpg" alt="enter image description here"></a></p>
| 25,013
|
<p>I have an ASP.Net/AJAX control kit project that i am working on. 80% of the time there is no problem. The page runs as it should. If you refresh the page it will sometimes show a javascript error "Sys is undefined".</p>
<p>It doesn't happen all the time, but it is reproducible. When it happens, the user has to shut down their browser and reopen the page.</p>
<p>This leads me to believe that it could be an IIS setting.</p>
<p>Another note. I looked at the page source both when I get the error, and when not. When the page throws errors the following code is missing:</p>
<pre><code><script src="/ScriptResource.axd?d=EAvfjPfYejDh0Z2Zq5zTR_TXqL0DgVcj_h1wz8cst6uXazNiprV1LnAGq3uL8N2vRbpXu46VsAMFGSgpfovx9_cO8tpy2so6Qm_0HXVGg_Y1&amp;t=baeb8cc" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
if (typeof(Sys) === 'undefined') throw new Error('ASP.NET Ajax client-side framework failed to load.');
//]]>
</script>
</code></pre>
|
<p>I fixed my problem by moving the <code><script type="text/javascript"></script></code> block containing the Sys.* calls lower down (to the last item before the close of the body's <code><asp:Content/></code> section) in the HTML on the page. I originally had my the script block in the HEAD <code><asp:Content/></code> section of my page. I was working inside a page that had a MasterPageFile. Hope this helps someone out.</p>
|
<p>Please please please do check that the Server has the correct time and date set...</p>
<p>After about wasting 6 hours, i read it somewhere...</p>
<p>The date and time for the server must be updated to work correctly...</p>
<p>otherwise you will get 'Sys' is undefined error.</p>
| 10,096
|
<p>Within Ruby on Rails applications database.yml is a plain text file that stores database credentials.</p>
<p>When I deploy my Rails applications I have an after deploy callback in my Capistrano
recipe that creates a symbolic link within the application's /config directory to the database.yml file. The file itself is stored in a separate directory that's outside the standard Capistrano /releases directory structure. I chmod 400 the file so it's only readable by the user who created it.</p>
<ul>
<li>Is this sufficient to lock it down? If not, what else do you do?</li>
<li>Is anyone encrypting their database.yml files?</li>
</ul>
|
<p>You'll also want to make sure that your SSH system is well secured to prevent people from logging in <em>as</em> your Capistrano bot. I'd suggest restricting access to password-protected key pairs.</p>
<p>Encrypting the .yml file on the server is useless since you have to give the bot the key, which would be stored . . . on the same server. Encrypting it on your machine is probably a good idea. Capistrano can decrypt it before sending.</p>
|
<p>If you're very concerned about security of the yml file, I have to ask: Is it stored in your version control? If so, that's another point where an attacker can get at it. If you're doing checkout/checkin over non-SSL, someone could intercept it.</p>
<p>Also, with some version control (svn, for exampl), even if you remove it, it's still there in the history. So, even if you removed it at some point in the past, it's still a good idea to change the passwords.</p>
| 3,889
|
<p>I have a function I've written that was initially supposed to take a string field and populate an excel spreadsheet with the values. Those values continually came up null. I started tracking it back to the recordset and found that despite the query being valid and running properly through the Access query analyzer the recordset was empty or had missing fields.</p>
<p>To test the problem, I created a sub in which I created a query, opened a recordset, and then paged through the values (outputting them to a messagebox). The most perplexing part of the problem seems to revolve around the "WHERE" clause of the query. If I don't put a "WHERE" clause on the query, the recordset always has data and the values for "DESCRIPTION" are normal.</p>
<p>If I put <em>anything</em> in for the WHERE clause the recordset comes back either totally empty (<code>rs.EOF = true</code>) or the Description field is totally blank where the other fields have values. I want to stress again that if I debug.print the query, I can copy/paste it into the query analyzer and get a valid and returned values that I expect.</p>
<p>I'd sure appreciate some help with this. Thank you!</p>
<pre><code>Private Sub NewTest()
' Dimension Variables
'----------------------------------------------------------
Dim rsNewTest As ADODB.Recordset
Dim sqlNewTest As String
Dim Counter As Integer
' Set variables
'----------------------------------------------------------
Set rsNewTest = New ADODB.Recordset
sqlNewTest = "SELECT dbo_partmtl.partnum as [Job/Sub], dbo_partmtl.revisionnum as Rev, " & _
"dbo_part.partdescription as Description, dbo_partmtl.qtyper as [Qty Per] " & _
"FROM dbo_partmtl " & _
"LEFT JOIN dbo_part ON dbo_partmtl.partnum = dbo_part.partnum " & _
"WHERE dbo_partmtl.mtlpartnum=" & Chr(34) & "3C16470" & Chr(34)
' Open recordset
rsNewTest.Open sqlNewTest, CurrentProject.Connection, adOpenDynamic, adLockOptimistic
Do Until rsNewTest.EOF
For Counter = 0 To rsNewTest.Fields.Count - 1
MsgBox rsNewTest.Fields(Counter).Name
Next
MsgBox rsNewTest.Fields("Description")
rsNewTest.MoveNext
Loop
' close the recordset
rsNewTest.Close
Set rsNewTest = Nothing
End Sub
</code></pre>
<p>EDIT: Someone requested that I post the DEBUG.PRINT of the query. Here it is:</p>
<pre><code>SELECT dbo_partmtl.partnum as [Job/Sub], dbo_partmtl.revisionnum as Rev, dbo_part.partdescription as [Description], dbo_partmtl.qtyper as [Qty Per] FROM dbo_partmtl LEFT JOIN dbo_part ON dbo_partmtl.partnum = dbo_part.partnum WHERE dbo_partmtl.mtlpartnum='3C16470'
</code></pre>
<hr>
<p>I have tried double and single quotes using ASCII characters and implicitly.</p>
<p>For example:</p>
<pre><code>"WHERE dbo_partmtl.mtlpartnum='3C16470'"
</code></pre>
<p>I even tried your suggestion with chr(39):</p>
<pre><code>"WHERE dbo_partmtl.mtlpartnum=" & Chr(39) & "3C16470" & Chr(39)
</code></pre>
<p>Both return a null value for description. However, if I debug.print the query and paste it into the Access query analyzer, it displays just fine. Again (as a side note), if I do a LIKE statement in the WHERE clause, it will give me a completely empty recordset. Something is really wonky here.</p>
<hr>
<p>Here is an interesting tidbit. The tables are linked to a <code>SQL Server</code>. If I copy the tables (data and structure) locally, the ADO code above worked flawlessly. If I use DAO it works fine. I've tried this code on <code>Windows XP</code>, <code>Access 2003</code>, and various versions of <code>ADO (2.5, 2.6, 2.8)</code>. <code>ADO</code> will not work if the tables are linked.</p>
<p>There is some flaw in ADO that causes the issue.</p>
<hr>
<p>Absolutely I do. Remember, the <code>DEBUG.PRINT</code> query you see runs perfectly in the query analyzer. It returns the following:</p>
<pre>
Job/Sub Rev Description Qty Per
36511C01 A MAIN ELECTRICAL ENCLOSURE 1
36515C0V A VISION SYSTEM 1
36529C01 A MAIN ELECTRICAL ENCLOSURE 1
</pre>
<p>However, the same query returns empty values for Description (everything else is the same) when run through the recordset (messagebox errors because of "Null" value).</p>
<hr>
<p>I tried renaming the "description" field to "testdep", but it's still empty. The only way to make it display data is to remove the WHERE section of the query. I'm starting to believe this is a problem with ADO. Maybe I'll rewriting it with DAO and seeing what results i get.</p>
<p>EDIT: I also tried compacting and repairing a couple of times. No dice.</p>
|
<p>When using ADO LIKE searches must use % instead of *. I know * works in Access but for some stupid reason ADO won't work unless you use % instead. </p>
<p>I had the same problem and ran accoss this forum while trying to fix it. Replacing *'s with %'s worked for me.</p>
|
<p>I put brackets around the word "Description" in the SELECT statement, but it's behavior remains. It works fine as long as I don't put anything in the WHERE clause. I've found if I put anything in the where clause, the description is blank (despite showing up in the Query analyzer). If I use a LIKE statement in the WHERE clause, the entire recordset is empty but it still works properly in the Query Analyzer.</p>
| 31,656
|
<p>For example, how can I run me.test below?</p>
<pre><code>myvar = 'test'
me.myvar
</code></pre>
<p>ASP looks for the method "myvar" and doesn't find it. In PHP I could simply say $me->$myvar but ASP's syntax doesn't distinguish between variables and methods. Suggestions?</p>
<p>Closely related to this, is there a method_exists function in ASP Classic?</p>
<p>Thanks in advance!</p>
<p><strong>EDIT:</strong> I'm writing a validation class and would like to call a list of methods via a pipe delimited string. </p>
<p>So for example, to validate a name field, I'd call:</p>
<pre><code>validate("required|min_length(3)|max_length(100)|alphanumeric")
</code></pre>
<p>I like the idea of having a single line that shows all the ways a given field is being validated. And each pipe delimited section of the string is the name of a method.</p>
<p>If you have suggestions for a better setup, I'm all ears!</p>
|
<p>You can achieve this in VBScript by using the <code>GetRef</code> function:-</p>
<pre><code>Function Test(val)
Test = val & " has been tested"
End Function
Dim myvar : myvar = "Test"
Dim x : Set x = GetRef(myvar)
Response.Write x("Thing")
</code></pre>
<p>Will send "Thing has been tested" to the client.</p>
<p>So here is your validate requirement using GetRef:-</p>
<pre><code>validate("Hello World", "min_length(3)|max_length(10)|alphanumeric")
Function required(val)
required = val <> Empty
End Function
Function min_length(val, params)
min_length = Len(val) >= CInt(params(0))
End Function
Function max_length(val, params)
max_length = Len(val) <= CInt(params(0))
End Function
Function alphanumeric(val)
Dim rgx : Set rgx = New RegExp
rgx.Pattern = "^[A-Za-z0-9]+$"
alphanumeric = rgx.Test(val)
End Function
Function validate(val, criterion)
Dim arrCriterion : arrCriterion = Split(criterion, "|")
Dim criteria
validate = True
For Each criteria in arrCriterion
Dim paramListPos : paramListPos = InStr(criteria, "(")
If paramListPos = 0 Then
validate = GetRef(criteria)(val)
Else
Dim paramList
paramList = Split(Mid(criteria, paramListPos + 1, Len(criteria) - paramListPos - 1), ",")
criteria = Left(criteria, paramListPos - 1)
validate = GetRef(criteria)(val, paramList)
End If
If Not validate Then Exit For
Next
End Function
</code></pre>
<p>Having provided this I have to say though that if you are familiar with PHP then JScript would be a better choice on the server. In Javascript you can call a method like this:-</p>
<pre><code>function test(val) { return val + " has been tested"; )
var myvar = "test"
Response.Write(this[myvar]("Thing"))
</code></pre>
|
<p>ASP does not support late binding in this manner. What are you trying to do, in a larger sense? Explain that, and someone can show you how to accomplish it in asp.</p>
| 43,543
|
<p>I have great doubts about this forum, but I am willing to be pleasantly surprised ;) <strong>Kudos and great karma to those who get me back on track.</strong></p>
<p>I am attempting to use the blitz implementation of JavaSpaces (<a href="http://www.dancres.org/blitz/blitz_js.html" rel="nofollow noreferrer">http://www.dancres.org/blitz/blitz_js.html</a>) to implement the ComputeFarm example provided at <a href="http://today.java.net/pub/a/today/2005/04/21/farm.html" rel="nofollow noreferrer">http://today.java.net/pub/a/today/2005/04/21/farm.html</a></p>
<p>The in memory example works fine, but whenever I attempt to use the blitz out-of-box implementation i get the following error:</p>
<p>(yes <strong><code>com.sun.jini.mahalo.TxnMgrProxy</code></strong> is in the class path)</p>
<pre><code>2008-09-24 09:57:37.316 ERROR [Thread-4] JavaSpaceComputeSpace 155 - Exception while taking task.
java.rmi.ServerException: RemoteException in server thread; nested exception is:
java.rmi.UnmarshalException: unmarshalling method/arguments; nested exception is:
java.lang.ClassNotFoundException: com.sun.jini.mahalo.TxnMgrProxy
at net.jini.jeri.BasicInvocationDispatcher.dispatch(BasicInvocationDispatcher.java:644)
at com.sun.jini.jeri.internal.runtime.ObjectTable$6.run(ObjectTable.java:597)
at net.jini.export.ServerContext.doWithServerContext(ServerContext.java:103)
at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch0(ObjectTable.java:595)
at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.access$700(ObjectTable.java:212)
at com.sun.jini.jeri.internal.runtime.ObjectTable$5.run(ObjectTable.java:568)
at com.sun.jini.start.AggregatePolicyProvider$6.run(AggregatePolicyProvider.java:527)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch(ObjectTable.java:565)
at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch(ObjectTable.java:540)
at com.sun.jini.jeri.internal.runtime.ObjectTable$RD.dispatch(ObjectTable.java:778)
at net.jini.jeri.connection.ServerConnectionManager$Dispatcher.dispatch(ServerConnectionManager.java:148)
at com.sun.jini.jeri.internal.mux.MuxServer$2.run(MuxServer.java:244)
at com.sun.jini.start.AggregatePolicyProvider$5.run(AggregatePolicyProvider.java:513)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.jini.jeri.internal.mux.MuxServer$1.run(MuxServer.java:241)
at com.sun.jini.thread.ThreadPool$Worker.run(ThreadPool.java:136)
at java.lang.Thread.run(Thread.java:595)
at com.sun.jini.jeri.internal.runtime.Util.__________EXCEPTION_RECEIVED_FROM_SERVER__________(Util.java:108)
at com.sun.jini.jeri.internal.runtime.Util.exceptionReceivedFromServer(Util.java:101)
at net.jini.jeri.BasicInvocationHandler.unmarshalThrow(BasicInvocationHandler.java:1303)
at net.jini.jeri.BasicInvocationHandler.invokeRemoteMethodOnce(BasicInvocationHandler.java:832)
at net.jini.jeri.BasicInvocationHandler.invokeRemoteMethod(BasicInvocationHandler.java:659)
at net.jini.jeri.BasicInvocationHandler.invoke(BasicInvocationHandler.java:528)
at $Proxy0.take(Unknown Source)
at org.dancres.blitz.remote.BlitzProxy.take(BlitzProxy.java:157)
at compute.impl.javaspaces.JavaSpaceComputeSpace.take(JavaSpaceComputeSpace.java:138)
at example.squares.SquaresJob.collectResults(SquaresJob.java:47)
at compute.impl.AbstractJobRunner$CollectThread.run(AbstractJobRunner.java:28)
Caused by: java.rmi.UnmarshalException: unmarshalling method/arguments; nested exception is:
java.lang.ClassNotFoundException: com.sun.jini.mahalo.TxnMgrProxy
at net.jini.jeri.BasicInvocationDispatcher.dispatch(BasicInvocationDispatcher.java:619)
at com.sun.jini.jeri.internal.runtime.ObjectTable$6.run(ObjectTable.java:597)
at net.jini.export.ServerContext.doWithServerContext(ServerContext.java:103)
at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch0(ObjectTable.java:595)
at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.access$700(ObjectTable.java:212)
at com.sun.jini.jeri.internal.runtime.ObjectTable$5.run(ObjectTable.java:568)
at com.sun.jini.start.AggregatePolicyProvider$6.run(AggregatePolicyProvider.java:527)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch(ObjectTable.java:565)
at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch(ObjectTable.java:540)
at com.sun.jini.jeri.internal.runtime.ObjectTable$RD.dispatch(ObjectTable.java:778)
at net.jini.jeri.connection.ServerConnectionManager$Dispatcher.dispatch(ServerConnectionManager.java:148)
at com.sun.jini.jeri.internal.mux.MuxServer$2.run(MuxServer.java:244)
at com.sun.jini.start.AggregatePolicyProvider$5.run(AggregatePolicyProvider.java:513)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.jini.jeri.internal.mux.MuxServer$1.run(MuxServer.java:241)
at com.sun.jini.thread.ThreadPool$Worker.run(ThreadPool.java:136)
at java.lang.Thread.run(Thread.java:595)
Caused by: java.lang.ClassNotFoundException: com.sun.jini.mahalo.TxnMgrProxy
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at net.jini.loader.pref.PreferredClassLoader.loadClass(PreferredClassLoader.java:922)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:242)
at net.jini.loader.pref.PreferredClassProvider.loadClass(PreferredClassProvider.java:613)
at java.rmi.server.RMIClassLoader.loadClass(RMIClassLoader.java:247)
at net.jini.loader.ClassLoading.loadClass(ClassLoading.java:138)
at net.jini.io.MarshalInputStream.resolveClass(MarshalInputStream.java:296)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1544)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1466)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1699)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1305)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1908)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1832)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1719)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1305)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:348)
at com.sun.jini.jeri.internal.runtime.Util.unmarshalValue(Util.java:221)
at net.jini.jeri.BasicInvocationDispatcher.unmarshalArguments(BasicInvocationDispatcher.java:1049)
at net.jini.jeri.BasicInvocationDispatcher.dispatch(BasicInvocationDispatcher.java:599)
... 17 more
</code></pre>
|
<p>So com.sun.jini.mahalo.TxnMgrProxy is contained in some jar, that is contained in your CLASSPATH environment variable.</p>
<p>But probably your are using some script to start the server. And this most probably starts java by specifying a "-classpath" commandline switch which takes precendence over your environment CLASSPATH variable.</p>
<p><a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/classpath.html" rel="nofollow noreferrer">http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/classpath.html</a></p>
<p>You can simulate this by executing:</p>
<p>javap -classpath someUnknownJar.jar com.sun.jini.mahalo.TxnMgrProxy</p>
<p>... and suddenly the class cannot be found anymore. So can you please try and find out the way the java VM of the client and server are started and provide the complete command line.
(If you are using some kind of script just add an "echo ..." in front of the java command and paste the output in here).</p>
|
<p>Well, your java spaces server does not seem to find the class:</p>
<p>com.sun.jini.mahalo.TxnMgrProxy.</p>
<p>So I guess you just have to add Mahalo (should be included in the blitz distribution according to this: <a href="http://www.dancres.org/blitz/blitz_inst.html" rel="nofollow noreferrer">http://www.dancres.org/blitz/blitz_inst.html</a> page) to your classpath when starting the server.</p>
<p>Please post some more information about how you are starting your server, if this advice does not help.</p>
| 15,560
|
<p>I need to find out time taken by a function in my application. Application is a MS VIsual Studio 2005 solution, all C code. </p>
<p>I used thw windows API GetLocalTime(SYSTEMTIME *) to get the current system time before and after the function call which I want to measure time of.
But this has shortcoming that it lowest resolution is only 1msec. Nothing below that. So I cannot get any time granularity in micro seconds. </p>
<p>I know that time() which gives the time elapsed since the epoch time, also has resolution of 1msec (No microseconds) </p>
<p>1.) Is there any other Windows API which gives time in microseconds which I can use to measure the time consumed by my function?</p>
<p>-AD</p>
|
<p>There are some other possibilities.</p>
<h2>QueryPerformanceCounter and QueryPerformanceFrequency</h2>
<p><a href="http://msdn.microsoft.com/en-us/library/ms644904.aspx" rel="noreferrer">QueryPerformanceCounter</a> will return a "performance counter" which is actually a CPU-managed 64-bit counter that increments from 0 starting with the computer power-on. The frequency of this counter is returned by the <a href="http://msdn.microsoft.com/en-us/library/ms644905.aspx" rel="noreferrer">QueryPerformanceFrequency</a>. To get the time reference in <strong>seconds</strong>, divide performance counter by performance frequency. In Delphi: </p>
<pre><code>function QueryPerfCounterAsUS: int64;
begin
if QueryPerformanceCounter(Result) and
QueryPerformanceFrequency(perfFreq)
then
Result := Round(Result / perfFreq * 1000000);
else
Result := 0;
end;
</code></pre>
<p>On multiprocessor platforms, QueryPerformanceCounter <strong>should</strong> return consistent results regardless of the CPU the thread is currently running on. There are occasional problems, though, usually caused by bugs in hardware chips or BIOSes. Usually, patches are provided by motherboard manufacturers. Two examples from the MSDN:</p>
<ul>
<li><a href="http://support.microsoft.com/kb/895980" rel="noreferrer">Programs that use the QueryPerformanceCounter function may perform poorly in Windows Server 2003 and in Windows XP</a></li>
<li><a href="http://support.microsoft.com/kb/274323" rel="noreferrer">Performance counter value may unexpectedly leap forward</a></li>
</ul>
<p>Another problem with QueryPerformanceCounter is that it is quite slow.</p>
<h2>RDTSC instruction</h2>
<p>If you can limit your code to one CPU (SetThreadAffinity), you can use <a href="http://en.wikipedia.org/wiki/RDTSC" rel="noreferrer">RDTSC</a> assembler instruction to query performance counter directly from the processor.</p>
<pre><code>function CPUGetTick: int64;
asm
dw 310Fh // rdtsc
end;
</code></pre>
<p>RDTSC result is incremented with same frequency as QueryPerformanceCounter. Divide it by QueryPerformanceFrequency to get time in seconds.</p>
<p>QueryPerformanceCounter is much slower thatn RDTSC because it must take into account multiple CPUs and CPUs with variable frequency. From <a href="http://blogs.msdn.com/oldnewthing/archive/2008/09/08/8931563.aspx" rel="noreferrer">Raymon Chen's blog</a>:</p>
<blockquote>
<p>(QueryPerformanceCounter) counts elapsed time. It has to, since its value is
governed by the QueryPerformanceFrequency function, which returns a number
specifying the number of units per second, and the frequency is spec'd as not
changing while the system is running. </p>
<p>For CPUs that can run at variable speed, this means that the HAL cannot
use an instruction like RDTSC, since that does not correlate with elapsed time. </p>
</blockquote>
<h2>timeGetTime</h2>
<p><a href="http://msdn.microsoft.com/en-us/library/ms713418.aspx" rel="noreferrer">TimeGetTime</a> belongs to the Win32 multimedia Win32 functions. It returns time in milliseconds with 1 ms resolution, at least on a modern hardware. It doesn't hurt if you run timeBeginPeriod(1) before you start measuring time and timeEndPeriod(1) when you're done.</p>
<h2>GetLocalTime and GetSystemTime</h2>
<p>Before Vista, both <a href="http://msdn.microsoft.com/en-us/library/ms713418.aspx" rel="noreferrer">GetLocalTime</a> and <a href="http://msdn.microsoft.com/en-us/library/ms724390.aspx" rel="noreferrer">GetSystemTime</a> return current time with millisecond precision, but they are not accurate to a millisecond. Their accuracy is typically in the range of 10 to 55 milliseconds. (<a href="http://blogs.msdn.com/oldnewthing/archive/2005/09/02/459952.aspx" rel="noreferrer">Precision is not the same as accuracy</a>)
On Vista, GetLocalTime and GetSystemTime both work with 1 ms resolution.</p>
|
<p>On Windows you can use the 'high performance counter API'. Check out: <a href="http://msdn.microsoft.com/en-us/library/ms644904(VS.85).aspx" rel="nofollow noreferrer">QueryPerformanceCounter</a> and <a href="http://msdn.microsoft.com/en-us/library/ms644905(VS.85).aspx" rel="nofollow noreferrer">QueryPerformanceCounterFrequency</a> for the details.</p>
| 7,231
|
<p>I'm working on a project that generates PDFs that can contain fairly complex math and science formulas. The text is rendered in Times New Roman, which has pretty good Unicode coverage, but not complete. We have a system in place to swap in a more Unicode complete font for code points that don't have a glyph in TNR (like most of the "stranger" math symbols,) but I can't seem to find a way to query the *.ttf file to see if a given glyph is present. So far, I've just hard-coded a lookup table of which code points are present, but I'd much prefer an automatic solution.</p>
<p>I'm using VB.Net in a web system under ASP.net, but solutions in any programming language/environment would be appreciated.</p>
<p>Edit: The win32 solution looks excellent, but the specific case I'm trying to solve is in an ASP.Net web system. Is there a way to do this without including the windows API DLLs into my web site?</p>
|
<p>Here's a pass at it using c# and the windows API.</p>
<pre><code>[DllImport("gdi32.dll")]
public static extern uint GetFontUnicodeRanges(IntPtr hdc, IntPtr lpgs);
[DllImport("gdi32.dll")]
public extern static IntPtr SelectObject(IntPtr hDC, IntPtr hObject);
public struct FontRange
{
public UInt16 Low;
public UInt16 High;
}
public List<FontRange> GetUnicodeRangesForFont(Font font)
{
Graphics g = Graphics.FromHwnd(IntPtr.Zero);
IntPtr hdc = g.GetHdc();
IntPtr hFont = font.ToHfont();
IntPtr old = SelectObject(hdc, hFont);
uint size = GetFontUnicodeRanges(hdc, IntPtr.Zero);
IntPtr glyphSet = Marshal.AllocHGlobal((int)size);
GetFontUnicodeRanges(hdc, glyphSet);
List<FontRange> fontRanges = new List<FontRange>();
int count = Marshal.ReadInt32(glyphSet, 12);
for (int i = 0; i < count; i++)
{
FontRange range = new FontRange();
range.Low = (UInt16)Marshal.ReadInt16(glyphSet, 16 + i * 4);
range.High = (UInt16)(range.Low + Marshal.ReadInt16(glyphSet, 18 + i * 4) - 1);
fontRanges.Add(range);
}
SelectObject(hdc, old);
Marshal.FreeHGlobal(glyphSet);
g.ReleaseHdc(hdc);
g.Dispose();
return fontRanges;
}
public bool CheckIfCharInFont(char character, Font font)
{
UInt16 intval = Convert.ToUInt16(character);
List<FontRange> ranges = GetUnicodeRangesForFont(font);
bool isCharacterPresent = false;
foreach (FontRange range in ranges)
{
if (intval >= range.Low && intval <= range.High)
{
isCharacterPresent = true;
break;
}
}
return isCharacterPresent;
}
</code></pre>
<p>Then, given a char toCheck that you want to check and a Font theFont to test it against...</p>
<pre><code>if (!CheckIfCharInFont(toCheck, theFont) {
// not present
}
</code></pre>
<p>Same code using VB.Net</p>
<pre><code><DllImport("gdi32.dll")> _
Public Shared Function GetFontUnicodeRanges(ByVal hds As IntPtr, ByVal lpgs As IntPtr) As UInteger
End Function
<DllImport("gdi32.dll")> _
Public Shared Function SelectObject(ByVal hDc As IntPtr, ByVal hObject As IntPtr) As IntPtr
End Function
Public Structure FontRange
Public Low As UInt16
Public High As UInt16
End Structure
Public Function GetUnicodeRangesForFont(ByVal font As Font) As List(Of FontRange)
Dim g As Graphics
Dim hdc, hFont, old, glyphSet As IntPtr
Dim size As UInteger
Dim fontRanges As List(Of FontRange)
Dim count As Integer
g = Graphics.FromHwnd(IntPtr.Zero)
hdc = g.GetHdc()
hFont = font.ToHfont()
old = SelectObject(hdc, hFont)
size = GetFontUnicodeRanges(hdc, IntPtr.Zero)
glyphSet = Marshal.AllocHGlobal(CInt(size))
GetFontUnicodeRanges(hdc, glyphSet)
fontRanges = New List(Of FontRange)
count = Marshal.ReadInt32(glyphSet, 12)
For i = 0 To count - 1
Dim range As FontRange = New FontRange
range.Low = Marshal.ReadInt16(glyphSet, 16 + (i * 4))
range.High = range.Low + Marshal.ReadInt16(glyphSet, 18 + (i * 4)) - 1
fontRanges.Add(range)
Next
SelectObject(hdc, old)
Marshal.FreeHGlobal(glyphSet)
g.ReleaseHdc(hdc)
g.Dispose()
Return fontRanges
End Function
Public Function CheckIfCharInFont(ByVal character As Char, ByVal font As Font) As Boolean
Dim intval As UInt16 = Convert.ToUInt16(character)
Dim ranges As List(Of FontRange) = GetUnicodeRangesForFont(font)
Dim isCharacterPresent As Boolean = False
For Each range In ranges
If intval >= range.Low And intval <= range.High Then
isCharacterPresent = True
Exit For
End If
Next range
Return isCharacterPresent
End Function
</code></pre>
|
<p>This Microsoft KB article may help:
<a href="http://support.microsoft.com/kb/241020" rel="nofollow noreferrer">http://support.microsoft.com/kb/241020</a></p>
<p>It's a bit dated (was originally written for Windows 95), but the general principle may still apply. The sample code is C++, but since it's just calling standard Windows APIs, it'll more than likely work in .NET languages as well with a little elbow grease.</p>
<p>-Edit-
It seems that the old 95-era APIs have been obsoleted by a new API Microsoft calls "<a href="http://msdn.microsoft.com/en-us/library/ms776488(VS.85).aspx" rel="nofollow noreferrer">Uniscribe</a>", which should be able to do what you need it to.</p>
| 12,939
|
<p>See title: what does it mean for a C++ function to be inline?</p>
|
<p>The function is placed in the code, rather than being called, similar to using macros (conceptually).</p>
<p>This can improve speed (no function call), but causes code bloat (if the function is used 100 times, you now have 100 copies).</p>
<p>You should note this does not force the compiler to make the function inline, and it will ignore you if it thinks its a bad idea. Similarly the compiler may decide to make normal functions inline for you.</p>
<p>This also allows you to place the entire function in a header file, rather than implementing it in a cpp file (which you can't anyways, since then you get an unresolved external if it was declared inline, unless of course only that cpp file used it).</p>
|
<p>Informally, it means that compilers are allowed to graft the contents of the function onto the call site, so that there is no function call. If your function has big control statements (e.g., <code>if</code>, <code>switch</code>, etc.), and the conditions can be evaluated at compile time at the call site (e.g., constant values used at call site), then your code ends up much smaller (the unused branches are dropped off).</p>
<p>More formally, inline functions have different linkage too. I'll let C++ experts talk about that aspect.</p>
| 18,923
|
<p>I have a .NET dll which needs to read it's config settings from it's config file. Usually, the config file is placed in the same directory as the DLL. But how do i read the config file if the DLL is GAC'ed, because I can put only the DLLs in the GAC, and not it's config files.</p>
|
<p>Does the user need to configure the Dll? If so, then the DLL should be using configuration settings from the app.config file, not it's own config. The app.config file should be stored in the same directory as the application. If not, then you could go a couple of different ways. You could make changes to the machine.config file so that your Dll can find them there. I would not do this. Alternatively, you can store the configuration in a settings class. These can be overridden via configuration, but your defaults will be set in the generated code for the settings class via attributes and so the absence of a configuration file will not affect your Dll when the defaults are all that are required.</p>
|
<p>You can make use of <code>AppDomain.CurrentDomain.BaseDirectory</code> since the DLL library will not be executed by itself you just need to get Executable file directory who is calling him</p>
<p>Something like:</p>
<pre><code>var appDomain = AppDomain.CurrentDomain.BaseDirectory;
string sFileName = appDomain.Replace("\\bin\\Debug", "");
sFileName = sFileName + "Config\\config.xml";
</code></pre>
<p>Here my executable is in folder <code>bin\Debug</code> and inside the folder i have a folder called <code>Config</code> where i have the xml config file <code>config.xml</code>. So the <code>sFileName</code> will provide you the relative path to the config file as <code>\bin\Debug\Config\config.xml</code> </p>
| 40,115
|
<p>This question is a follow up on one of my other questions, <a href="https://stackoverflow.com/questions/94346/can-i-legally-incorporating-gpl-lgpl-open-sourced-software-in-a-proprietary-clo">Can I legally Incorporating GPL & LGPL, open-sourced software in a proprietary, closed-source project?</a></p>
<p>Many of the conditions of the <a href="http://www.gnu.org/licenses/lgpl-3.0.txt" rel="nofollow noreferrer">LGPL license</a> are based on the notion of distribution. My company does business as a consultant. We are contracted to create software, which we deliver to our clients. Does this constitute distribution under the LGPL license?</p>
<p>We have also made available the software, to our clients, for download through a password-protected file server. Does this constitute distribution?</p>
|
<p>Yes it does. One of the reasons the GPL came into being in the first place was to prevent the situation where somebody had a binary, but no source to go with it. </p>
<p>IANAL, so I can't speak to whether the consultancy-client relationship would constitute a loophole which you could use to avoid passing on source code, but it is certainly against the license's intent to do what you're suggesting.</p>
|
<p>Any time you give someone else a copy of some software you have distributed that software. It does not have to be to the public at large to qualify as distribution.</p>
| 12,028
|
<p>When I parse my xml file (variable f) in this method, I get an error </p>
<blockquote>
<p>C:\Documents and Settings\joe\Desktop\aicpcudev\OnlineModule\map.dtd (The system cannot find the path specified)</p>
</blockquote>
<p>I know I do not have the dtd, nor do I need it. How can I parse this File object into a Document object while ignoring DTD reference errors?</p>
<pre><code>private static Document getDoc(File f, String docId) throws Exception{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(f);
return doc;
}
</code></pre>
|
<p>A similar approach to the one suggested by <a href="https://stackoverflow.com/questions/155101/make-documentbuilderparse-ignore-dtd-references#155330">@anjanb</a></p>
<pre><code> builder.setEntityResolver(new EntityResolver() {
@Override
public InputSource resolveEntity(String publicId, String systemId)
throws SAXException, IOException {
if (systemId.contains("foo.dtd")) {
return new InputSource(new StringReader(""));
} else {
return null;
}
}
});
</code></pre>
<p>I found that simply returning an empty InputSource worked just as well?</p>
|
<p>I'm working with sonarqube, and sonarlint for eclipse showed me <strong>Untrusted XML should be parsed without resolving external data (squid:S2755)</strong></p>
<p>I managed to solve it using:</p>
<pre><code> factory = DocumentBuilderFactory.newInstance();
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
// If you can't completely disable DTDs, then at least do the following:
// Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-general-entities
// Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-general-entities
// JDK7+ - http://xml.org/sax/features/external-general-entities
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
// Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-parameter-entities
// Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-parameter-entities
// JDK7+ - http://xml.org/sax/features/external-parameter-entities
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
// Disable external DTDs as well
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
// and these as well, per Timothy Morgan's 2014 paper: "XML Schema, DTD, and Entity Attacks"
factory.setXIncludeAware(false);
factory.setExpandEntityReferences(false);
</code></pre>
| 18,753
|
<p>Can you use Windows Workflow and Compact Framework 3.5?</p>
<p>I've just got an evaluation version of Visual Studio 2008 and I've had a look around but can't work out quickly if there is a way of doing this.
I just don't want to waste anymore time looking around if there is no way of doing it.</p>
|
<p>The best answer I've come across is a "No." at this point. I haven't been able to find anything or see anything that says otherwise as well. Looks like other folks are <a href="http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=4014836&SiteID=1" rel="nofollow noreferrer">asking</a> as well.</p>
|
<p>I think the answer is 'No', although I have no definite proof. It certainly wouldn't have been in any version of compact framework earlier than 3.5. According to the release notes, it looks like compact framework 3.5 adds WCF, but no WF. Definite proof would be to try and fail and find WF dlls inside the framework itself.</p>
<p>This is actually in line with what I expect. WCF is obviously applicable to mobile devices, but WF less so (I would expect to see it on servers rather than clients).</p>
| 33,233
|
<p>I'm writing a C++ client which is using libcurl for communicating with a PHP script.</p>
<p>The communication should be session based, and thus the first task is to login and make the PHP script set up a session.</p>
<p>I'm not used to working with sessions either from C++ or PHP. I basically know that it has to do with cookies and communicating session id.</p>
<p>I can't find any example on the curl homepage which demonstrates a simple session management use case.</p>
<p>I'm assuming it has something to do with one or many of the following options in curl:</p>
<pre><code>CURLOPT_COOKIE
CURLOPT_COOKIEFILE
CURLOPT_COOKIEJAR
CURLOPT_COOKIESESSION
CURLOPT_COOKIELIST
</code></pre>
<p>But I can't really see the big picture just from the documentation of CURLOPT_COOKIESESSION for instance.</p>
<p>Anybody who has done this, please share a simple piece of code which shows the concept.</p>
<p>Regards</p>
<p>Robert</p>
|
<p>As far as I understand it, CURL will handle session cookies automatically for you if you enable cookies, as long as you reuse your CURL handle for each request in the session:</p>
<pre><code>CURL *Handle = curl_easy_init();
// Read cookies from a previous session, as stored in MyCookieFileName.
curl_easy_setopt( Handle, CURLOPT_COOKIEFILE, MyCookieFileName );
// Save cookies from *this* session in MyCookieFileName
curl_easy_setopt( Handle, CURLOPT_COOKIEJAR, MyCookieFileName );
curl_easy_setopt( Handle, CURLOPT_URL, MyLoginPageUrl );
assert( curl_easy_perform( Handle ) == CURLE_OK );
curl_easy_setopt( Handle, CURLOPT_URL, MyActionPageUrl );
assert( curl_easy_perform( Handle ) == CURLE_OK );
// The cookies are actually saved here.
curl_easy_cleanup( Handle );
</code></pre>
<p>I'm not positive that you need to set both COOKIEFILE and COOKIEJAR, but the documentation makes it seem that way. In any case, you have to set one of the two in order to enable cookies at all in CURL. You can do something as simple as:</p>
<pre><code>curl_easy_setopt( Handle, CURLOPT_COOKIEFILE, "" );
</code></pre>
<p>That won't read any cookies from disk, but it will enable session cookies for the duration of the curl handle.</p>
|
<p>A session in PHP has the purpose of preserving some state over several requests, since HTTP in itself is stateless. To get a session from PHP, simply request a php page that starts a session, and keep the cookie you get back for subsequent requests.</p>
<p>Starting a session in php is simple - call the session_start() function. That function will resume an existsing session if the cookie exists in the request. When the session is started, persistent variables can be set using the superglobal array $_SESSION. It's a good idea to store a 'is logged in'-token there =) To end the PHP session, set $_SESSION to array(), so that the token is destroyed.</p>
| 24,954
|
<p>I need a SQL query that returns ContactDate, SortName, City, ContactType, and Summary from the tables below. If any value is null, I need it to return the text “No Entry”.</p>
<p><strong>ContactTable</strong></p>
<ul>
<li><em>ContactID</em></li>
<li>ContactDate </li>
<li>UserID </li>
<li>Summary </li>
<li>ContactType</li>
<li>SortName</li>
</ul>
<p><strong>UserTable</strong></p>
<ul>
<li><em>UserID</em></li>
<li>FirstName</li>
<li>LastName </li>
<li>AddressID</li>
</ul>
<p><strong>AddressTable</strong></p>
<ul>
<li><em>AddressID</em></li>
<li>City</li>
<li>Street </li>
<li>State</li>
<li>Zip</li>
</ul>
|
<pre><code>SELECT COALESCE(CAST(CONVERT(VARCHAR(10), ContactTable.ContactDate, 101) AS VARCHAR(10)), 'No Entry') AS ContactDate,
COALESCE(ContactTable.SortName, 'No Entry') AS SortName,
COALESCE(AddressTable.City, 'No Entry') AS City,
COALESCE(ContactTable.ContactType, 'No Entry') AS ContactType
FROM ContactTable
LEFT OUTER JOIN UserTable ON ContactTable.UserID = UserTable.UserID
LEFT OUTER JOIN AddressTable ON UserTable.AddressID = AddressTable.AddressID
</code></pre>
<p><a href="http://www.blackwasp.co.uk/SQLDateTimeFormats.aspx" rel="noreferrer">Here</a> is a chart of SQL DateTime formats for the CONVERT statement above.</p>
|
<p>Using '<strong>IIF</strong>' is an Access DB solution but may work in other DBs.</p>
<pre><code>SELECT IIF(IsNull(Foo), 'No Entry' ,Foo), IIF(IsNull(Bar), 'No Entry' ,Bar) From TableName
</code></pre>
<p>The function IIF returns one of 2 values depends of the evaluation of an expression.<br>
SQL Syntax:
IIF( expression, true-value1, false-value ) </p>
| 25,326
|
<p>Is the sorting algorithm used by .NET's <code>Array.Sort()</code> method a <a href="http://en.wikipedia.org/wiki/Stable_sort#Classification" rel="noreferrer">stable</a> algorithm?</p>
|
<p>From <a href="http://msdn.microsoft.com/en-us/library/6tf1f0bc.aspx" rel="noreferrer">MSDN</a>:</p>
<blockquote>
<p>This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. In contrast, a stable sort preserves the order of elements that are equal.</p>
</blockquote>
<p>The sort uses introspective sort. (Quicksort in version 4.0 and earlier of the .NET framework).</p>
<p>If you need a stable sort, you can use <a href="http://msdn.microsoft.com/en-us/library/bb534966.aspx" rel="noreferrer">Enumerable.OrderBy</a>.</p>
|
<p><strong>UPDATE:</strong> This code not stabilizing Array.Sort (ensure that the elements are always sorted in the same order):</p>
<pre><code>public static class ComparisonExtensions
{
public static Comparison<T> WithGetHashCode<T>(this Comparison<T> current)
{
return (x, y) =>
{
var result = current(x, y);
if (result == 0)
return x.GetHashCode() - y.GetHashCode();
return result;
};
}
}
</code></pre>
<p>Use:</p>
<pre><code>Comparison<Person> comparison = (x, y) => x.BirthYear.CompareTo(y.BirthYear);
Array.Sort(unstable, comparison.WithGetHashCode());
</code></pre>
| 17,840
|
<p>I am building application that required some data from iPhone's Call log(read only).
The call log is a sqlite db located at "<em>/User/Library/CallHistory/call_history.db</em>". I used a jailbroken device to extract the log.
However trying to open this location using the <em>sqlite_open3()</em> command I get a <em>SQLITE_ERROR</em> error, which according to the library documentation means "SQL error or missing database". In an attempt to debug the error I've used NSFileManager to enumerate the folder('/User/Library/'). It would appear as if it's returning a "filtered" set of results, that exclude the 'CallHistory' folder along with several of the other folders. </p>
<p>The File system uses a series of alias to give the illusion of tradition OS X file structure, and I don't know if these are having an effect on my results.</p>
<p><strong>The call log is only present on a device, and not the simulator</strong>. I've been unable to get it to work on a 1st gen iPhone running fireware 2.1.</p>
<p>This is some code I used to test the output</p>
<pre><code>NSDirectoryEnumerator *dirnum = [[NSFileManager defaultManager] enumeratorAtPath: @"/private/var/mobile/Library/"];
while( bar = [dirnum nextObject])
{
//Uncomment if you don't want to log sub folders
//[dirnum skipDescendents];
NSLog(bar);
}
</code></pre>
<p>I have a suspicion that Apple is blocking access to the directory as part of its sandboxing strategy, however I have no proof at this stage. However, I can access the address book without any issues, so I'm a little confused.</p>
<p>Thanks</p>
|
<p>There is no access to the call log from Cocoa Touch or other iPhone APIs.</p>
|
<p>Honestly, how can you imagine they would let you access the whole Call log? How about you transmit it over the Internet once you have fetched it and make good use of this information?</p>
| 44,407
|
<p>I'm trying to model the threads of a "Poland Spring" 500 ml bottle so I can 3D print an adapter for it. But I can't find information about it. I emailed them but they said they didn't have the information.</p>
<p>How can I find this information out?</p>
<p>The bottle seems to use non standard threads. It uses 3 threads 120 degrees apart that does not go all the way around. Any information on how to get this information?</p>
<p><a href="https://i.stack.imgur.com/nEnwV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nEnwV.png" alt="bottle" /></a></p>
|
<p>You can use a program known as <a href="http://www.openscad.org/" rel="nofollow noreferrer">OpenSCAD</a> with the <a href="https://dkprojects.net/openscad-threads/" rel="nofollow noreferrer">threads library</a> to assist your objective.</p>
<p>The important aspects of a thread are the major diameter (outside diameter at the thread surface), the length of the bolt/nut and for your project, the start count. The noted library has a parameter called n-starts, which covers your triple start requirement.</p>
<p>It may require some trial and error processing, but you have a good foundation with OpenSCAD library.</p>
<p>Even if the bottle is manufactured with Imperial reference (unlikely), you'd probably have an easier time with metric threads. I just checked a Dasani water bottle, which measured at 27.27 mm major diameter, 10 mm length, thread pitch 2 mm. The thread pitch in metric is the distance between peaks (or valleys) from one to the next. This particular bottle has an interrupted thread, but that should not be a factor for creating an adapter.</p>
<p>This Dasani bottle does not have a multi-start thread. It's not a complete thread, but it is single start. Considering that a water bottle top has minimal length, you may also have an interrupted rather than a multi-start thread.</p>
<p>The code for the measured thread in OpenSCAD is relatively simple.</p>
<blockquote>
<p>use <threads.scad>;<br />
thread_dia = 27.27;<br />
thread_pitch = 2;<br />
thread_length = 10;<br />
metric_thread(thread_dia, thread_pitch, thread_length, n_starts = 3);</p>
</blockquote>
<p>The above code would generate a 3-start thread in the form of a bolt. Using a difference() code would provide for the inverse required for your proposed adapter.</p>
<p><a href="https://i.stack.imgur.com/bvliP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bvliP.png" alt="single start 27 mm threads" /></a></p>
<p><a href="https://i.stack.imgur.com/i4vsS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/i4vsS.png" alt="triple start threads" /></a></p>
<p>top image is single start, bottom is triple start.</p>
<p>Top view comparison:</p>
<p><a href="https://i.stack.imgur.com/0oGnP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0oGnP.png" alt="comparison top view" /></a></p>
|
<p>It's really unlikely that a bottle is using nonstandard threads; the engineering and tooling cost for doing so would not make sense. Most plastic drink bottles use PCO 1881 or PCO 1810 threads. If not, it should be one of a number of other less widely used standards.</p>
<p>The industry term for drink bottle thread is "neck finish". Searching on that, or on one of the standard names like PCO 1881, will find you a lot of information. You can then try to find a match for your threads. Note that the breaks 120 degrees apart do not affect the thread design, and may or may not be part of the neck finish standard, so you can ignore them.</p>
<p>There are existing OpenSCAD libraries for some of these, including</p>
<ul>
<li><a href="https://github.com/adrianschlatter/threadlib#list-of-supported-threads" rel="nofollow noreferrer">threadlib</a></li>
<li><a href="https://github.com/MisterHW/IoP-satellite" rel="nofollow noreferrer">IoP-satellite</a></li>
</ul>
<p>And some related articles on Hackaday about their development and use:</p>
<ul>
<li><a href="https://hackaday.com/2020/07/12/learn-the-secrets-of-matching-bottle-cap-threads-to-one-another/" rel="nofollow noreferrer">Learn The Secrets Of Matching Bottle Cap Threads To One Another</a></li>
<li><a href="https://hackaday.io/page/5252-generating-nice-threads-in-openscad" rel="nofollow noreferrer">Generating Nice Threads in OpenSCAD</a></li>
</ul>
| 1,721
|
<p>How do you add a JAR file to an already existing Java library in Eclipse? Note that this is not a user library.</p>
<p>That is, if you look at the Java Build Path for a Java project and click on the Libraries tab, you will see the list of libraries used by the project. If you expand a given library, you will see a list of JAR files included in that library. I want to add an additional JAR file to one of these libraries.</p>
<p>I am using Version 3.4.0 of Eclipse.</p>
|
<p>In eclipse Galileo :</p>
<ul>
<li>Open the project's properties</li>
<li>Select <em>Java Build Path</em></li>
<li>Select <em>Libraries</em> tab</li>
</ul>
<p>From there you can Add External Jars</p>
|
<p>You might also consider using a build tool like Maven to manage your dependencies. It is very easy to setup and helps manage those dependencies automatically in eclipse. Definitely worth the effort if you have a large project with a lot of external dependencies.</p>
| 21,588
|
<p>I am a bit confused in what the application controller should do? Because I see the functionality will also exists in your MVP pattern to make the decisions which form should be shown when a button is clicked? Are there any good examples for Windows Forms that uses the application controller pattern?</p>
<p>There is a difference in the MVC(ontroler) and the Application Controller. I know the MVC(ontroller), I am not sure what is the responsibilities for an Application Controller, and how does it fit into a WinForms application. Martin Fowler also calls this the Application Controller pattern, surely it is not the same thing as the MVC(ontroller)?</p>
|
<p>I recently wrote an article on creating and using an ApplicationController in a C# Winforms project, to decouple the workflow and presenters from the forms directly. It may help:</p>
<p><a href="http://www.lostechies.com/blogs/derickbailey/archive/2009/04/18/decoupling-workflow-and-forms-with-an-application-controller.aspx" rel="nofollow noreferrer">Decoupling Workflow And Forms With An Application Controller</a></p>
<p><strong>edit:</strong><br>
Archive.org has got a <a href="https://web.archive.org/web/20100414033935/http://www.lostechies.com/blogs/derickbailey/archive/2009/04/18/decoupling-workflow-and-forms-with-an-application-controller.aspx" rel="nofollow noreferrer">more readable copy of the article</a> at this time.</p>
|
<p>Personally I have no experience with MVP or winforms, but I have worked with MVC. I hope this is what you're asking, otherwise ignore my answer completely.</p>
<p>The C in MVC is responsible for more than just choosing the next view to be presented to the client. It holds most, preferably <b>all</b>, business-logic of the application, including performance of system tasks (such as logging and enforcement of permissions upon the flow of data from the model and to it).</p>
<p>Its primary task is, naturally, to serve the presentation layer above it and separate it from the model layer below while mediating between them. I guess you can think of it as the brain of the application.</p>
<p>Hope this helps,</p>
<p>Yuval =8-)</p>
| 14,687
|
<p>How do type casting happen without loss of data inside the compiler?</p>
<p>For example:</p>
<pre><code> int i = 10;
UINT k = (UINT) k;
float fl = 10.123;
UINT ufl = (UINT) fl; // data loss here?
char *p = "Stackoverflow Rocks";
unsigned char *up = (unsigned char *) p;
</code></pre>
<p>How does the compiler handle this type of typecasting? A low-level example showing the bits would be highly appreciated.</p>
|
<p>Well, first note that a cast is an <em>explicit request to convert a value of one type to a value of another type</em>. A cast will also always produce a new object, which is a temporary returned by the cast operator. Casting to a reference type, however, will not create a new object. The object referenced by the value is reinterpreted as a reference of a different type. </p>
<p>Now to your question. Note that there are two major types of conversions:</p>
<ul>
<li><em>Promotions</em>: This type can be thought of casting from a possibly more narrow type to a wider type. Casting from char to int, short to int, float to double are all promotions. </li>
<li><em>Conversions</em>: These allow casting from long to int, int to unsigned int and so forth. They can in principle cause loss of information. There are rules for what happens if you assign a <code>-1</code> to an unsigned typed object for example. In some cases, a wrong conversion can result in undefined behavior. If you assign a double larger than what a float can store to a float, the behavior is not defined. </li>
</ul>
<p>Let's look at your casts:</p>
<pre><code>int i = 10;
unsigned int k = (unsigned int) i; // :1
float fl = 10.123;
unsigned int ufl = (unsigned int) fl; // :2
char *p = "Stackoverflow Rocks";
unsigned char *up = (unsigned char *) p; // :3
</code></pre>
<ol>
<li>This cast causes a conversion to happen. No loss of data happens, since 10 is guaranteed to be stored by an <code>unsigned int</code>. If the integer were negative, the value would basically wrap around the maximal value of an unsigned int (see <strong>4.7/2</strong>). </li>
<li>The value <code>10.123</code> is truncated to 10. Here, it <em>does</em> cause lost of information, obviously. As 10 fits into an unsigned int, the behavior is defined. </li>
<li>This actually requires more attention. First, there is a deprecated conversion from a string literal to <code>char*</code>. But let's ignore that here. (see <a href="https://stackoverflow.com/questions/308279/c-vs#308724">here</a>). More importantly, what does happen if you cast to an unsigned type? Actually, the result of that is unspecified per <strong>5.2.10/7</strong> (note the semantics of that cast is the same as using reinterpret_cast in this case, since that is the only C++ cast being able to do that):</li>
</ol>
<blockquote>
<p>A pointer to an object can be explicitly converted to a pointer to
an object of different type. Except that converting an rvalue of type “pointer to T1” to the type "pointer to T2" (where T1 and T2 are object types and where the alignment requirements of T2 are no stricter than those of T1) and back to its original type yields the original pointer value, the result of such a pointer conversion is unspecified.</p>
</blockquote>
<p>So you are only safe to use the pointer after you cast back to <code>char *</code> again. </p>
|
<p>Casts mean different things depending on what they are. They can just be renamings of a data type, with no change in the bits represented (most casts between integral types and pointers are like this), or conversions that don't even preserve length (such as between double and int on most compilers). In many cases, the meaning of a cast is simply unspecified, meaning the compiler has to do something reasonable but doesn't have to document exactly what.</p>
<p>A cast doesn't even need to result in a usable value. Something like <code>
char * cp;
float * fp;
cp = malloc(100);
fp = (float *)(cp + 1);</code>
will almost certainly result in a misaligned pointer to float, which will crash the program on some systems if the program attempts to use it.</p>
| 44,230
|
<p>I need a webserver to serve up very simple POST/GET requests as JSON. I don't need MVC, Rails, Django. I need something that takes up very little memory, preferrably around 5K per reqeust. The webserver will talk to backend services like Scribe using Facebook Thrift. Each http request will also access a SQLLite database, one for each user and user's data do not overlap. It will serve up static html files as well as the json webservice.</p>
<p>I am considering the following:</p>
<ul>
<li>Njinx with PHP,</li>
<li>Kepler from Lua,</li>
<li>rolling my own with libevent or libev perhaps calling out to Lua, or</li>
<li>MochiWeb.</li>
</ul>
<p>Which of these options are best and what other options are out there? I can use PHP, python, or Lua for basic scripting and even could do basic C. I am leaning towards some sort of Erlang solution.</p>
|
<p>I've had a good experience with nginx (<a href="https://nginx.org/" rel="nofollow noreferrer">https://nginx.org/</a>), that said, when choosing a webserver, you should look closely at your requirements and make an informed decision as these things can be very application specific.</p>
<p>You'll notice that in this question that a lot of people recommend g-wan, Webmachine, etc... these are all things you should look at and benchmark to see if they are faster for your use case.</p>
<p>This is the kind of question that encourages cheerleading, there is no "right answer".</p>
|
<p>Take a look at klone at koanlogic.com site ... being targeted at embedded systems it's very small, and incidentally very fast too: <a href="http://john.freml.in/teepeedee2-vs-klone" rel="nofollow noreferrer">http://john.freml.in/teepeedee2-vs-klone</a> .
It can be scripted in C/C++ (ultra performant) or usual PHP/CGI (a lot less performant), depending on skills/taste ...</p>
| 30,974
|
<p>Haven't fired up reflector to look at the difference but would one expect to see the exact same compiled code when comparing <code>Func<T, bool></code> vs. <code>Predicate<T></code> </p>
<p>I would imagine there is no difference as both take a generic parameter and return bool?</p>
|
<p>They share the same signature, but they're still different types.</p>
|
<p>Even without generics, you can have different delegate types that are identical in signatures and return types. For example:</p>
<pre><code>namespace N
{
// Represents a method that takes in a string and checks to see
// if this string has some predicate (i.e. meets some criteria)
// or not.
internal delegate bool StringPredicate(string stringToTest);
// Represents a method that takes in a string representing a
// yes/no or true/false value and returns the boolean value which
// corresponds to this string
internal delegate bool BooleanParser(string stringToConvert);
}
</code></pre>
<p>In the above example, the two non-generic types have the same signature and return type. (And actually also the same as <code>Predicate<string></code> and <code>Func<string, bool></code>). But as I tried to indicate, the "meaning" of the two are different.</p>
<p>This is somewhat like if I make two classes, <code>class Car { string Color; decimal Price; }</code> and <code>class Person { string FullName; decimal BodyMassIndex; }</code>, then just because both of them hold a <code>string</code> and a <code>decimal</code>, that doesn't mean they're the "same" type.</p>
| 5,269
|
<p>From C# on a Windows box, is there a way to find out how a process was stopped?
I've had a look at the <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx" rel="nofollow noreferrer">Process</a> class, managed to get a nice friendly callback from the Exited event once I set <code>EnableRaisingEvents = true;</code> but I have not managed to find out whether the process was killed or whether it exited naturally?</p>
|
<p>Fire up Process Monitor (from Sysinternals, part of Microsoft), run your process and let it die, then filter the Process Monitor results by your process name -- you will be able to see everything that it did, including exit codes.</p>
|
<p>You can use the return code of the process for that. If your process returns a non-zero value from its Main method, you can then check whether or not the process exited by itself (the return value matches).</p>
| 8,249
|
<p>I have a web forum that I have coded in Python for the App Engine platform. I have noticed that it is not being indexed well by Google and I am trying to fix that.<br>
I have used Google Webmaster to submit a sitemap with almost 400 URLs but apparently only 8 were indexed!<br>
I even get a warning stating:</p>
<blockquote>
<p>All the URLs in your Sitemap are marked as having dynamic content (the value of is "always"). Because dynamic content is difficult for search engines to crawl and index, this may impact your site's performance in search results. Check your Sitemap to make sure your site information is correct.</p>
</blockquote>
<p>One thing I am considering is the way my URLs are formed. Almost all URLs use arguments and I allocate each post, thread, forum, user etc... an ID.</p>
<p>So for example one of my forums is:</p>
<p><a href="http://silicon.appspot.com/readforum?id=2075" rel="nofollow noreferrer">http://silicon.appspot.com/readforum?id=2075</a></p>
<p>Where the forum's ID is 2075. I have heard this is bad practice so I am considering changing this but I am not sure whether it will make any difference. Could someone give me some hints in relation to how to get Google to index my <em>entire</em> site?</p>
|
<p>The real thing to look out for it stuff like:</p>
<pre><code> http://www.example.com/forum.py?thread=1000
http://www.example.com/forum.py?thread=1000&mode=printer
</code></pre>
<p>The web crawler sees two different URLs with the same content and assume you are trying to do something fishy. You need to make sure your "Print this Page" links have rel="nofollow" in them. The goal is to have only one link per unique set of data on your website.</p>
<p>Forums of course are going to be a problem of duplicate content all the time. But for articles/blogs you should be able to approach a 1:1 ratio of pages to URLs.</p>
|
<p>URL content is part of the picture, but only a small part.</p>
<p>Having the URL say readforum2106 instead of /readforum?id=2106 doesn't do anything, unless someone is searching for the word "readforum". To have the URL really help, you need to include some good search terms in the text, which just doesn't make sense for forums.</p>
<p>I don't think URL mapping is really going to help you much. Maybe you should be looking at ways to dynamically generate a site map?</p>
| 46,618
|
<p>I'm running PHP 5.2.6 on a Windows Server 2003 Enterprise box. IIS is set to deny anonymous access and use Integrated Windows authentication.</p>
<p>I'm using a PHP script to save a file uploaded from a web form. The file is uploaded to a temp folder, the script creates a file name and path depending on other variables from the web form, and then the script uses PHP's move_uploaded_file() to move the temp file to the final location. All that works fine. In short, people are uploading files so everyone in the group can see them and the files are organized by the script.</p>
<p>My problem is that the file in the final location has odd permissions. It is not ending up with permissions from either the temp location or the final location. Both the temp location and final location have the same permissions: full rights for owner and administrations; read and read/execute for 2 specific AD security groups. The final file ends up with only: full rights for owner and administrations. So while the admins and the original uploader have no problem viewing the file, all others in the group get "permission denied" when trying to access it.</p>
<p>Any ideas or suggestions will be greatly appreciated! Thanks!</p>
|
<p>This seems to be an issue with the <code>move_uploaded_file()</code> function:<br>
<a href="http://us3.php.net/move_uploaded_file" rel="nofollow noreferrer">http://us3.php.net/<code>move_uploaded_file</code></a><br>
Take a look at the comments below, take note of Florian's comment about copy().<br>
<br>
Would copy() solve the issue?:<br>
<a href="http://us3.php.net/manual/en/function.copy.php" rel="nofollow noreferrer">http://us3.php.net/manual/en/function.copy.php</a><br></p>
|
<p>This seems to be an issue with the <code>move_uploaded_file()</code> function:<br>
<a href="http://us3.php.net/move_uploaded_file" rel="nofollow noreferrer">http://us3.php.net/<code>move_uploaded_file</code></a><br>
Take a look at the comments below, take note of Florian's comment about copy().<br>
<br>
Would copy() solve the issue?:<br>
<a href="http://us3.php.net/manual/en/function.copy.php" rel="nofollow noreferrer">http://us3.php.net/manual/en/function.copy.php</a><br></p>
| 25,219
|
<p>I have Java and Flash client applications. What is the best way for the two to communicate without special Flash-specific servers such as BlazeDS or Red5? I am looking for a light client-only solution.</p>
|
<p>Well, you can make http requests from flash to any url... so if your java server has a point where it can listen to incoming requests and process XML or JSON, your flash client can just make the request to that url. BlazeDS and Red5 just aim to make it simpler by handling the translation for you making it possible to call the server-side functions transparently.</p>
|
<p>WebORB for Java may be of some help to you. It integrates with your J2EE code.</p>
<p>For more info:
<a href="http://www.themidnightcoders.com/weborb/java/" rel="nofollow noreferrer">http://www.themidnightcoders.com/weborb/java/</a></p>
<p>I'm sorry, I reread your question that you are only looking for a client side solution. In this case, WebORB will not help you. Sorry for the misunderstanding.</p>
| 12,949
|
<p>I'm printing on an Ender 5 with the default flex/magnetic build surface.
I read that PLA and PETG may sometimes be printed without any bed heating at all and also that bed heating is the main contributor to the power consumption of a printer.</p>
<p>As I do see that bed heating definitely helps with the first layer adhesion I did not want to turn it off completely, but I did start experimenting with turning off bed heating after all solid bottom layers have printed (using the ChangeAtZ script in Cura) and so far I haven't seen any negative effects, especially no warping (I am usually printing with a brim or raft; I think that might also help in that regard).</p>
<p>Am I missing something? Why is <em>anyone</em> keeping the bed heated for an entire print?</p>
|
<p>There are three reasons (I can think of):</p>
<ol>
<li><p>A large problem you'd face with allowing the bed to cool after first layer is you stand the chance of losing adhesion after it cools. When you heat the bed, it expands somewhat. When it cools it contracts. It has been known for parts to actually pop off the bed if left on there to cool (after a print). If you allow the bed to cool fully, you could ruin a print due to it losing the adhesion, popping off the bed, then the printer keeps on going. </p></li>
<li><p>When you're dealing with 0.1 mm layer height, that's not a lot of wiggle room. When you level your bed before printing, it should be done after everything is heated. If you were to turn off the bed after you start printing, you could very easily shift the bed enough to take up the worth of an entire layer, which means your print has adjusted and will then have major imperfections. This isn't a <em>given</em>, but definitely a concern ... especially for larger or taller prints.</p></li>
<li><p>Whether PLA or PETG, the extruded filament needs to have heat in order to stay. This is not only heat in the extruder, but heat in the print itself. If the print cools off, this could affect subsequent adhesion for the filament getting laid down. If you turn the bed heater off after print start, you'll lose that heated environment. The print will cool off and you'll start seeing variations in the print, which, if the print is large enough, would most likely be more noticable. Think of it as a heated environment, not just putting piling host plastic on top of each other.</p></li>
</ol>
<p>There may be other reasons, but I believe these are <em>very good</em> reasons not to turn your bed off after print start. If you are worried your power supply isn't providing enough power, then get a bigger power supply. If you're worried about power consumption overall, once the bed is heated, consumption goes way down (as @r_ahlskog stated in their answer). </p>
|
<p>A way to save energy would be use a pretty tight enclosure around the printer, I think a pretty thin layer of insulation would be enough to reduce power usage by a large factor. I've not build one myself yet but there seems to be so many benefits.</p>
| 1,426
|
<pre><code>#include<iostream>
using namespace std;
class A
{
int a;
int b;
public:
void eat()
{
cout<<"A::eat()"<<endl;
}
};
class B: public A
{
public:
void eat()
{
cout<<"B::eat()"<<endl;
}
};
class C: public A
{
public:
void eat()
{
cout<<"C::eat()"<<endl;
}
};
class D: public B, C
{
};
int foo(A *ptr)
{
ptr->eat();
}
main()
{
D obj;
foo(&(obj.B)); //error. How do i call with D's B part.
}
</code></pre>
<p>The above foo call is a compile time error.
I want to call foo with obj's B part without using virtual inheritance. How do i do that. </p>
<p>Also, in case of virtual inheritance, why the offset information need to be stored in the vtable. This can be determined at the compile time itself. In the above case, if we pass foo with D's object, at compile time only we can calculate the offset of D's A part. </p>
|
<h2>Inheriting twice</h2>
<p>With double inheritance you have an ambiguity - the compiler cannot know which of the two A bases do you want to use. If you want to have two A bases (sometimes you may want to do this), you may select between them by casting to B or C. The most appropriate from default casts here is the <code>static_cast</code> (as the weakest available), however it is not realy needed (it is still stronger than your case needs), as you are not casting to a derived type. A custom <code>safe_cast</code> template should do the job:</p>
<pre><code>/// cast using implicit conversions only
template <class To,class From>
inline To safe_cast( const From &from ) {return from;}
main()
{
D obj;
foo(safe_cast<B *>(&obj)); //error. How do i call with D's B part.
}
</code></pre>
<h2>Compile time types - use templates</h2>
<blockquote>
<p>Also, in case of virtual inheritance,
why the offset information need to be
stored in the vtable. This can be
determined at the compile time itself.
In the above case, if we pass foo with
D's object, at compile time only we
can calculate the offset of D's A
part.</p>
</blockquote>
<p>This is a misconception. The foo function as it is written now has no compile type information about ptr type other than it is A *, even if you pass B * or C*. If you want foo to be able to act based on the type passed compile time, you need to use templates:</p>
<pre><code>template <class TypeDerivedFromA>
int foo(TypeDerivedFromA *ptr)
{
ptr->eat();
}
</code></pre>
<h2>Virtual Inheritance</h2>
<p>Your questions mentions virtual inheritance. If you want to use virtual inheritance, you need to specify so:</p>
<pre><code>class B: public virtual A ...
class C: public virtual A ...
</code></pre>
<p>With this the code would compile, but with this solution there is no way you could select between B::A or C::A (there is only one A), therefore this is probably not what you are about.</p>
<h2>Virtual functions</h2>
<p>Furthermore, your questions seems to be confusing two different concepts, virtual inheritance (which means sharing one base class between two intermediate base classes) and virtual functions (which mean allowing derived class function to be called via base class pointer). If you want the B::eat to be called using A pointer, you can do this without virtual inheritance (actually virtual inheritance would prevent you doing so, as explained above), using virtual functions:</p>
<pre><code>class A
{
int a;
int b;
public:
virtual void eat()
{
cout<<"A::eat()"<<endl;
}
};
</code></pre>
<p>If virtual functions are not acceptable for you, the compile time mechanism for this are templates, as explained above.</p>
|
<p>First of all, <code>obj</code> does not have a member named B. It Inherits from B, which means that it inherits all of B's members as its own.</p>
<p>You can call:</p>
<p><pre><code>foo(static_cast<B*>(&obj));</code></pre> to make it work.</p>
| 49,866
|
<p>I have implemented a YUV to RGB conversion via a fragment shader written in Nvidia's shader language. (Y, U and V are stored in separate textures that are combined via multi texturing in my fragment shader). It works great under OpenGL, but under Direct3D I just can't get the output image to look right. I'm starting to suspect that Direct3D is somehow modifying the Y, U and V samples before I get a chance to do my YUV conversion thing. Does anyone know if Direct3D makes any modifications to the values stored in textures before the fragment shader is run and how to disable them>?</p>
|
<p>We figured it out. :) Basically the problem was that while our YUV to RGB equations were correct, we weren't properly sampling the V data! So no amount of futzing with the equations would have helped!</p>
<p>In the end, I would recommend the following strategy for anyone attempting to do this:</p>
<p>1) Set R, G, and B to the value from Y. You should get a grayscale image (as Y contains just luminance).
2) Next, set R, G, and B to U. You should get funny colors!
3) Finally set R, G, and B to V. Again, you should get funny colors.</p>
<p>Also, properly normalizing the values is critical. Check our fourcc.org for a discussion of proper YUV normalization.</p>
|
<p>The only suggestion that comes to mind is that the textures are in an inappropriate format (low-precision or compressed).</p>
<p>Can you describe in what way the output looks wrong? Any chance of a right vs wrong screenshot?</p>
| 17,493
|
<p>I have a class derived from <code>CTreeCtrl</code>. In <code>OnCreate()</code> I replace the default <code>CToolTipCtrl</code> object with a custom one:</p>
<pre><code>int CMyTreeCtrl::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CTreeCtrl::OnCreate(lpCreateStruct) == -1)
return -1;
// Replace tool tip with our own which will
// ask us for the text to display with a TTN_NEEDTEXT message
CTooltipManager::CreateToolTip(m_pToolTip, this, AFX_TOOLTIP_TYPE_DEFAULT);
m_pToolTip->AddTool(this, LPSTR_TEXTCALLBACK);
SetToolTips(m_pToolTip);
// Update: Added these two lines, which don't help either
m_pToolTip->Activate(TRUE);
EnableToolTips(TRUE);
return 0;
}
</code></pre>
<p>My message handler looks like this:</p>
<pre><code>ON_NOTIFY_EX(TTN_NEEDTEXT, 0, &CMyTreeCtrl::OnTtnNeedText)
</code></pre>
<p>However I never receive a <code>TTN_NEEDTEXT</code> message. I had a look with Spy++ and it also looks like this message never gets sent.</p>
<p>What could be the problem here?</p>
<h2>Update</h2>
<p>I'm not sure whether this is relevant: The <code>CTreeCtrl</code>'s parent window is of type <code>CDockablePane</code>. Could there be some extra work needed for this to work?</p>
|
<p>Finally! I (partially) solved it:</p>
<p>It looks like the CDockablePane parent window indeed caused this problem...</p>
<p>First I removed all the tooltip-specific code from the CTreeCtrl-derived class. Everything is done in the parent pane window.</p>
<p>Then I edited the parent window's <code>OnCreate()</code> method:</p>
<pre><code>int CMyPane::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CDockablePane::OnCreate(lpCreateStruct) == -1)
return -1;
const DWORD dwStyle = WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN |
TVS_CHECKBOXES | TVS_DISABLEDRAGDROP | TVS_HASBUTTONS | TVS_HASLINES | TVS_LINESATROOT |
TVS_INFOTIP | TVS_NOHSCROLL | TVS_SHOWSELALWAYS;
// TREECTRL_ID is a custom member constant, set to 1
if(!m_tree.Create(dwStyle, m_treeRect, this, TREECTRL_ID ) )
{
TRACE0("Failed to create trace tree list control.\n");
return -1;
}
// m_pToolTip is a protected member of CDockablePane
m_pToolTip->AddTool(&m_tree, LPSTR_TEXTCALLBACK, &m_treeRect, TREECTRL_ID);
m_tree.SetToolTips(m_pToolTip);
return 0;
</code></pre>
<p>}</p>
<p>Unforunately we cannot simply call <code>AddTool()</code> with less parameters because the base class will complain in the form of an <code>ASSERT</code> about a <code>uFlag</code> member if there is no tool ID set.
And since we need to set the ID, we also need to set a rectangle. I created a <code>CRect</code> member and set it to <code>(0, 0, 10000, 10000)</code> in the CTor. I have not yet found a working way to change the tool's rect size so this is my very ugly workaround. This is also why I call this solution partial. <strong>Update: <a href="https://stackoverflow.com/questions/867724/how-to-modify-the-tool-rect-of-a-ctooltipctrl">I asked a question regarding this.</a></strong></p>
<p>Finally there is the handler to get the tooltip info:</p>
<pre><code>// Message map entry
ON_NOTIFY(TVN_GETINFOTIP, TREECTRL_ID, &CMobileCatalogPane::OnTvnGetInfoTip)
// Handler
void CMyPane::OnTvnGetInfoTip(NMHDR *pNMHDR, LRESULT *pResult)
{
LPNMTVGETINFOTIP pGetInfoTip = reinterpret_cast<LPNMTVGETINFOTIP>(pNMHDR);
// This is a CString member
m_toolTipText.ReleaseBuffer();
m_toolTipText.Empty();
// Set your text here...
pGetInfoTip->pszText = m_toolTipText.GetBuffer();
*pResult = 0;
}
</code></pre>
|
<p>Try to specifically handle all tooltip ids:</p>
<pre><code>ON_NOTIFY_EX_RANGE(TTN_NEEDTEXT, 0, 0xFFFF, &CMyTreeCtrl::OnNeedTipText)
</code></pre>
<p>If that doesn't work, you may have to manually call RelayEvent() from PreTranslateMessage().</p>
| 33,907
|
<p>If you've used Oracle, you've probably gotten the helpful message "ORA-00942: Table or view does not exist". Is there a legitimate technical reason the message doesn't include the name of the missing object? </p>
<p>Arguments about this being due to security sound like they were crafted by the TSA. If I'm an attacker, I'd know what table I just attempted to exploit, and be able to interpret this unhelpful message easily. If I'm a developer working with a complex join through several layers of application code, it's often very difficult to tell.</p>
<p>My guess is that when this error was originally implemented, someone neglected to add the object name, and now, people are afraid it will break compatibility to fix it. (Code doing silly things like parsing the error message will be confused if it changes.)</p>
<p>Is there a developer-friendly (as opposed to recruiting your DBA) way to determine the name of the missing table?</p>
<hr>
<p>Although I've accepted an answer which is relevant to the topic, it doesn't really answer my question: <em>Why isn't the name part of the error message?</em> If anyone can come up with the real answer, I'll be happy to change my vote.</p>
|
<p>You can set an EVENT in your parameter file (plain text or spfile) to force Oracle to dump a detailed trace file in the user_dump_dest, the object name might be in there, if not the SQL should be.</p>
<p>EVENT="942 trace name errorstack level 12"</p>
<p>If you are using a plain text file you need to keep all your EVENT settings on consecutive lines. Not sure how that applied to spfile.</p>
|
<p>@Matthew</p>
<p>Your query's a start, but it might not work when you have multiple schemas. For example, if I log into our instance as myself, I have read access to all our tables. But if I don't qualify the table name with the schema I'll get an ORA-00942 for tables without synonyms:</p>
<pre>
SQL> select * from tools;
select * from tools
*
ERROR at line 1:
ORA-00942: table or view does not exist
</pre>
<p>The table still shows up in all_tables though:</p>
<pre>
SQL> select owner, table_name from all_tables where table_name = 'TOOLS';
OWNER TABLE_NAME
------------------------------ ------------------------------
APPLICATION TOOLS
</pre>
<p>@erikson
Sorry that doesn't help much. I'm with Mark - I used TOAD.</p>
| 6,850
|
<p>I have a fairly simple const struct in some C code that simply holds a few pointers and would like to initialize it statically if possible. Can I and, if so, how?</p>
|
<p>You can, if the pointers point to global objects:</p>
<pre><code>// In global scope
int x, y;
const struct {int *px, *py; } s = {&x, &y};
</code></pre>
|
<p>But if there is some <code>struct</code> as following:</p>
<pre><code>struct Foo
{
const int a;
int b;
};
</code></pre>
<p>and we want to dynamically create the pointer to the <code>struct</code> using <code>malloc</code>, so can we play the trick:</p>
<pre><code>struct Foo foo = { 10, 20 };
char *ptr = (char*)malloc(sizeof(struct Foo));
memcpy(ptr, &foo, sizeof(foo));
struct Foo *pfoo = (struct Foo*)ptr;
</code></pre>
<p>this is very useful especially when some function needs to return pointer to <code>struct Foo</code></p>
| 24,246
|
<p>You'll have to forgive my ignorance, but I'm not used to using wide character sets in c++, but is there a way that I can use wide string literals in c++ without putting an L in front of each literal?</p>
<p>If so, how?</p>
|
<p>No, there isn't. You have to use the L prefix (or a macro such as _T() with VC++ that expands to L anyway when compiled for Unicode).</p>
|
<p>Why do you not want to prefix string literals with an L? It's quite simple - strings without an L are ANSI strings (<code>const char*</code>), strings with an L are wide-character strings (<code>const wchar_t*</code>). There is the <code>TEXT()</code> macro, which makes a string literal into an ANSI or a wide-character string depending on of the current project is set to use Uncode:</p>
<pre><code>
#ifdef UNICODE
#define TEXT(s) L ## s
#else
#define TEXT(s) s
#endif
</code></pre>
<p>There's also the <code>_T()</code> macro, which is equivalent to <code>TEXT()</code>.</p>
| 32,506
|
<p>How do I set the date/time of the computer in C#?</p>
|
<p>You can set the date using <a href="http://msdn.microsoft.com/en-us/library/9z20y6ha(VS.80).aspx" rel="nofollow noreferrer">Microsoft.VisualBasic.Today</a> and <a href="http://msdn.microsoft.com/en-us/library/8hhbhw4c(VS.80).aspx" rel="nofollow noreferrer">Microsoft.VisualBasic.TimeOfDay</a>, although they're subject to security restrictions.</p>
<p>Yes, it's strange accessing the Microsoft,VisualBasic namespace, but there doesn't appear to be a C# equivalent.</p>
|
<p>You will need to call the <a href="http://www.pinvoke.net/default.aspx/kernel32.SetSystemTime" rel="nofollow noreferrer">SetSystemTime</a> Win32 API function through P/Invoke.</p>
| 35,226
|
<p>I read in <a href="http://www.ddj.com/hpc-high-performance-computing/210605281" rel="noreferrer">this article </a> that a company has created a software capable of using multiple GPU-based video cards in parallel to process hundreds of billions fixed-point calculations per second.</p>
<p>The program seems to run in Windows. Is it possible from Windows to assign a thread to a GPU? Do they create their own driver and then interact with it? Any idea of how they do it?</p>
|
<p>I imagine that they are using a language like <a href="http://en.wikipedia.org/wiki/CUDA" rel="nofollow noreferrer">CUDA</a> to program the critical sections of code on the GPUs to accelerate their computation.</p>
<p>The main function for the program (and its threads) would still run on the host CPU, but data are shipped off the the GPUs for processing of advanced algorithms. CUDA is an extension to C syntax, so it makes it easier to programmer than having to learn the older shader languages like <a href="http://en.wikipedia.org/wiki/Cg_(programming_language)" rel="nofollow noreferrer">Cg</a> for programming general purpose calculations on a GPU.</p>
|
<p>A good place to start - <a href="http://en.wikipedia.org/wiki/GPGPU" rel="nofollow noreferrer">GPGPU</a></p>
<p>Also, for the record, I don't think there is such a thing as non-GPU based graphic cards. GPU stands for graphics processing unit which is by definition the heart of a graphics card.</p>
| 19,959
|
<p>I'm trying to search multiple attributes in XML :</p>
<pre><code><APIS>
<API Key="00001">
<field Username="username1" UserPassword="password1" FileName="Filename1.xml"/>
<field Username="username2" UserPassword="password2" FileName="Filename2.xml"/>
<field Username="username3" UserPassword="password3" FileName="Filename3.xml"/>
</API>
</APIS>
</code></pre>
<p>I need to check if in the "field" the Username AND UserPassword values are both what I am comparing with my Dataset values, is there a way where I can check multiple attributes (AND condition) without writing my own logic of using Flags and breaking out of loops. </p>
<p>Is there a built in function of XMLDoc that does it? Any help would be appreciated! </p>
|
<p>To search for what you want in the snippet of XML you provided, you would need the following XPath expression:</p>
<pre><code>/APIS/API/field[@Username='username1' and @UserPassword='password1']
</code></pre>
<p>This would either return something, if user name and password match - or not if they don't.</p>
<p>Of couse the XPath expression is just a string - you can build it dynamically with values that were entered into a form field, for example.</p>
<p>If you tell what language/environment you are in, code samples posted here will likely get more specific.</p>
<p>This is a way to do it in C# (VB.NET is analogous):</p>
<pre><code>// make sure the following line is included in your class
using System.Xml;
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load("your XML string or file");
string xpath = "/APIS/API/field[@Username='{0}' and @UserPassword='{1}']";
string username = "username1";
string password = "password1";
xpath = String.Format(xpath, username, password);
XmlNode userNode = xmldoc.SelectSingleNode(xpath);
if (userNode != null)
{
// found something with given user name and password
}
else
{
// username or password incorrect
}
</code></pre>
<p>Be aware that neither user names nor passwords can contain single quotes, or the above example will fail. Here is <a href="http://kushalm.com/the-perils-of-xpath-expressions-specifically-escaping-quotes" rel="noreferrer">some info on this peculiarity</a>.</p>
<p>There is also a How-To from Microsoft available: <a href="http://support.microsoft.com/kb/318499" rel="noreferrer">HOW TO: Use the System.Xml.XmlDocument Class to Execute XPath Queries in Visual C# .NET</a></p>
|
<p>To search for multiple attributes in case of XML tag, we can use the following XPATH
/APIS/API/field[@Username='username1'][@UserPassword='password1'] </p>
| 46,094
|
<p>I'm looking for a technique or tool which we can use to obfuscate or somehow secure our compiled c# code. The goal is not for user/data security but to hinder reverse engineering of some of the technology in our software. </p>
<p>This is not for use on the web, but for a desktop application.</p>
<p>So, do you know of any tools available to do this type of thing? (They need not be free)</p>
<p>What kind of performance implications do they have if any?</p>
<p>Does this have any negative side effects when using a debugger during development?</p>
<p>We log stack traces of problems in the field. How would obfuscation affect this?</p>
|
<p>This is a pretty good list of obfuscators from <a href="https://marketplace.visualstudio.com/search?term=.net%20obfuscators&target=VS&category=All%20categories&vsVersion=&sortBy=Relevance" rel="noreferrer">Visual Studio Marketplace</a>
Obfuscators</p>
<ul>
<li><a href="https://www.armdot.com/" rel="noreferrer">ArmDot</a></li>
<li><a href="http://www.ssware.com/cryptoobfuscator/obfuscator-net.htm" rel="noreferrer">Crypto Obfuscator</a></li>
<li><a href="http://www.wiseowl.com/products/products.aspx" rel="noreferrer">Demeanor</a> for .NET</li>
<li><a href="http://xheo.com/products/code-protection" rel="noreferrer">DeployLX CodeVeil</a></li>
<li><a href="http://www.preemptive.com/" rel="noreferrer">Dotfuscator</a> .NET Obfuscator</li>
<li><a href="http://www.semdesigns.com/products/obfuscators/csharpobfuscator.html" rel="noreferrer">Semantic Designs</a>: C# Source Code Obfuscator</li>
<li><a href="http://www.smartassembly.com" rel="noreferrer">Smartassembly</a></li>
<li><a href="http://www.9rays.net/Products/Spices.Net/" rel="noreferrer">Spices.Net</a></li>
<li><a href="http://www.xenocode.com/Products/Postbuild/" rel="noreferrer">Xenocode</a> Postbuild 2006</li>
<li><a href="http://www.eziriz.com/" rel="noreferrer">.NET Reactor</a></li>
</ul>
<p>I have not observed any performance issues when obfuscating my code. If your just sending text basted stack traces you might have a problem translating the method names.</p>
|
<p>You are wasting your time going down that path. If you have code that you don't want anyone to see, you need to keep it behind closed doors. For example, only execute that code on your own server using a web service interface.</p>
<p>Obfuscating your code only deters the most casual of people. As the video game industry leaned a long time ago, no code is safe from cracking.</p>
| 8,465
|
<p>OK, I am trying to generate the rDoc for paperclip, but the rake task is choking on another plugin before it gets to it, so this is out of the question:</p>
<pre><code>rake doc:plugins
</code></pre>
<p>I could go and fix up the broken plugin, but I'm busy and lazy, so I just want to generate the docs for paperclip. Is there any way of doing this?</p>
|
<p>Unbelievably, I've just figured it out!</p>
<pre><code>rake doc:plugins:paperclip
</code></pre>
<p>That was simple.</p>
|
<p>You can always just run rdoc from the plugin's individual directory. This wouldn't include it in your project's /doc folder, but it would create a /doc folder inside the plugin which you can browse</p>
| 30,599
|
<p>I am extending a class defined in a library which I cannot change:</p>
<pre><code>public class Parent
{
public void init(Map properties) { ... }
}
</code></pre>
<p>If I am defining a class 'Child' that extends Parent and I am using Java 6 with generics, what is the best way to override the init method without getting unchecked warnings?</p>
<pre><code>public class Child extends Parent
{
// warning: Map is a raw type. References to generic type Map<K,V> should be parameterized
public void init(Map properties) { }
}
</code></pre>
<p>If I add generic parameters, I get:</p>
<pre><code> // error: The method init(Map<Object,Object>) of type Child has the same erasure as init(Map) of type Parent but does not override it
public void init(Map<Object,Object>) { ... }
// same error
public void init(Map<? extends Object,? extends Object>) { ... }
// same error
public void init(Map<?,?>) { ... }
</code></pre>
<p>This error occurs regardless of whether I use a specific type, a bounded wildcard, or an unbounded wildcard. Is there a correct or idiomatic way to override a non-generic method without warnings, and without using @SuppressWarnings("unchecked")?</p>
|
<p>Yes, you have to declare the overriding method with the same signature as in the parent class, without adding any generics info.</p>
<p>I think your best bet is to add the <code>@SuppressWarnings("unchecked")</code> annotation to the raw-type parameter, not the method, so you won't squelch other generics warnings you might have in your own code.</p>
|
<p>You have to declare the method with the same signature as the parent, and therefore you will get warnings when you compile. You can suppress them with @SuppressWarnings("unchecked")</p>
<p>The reason why there is no way to get rid of this is that the warnings are there to let you know that it's possible to create Collections with invalid types in them. The warnings should only go away when all code that might allow that has been removed. Since you are inheriting from a non-generic class it will always be possible to create a Collection with invalid contents. </p>
| 29,898
|
<p>I have been using netbeans as a tool for my java, and i have a problem. I read <a href="http://www.netbeans.org/kb/61/java/gui-db-custom.html" rel="nofollow noreferrer">this tutorial</a> and then i tried to create a table using this SQL:</p>
<pre><code>CREATE TABLE CUSTOMERS (
ID INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
FIRST_NAME VARCHAR(20),
LAST_NAME VARCHAR(30),
ADDRESS VARCHAR(30),
CITY VARCHAR(30),
STATE_ VARCHAR(30),
ZIP VARCHAR(15),
COUNTRY_ID INTEGER,
PHONE VARCHAR(15),
EMAIL_ADDRESS VARCHAR(50)
)ENGINE=INNODB;
</code></pre>
<p>When i tried to run it, I got this error message:</p>
<blockquote>
<p>sql state 42X01 : Syntax error :
encountered "AUTO_INCREMENT" at line 2
column 29</p>
</blockquote>
<p>and when i delete the AUTO_INCREMENT, another error:</p>
<blockquote>
<p>detected ENGINE=INNODB;</p>
</blockquote>
<p>can someone help me? Thanks.</p>
|
<p>You seem to be using MySQL syntax with another database engine. The parts it complained about are precisely the MySQL-specific ones.</p>
|
<p>Been a long time but if anybody else stumbles on this like I did, a solution that worked for me is instead of using <code>auto_increment</code>, describe the ID column as </p>
<p><code>ID INTEGER GENERATED ALWAYS AS IDENTITY, WHATEVER VARCHAR(20), ETC ETC...</code></p>
| 34,812
|
<pre><code> <object height="25" width="75" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000">
<param value="http://click-here-to-listen.com/players/iaPlay13.swf?x=1058286910FTRZGK" name="movie"/>
<param value="high" name="quality"/>
<param value="#FFFFFF" name="bgcolor"/>
<param value="opaque" name="wmode"/>
<embed height="25" width="75" wmode="opaque" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" bgcolor="#FFFFFF" quality="high" src="http://click-here-to-listen.com/players/iaPlay13.swf?x=1058286910FTRZGK"/>
</object>
</code></pre>
<p>I am having to insert this legacy markup into a new site that I'm building. Problem is its using an <code><embed></code> tag. </p>
<p>Would I just do away with the <code><embed></code> and put some content in as an alternative, for those that do not have flash? Basically I'm just trying to bring this piece of html into the 21st century.</p>
|
<p>You can nest object elements to display alternatives. The W3C explains it <a href="http://www.w3.org/TR/html401/struct/objects.html#h-13.3" rel="nofollow noreferrer">here</a>. I copied a snippet below:</p>
<blockquote>
<p>One significant consequence of the OBJECT element's design is that it offers a mechanism for specifying alternate object renderings; each embedded OBJECT declaration may specify alternate content types. If a user agent cannot render the outermost OBJECT, it tries to render the contents, which may be another OBJECT element, etc.</p>
<p>In the following example, we embed several OBJECT declarations to illustrate how alternate renderings work. A user agent will attempt to render the first OBJECT element it can, in the following order: (1) an Earth applet written in the Python language, (2) an MPEG animation of the Earth, (3) a GIF image of the Earth, (4) alternate text.</p>
</blockquote>
<pre><code><P> <!-- First, try the Python applet -->
<OBJECT title="The Earth as seen from space"
classid="http://www.observer.mars/TheEarth.py">
<!-- Else, try the MPEG video -->
<OBJECT data="TheEarth.mpeg" type="application/mpeg">
<!-- Else, try the GIF image -->
<OBJECT data="TheEarth.gif" type="image/gif">
<!-- Else render the text -->
The <STRONG>Earth</STRONG> as seen from space.
</OBJECT>
</OBJECT>
</OBJECT>
</code></pre>
|
<p>I use function AC_FL_RunContent for embedding flash objects - it's good because it supports all browsers and is recommended by Adobe.</p>
<p>More is <a href="http://www.adobe.com/devnet/activecontent/articles/devletter.html" rel="nofollow noreferrer">here</a>:</p>
<p>They also suggest using <object> tag instead of <embed></p>
| 34,266
|
<p>This question comes on the heels of the question asked <a href="https://stackoverflow.com/questions/371/how-do-you-make-sure-email-you-send-programmatically-is-not-automatically-marke">here</a>.</p>
<p>The email that comes from our web server comes from an IP address that is different than that for the Exchange server. Is this okay if the SPF and Domain keys are setup properly?</p>
|
<p>The use of <code>System.exit</code> is frowned upon when the 'application' is really a sub-application (e.g. servlet, applet) of a larger Java application (server): in this case the <code>System.exit</code> could stop the JVM and hence also all other sub-applications. In this situation, throwing an appropriate exception, which could be caught and handled by the application framework/server is the best option.</p>
<p>If the java application is really meant to be run as a standalone application, there is nothing wrong with using <code>System.exit</code>. in this case, setting an exit value is probably the easiest (and also most used) way of communicating failure or success to the parent process.</p>
|
<p>It's frowned upon for <em>normal</em> exits. If "not everything is going according to plan", then System.exit is fine.</p>
<p>Update: I should add that I assume your '1' has meaning that is documented somewhere.</p>
| 5,280
|
<p>I have a Probablistic Neural Network classification experiment set up in MATLAB. I can get the classes for unseen data using the <code>sim</code> command. Is there any way I can get the probabilities for the classes that the classifier calculates? Also, is there any direct way to plot the Reciever Operating Characterstic curve and calculate the Area Under the ROC for my classifier?</p>
|
<p>if you have the Statistics Toolbox, you can use <strong><a href="http://www.mathworks.com/access/helpdesk/help/toolbox/stats/perfcurve.html" rel="nofollow noreferrer">perfcurve</a></strong> function added in recent versions of MATLAB to plot ROC curves and get AUC.</p>
|
<p>You may have better luck getting a response if you include a little more background and define your terms. I recognize ROC as receiver operating characteristic curve, but PNN and AUC are just alphabet soup to me. Don't make the mistake of assuming that someone outside of your very specific problem domain cannot help you. You have to build a bit of a language bridge by explaining your jargon first, though. This has the added advantage of making this particular question more useful to the stackoverflow community at large when it is eventually answered.</p>
| 36,543
|
<p>Anyone know of a good, hopefully free FTP class for use in .NET that can actually work behind an HTTP proxy or FTP gateway? The FtpWebRequest stuff in .NET is horrible at best, and I really don't want to roll my own here.</p>
|
<p>Our <a href="http://www.rebex.net/ftp.net/" rel="nofollow noreferrer">Rebex FTP</a> works with proxies just fine. Following code shows how to connect to the FTP using HTTP proxy (code is taken from <a href="http://www.rebex.net/ftp.net/tutorial-ftp.aspx#proxy" rel="nofollow noreferrer">FTP tutorial page</a>).</p>
<pre><code>// initialize FTP client
Ftp client = new Ftp();
// setup proxy details
client.Proxy.ProxyType = FtpProxyType.HttpConnect;
client.Proxy.Host = proxyHostname;
client.Proxy.Port = proxyPort;
// add proxy username and password when needed
client.Proxy.UserName = proxyUsername;
client.Proxy.Password = proxyPassword;
// connect, login
client.Connect(hostname, port);
client.Login(username, password);
// do some work
// ...
// disconnect
client.Disconnect();
</code></pre>
<p>You can download the trial at <a href="http://www.rebex.net/ftp.net/download.aspx" rel="nofollow noreferrer">www.rebex.net/ftp.net/download.aspx</a></p>
|
<p>System.Net.WebClient can handle ftp urls, and it's a bit easier to work with. You can set credentials and proxy information with it, too.</p>
| 9,930
|
<p>I'm learning functional programming, and have tried to solve a couple problems in a functional style. One thing I experienced, while dividing up my problem into functions, was it seemed I had two options: use several disparate functions with similar parameter lists, or using nested functions which, as closures, can simply refer to bindings in the parent function. </p>
<p>Though I ended up going with the second approach, because it made function calls smaller and it seemed to "feel" better, from my reading it seems like I may be missing one of the main points of functional programming, in that this seems "side-effecty"? Now granted, these nested functions cannot modify the outer bindings, as the language I was using prevents that, but if you look at each individual inner function, you can't say "given the same parameters, this function will return the same results" because they do use the variables from the parent scope... am I right? </p>
<p>What is the desirable way to proceed? </p>
<p>Thanks!</p>
|
<p>Nesting functions is an excellent way to divide up the labor in many functions. It's not really "side-effecty"; if it helps, think of the captured variables as implicit parameters. </p>
<p>One example where nested functions are useful is to replace loops. The parameters to the nested function can act as induction variables which accumulate values. A simple example:</p>
<pre><code>let factorial n =
let rec facHelper p n =
if n = 1 then p else facHelper (p*n) (n-1)
in
facHelper 1 n
</code></pre>
<p>In this case, it wouldn't really make sense to declare a function like <code>facHelper</code> globally, since users shouldn't have to worry about the <code>p</code> parameter.</p>
<p>Be aware, however, that it can be difficult to test nested functions individually, since they cannot be referred to outside of their parent.</p>
|
<p>Consider the following (contrived) Haskell snippet:</p>
<pre><code>putLines :: [String] -> IO ()
putLines lines = putStr string
where string = concat lines
</code></pre>
<p><code>string</code> is a locally bound named constant. But isn't it also a function taking no arguments that closes over <code>lines</code> and is therefore referentially intransparent? (In Haskell, constants and nullary functions are indeed indistinguishable!) Would you consider the above code “side-effecty” or non-functional because of this?</p>
| 40,072
|
<p>I'm new to the MVC framework and wondering how to pass the RSS data from the controller to a view. I know there is a need to convert to an IEnumerable list of some sort. I have seen some examples of creating an anonymous type but can not figure out how to convert an RSS feed to a generic list and pass it to the view. </p>
<p>I don't want it to be strongly typed either as there will be multiple calls to various RSS feeds. </p>
<p>Any suggestions. </p>
|
<p>I've been playing around with a way of doing WebParts in MVC which are basically UserControls wrapped in a webPart container. One of my test UserControls is an Rss Feed control. I use the RenderAction HtmlHelper extension in the Futures dll to display it so a controller action is called. I use the SyndicationFeed class to do most of the work</p>
<pre><code>using (XmlReader reader = XmlReader.Create(feed))
{
SyndicationFeed rssData = SyndicationFeed.Load(reader);
return View(rssData);
}
</code></pre>
<p>Below is the controller and UserControl code:</p>
<p>The Controller code is:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.Xml;
using System.ServiceModel.Syndication;
using System.Security;
using System.IO;
namespace MvcWidgets.Controllers
{
public class RssWidgetController : Controller
{
public ActionResult Index(string feed)
{
string errorString = "";
try
{
if (String.IsNullOrEmpty(feed))
{
throw new ArgumentNullException("feed");
}
**using (XmlReader reader = XmlReader.Create(feed))
{
SyndicationFeed rssData = SyndicationFeed.Load(reader);
return View(rssData);
}**
}
catch (ArgumentNullException)
{
errorString = "No url for Rss feed specified.";
}
catch (SecurityException)
{
errorString = "You do not have permission to access the specified Rss feed.";
}
catch (FileNotFoundException)
{
errorString = "The Rss feed was not found.";
}
catch (UriFormatException)
{
errorString = "The Rss feed specified was not a valid URI.";
}
catch (Exception)
{
errorString = "An error occured accessing the RSS feed.";
}
var errorResult = new ContentResult();
errorResult.Content = errorString;
return errorResult;
}
}
}
</code></pre>
<p>The UserControl</p>
<pre><code><%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Index.ascx.cs" Inherits="MvcWidgets.Views.RssWidget.Index" %>
<div class="RssFeedTitle"><%= Html.Encode(ViewData.Model.Title.Text) %> &nbsp; <%= Html.Encode(ViewData.Model.LastUpdatedTime.ToString("MMM dd, yyyy hh:mm:ss") )%></div>
<div class='RssContent'>
<% foreach (var item in ViewData.Model.Items)
{
string url = item.Links[0].Uri.OriginalString;
%>
<p><a href='<%= url %>'><b> <%= item.Title.Text%></b></a>
<% if (item.Summary != null)
{%>
<br/> <%= item.Summary.Text %>
<% }
} %> </p>
</div>
</code></pre>
<p>with the code behind modified to have a typed Model</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ServiceModel.Syndication;
namespace MvcWidgets.Views.RssWidget
{
public partial class Index : System.Web.Mvc.ViewUserControl<SyndicationFeed>
{
}
}
</code></pre>
|
<p>A rss is a xml file with special format. You may design a dataset with that generic format and read the rss(xml) with ReadXml method and the uri as the path to the file. Then you have got a dataset you can consume from another clases.</p>
| 34,081
|
<p>I think it can be done by applying the transformation matrix of the scenegraph to z-normal (0, 0, 1), but it doesn't work. My code goes like this:</p>
<pre><code>Vector3f toScreenVector = new Vector3f(0, 0, 1);
Transform3D t3d = new Transform3D();
tg.getTransform(t3d); //tg is Transform Group of all objects in a scene
t3d.transform(toScreenVector);
</code></pre>
<p>Then I tried something like this too:</p>
<pre><code>Point3d eyePos = new Point3d();
Point3d mousePos = new Point3d();
canvas.getCenterEyeInImagePlate(eyePos);
canvas.getPixelLocationInImagePlate(new Point2d(Main.WIDTH/2, Main.HEIGHT/2), mousePos); //Main is the class for main window.
Transform3D motion = new Transform3D();
canvas.getImagePlateToVworld(motion);
motion.transform(eyePos);
motion.transform(mousePos);
Vector3d toScreenVector = new Vector3f(eyePos);
toScreenVector.sub(mousePos);
toScreenVector.normalize();
</code></pre>
<p>But still this doesn't work correctly. I think there must be an easy way to create such vector. Do you know what's wrong with my code or better way to do so?</p>
|
<p>If I get this right, you want a vector that is normal to the screen plane, but in world coordinates?</p>
<p>In that case you want to <code>INVERT</code> the transformation from <code>World -> Screen and do Screen -> World</code> of <code>(0,0,-1)</code> or <code>(0,0,1)</code> depending on which axis the screen points down.</p>
<p>Since the ModelView matrix is just a rotation matrix (ignoring the homogeneous transformation part), you can simply pull this out by taking the transpose of the rotational part, or simple reading in the bottom row - as this transposes onto the <code>Z</code> coordinate column under transposition.</p>
|
<p>Yes, you got my question right. Sorry that I was a little bit confused yesterday. Now I have corrected the code by following your suggestion and mixing two pieces of code in the question together:</p>
<pre><code>Vector3f toScreenVector = new Vector3f(0, 0, 1);
Transform3D t3d = new Transform3D();
canvas.getImagePlateToVworld(t3d);
t3d.transform(toScreenVector);
tg.getTransform(t3d); //tg is Transform Group of all objects in a scene
t3d.transform(toScreenVector);
</code></pre>
<p>Thank you.</p>
| 6,122
|
<p>I have a few things that I cannot find a good way to perform in Visual Studio:</p>
<ol>
<li><p>Pre-build step invokes a code generator that generates some source files which are later compiled. This can be solved to a limited extent by adding blank files to the project (which are later replaced with real generated files), but it does not work if I don't know names and/or the number of auto-generated source files. I can easily solve it in <code>GNU make</code> using <code>$(wildcard generated/*.c)</code>. How can I do something similar with Visual Studio?</p></li>
<li><p>Can I prevent pre-build/post-build event running if the files do not need to be modified (<code>"make"</code> behaviour)? The current workaround is to write a wrapper script that will check timestamps for me, which works, but is a bit clunky.</p></li>
<li><p>What is a good way to locate external libraries and headers installed outside of VS? In *nix case, they would normally be installed in the system paths, or located with <code>autoconf</code>. I suppose I can specify paths with user-defined macros in project settings, but where is a good place to put these macros so they can be easily found and adjusted?</p></li>
</ol>
<p>Just to be clear, I am aware that better Windows build systems exist (<code>CMake</code>, <code>SCons</code>), but they usually generate VS project files themselves, and I need to integrate this project into existing VS build system, so it is desirable that I have just plain VS project files, not generated ones.</p>
|
<ol>
<li><p>If you need make behavior and are used to it, you can create <a href="http://msdn.microsoft.com/en-us/library/txcwa2xx(VS.80).aspx" rel="noreferrer">visual studio makefile projects</a> and include them in your project.</p></li>
<li><p>If you want less clunky, you can write visual studio <a href="http://visualstudiohacks.com/articles/general/customize-your-project-build-process/" rel="noreferrer">macros</a> and custom build events and tie them to specific build callbacks / hooks.</p></li>
<li><p>You can try something like <a href="http://workspacewhiz.com/SolutionBuildEnvironmentReadme.html" rel="noreferrer">workspacewhiz</a> which will let you setup environment variables for your project, in a file format that can be checked in. Then users can alter them locally.</p></li>
</ol>
|
<p><strong>(1)</strong>. I don't know a simple answer to this, but there are workarounds:</p>
<p>1a. If content of generated files does not clash (i.e. there is no common static identifiers etc.), you can add to the project a single file, such as AllGeneratedFiles.c, and modify your generator to append a #include "generated/file.c" to this file when it produces generated/file.c. </p>
<p>1b. Or you can create a separate makefile-based project for generated files and build them using nmake.</p>
<p><strong>(2)</strong>. Use a custom build rule instead of post-build event. You can add a custom build rule by right-clicking on the project name in the Solution Explorer and selecting Custom Build Rules.</p>
<p><strong>(3)</strong>. There is no standard way of doing this; it has to be defined on a per-project basis. One approach is to use environment variables to locate external dependencies. You can then use those environment variables in project properties. Add a readme.txt describing required tools and libraries and corresponding environment variables which the user has to set, and it should be easy enough for anyone to set up.</p>
| 39,645
|
<p>I keep hearing about the DRY Principle and how it is so important in ASP.NET MVC, but when I do research on Google I don't seem to quite understand exactly how it applies to MVC.</p>
<p>From what I've read its not really the copy & paste code smell, which I thought it was, but it is more than that.</p>
<p>Can any of you give some insight into how I might use the DRY Principle in my ASP.NET MVC application?</p>
|
<p>DRY just means "Don't Repeat Yourself". Make sure that when you write code, you only write it one time. If you find yourself writing similar functionality in all of your Controller classes, make a base controller class that has the functionality and then inherit from it, or move the functionality into another class and call it from there instead of repeating it in all the controllers.</p>
|
<p>DRY should not only be applied to code, but to information in general. Are you repeating things in your build system? Do you have data which should be moved to a common configuration file, etc.</p>
| 22,764
|
<p>I'm trying to convince my providers to use ANT instead of Rational Application Development so anyone can recompile, recheck, redeploy the solution anyplace, anytime, anyhow. :P</p>
<p>I started a build.xml for a project that generates a JAR file but stopped there and I need real examples to compare notes. My good friends! I don't have anyone close to chat about this! </p>
<p>This is my <a href="http://pastebin.ca/1094382" rel="noreferrer">build.xml</a> so far. </p>
<p><i>(*) I edited my question based in the <a href="https://stackoverflow.com/questions/4046/can-someone-give-me-a-working-example-of-a-buildxml-for-an-ear-that-deploys-in-#4298">suggestion</a> of to use pastebin.ca</i></p>
|
<p>My Environment: Fedora 8; WAS 6.1 (as installed with Rational Application Developer 7)</p>
<p>The documentation is very poor in this area and there is a dearth of practical examples.</p>
<p><strong>Using the WebSphere Application Server (WAS) Ant tasks</strong></p>
<p>To run as described here, you need to run them from your server <strong>profile</strong> bin directory using the <strong>ws_ant.sh</strong> or <strong>ws_ant.bat</strong> commands.</p>
<pre><code><?xml version="1.0"?>
<project name="project" default="wasListApps" basedir=".">
<description>
Script for listing installed apps.
Example run from:
/opt/IBM/SDP70/runtimes/base_v61/profiles/AppSrv01/bin
</description>
<property name="was_home"
value="/opt/IBM/SDP70/runtimes/base_v61/">
</property>
<path id="was.runtime">
<fileset dir="${was_home}/lib">
<include name="**/*.jar" />
</fileset>
<fileset dir="${was_home}/plugins">
<include name="**/*.jar" />
</fileset>
</path>
<property name="was_cp" value="${toString:was.runtime}"></property>
<property environment="env"></property>
<target name="wasListApps">
<taskdef name="wsListApp"
classname="com.ibm.websphere.ant.tasks.ListApplications"
classpath="${was_cp}">
</taskdef>
<wsListApp wasHome="${was_home}" />
</target>
</project>
</code></pre>
<p>Command:</p>
<pre><code>./ws_ant.sh -buildfile ~/IBM/rationalsdp7.0/workspace/mywebappDeploy/applist.xml
</code></pre>
<p><strong>A Deployment Script</strong></p>
<pre><code><?xml version="1.0"?>
<project name="project" default="default" basedir=".">
<description>
Build/Deploy an EAR to WebSphere Application Server 6.1
</description>
<property name="was_home" value="/opt/IBM/SDP70/runtimes/base_v61/" />
<path id="was.runtime">
<fileset dir="${was_home}/lib">
<include name="**/*.jar" />
</fileset>
<fileset dir="${was_home}/plugins">
<include name="**/*.jar" />
</fileset>
</path>
<property name="was_cp" value="${toString:was.runtime}" />
<property environment="env" />
<property name="ear" value="${env.HOME}/IBM/rationalsdp7.0/workspace/mywebappDeploy/mywebappEAR.ear" />
<target name="default" depends="deployEar">
</target>
<target name="generateWar" depends="compileWarClasses">
<jar destfile="mywebapp.war">
<fileset dir="../mywebapp/WebContent">
</fileset>
</jar>
</target>
<target name="compileWarClasses">
<echo message="was_cp=${was_cp}" />
<javac srcdir="../mywebapp/src" destdir="../mywebapp/WebContent/WEB-INF/classes" classpath="${was_cp}">
</javac>
</target>
<target name="generateEar" depends="generateWar">
<mkdir dir="./earbin/META-INF"/>
<move file="mywebapp.war" todir="./earbin" />
<copy file="../mywebappEAR/META-INF/application.xml" todir="./earbin/META-INF" />
<jar destfile="${ear}">
<fileset dir="./earbin" />
</jar>
</target>
<!-- http://publib.boulder.ibm.com/infocenter/wasinfo/v6r1/index.jsp?topic=/com.ibm.websphere.javadoc.doc/public_html/api/com/ibm/websphere/ant/tasks/package-summary.html -->
<target name="deployEar" depends="generateEar">
<taskdef name="wsInstallApp" classname="com.ibm.websphere.ant.tasks.InstallApplication" classpath="${was_cp}"/>
<wsInstallApp ear="${ear}"
failonerror="true"
debug="true"
taskname=""
washome="${was_home}" />
</target>
</project>
</code></pre>
<p>Notes:</p>
<ul>
<li>You can only run this once! You cannot install if the app name is in use - see other tasks like <strong>wsUninstallApp</strong></li>
<li>It probably won't start the app either</li>
<li>You need to run this on the server and the script is quite fragile</li>
</ul>
<p><strong>Alternatives</strong></p>
<p>I would probably use Java Management Extensions (JMX). You could write a file-upload servlet that accepts an EAR and uses the deployment MBeans to deploy the EAR on the server. You would just POST the file over HTTP. This would avoid any WAS API dependencies on your dev/build machine and could be independent of any one project.</p>
|
<p>If you just want to play around why not use the netbeans IDE to generate your ear files. If you create an enterprise project it will automatically generate the ant files for you. Good for prototyping and just getting started :-)</p>
<p>There is even a was plugin which allows automated deployment however this seems very shakey!</p>
| 2,605
|
<p>I have a project with a number of different classes querying and modifying data in a common set of tables. I've set up a .dbml file which provides us with a DataContext class. My question is whether a single instance of the DataContext should be used by all objects, or whether multiple instances are safe to use. I'm also wondering about thread safety in the case of a single DataContext, and whether access to it's methods should be synchronized.</p>
|
<p>Rick Strahl has a nice article about your options: <a href="http://www.west-wind.com/weblog/posts/246222.aspx" rel="nofollow noreferrer">http://www.west-wind.com/weblog/posts/246222.aspx</a>.</p>
<p>See also: <a href="https://stackoverflow.com/questions/196253/linq-to-sql-where-does-your-datacontext-live">LINQ to SQL - where does your DataContext live?</a>.</p>
<p>You may want a slightly different strategy for each type of deployment - web, desktop, windows service... </p>
<p>Summarized, your options are:</p>
<ul>
<li>Global DataContext - dangerous in multi-threaded environments (including web apps). Remember that instance members are not guaranteed to be thread-safe (from Bradley Grainger's <a href="https://stackoverflow.com/questions/196253/linq-to-sql-where-does-your-datacontext-live#196264">answer</a> above).</li>
<li>DataContext per thread - complicated. If your DataContext is tracking changes you must be sure to flush them at the appropriate time. Instantiating, storing, and retrieving the DataContext is a pain.</li>
<li>DataContext per atomic action - you lose the ability to track changes since one DataContext creates an object while another updates or deletes it. Attaching a data object to a new DataContext may not work like you expect.</li>
<li>DataContext per data object - seems inelegant because you have to fuss with the DataContext on instantiation(create and attach) and update/delete (pull it off the data object and use it).</li>
</ul>
<p>I opted for a DataContext per data object. It may not be the fanciest solution but it works in all deployment environments.</p>
|
<p>I've always heard that you should use a single instance of the DataContext. I usually create a singleton instance of my DC in my business logic class, and use it for all my linq queries.</p>
<p>I'm sure some of the linq gurus on here might be able to give you exact reasons as to why you should only have on instance of your data context class... I'm not quite certain.</p>
| 27,955
|
<p>We have PHP 5.2.6 deployed to c:\php and in that folder there is the php.ini file. On Windows, can a website override these settings similar to the way that apache has .htaccess? e.g.</p>
<pre><code>DirectoryIndex index.php index.html
<IfModule mod_php5.c>
php_flag magic_quotes_gpc off
php_flag register_globals off
</IfModule>
<IfModule mod_php4.c>
php_flag magic_quotes_gpc off
php_flag register_globals off
</IfModule>
</code></pre>
<p><strong><em>Update:</em></strong> </p>
<p>I was aware of ini_set() but wondered if there was a declarative way to do this in a configuration file in the website rather than in script.</p>
|
<p>I would recommend doing all you can to avoid changing r<code>egister_globals</code> to on as it's a major security hole.</p>
<p>But you can try using <code>init_set()</code> to change the settings within your PHP code, although some settings cannot be changed once PHP has started running. (These are somewhat server dependent I believe.)</p>
|
<p>For cgi environments, there is a module called <a href="http://pecl.php.net/package/htscanner" rel="nofollow noreferrer">htscanner</a>. It basically fakes .htaccess behavior and allows per directory configurations. Unfortunately I have no experience with this on Windows, let alone with IIS6.</p>
| 23,339
|
<p>For example, I have an ASP.NET form that is called by another aspx:</p>
<pre><code>string url = "http://somewhere.com?P1=" + Request["param"];
Response.Write(url);
</code></pre>
<p>I want to do something like this:</p>
<pre><code>string url = "http://somewhere.com?P1=" + Request["param"];
string str = GetResponse(url);
if (str...) {}
</code></pre>
<p>I need to get whatever Response.Write is getting as a result or going to url, manipulate that response, and send something else back.</p>
<p>Any help or a point in the right direction would be greatly appreciated.</p>
|
<pre><code>WebClient client = new WebClient();
string response = client.DownloadString(url);
</code></pre>
|
<p>An HttpResponse is something that is sent back to the client in response to an HttpRequest. If you want process something on the server, then you can probably do it with either a web service call or a page method. However, I'm not totally sure I understand what you're trying to do in the first place.</p>
| 14,924
|
<p>I want to import data from MS SQL Server, run it through some sort of regexp to filter out stuff, and import it into MySQL. I then, for each query, wish to display a relevant image from a third database. What would be the easiest way to do this, importing and linking wise?</p>
<p>Thank you.</p>
<p>Clarification: It is a php application to filter data from another database, and then for each record show an associated image from a 3rd database. It is from scratch...</p>
|
<p>You can try the MySQL Migration Toolkit.
<a href="http://dev.mysql.com/downloads/gui-tools/5.0.html" rel="nofollow noreferrer">http://dev.mysql.com/downloads/gui-tools/5.0.html</a></p>
<p>Now archived at <a href="http://downloads.mysql.com/archives.php?p=mysql-migration-toolkit" rel="nofollow noreferrer">http://downloads.mysql.com/archives.php?p=mysql-migration-toolkit</a></p>
|
<p>I would use the Microsoft SQL Server Data Publishing Wizard (free). You can use it to script your entire database (including insert statements.) You'll have to edit this script a little bit probably to get it to run in MySQL. Now you just have a regex problem. You can try:</p>
<ul>
<li>Manipulating the data in MS SQL via a query, or from code (using regex) the transfer.</li>
<li>Running your regexes on the script file itself, maybe try some macros, find and replace, etc.</li>
<li>Manipulating the data in MySQL via a query, or from code (using regex) after the transfer.</li>
</ul>
| 22,092
|
<p><a href="https://www.youtube.com/watch?v=WIkT8asT90A" rel="nofollow noreferrer">This video</a> brought to my attention the 8 mm lead of the Ender 3's Z axis screw, which seems like an exceedingly bad choice from a standpoint of accuracy with respect to common grid alignments in the Z direction. In particular, with the stepper having 200 full steps per rotation, the 8 mm lead consumes all the powers of two out of 200, leaving 25 full steps per mm - and 25ths of a mm are not a typical unit that layer heights/feature heights are going to be in. It seems like a 5 mm lead would be ideal, giving you 40 steps per mm, evenly divisible by 3 powers of 2 and one power of 5, for exact tenths and exact eights.</p>
<p>Is there a motivation behind the choice of 8 mm lead? Is this common for other printers, and are there printers that use a 5 mm lead, or 5 mm replacements that work well?</p>
|
<p>I've not seen trapezoid lead screws with 5 mm lead, you can get 5 mm lead ball screws though.</p>
<p>On one printer I use 4 mm lead screws to get native 0.02 mm resolution (so 5 full steps for 0.1 mm, 10 for 0.2 mm, etc.). I also geared down 8 mm lead screws with a 2:1 ratio (e.g. to use a single Z-stepper driving a belt that drives 2 lead screws), works fine.</p>
|
<p>You are delving into the darker recesses of 3D printing here!</p>
<p>ACME threads, anti-backlash nuts, ball-screws, etc. will ALL follow...</p>
<p>The simple answer is that the Z-axis screw on all the cheaper 3D printers are pure crap! They use 8mm With triangular threads because it they are cheap and most software works with it. </p>
<p>The first major upgrade most folks make to a printer (after the print bed surface) is to replace the Z-axis screw and nut. Many are poorly mounted and/or warped, resulting in Z-axis wobble. Most suffer major backlash - offset only by the fact that most printing only ever goes upwards...</p>
<p>The ideal upgrade would be to replace the rod and nut with a good quality ball-screw assembly that is properly mounted. But, if you do change the pitch, make sure you can alter the software to account for it...</p>
<p>That said, if your prints are good, enjoy, and don’t sweat the details!</p>
| 1,363
|
<p>In some of our projects, there's an class hierarchy that adds more parameters as it goes down the chain. At the bottom, some of the classes can have up to 30 parameters, 28 of which are just being passed into the super constructor.</p>
<p>I'll acknowledge that using automated DI through something like Guice would be nice, but because of some technical reasons, these specific projects are constrained to Java. </p>
<p>A convention of organizing the arguments alphabetically by type doesn't work because if a type is refactored (the Circle you were passing in for argument 2 is now a Shape) it can suddenly be out of order.</p>
<p>This question might be to specific and fraught with "If that's your problem, you're doing it wrong at a design level" criticisms, but I'm just looking for any viewpoints.</p>
|
<p>The Builder Design Pattern might help. Consider the following example</p>
<pre><code>public class StudentBuilder
{
private String _name;
private int _age = 14; // this has a default
private String _motto = ""; // most students don't have one
public StudentBuilder() { }
public Student buildStudent()
{
return new Student(_name, _age, _motto);
}
public StudentBuilder name(String _name)
{
this._name = _name;
return this;
}
public StudentBuilder age(int _age)
{
this._age = _age;
return this;
}
public StudentBuilder motto(String _motto)
{
this._motto = _motto;
return this;
}
}
</code></pre>
<p>This lets us write code like</p>
<pre><code>Student s1 = new StudentBuilder().name("Eli").buildStudent();
Student s2 = new StudentBuilder()
.name("Spicoli")
.age(16)
.motto("Aloha, Mr Hand")
.buildStudent();
</code></pre>
<p>If we leave off a required field (presumably name is required) then we can have the Student constructor throw an exception.
And it lets us have default/optional arguments without needing to keep track of any kind of argument order, since any order of those calls will work equally well.</p>
|
<p>Refactoring to reduce the number of parameters and depth of you inheritance hierarchy is pretty much all I can think of because, nothing is really going to help keep 20-something parameters straight. You're just going to have to every single call while looking at the documentation.</p>
<p>One thing you could do, is to group some logically grouped parameters into their own higher level object, but that has it's own problems.</p>
| 27,411
|
<p>when calling a SSIS package (C# app) using LoadFromSqlServer, does the user account have to have any special permissions on the database or server?</p>
<p>I can't seem to view the packages in EM at the moment ...</p>
|
<p>You will need to grant some rights to the users which need to run the SSIS packages.</p>
<p><a href="http://sqljunkies.com/WebLog/knight_reign/archive/2006/01/05/17769.aspx" rel="nofollow noreferrer">This page</a> should provide the information you need.</p>
|
<p>I don't know the answer exactly, but where an SSIS package is run from is important. If I run it from Visual Studio, it's using my account and permissions. If I load it to the server and just try to run the package directly, it's using something else (and usually fails because of they way our servers are set up). If I run it from a job on the server, it uses the server SQA account, with the permissions from that account.</p>
| 46,025
|
<p>I just recently got my first mac. I do lots of programming on windows but now I want to get into Mac development. What are some languages i should know or tools i should use to get started with mac development?</p>
|
<p><a href="https://rads.stackoverflow.com/amzn/click/com/0321503619" rel="nofollow noreferrer" rel="nofollow noreferrer">Cocoa(R) Programming for Mac(R) OS X (3rd Edition) by Aaron Hillegass</a>:</p>
<p><img src="https://i.stack.imgur.com/2AHwE.jpg" alt="enter image description here"></p>
<p>Fantastic book and the author has alot of credibility - Apple brought him in to train their developers on Cocoa.</p>
|
<p>If you have Windows experience but also want to develop Mac software you might consider looking into <a href="http://www.realsoftware.com" rel="nofollow noreferrer">REALbasic</a>. It doesn't give you complete access to the Mac OS X Cocoa framework, but it can be used to make some slick Mac apps. And it's really easy to get started with.</p>
| 19,605
|
<p>I am trying to send a user to another page using a Javascript Function:</p>
<pre><code><input type="button" name="confirm" value="nextpage" onClick="message()">
</code></pre>
<p>And my JavaScript:</p>
<pre><code>function message() {
ConfirmStatus = confirm("Install a Virus?");
if (ConfirmStatus == true) {
//Send user to another page
}
}
</code></pre>
<p>Does anyone know how to send a user to another specific page?</p>
|
<p>your code got messed up, but if I got it right you can use the following:</p>
<pre><code>location.href = 'http://www.google.com';
or
location.href = 'myrelativepage.php';
</code></pre>
<p>Good luck!</p>
<p>But I must say to you, </p>
<ol>
<li>Javascript can be turned off, so your function won't work.</li>
</ol>
<p>Other option is to do this by code:</p>
<p>PHP: <code> header('Location: index.php'); </code> </p>
<p>C#: <code> Response.Redirect("yourpage.aspx"); </code> </p>
<p>Java: <code> response.sendRedirect("<a href="http://www.google.com" rel="noreferrer">http://www.google.com</a>"); </code> </p>
<p>Note: </p>
<ol>
<li>All of those redirects must be placed before any outputs to the client ok?</li>
</ol>
|
<p>window.location.href = url; </p>
<p>It is ok for redirecting to the required url using javascript.</p>
<p>The simple example can be found in <a href="http://ramsharanshrestha.blogspot.com/2013/04/window.html" rel="nofollow">this url</a></p>
| 37,462
|
<p>I need to run a stored procedure from a C# application.</p>
<p>I use the following code to do so:</p>
<pre><code>Process sqlcmdCall = new Process();
sqlcmdCall.StartInfo.FileName = "sqlcmd.exe";
sqlcmdCall.StartInfo.Arguments = "-S localhost\\SQLEXPRESS -d some_db -Q \":EXIT(sp_test)\""
sqlcmdCall.Start();
sqlcmdCall.WaitForExit();
</code></pre>
<p>From the sqlcmdCall object after the call completes, I currently get an ExitCode of -100 for success and of 1 for failure (i.e. missing parameter, stored proc does not exist, etc...).</p>
<p>How can I customize these return codes?</p>
<p>H.</p>
|
<p>If you are trying to call a stored procedure from c# you would want to use ADO.Net instead of the calling sqlcmd via the command line. Look at <code>SqlConnection</code> and <code>SqlCommand</code> in the <code>System.Data.SqlClient</code> namespace.</p>
<p>Once you are calling the stored procedure via <code>SqlCommand</code> you will be able to catch an exception raised by the stored procedure as well we reading the return value of the procedure if you need to.</p>
|
<p>Even with windows authentication you can still use <code>SqlCommand</code> and <code>SqlConnection</code> to execute, and you don't have to re-invent the wheel for exception handling.</p>
<p>A simple connection configuration and a single <code>SqlCommand</code> can execute it without issue.</p>
| 9,871
|
<p>After attending a talk on Oslo/M I am struggling a bit to see the advantages of using it over existing methods and in what situation it would be useful.</p>
<p>I know its quite new and not all details have been released etc but can some one give me some advantages and when you might use it?</p>
<p>Thanks,</p>
<p>Alex</p>
|
<p>This questions seems to have the answer you're looking for:<br>
<a href="https://stackoverflow.com/questions/308803/what-is-model-driven-development-good-for">What is model driven development good for?</a></p>
<p>Erik Wynne has a nice blog-post on this topic:<br>
<a href="http://erikwynne.blogspot.com/2008/11/oslo-42.html" rel="nofollow noreferrer">Oslo == 42</a></p>
<p>He also links to a post on MSDN, that contains some interesting thoughts:<br>
<a href="http://social.msdn.microsoft.com/Forums/en-US/oslo/thread/ae08521d-c61b-4622-9a12-3d572bd97b6a" rel="nofollow noreferrer">Why do we need Oslo?</a></p>
|
<p>Thinking about this a bit more and after reading the articles posted by Qdoom and RoadWarrior I can see Oslo aiding sharing,</p>
<p>Okay you can share a model with something like xml & xsd but Oslo could make it easier as it looks like you can generate classes and your database from them whilst storing the model in a central repository.</p>
<p>Perhaps later on people will sell models for common scenarios as well.</p>
| 40,264
|
<p>Many developers will claim that moving from one programming language to another is relatively simple especially if the languages are based on similar paradigms. However, in practice the effort comes not from learning the syntax of the language but in developing a deep understanding of the language nuances and more importantly knowing what is offered in the language’s libraries. For example, switching from Java to .Net is not difficult from a syntactic perspective but programming efficiency requires a good knowledge of the available libraries. Switching from PHP to .Net could present an even greater hurdle given the language disparities.</p>
<p>What are the real overheads for a developer to move to a different language in the same paradigm? What if the paradigms are different?</p>
|
<p>The biggest challenge (for me) is usually the API, rather than the language itself (.NET notwithstanding). For example, I've been using Microsoft's C++ and C# for a lot of years (Delphi before that). But I have great difficulty getting started on Java; even trivial projects can take me a while. Not because the language is difficult (it's not), but because the APIs are different, and arranged differently.</p>
<p>It takes months to get up to speed on an API to the point you can use it fluently, and years to become "good" and learn all the ins and outs of the language. That's daunting for a lot of developers, because you basically have to devote a significant amount (if not all) of your time and effort toward working in the new language to become an expert at it. Many times, the incentive to move out of your current area of expertise just isn't there.</p>
|
<p>Just like learning a new human language, for me the biggest problem lies on typical constructions you need to do to solve a problem.</p>
<p>I know that perhaps learning "while" or "for" loops in several languages aren't so difficult - but when your problem goes up one level of abstraction (iterate through this array) you'll find yourself using "[" instead of "(" and vice-versa.</p>
<p>The learning curve can be even steeper if, besides learning a new language, you have to learn a new framework. When I went from typícal ASP.Net to MVC (using NVelocity) I kinda felt myself completely lost - all my knowledge on how to solve typical problems with asp.net control had to be forgotten.</p>
<p>Finally, the biggest challenge happens when you change between languages with different paradigms - because you can no longer think in the same way to solve a problem. Like - when moving from C# to Prolog, instead of thinking in functions, arguments, class hierarchy, etcs... I had to think only in states, events linked to data changes and event chaining via recursion - it was madness but I could finish my university homework.</p>
| 26,074
|
<p>I have a web system which has a classical parent-children menu saved in a database, with fields id as the PK, and parent_id to pointing to the owning menu. (Yes, I know this doesn't scale very well, but that's another topic). </p>
<p>So for these records (id-parent_id pairs):</p>
<pre><code>0-7 0-4 4-9 4-14 4-16 9-6
</code></pre>
<p>I have this tree:</p>
<pre><code>0
├ 7
└ 4
├ 9
| └ 6
├ 14
└ 16
</code></pre>
<p>I'm needing to hide a top node, so I have to make a list of all the childrens of that certain node, i.e. for 4, they will be (9, 6, 14, 16). Order doesn't matters.</p>
<p>I'm confused... does this fits into the classical tree problems? or is it a graph one?</p>
<p>How can I compose this structure and solve this problem using php?</p>
|
<p>This is the perfect chance to use recursion!</p>
<p>Pseudo-code:</p>
<pre><code>nodeList = {}
enumerateNodes(rootNode, nodeList);
function enumerateNodes(node, nodeList) {
nodeList += node;
foreach ( childnode in node.children ) {
enumerateNodes(childnode, nodeList);
}
}
</code></pre>
<p>Edit: Didn't notice that your tree is in the adjacent list format. I would probably just build that into an actual tree datastructure before I started working with it. Just loop through all pairs (creating nodes the first time you see them) and linking them. I <em>think</em> it should be easy...</p>
|
<p>This is a graph problem. Check out <a href="http://en.wikipedia.org/wiki/Breadth-first_search" rel="nofollow noreferrer">BFS(breadth first search)</a> and <a href="http://en.wikipedia.org/wiki/Depth-first_search" rel="nofollow noreferrer">DFS(depth first search).</a>. You can google out those terms and find hundreds of implementations on the web.</p>
| 10,445
|
<p>I would like to write a utility that will provide me with a relatively unique ID in Java. Something pretty simple, like x bits from timestamp + y bits from random number.</p>
<p>So, how would I implement the following method:</p>
<pre><code>long getUniqueID()
{
long timestamp = System.currentTimeMillis();
long random = some random long
...
return id;
}
</code></pre>
<p>BONUS</p>
<p>Any suggestions for other easily obtainable information I could use to form my ID?</p>
<p>note: I am aware of GUIDs and I know Java has a UUID class, but I don't want something that is 128 bits long.</p>
|
<p>Just clip the bits you don't need:</p>
<pre><code>return java.util.UUID.randomUUID().getLeastSignificantBits();
</code></pre>
|
<p>What you are trying to do is create a <a href="http://en.wikipedia.org/wiki/Hash_function" rel="nofollow noreferrer">hash function</a> that combines two long values into a single long value. In this case, the <a href="http://en.wikipedia.org/wiki/Hash_function#Uniformity" rel="nofollow noreferrer">uniformity</a> of the hash function will be of utmost importance since collisions in created unique ID values are unacceptable. However, if you can compare hash values to previously created identifiers, then collisions can be resolved by modifying the hash until no collision occurs.</p>
<p>For example, you could take the time stamp and perform an <a href="http://en.wikipedia.org/wiki/Exclusive_or" rel="nofollow noreferrer">exclusive-or</a> (using the caret ^ operator in Java) with the random value. If a collision is detected, then add one to the result.</p>
| 41,027
|
<p>What are the advantages of rendering a control like this:</p>
<pre><code><% Html.RenderPartial("MyControl") %> or
<%=Html.TextBox("txtName", Model.Name) %>
</code></pre>
<p>over the web Forms style:</p>
<pre><code><uc1:MyControl ID=MyControl runat=server />
</code></pre>
<p>I understand that performance can be one reason because no object needs to be created but having the possibility of calling it from the codebehing just to do some basic rendering logic can be very useful. </p>
<p>If this is discouraged then how you are suposed to deal with this scenarios:</p>
<ul>
<li><p>You need to make the control visible conditionally and you dont want to fill your HTML with rendering logic.</p></li>
<li><p>You have <code><input type="text" value="<%= Model.Name %>" /></code> but you need to check if Model is null because otherways a NullPointerException will raise.</p></li>
</ul>
<p><strong>[EDIT]</strong> I asked this when I was beginning with ASP MVC, now I see the advantages of the MVC way like in Cristian answer.</p>
|
<p>There are a couple of reasons for this. A "traditional" ASP.NET WebForm control encapsulates both the Controller and View aspect of an MVC application and that would be a violation to the pattern. Also by making them extension methods you gain nice abilities such as being able to swap them out with your own implementation and to swap them out for testing</p>
<p>Phil Haack (Program Manager of ASP.NET MVC) talks a bit about this when he got interviewed on the Herdering Code podcast</p>
<p>Episode 24: Phil Haack on the ASP.NET MVC Beta Release (part 1)</p>
<p><a href="http://herdingcode.com/?p=75" rel="noreferrer">http://herdingcode.com/?p=75</a></p>
<p>Episode 24: Phil Haack on the ASP.NET MVC Beta Release (part 2)</p>
<p><a href="http://herdingcode.com/?p=82" rel="noreferrer">http://herdingcode.com/?p=82</a></p>
|
<p>I found <a href="https://stackoverflow.com/questions/108320/code-behind-in-aspnet-mvc">this question</a> where @Matt answers:</p>
<blockquote>
<p>Does this code A) Process, store,
retrieve, perform operations on or
analyze the data, or B) Help to
display the data?</p>
<p>If the answer is A, it belongs in your
controller. If the answer is B, then
it belongs in the view.</p>
<p>If B, it ultimately becomes a question
of style. If you have some rather long
conditional operations for trying to
figure out if you display something to
the user, then you might hide those
conditional operations in the code
behind in a Property.</p>
</blockquote>
<p>and I agree. To me it is cleaner to write in the aspx:</p>
<pre><code><custom:HtmlTextBox ID="txtName" runat="server" />
</code></pre>
<p>and in the codebehind something like:</p>
<pre><code>if(this.Model != null)
{
this.txtName.Text = Model.Name;
}
</code></pre>
<p>than in the .aspx for instance:</p>
<pre><code><% if(this.Model != null) { %>
<input type="text" name="txtName" value="<%= Model.Name %>" />
<% } else { %>
<input type="text" name="txtName" value="" />
<% } %>
</code></pre>
<p>Being able to manipulate controls from the codebehind is very useful and doesn't violate the MVC pattern. Maybe I am missing something?</p>
<p>Thanks!</p>
| 34,188
|
<p>The question is actually about stack overflows in C.
I have an assigment that I can not get done for the life of me, I've looked at everything in the gdb and I just cant figure it.</p>
<p>The question is the following:</p>
<pre><code>int i,n;
void confused()
{
printf("who called me");
exit(0);
}
void shell_call(char *c)
{
printf(" ***Now calling \"%s\" shell command *** \n",c);
system(c);
exit(0);
}
void victim_func()
{
int a[4];
printf("[8]:%x\n", &a[8]);
printf("Enter n: "); scanf("%d",&n);
printf("Enter %d HEX Values \n",n);
for(i=0;i<n;i++) scanf("%x",&a[i]);
printf("Done reading junk numbers\n");
}
int main()
{
printf("ls=736c --- ps = 7370 --- cal = 6c6163\n");
printf("location of confused %x \n", confused);
printf("location of shell_call %x \n", shell_call);
victim_func();
printf("Done, thank you\n");
}
</code></pre>
<p>Ok, so I managed to get the first question correctly, which is to arbitrarily call one of the two functions not explicitly called in the main path. By the way, this has to be done while running the program without any modifications.
I did this by running the program, setting <code>N</code> to <code>7</code>, which gets me to the Function Pointer of the <code>victim_func</code> frame, I write <code>a[7]</code> with the memory address of confused or <code>shell_call</code>, and it works. (I have a 64 bit machine, thats why I have to get it to 7, since the EBI pointer is 2 ints wide, instead of 1)</p>
<p>My question is the following, how could I control which argument gets passed to the <code>shell_code</code> funcion? ie. how do I write a <code>string</code> to <code>char* c</code>.
The whole point is executing unix commands like <strong>ps</strong> etc, by running only the program.</p>
<p>I figured writing the EBI pointer with the hex representation of <strong>ps</strong> and setting the arg list of <code>shell_call</code> to that, but that didn't work. I also tried inputing <code>argsv</code> arguments and setting the arg list of <code>shell_call</code> to the <code>arg_list</code> of main, but didn't work either. </p>
<p>I think the second version should work, but I believe I'm not setting the arg list of the new stack frame correctly ( I did it by writing <code>a[8]</code> to <code>0</code>, since its the first part of the function pointer, and writing <code>a[9]=736c</code> and <code>a[10]=0000</code>, but its probably not right since those are the parameters of <code>victim_func</code>. So how do I access the parameters of <code>shell_call</code>? </p>
|
<p>I probably shouldn't do your homework for you. But the basically:</p>
<p>You need to get a character buffer somewhere in memory to store the string you want to execute. Obviously, you can do this the same way you are getting the other functions called (i.e. you put the text on the stack as well). After you have that written, you need to write a pointer to it on to the stack in the location that the shell_code function expects to find its arguments.</p>
<p>The best way to figure this out without me doing <em>all</em> of the work for you is to write down your stack/memory contents on a piece of paper/whiteboard. Write down how it would look if you called shell_code normally from inside the program. Then write down what the stack looks like inside victum_func and figure out which things to change to get it to look like it would look "naturally" (of course keeping in mind some things are "don't cares" like the return address).</p>
<p>That's all the charity you're gonna get from me today! :-P</p>
|
<p>You need to manipulate the stack-frame of the caller (<code>main()</code>), and arrange it in such a way that returning to <code>shell_call()</code> from the epilog of the overflowed <code>victim_func()</code> the latter could find a settled stack as it was been called by the main. </p>
<p>In doing so you probably have to mangle the frame-pointer in the stackframe of the victim, that will be restored in %ebp by means of <code>leave</code>.</p>
| 36,344
|
<p>I have seen some lasers attached to the RepRap platform for cutting but most seem to be cutting paper, balsa wood, or merely etching. If I were wanting to build a platform for cutting wood, similar to the wood framed or boxed 3D printers on the market, what power laser would I need for that? I assume that a lower powered laser would have to travel slower but going too slow would add the possibility of catching the wood on fire (not good). </p>
|
<p>Please do not go down this road. First, not all lasers are equally absorbed by the material and the energy converted to heat to vaporize the material. The light not absorbed is reflected right back into your eyes. This is especially dangerous because it doesn't make you go blind instantly, fooling you into thinking there is no harm. You got the other part right, the lower the laser power, the less turned to heat, the longer it takes to cut, the longer you risk exposure to your eyes. That's right, a low powered laser is MORE dangerous than a big one. Next, the only way to properly cut is with air assist. This means a stream of air blows away the vaporized material so the laser can keep cutting deeper. This also prevents fires. The thing we haven't even touched is a proper safety enclosure, proper bed design to not reflect the laser beam back into the laser killing it and your eyes, and finally smoke/particle exhaust. </p>
<p>Simply put, these cheapo DIY lasers are dangerous, and are also illegal.</p>
|
<p>Strapping a laser to a cheap robot made with flammable plastic parts and no enclosure is stupid in the extreme. Don't do it. Seriously, just don't. <strong>RepRaps are not suitable for laser conversions.</strong> </p>
<p>You have to worry about reflected light damaging your eyes, and for the blue diode lasers currently growing in popularity, causing skin melanomas. You have to worry about mechanical vibration from jerky motion loosening fasteners. You have to worry about the workpiece catching on fire. You have to worry about the fumes being generated from etching and cutting. You have to worry about firmware freezes locking the laser on. It's dangerous to you, anybody in line of sight of the machine, and your property. </p>
<p>Many of the lasers currently being sold for RepRap conversions, particularly from Russia, violate US and EU safety regulations related to power and safety interlocks and should not be on the market at all. </p>
<p>The people posting videos of their RepRap laser conversions are almost always ignorant of proper laser safety requirements and regulations. It's downright scary how much blue flare you can see the camera picking up in a lot of these videos. Don't follow in those people's footsteps. </p>
<p>More directly answering the question details, most people doing light etching or paper cutting type work are using small 0.5-2W diode lasers. These are particularly dangerous because they have poor focus and because they don't have the power to cut cleanly and quickly. That means more fumes, more fire risk, and more damage to the workpiece from edge charring. </p>
<p>Slowing down the laser is not a good solution: dwell time is your enemy. You want a beam powerful enough to near-instantly vaporize the material, not slowly burn it away. </p>
<p>An entry-level proper lasercutter for cutting things like plywood and acrylic is more likely to use a 40w CO2 laser. It should have air assist and fume extraction, and a safety-interlocked enclosure that 100% reflects or absorbs the CO2 laser light wavelength. That basically means a dedicated machine.</p>
| 208
|
<p>Programs that index filesystems seem to know which parts have changed since their last index and only rescan that part. How can I determine where the filesystem/files have changed since my last index. Don't care what language you answer in but I'm thinking c and windows.</p>
<p>An example of such a program is Sequoia View which generates a treemap of your hard disk.</p>
|
<p>A fairly simplistic method would be to take the file system's reported files sizes, dates (as integer values), and file names in a given directory and calculate a <a href="http://en.wikipedia.org/wiki/Checksum" rel="noreferrer">checksum</a> you could then associate with that directory. You would still need to perform this calculation on all of the directories using file system data but you wouldn't have to go in depth (opening files to check for differences) unless a checksum reported a difference.</p>
<p>For tracking specific changes at the file level you would store checksums based on individual file attributes, and of the course the presence of or absence of files and subdirectories since the last scan.</p>
<p>This wouldn't necessarily guarantee that changes have not occurred as there are file system utilities for altering all manner of attributes though it would be a good first step for a basic scan.</p>
<p>You may find the <a href="http://sourceforge.net/project/showfiles.php?group_id=156978&package_id=175371" rel="noreferrer">source code</a> for <a href="http://sourceforge.net/projects/fswatch" rel="noreferrer">fswatch</a> helpful.</p>
|
<p>FindFirstChangeNotification</p>
| 31,001
|
<p>I have my SVN repository hosted somewhere. I want to move to somebody else. How can I create a dump of my repository so I can import it into my new host? This is all I keep seeing: svnadmin dump /path/to/repos > repos.dump</p>
<p>My repository is hosted, so it's not local.</p>
|
<p>svnadmin dump is the recommended way to <a href="http://svnbook.red-bean.com/en/1.1/ch05s03.html#svn-ch-5-sect-3.5" rel="noreferrer">migrating your repositories</a>, but you'll need shell access to do it, otherwise you will have to contact your hosting provider and ask them to do the full repository dump for you. </p>
|
<p>Sounds like you need a <a href="http://rsvndump.sourceforge.net/" rel="nofollow noreferrer">remote SVN dump command</a>. I haven't used it but it claims to do what you want.</p>
| 46,260
|
<p>I am a bit rusty on my Haskell and am looking to ramp back up. One thing I enjoy from F# is the F# Interactive shell integrated with Visual Studio: I can evaluate virtually anything (including function and class definitions) and use F# as a shell. Is there an equivalent in Haskell? When I use <code>ghci</code>, I cannot evaluate function definitions. How do you work around that?</p>
<p>My current preferred setting is using Emacs with haskell-mode and opening an interactive ghi interpreter. However, is there a way to evaluate just region of a file?</p>
|
<p>You can define a function using 'let':</p>
<pre><code>$ ghci
Prelude> let double n = n + n
Prelude> double 42
84
</code></pre>
<p>Also, I won't quite recommend this, since (A) I wrote it, and (B) it's terribly undeveloped, but <a href="http://github.com/darius/halp/" rel="noreferrer">Halp</a> can be handy in Emacs -- it's a little bit like a spreadsheet for Haskell code integrated right into your source-code buffer. You can have a set of expressions you're interested in and with one keystroke see how all their values change depending on your edits since the last reevaluation.</p>
|
<p>With O'Caml and F#, definitions proceed from the top of the file down. However, in Haskell, a type or function defined earlier in a file can reference a type or function later in that file. So in Haskell, a module needs to be compiled all at once. An interactive loop is incompatible with compilation all-at-once.</p>
| 44,445
|
<p>I'd like to use alternatives to System Center Virtual Machine Manager 2008 is possible, in other words, any FREE tools?</p>
|
<p>Before SCVMM, Microsoft's solution was the <a href="http://technet.microsoft.com/en-us/virtualserver/bb676674.aspx" rel="nofollow noreferrer">Virtual Server Migration Toolkit</a>. This requires Windows Server 2003 Automated Deployment Services, which in turn can only be installed on Windows Server 2003 Enterprise Edition. It's about as far from a free tool as you can get. It only works on SP1, not SP2 (unless ADS has been updated since I last checked), and you have to obtain all the patches you've applied to the physical system.</p>
<p>ADS is limited to four partitions per physical disk, because it can't create extended partitions. If your physical system has more than four partitions you have a problem.</p>
<p>Once you do have it running, though, it does actually work.</p>
<p>Many disk copying tools like Ghost or True Image can now produce .vhd files from a physical system.</p>
|
<p>Use VMWare its not free, but you can get a decent 30 day trial, which should be enough to do your conversions. VMWare also has other great advantages if you're willing to pay for the product. </p>
| 9,001
|
<p>Are there any free tools to help simplify working with an NHibernate project in .NET 3.5? Primarily, I'm looking for some kind of code and config file generator to automate some of the more tedious parts of working with NHibernate.</p>
|
<p><a href="http://code.google.com/p/fluent-nhibernate/" rel="nofollow noreferrer">Fluent-NHibernate</a> presents an alternative way of writing your mapping, that for example is more refactor friendly than the standard XML approach.</p>
<p>Example:</p>
<pre><code>public CustomerMap : ClassMap<Customer>
{
public CustomerMap()
{
Id(x => x.ID);
Map(x => x.Name);
Map(x => x.Credit);
HasMany<Product>(x => x.Products)
.AsBag();
Component<Address>(x => x.Address, m =>
{
m.Map(x => x.AddressLine1);
m.Map(x => x.AddressLine2);
m.Map(x => x.CityName);
m.Map(x => x.CountryName);
});
}
</code></pre>
|
<p>Have a look at: <a href="http://www.dpulpo.com" rel="nofollow">dPulpo</a>, a datalayer generation tool that generates NHibernate mapping files, C# entity classes and your SQL database. There is a Visual Studio plugin and it's currently in beta and free for download.</p>
| 35,102
|
<p>If not, what are the significant differences?</p>
<hr>
<p><strong>Edit:</strong> Daren Thomas asks:</p>
<blockquote>
<p>which ones?</p>
<p>I use gvim on Windows and MacVim on the mac. Seem similar enough to be the same to me...</p>
</blockquote>
<p>By which ones, I'm guessing that you mean a specific implementation of vi and emacs for Windows. I'm not sure as I thought there were only one or two. I'm looking for the ones that are closest to the Unix counterparts.</p>
|
<p>I use <a href="http://ftp.gnu.org/pub/gnu/emacs/windows/" rel="nofollow noreferrer">GNU emacs built for Windows</a>, and have found very few, if any, differences. There's the option to load your .emacs file from _emacs or .emacs (although .emacs works fine on XP and above). You can configure it to use Windows-style or Unix-style line endings by default (which I suppose you could do on a Unix system too...).</p>
<p>You may want to tweak such settings as Emacs's startup directory and home directory. To do the former, modify the shortcut that starts emacs. To do the latter, add a HOME environment variable - this will control where your .emacs is loaded from. For more information, check the always-excellent EmacsWiki's <a href="http://www.emacswiki.org/cgi-bin/wiki/MsWindowsInstallation" rel="nofollow noreferrer">MsWindowsInstallation</a> page.</p>
|
<p>which ones?</p>
<p>I use <code>gvim</code> on Windows and <code>MacVim</code> on the mac. Seem similar enough to be the same to me...</p>
| 6,285
|
<p>We are experiencing some slowdowns on our web-app deployed on a Tomcat 5.5.17 running on a Sun VM 1.5.0_06-b05 and our hosting company doesn't gives enough data to find the problem.</p>
<p>We are considering installing <a href="http://www.lambdaprobe.org" rel="noreferrer">lambda probe</a> on the production server but it requires to enable JMX (com.sun.management.jmxremote) in order to obtain memory and CPU statistics.</p>
<p>Does enabling JMX incur a serious performance penalty?</p>
<p>If we enable JMX, are we opening any security flaw? Do I need to setup secure authentication if we are only enabling local access to JMX?</p>
<p>Is anyone using the same (tomcat + lambda probe) without problems on production?</p>
<h3>UPDATE</h3>
<p>Looking at the answers it seems that enabling JMX alone doesn't incur significant overhead to the VM. The extra work may come if the monitoring application attached to the VM, be it <em>JConsole</em>, <em>lambda probe</em> or any other, is polling with excessive dedication.</p>
|
<p>You can cross out security flaws by using secure authentication. Just keeping the JMX service ready does not incur any significant overhead and is generally a good idea. There's a benchmark <a href="http://weblogs.java.net/blog/emcmanus/archive/2006/07/how_much_does_i.html" rel="noreferrer">here</a> about this.</p>
|
<p>it depends on the JMX implementation and on how expensive the stuff is you want to monitor.
I now at least one JMX application, which has a relatively high memory overhead. </p>
| 40,448
|
<p>I have the following makefile that I use to build a program (a kernel, actually) that I'm working on. Its from scratch and I'm learning about the process, so its not perfect, but I think its powerful enough at this point for my level of experience writing makefiles.</p>
<pre><code>AS = nasm
CC = gcc
LD = ld
TARGET = core
BUILD = build
SOURCES = source
INCLUDE = include
ASM = assembly
VPATH = $(SOURCES)
CFLAGS = -Wall -O -fstrength-reduce -fomit-frame-pointer -finline-functions \
-nostdinc -fno-builtin -I $(INCLUDE)
ASFLAGS = -f elf
#CFILES = core.c consoleio.c system.c
CFILES = $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c)))
SFILES = assembly/start.asm
SOBJS = $(SFILES:.asm=.o)
COBJS = $(CFILES:.c=.o)
OBJS = $(SOBJS) $(COBJS)
build : $(TARGET).img
$(TARGET).img : $(TARGET).elf
c:/python26/python.exe concat.py stage1 stage2 pad.bin core.elf floppy.img
$(TARGET).elf : $(OBJS)
$(LD) -T link.ld -o $@ $^
$(SOBJS) : $(SFILES)
$(AS) $(ASFLAGS) $< -o $@
%.o: %.c
@echo Compiling $<...
$(CC) $(CFLAGS) -c -o $@ $<
#Clean Script - Should clear out all .o files everywhere and all that.
clean:
-del *.img
-del *.o
-del assembly\*.o
-del core.elf
</code></pre>
<p>My main issue with this makefile is that when I modify a header file that one or more C files include, the C files aren't rebuilt. I can fix this quite easily by having all of my header files be dependencies for all of my C files, but that would effectively cause a complete rebuild of the project any time I changed/added a header file, which would not be very graceful.</p>
<p>What I want is for only the C files that <em>include</em> the header file I change to be rebuilt, and for the entire project to be linked again. I can do the linking by causing all header files to be dependencies of the target, but I cannot figure out how to make the C files be invalidated when their included header files are newer.</p>
<p>I've heard that GCC has some commands to make this possible (so the makefile can somehow figure out which files need to be rebuilt) but I can't for the life of me find an actual implementation example to look at. Can someone post a solution that will enable this behavior in a makefile?</p>
<p>EDIT: I should clarify, I'm familiar with the concept of putting the individual targets in and having each target.o require the header files. That requires me to be editing the makefile every time I include a header file somewhere, which is a bit of a pain. I'm looking for a solution that can derive the header file dependencies on its own, which I'm fairly certain I've seen in other projects.</p>
|
<p>As already pointed out elsewhere on this site, see this page:
<a href="http://make.mad-scientist.net/papers/advanced-auto-dependency-generation/" rel="noreferrer">Auto-Dependency Generation</a></p>
<p>In short, gcc can automatically create .d dependency files for you, which are mini makefile fragments containing the dependencies of the .c file you compiled.
Every time you change the .c file and compile it, the .d file will be updated.</p>
<p>Besides adding the -M flag to gcc, you'll need to include the .d files in the makefile (like Chris wrote above).
There are some more complicated issues in the page which are solved using sed, but you can ignore them and do a "make clean" to clear away the .d files whenever make complains about not being able to build a header file that no longer exists.</p>
|
<p>I believe the <code>mkdep</code> command is what you want. It actually scans .c files for <code>#include</code> lines and creates a dependency tree for them. I believe Automake/Autoconf projects use this by default.</p>
| 38,072
|
<p>I have a very long-running stored procedure in SQL Server 2005 that I'm trying to debug, and I'm using the 'print' command to do it. The problem is, I'm only getting the messages back from SQL Server at the very end of my sproc - I'd like to be able to flush the message buffer and see these messages immediately during the sproc's runtime, rather than at the very end.</p>
|
<p>Use the <a href="http://msdn.microsoft.com/en-us/library/ms178592.aspx" rel="noreferrer"><code>RAISERROR</code></a> function:</p>
<pre><code>RAISERROR( 'This message will show up right away...',0,1) WITH NOWAIT
</code></pre>
<p>You shouldn't completely replace all your prints with raiserror. If you have a loop or large cursor somewhere just do it once or twice per iteration or even just every several iterations.</p>
<p>Also: I first learned about RAISERROR at this link, which I now consider the definitive source on SQL Server Error handling and definitely worth a read:<br>
<a href="http://www.sommarskog.se/error-handling-I.html" rel="noreferrer">http://www.sommarskog.se/error-handling-I.html</a></p>
|
<p>To extend <a href="https://stackoverflow.com/a/36703942/4255824">Eric Isaac's answer</a>, here is how to use the table approach correctly:</p>
<p>Firstly, if your sp uses a transaction, you won't be able monitor the contents of the table live, unless you use the <code>READ UNCOMMITTED</code> option:</p>
<pre><code>SELECT *
FROM table_log WITH (READUNCOMMITTED);
</code></pre>
<p>or</p>
<pre><code>SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
SELECT *
FROM table_log;
</code></pre>
<p>To solve rollback issues, put an increasing ID on the log table, and use this code:</p>
<pre><code>SET XACT_ABORT OFF;
BEGIN TRY
BEGIN TRANSACTION mytran;
-- already committed logs are not affected by a potential rollback
-- so only save logs created in this transaction
DECLARE @max_log_id = (SELECT MAX(ID) FROM table_log);
/*
* do stuff, log the stuff
*/
COMMIT TRANSACTION mytran;
END TRY
BEGIN CATCH
DECLARE @log_table_saverollback TABLE
(
ID INT,
Msg NVARCHAR(1024),
LogTime DATETIME
);
INSERT INTO @log_table_saverollback(ID, Msg, LogTime)
SELECT ID, Msg, LogTime
FROM table_log
WHERE ID > @max_log_id;
ROLLBACK TRANSACTION mytran; -- this deletes new log entries from the log table
SET IDENTITY_INSERT table_log ON;
INSERT INTO table_log(ID, Msg, LogTime)
SELECT ID, Msg, LogTime
FROM @log_table_saverollback;
SET IDENTITY_INSERT table_log OFF;
END CATCH
</code></pre>
<p>Notice these important details:</p>
<ol>
<li><code>SET XACT_ABORT OFF;</code> prevents SQL Server from just shutting down the entire transaction instead of running your catch block, always include it if you use this technique.</li>
<li>Use a <code>@table_variable</code>, not a <code>#temp_table</code>. Temp tables are also affected by rollbacks.</li>
</ol>
| 39,490
|
<p>I'm specifically interested in Windows 2000/XP, but Vista/7 would be interesting too (if different).</p>
<p>I was thinking along the lines of task scheduling a batch file or equivalent on a daily basis.</p>
<p>EDIT: Sorry, I should have provided more info. The question pertains to 10 machines which I manually apply updates. I don't want to install the updates programatically, but just find out if there are updates ready to download/install (i.e. the update shield icon in the system tray is indicating this) using a batch or script. Thanks.</p>
|
<p>You could use <code>WUApiLib</code>:</p>
<pre class="lang-cs prettyprint-override"><code>UpdateSessionClass session = new UpdateSessionClass();
IUpdateSearcher search = session.CreateUpdateSearcher();
ISearchResult result = search.Search("IsInstalled=0 and IsPresent=0 and Type='Software'");
int numberOfUpdates = result.Updates.Count - 1;
Log.Debug("Found " + numberOfUpdates.ToString() + " updates");
UpdateCollection updateCollection = new UpdateCollection();
for (int i = 0; i < numberOfUpdates; i++)
{
IUpdate update = result.Updates[i];
if (update.EulaAccepted == false)
{
update.AcceptEula();
}
updateCollection.Add(update);
}
if (numberOfUpdates > 0)
{
UpdateCollection downloadCollection = new UpdateCollection();
for (int i = 0; i < updateCollection.Count; i++)
{
downloadCollection.Add(updateCollection[i]);
}
UpdateDownloader downloader = session.CreateUpdateDownloader();
downloader.Updates = downloadCollection;
IDownloadResult dlResult = downloader.Download();
if (dlResult.ResultCode == OperationResultCode.orcSucceeded)
{
for (int i = 0; i < downloadCollection.Count; i++)
{
Log.Debug(string.Format("Downloaded {0} with a result of {1}", downloadCollection[i].Title, dlResult.GetUpdateResult(i).ResultCode));
}
UpdateCollection installCollection = new UpdateCollection();
for (int i = 0; i < updateCollection.Count; i++)
{
if (downloadCollection[i].IsDownloaded)
{
installCollection.Add(downloadCollection[i]);
}
}
UpdateInstaller installer = session.CreateUpdateInstaller() as UpdateInstaller;
installer.Updates = installCollection;
IInstallationResult iresult = installer.Install();
if (iresult.ResultCode == OperationResultCode.orcSucceeded)
{
updated = installCollection.Count.ToString() + " updates installed";
for (int i = 0; i < installCollection.Count; i++)
{
Log.Debug(string.Format("Installed {0} with a result of {1}", installCollection[i].Title, iresult.GetUpdateResult(i).ResultCode));
}
if (iresult.RebootRequired == true)
{
ManagementClass mcWin32 = new ManagementClass("Win32_OperatingSystem");
foreach (ManagementObject shutdown in mcWin32.GetInstances())
{
shutdown.Scope.Options.EnablePrivileges = true;
shutdown.InvokeMethod("Reboot", null);
}
}
}
</code></pre>
|
<p>The "easiest" way to tell is to setup Windows Updates to occur nightly and download the updates if available which then puts the update shield icon in the system tray. Just glance at the tray to see if the icon is present. </p>
<p>You could also setup Windows to check nightly for the updates, then download and install them at a specified time.</p>
| 14,782
|
<p>Is it possible to get the equivalent of the focus and blur events that we have on other form controls for the RTE? That is, I would like to know when a given RTE gets the focus and when it loses it.</p>
<p>I see that the RTE supports lots of events (<a href="http://developer.yahoo.com/yui/editor/#events" rel="nofollow noreferrer">http://developer.yahoo.com/yui/editor/#events</a>), but I don't see anything about focus/blur. Am I missing something?</p>
|
<p>If anyone finds this question and is looking for the answer, Dav Glass poste an answer in the YUI community forums <a href="http://tech.groups.yahoo.com/group/ydn-javascript/message/40867" rel="nofollow noreferrer">http://tech.groups.yahoo.com/group/ydn-javascript/message/40867</a> .</p>
|
<p>If anyone finds this question and is looking for the answer, Dav Glass poste an answer in the YUI community forums <a href="http://tech.groups.yahoo.com/group/ydn-javascript/message/40867" rel="nofollow noreferrer">http://tech.groups.yahoo.com/group/ydn-javascript/message/40867</a> .</p>
| 36,411
|
<p>I'm writing in second-person just because its easy, for you. </p>
<p>You are working with a game engine and really wish a particular engine class had a new method that does 'bla'. But you'd rather not spread your 'game' code into the 'engine' code.</p>
<p>So you could derive a new class from it with your one new method and put that code in your 'game' source directory, but maybe there's another option?</p>
<p>So this is probably completely illegal in the C++ language, but you thought at first, "perhaps I can add a new method to an existing class via my own header that includes the 'parent' header and some special syntax. This is possible when working with a namespace, for example..."</p>
<p>Assuming you can't declare methods of a class across multiple headers (and you are pretty darn sure you can't), what are the other options that support a clean divide between 'middleware/engine/library' and 'application', you wonder?</p>
|
<p>My only question to you is, "does your added functionality need to be a member function, or can it be a free function?" If what you want to do can be solved using the class's existing interface, then the only difference is the syntax, and you should use a free function (if you think that's "ugly", then... suck it up and move on, C++ wasn't designed for monkeypatching).</p>
<p>If you're trying to get at the internal guts of the class, it may be a sign that the original class is lacking in flexibility (it doesn't expose enough information for you to do what you want from the public interface). If that's the case, maybe the original class can be "completed", and you're back to putting a free function on top of it.</p>
<p>If absolutely none of that will work, and you just must have a member function (e.g. original class provided protected members you want to get at, and you don't have the freedom to modify the original interface)... only then resort to inheritance and member-function implementation.</p>
<p>For an in-depth discussion (and deconstruction of <code>std::string</code>'), check out this <a href="http://www.gotw.ca/gotw/084.htm" rel="noreferrer">Guru of the Week "Monolith" class article</a>.</p>
|
<p>Sounds like you want Ruby mixins. Not sure there's anything close in C++. I think you have to do the inheritance.</p>
<p>Edit: You might be able to put a friend method in and use it like a mixin, but I think you'd start to break your encapsulation in a bad way.</p>
| 28,264
|
<p>I use a basic Post to send data to a Django server.</p>
<p>The data consists of a base64 encoded 640*380 PNG image dynamically created by the flex
component.</p>
<pre><code><mx:HTTPService id="formSend" showBusyCursor="true"
useProxy="false" url="http://127.0.0.1/form/"
method="POST" result="formSentConfirmation(event)" fault="formSendingFailed(event)"/>
private function sendForm(url:String, message:String, meteo:Number):void {
formSend.url = url;
var params:Object = { message: message, image_data: getEncodedImage() };
snapButton.label = "sending ...";
formSend.send(params);
}
</code></pre>
<p>On the server side i can see that the data is in the request.POST
not in request.FILES. That means the image is not send as a File with multiencode HTTP.</p>
<ol>
<li><p>Will i get into trouble on a real server ? since the limit is 200k for urlencoded POST var.</p></li>
<li><p>How to make HTTPservice send the data as a file?</p></li>
<li><p>Any other solutions?</p></li>
</ol>
<p>Thanks</p>
|
<p>Found something interesting than we can dig on it. Use this:</p>
<pre><code>var urlLoader:URLLoader = new URLLoader();
urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
urlLoader.data = _img.data;
urlLoader.addEventListener(Event.COMPLETE,LoadedComplete);
var request:URLRequest = new URLRequest("www.url.com?toto=toto");
request.method = URLRequestMethod.POST
request.contentType = "multipart/form-data";
request.data = _img.data;
request.requestHeaders = new Array(new URLRequestHeader("toto", "toto"));
urlLoader.load(request);
</code></pre>
<p>Well with that i get something in C# server side the request content length is not empty and i got toto in the params and in the header, one problem in files collection there are no files sent ... where are the sent bytes ???</p>
|
<ol>
<li><p>Probably, yes. It depends whether you impose a hard limit on the the file size and how the destination page handles the request.</p></li>
<li><p>I don't believe it's actually possible at the moment.</p></li>
<li><p>Read <a href="http://livedocs.adobe.com/flex/201/html/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Book_Parts&file=17_Networking_and_communications_173_8.html" rel="nofollow noreferrer">this</a>. FileReference is the recommended way of uploading files.</p></li>
</ol>
| 47,703
|
<p>I just saw a really useful UI feature of the forthcoming Windows 7 ( visit <a href="http://www.gizmodo.com.au/2008/10/windows_7_walkthrough_boot_video_and_impressions-2.html" rel="nofollow noreferrer">http://www.gizmodo.com.au/2008/10/windows_7_walkthrough_boot_video_and_impressions-2.html</a> and scroll down to the video entitled Super Scientific Video of New Window Resizing Feature)</p>
<p>In a nutshell you can drag a window by the title bar to the top of the screen to maximise it, drag it back down to restore and drag it to the left edge or the right edge of the screen to have it snap into position butted up against the edge you dragged it to, and resized to occupy half the screen.</p>
<p>Now I know there are a bunch of keyboard-based apps that do "similar" things but I've not seen a mouse-based program that does JUST the above, simple, useful and nothing more. If you know of one (or are smart enough to write one) please post the URL :)</p>
<p>Anyway, if I wanted to try and write a small app to do this I have a question:</p>
<p><strong>If I wanted to try and write a small app to do this, could I write it as a .NET app? I guess hooking into Windows' window drag/drop handling is pretty low-level and maybe not something that could be done in C#.NET?</strong></p>
<p><em>any smartypants here who can knock a small app like this out in their lunchbreak? ;) I'm sure anything mimicing Windows 7 features would prove very popular, at least pre Windows 7's launch.</em></p>
<p><strong>Edit:</strong> The AeroSnap guys (<a href="http://www.aerosnap.de/index_eng.htm" rel="nofollow noreferrer">http://www.aerosnap.de/index_eng.htm</a>) have done a nice job of implementing this feature and judging by the number of downloads, it was a popular feature!</p>
|
<p>There's an offical way: <a href="http://code.msdn.microsoft.com/WindowsAPICodePack" rel="nofollow noreferrer">Windows API Code Pack</a></p>
<p>The Windows® API Code Pack for Microsoft® .NET Framework provides a source code library that can be used to access some new Windows 7 features (and some existing features of older versions of Windows operating system) from managed code. These Windows features are not available to developers today in the .NET Framework. </p>
<p>The individual features supported in this version (v1.0) of the library are:</p>
<p>Windows 7 Taskbar Jump Lists, Icon Overlay, Progress Bar, Tabbed Thumbnails, and Thumbnail Toolbars.
Windows 7 Libraries, Known Folders, non-file system containers.
Windows Shell Search API support, a hierarchy of Shell Namespace entities, and Drag and Drop functionality for Shell Objects.
Explorer Browser Control.
Shell property system.
Windows Vista and Windows 7 Common File Dialogs, including custom controls.
Windows Vista and Windows 7 Task Dialogs.</p>
|
<p>Yes, you can do this from C#, via PInvoke. Tbh, the best way to learn such APIs is by looking at the source of something like Bblean. This'll show you what you need to know and exposing it to PInvoke is pretty trivial.</p>
| 30,871
|
<p>I have a master page with one form on it. It is a search form which must always be visible. When the button of that form is clicked I want the form data to be sent to search.aspx. The problem is, I don't know how. I cannot set the form action to search.aspx, because all my other pages which use the master form will go to search.aspx. This I don't want.</p>
<p>Hope someone can help me out :)</p>
<p>Thnx.</p>
|
<p>In order to pass the values of the control "txtSearch", when Server.Transfer is executed, you could do many things, including passing it via a querystring variable or setting up a session variable, and then check either of those in the Page_Load event of Search.aspx, and if it's populated, call the event that is fired when the user would hit the submit button on the Search.aspx page.</p>
<p>Also, if the Search.aspx file is using the same masterpage, then you can use this.Master.FindControl("txtSearch") to get the control (it you look a the source of the file after it is generated in the browser, you'll notice that controls in the master page aren't really called by their ID, rather that have something appended to them (i.e. it would now possibly be called "ctl00_txtSearch")</p>
|
<p>ASP.NET webform pages only have one form (which would generally be included on the master page). You can set the postback url for the search button to your search page..</p>
<pre><code><asp:Button ID="btnSearch" runat="server" Text="Search" PostBackUrl="~/search.aspx" />
</code></pre>
<p>..or just redirect to it from the handler in your master page like this:</p>
<pre><code>protected void btnSearch_Click(object sender, EventArgs e)
{
Response.Redirect(@"~/search.aspx?q=" + Server.UrlEncode(txtSearch.Text));
}
</code></pre>
<p>..or use Server.Transfer as suggested by David Kemp.</p>
<p><strong>Note:</strong> If you use Request.Query[@"q"] on your search page to get your query, you don't need to use Server.UrlDecode() - it's done for you.</p>
| 41,049
|
<p>How would one change the view on the screen programmatically in an iPhone app?</p>
<p>I've been able to create navigation view's and programmatically push/pop them to produce this behaviour, but if I wanted to simply change the current view (not using a UINavigation controller object), what is the neatest way to achieve this?</p>
<p>A simple example, imagine an application with a single button, when pressed will display a new view, or possibly one of multiple views depending on some internal state variable.</p>
<p>I have yet to see any examples that attempt to do this, and I don't seem to understand enough about the relationships and initialisation procedure between UIViewController/UIView objects to achieve this programmatically.</p>
|
<p>I use <code>presentModalViewController:animated:</code> to bring up a settings view from my main window's <code>UIViewController</code> and then when the user presses "done" in the settings view I call <code>dismissModalViewControllerAnimated:</code> from the settings view (reaching back to the parent view) like this:</p>
<pre><code>[[self parentViewController] dismissModalViewControllerAnimated:YES];
</code></pre>
|
<p>How about pushing a generic UIView into the UINavigationController?</p>
<p>When you want one particular view shown, simply add it as a subview to that previously pushed UIView. When you want to change views, remove the previous subview and add the new one.</p>
| 48,336
|
<p>I am using asp.net 2.0 I know can set the pages title via the code behind. But is it possible to set the page title using Theme, skin or css?</p>
<p>I need to display a different title depending on the theme selected.</p>
|
<p>By inserting a Literal control in the Head-element of the page you should be able to apply a theme to it and thereby set its Text property.</p>
<p>If that doesn't work you can always check the Page.Theme property and set the pages title accordingly.</p>
|
<p>Not via CSS</p>
| 33,141
|
<p>What are the best free resources for learning advanced batch-file usage?</p>
|
<p>It's not free, but it's probably the best. <a href="https://rads.stackoverflow.com/amzn/click/com/1578700477" rel="noreferrer" rel="nofollow noreferrer">"Windows NT Shell Scripting" by Tim Hill</a>.</p>
<p>That said, whenever I try to do something 'advanced' in cmd batch files, I always end up regretting it. </p>
<p><strong>Always.</strong></p>
<p>edit: some explanation of the shortcomings of batch files:</p>
<ul>
<li>math capabilities are pathetic</li>
<li>quoting support is an afterthought - if you need to pass a quoted string as an argument to a command that needs to be quoted itself, reserve a spot at the asylum (actually, I'm not sure it's possible)</li>
<li>string manipulation is a patchwork of half implemented functionality</li>
</ul>
<p>Then there are the seemingly never-ending bits of oddities, corner cases, and inconsistencies that you run into at every turn.</p>
<p>The only thing going for batch files is that they're supported on every Windows box out there. If you just want to automate executing a few commands as a group, great. Maybe add a simple loop, a couple of subroutines, and some environment variables to parameterize things. Beyond that I strongly recommend you use something else.</p>
|
<p>Tried <a href="http://en.wikipedia.org/wiki/Batch_file" rel="nofollow noreferrer">Wikipedia's batch file entry</a>? ...or any of <a href="http://www.google.co.uk/search?q=advanced+batch+file+usage&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-GB:official&client=firefox-a" rel="nofollow noreferrer">the multitude of answers google gives on advanced batch file usage</a>?</p>
| 21,805
|
<p>Suppose a large composite application built on several foundation components packaged in their own assemblies: (database reading, protocol handlers, etc.). For some deployments, this can include over 20 assemblies. Each of these assemblies has settings or configuration information. Our team tends to like the VS settings editor (and the easy-to-use code it generates!), and the application vs. user distinction meets most of our needs.</p>
<p>BUT....</p>
<p>It is very tedious to copy & paste the many configuration sections into our application's .xml. Furthermore, for shared components that tend to have similar configurations across applications, this means we need to maintain duplicate settings in multiple .config files.</p>
<p>Microsoft's EntLib solves this problem with an external tool to generate the monster .config file, but this feels klunky as well.</p>
<p>What techniques do you use to manage large .NET .config files with sections from multiple shared assemblies? Some kind of include mechanism? Custom configuration readers?</p>
<p>FOLLOWUP:</p>
<p>Will's <a href="https://stackoverflow.com/questions/89245/how-do-you-manage-net-appconfig-files-for-large-applications#89618">answer</a> was exactly what I was getting at, and looks elegant for flat key/value pair sections. Is there a way to combine this approach with <a href="https://stackoverflow.com/questions/89245/how-do-you-manage-net-appconfig-files-for-large-applications#89618">custom configuration sections</a> ? </p>
<p>Thanks also for the suggestions about managing different .configs for different build targets. That's also quite useful.</p>
<p>Dave </p>
|
<p>You use one master config file that points to other config files. <a href="http://blog.andreloker.de/post/2008/06/Keep-your-config-clean-with-external-config-files.aspx" rel="noreferrer">Here's an example of how to do this.</a></p>
<hr>
<p>In case the link rots, what you do is specify the <a href="http://msdn.microsoft.com/en-us/library/system.configuration.sectioninformation.configsource.aspx" rel="noreferrer">configSource</a> for a particular configuration section. This allows you to define that particular section within a separate file.</p>
<pre class="lang-xml prettyprint-override"><code><pages configSource="pages.config"/>
</code></pre>
<p>which implies that there is a file called "pages.config" within the same directory that contains the entire <code><pages /></code> node tree.</p>
|
<p>We created an AssemblySettingsConfig class that acts like ConfigurationManager, but loads a .config for each individual assembly. So the application has a .config, and any DLLs it references have their own .config files. Has worked out well so far.</p>
| 11,482
|
<p>I've got a User table with a bitmask that contains the user's roles. The linq query below returns all the users whose roles include 1, 4 or 16. </p>
<pre><code>var users = from u in dc.Users
where ((u.UserRolesBitmask & 1) == 1)
|| ((u.UserRolesBitmask & 4) == 4)
|| ((u.UserRolesBitmask & 16) == 16)
select u;
</code></pre>
<p>I'd like to rewrite this into the method below to returns all the users from the given roles so I can reuse it:</p>
<pre><code>private List<User> GetUsersFromRoles(uint[] UserRoles) {}
</code></pre>
<p>Any pointers on how to dynamically build my query? Thanks</p>
|
<p>You can use the <a href="http://www.albahari.com/nutshell/predicatebuilder.aspx" rel="noreferrer">PredicateBuilder</a> class.</p>
<p>PredicateBuilder has been released in the <a href="https://www.nuget.org/packages/LinqKit/" rel="noreferrer">LINQKit NuGet package</a></p>
<blockquote>
<p>LINQKit is a free set of extensions for LINQ to SQL and Entity Framework power users.</p>
</blockquote>
|
<pre><code>private List<User> GetUsersFromRoles(uint UserRoles) {
return from u in dc.Users
where (u.UserRolesBitmask & UserRoles) != 0
select u;
}
</code></pre>
<p>UserRoles parameter should be provided, however, as a bit mask, instead of array.</p>
| 21,764
|
<p>I have to produce an RSS/Atom feed in various applications, and I want to know a good library or class which is able to produce both, and which already handles all common problems.</p>
<p>For example, the one I used for years does not put the right format for date, so my feed is not well-handled by several aggregators.</p>
<p><strong>Update:</strong>
Why I am looking for a library? Because the one I used for years, which I had hacked a few times, has a little problem. Maybe a specification is not being correctly followed.</p>
<p><a href="https://stackoverflow.com/questions/182615/why-my-rss-feed-duplicate-some-entries">Why does my RSS feed duplicate some entries?</a></p>
|
<p>The <a href="http://www.phpclasses.org/package/4427-PHP-Generate-feeds-in-RSS-1-0-2-0-an-Atom-formats.html" rel="noreferrer">PHP Universal Feed Generator</a> seems to be exactly what you're after - it has a simple, OO-based way of declaring a new feed and outputting it to your desired specification. </p>
<p>It also has built-in date format conversions as one of it's features.</p>
<blockquote>
<p>Features:</p>
<ul>
<li>Generates RSS 1.0, RSS 2.0 and ATOM 1.0 feeds</li>
<li>All feeds are are validated by feed validator.</li>
<li>Implements appropriate namespaces for different versions.</li>
<li>Automatically converts date formats.</li>
<li>Generates UUID for ATOM feeds.</li>
<li>Handles CDATA encoding for required tags.</li>
</ul>
<p>Supported versions:</p>
<ul>
<li>RSS 1.0 (which officially obsoleted RSS 0.90)</li>
<li>RSS 2.0 (which officially obsoleted RSS 0.91, 0.92, 0.93 and 0.94)</li>
<li>ATOM 1.0</li>
</ul>
</blockquote>
|
<p>PHP Universal Feed Generator is a good answer. I had just to modify the code accordingly to a comment on the webpage to handle correcly french characters.</p>
<p><a href="http://www.ajaxray.com/blog/2008/03/08/php-universal-feed-generator-supports-rss-10-rss-20-and-atom/#comment-341" rel="nofollow noreferrer">http://www.ajaxray.com/blog/2008/03/08/php-universal-feed-generator-supports-rss-10-rss-20-and-atom/#comment-341</a></p>
<blockquote>
<p>Like Kereste says (1. June) FeedWrite
makes problems with some none-english
utf-8 characters like ä etc.. this is
because xml only knows 5 entities
(&,”,’,). So I changed line 298 in the
source code into</p>
<p>$nodeText .= (in_array($tagName,
$this->CDATAEncoding))? $tagContent :
str_replace ( array ( ‘&’, ‘”‘, “‘”, ”
), array ( ‘&’ , ‘"’, ‘'’ , ‘<’ , ‘>’
), $tagContent);</p>
<p>to avoiod converting charakters into
wrong xml entities.</p>
</blockquote>
| 22,053
|
<p>I am using Borland Builder C++ 2009. I want to add a button to a form that allows the user to open a file in Excel that I specify. I can't think of how to do this. I know how to link with other code and executables -- is there a Microsoft Excel executable that I could use? How could I specify the file then? Any hints on this, or at least a place to look online, would be greatly appreciated.</p>
|
<p>Assuming that the file type is registered with Excel, you could call ShellExecute() on the file, using the "open" verb. This will cause the file to be opened as if double clicked by the user in Explorer and will invoke Excel.</p>
<p>If that isn't the case, and you can assume that Excel is installed, you could instead pass "excel" to ShellExecute() as the application, and the path of the file as the parameter. (Note that I didn't test this, but it worked from the Run dialog, so I think that it should work from ShellExecute() as well).</p>
|
<p><code>System()</code> command should be enough i think.
For any Windows application, we can open any file using the Location of .exe file and the File Path.</p>
<p>Eg.,</p>
<pre><code>system("PATH C:\\Program\ Files\\Microsoft\ Office\\OFFICE11;%PATH% & excel \"C:\\Documents and Settings\\User\\Desktop\\ExcelFile.xls\"");
</code></pre>
| 39,946
|
<p>At my workplace, the traffic blocker/firewall has been getting progressively worse. I can't connect to my home machine on port 22, and lack of ssh access makes me sad. I was previously able to use SSH by moving it to port 5050, but I think some recent filters now treat this traffic as IM and redirect it through another proxy, maybe. That's my best guess; in any case, my ssh connections now terminate before I get to log in.</p>
<p>These days I've been using Ajaxterm over HTTPS, as port 443 is still unmolested, but this is far from ideal. (Sucky terminal emulation, lack of port forwarding, my browser leaks memory at an amazing rate...) I tried setting up <code>mod_proxy_connect</code> on top of <code>mod_ssl</code>, with the idea that I could send a <code>CONNECT localhost:22 HTTP/1.1</code> request through HTTPS, and then I'd be all set. Sadly, this seems to not work; the HTTPS connection works, up until I finish sending my request; then SSL craps out. It appears as though <code>mod_proxy_connect</code> takes over the whole connection instead of continuing to pipe through <code>mod_ssl</code>, confusing the heck out of the HTTPS client.</p>
<p>Is there a way to get this to work? I don't want to do this over plain HTTP, for several reasons:</p>
<ul>
<li>Leaving a big fat open proxy like that just stinks</li>
<li>A big fat open proxy is not good over HTTPS either, but with authentication required it feels fine to me</li>
<li>HTTP goes through a proxy -- I'm not <em>too</em> concerned about my traffic being sniffed, as it's ssh that'll be going "plaintext" through the tunnel -- but it's a lot more likely to be mangled than HTTPS, which fundamentally cannot be proxied</li>
</ul>
<p>Requirements:</p>
<ul>
<li>Must work over port 443, without disturbing other HTTPS traffic (i.e. I can't just put the ssh server on port 443, because I would no longer be able to serve pages over HTTPS)</li>
<li>I have or can write a simple port forwarder client that runs under Windows (or Cygwin)</li>
</ul>
<h2>Edit</h2>
<p><a href="http://dag.wieers.com/howto/ssh-http-tunneling/" rel="noreferrer">DAG: Tunnelling SSH over HTTP(S)</a> has been pointed out to me, but it doesn't help: at the end of the article, they mention <a href="http://issues.apache.org/bugzilla/show_bug.cgi?id=29744" rel="noreferrer">Bug 29744 - CONNECT does not work over existing SSL connection</a> preventing tunnelling over HTTPS, exactly the problem I was running into. At this point, I am probably looking at some CGI script, but I don't want to list that as a requirement if there's better solutions available.</p>
|
<p>Find out why the company has such a restrictive policy. It might be for a good reason.</p>
<p>If you still find that you want to bypass the policy, you could write a small proxy that will listen on your server on port 443 and then, depending on the request, will forward the traffic either to your web server or to the SSH daemon. There are two catches though.</p>
<ol>
<li><p>To determine whether it's an HTTPS request or an SSH request, you need to try to read some data with a (small) timeout, this is because TLS/SSL handshakes start with the client sending some data, whereas the SSH handshake starts with the server sending some data. The timeout has to be big enough to delays in delivering the initial data from the client in the TLS/SSL handshake, so it'll make establishing SSH connections slower.</p>
</li>
<li><p>If the HTTP proxy in your company is smart, it'll actually eavesdrop on the expected TLS/SSL "handshake" when you <code>CONNECT</code> to port 443, and, when it detects that it's not an TLS/SSL handshake, it might terminate the SSH connection attempt. To address that, you could wrap the SSH daemon into an TLS/SSL tunnel (e.g., <code>stunnel</code>), but then you'll need to differentiate requests based on the TLS/SSL version in your client request to determine whether to route the TLS/SSL connection to the web server or to the TLS/SSL-tunneled SSH daemon.</p>
</li>
</ol>
|
<blockquote>
<p>Must work over port 443, without disturbing other HTTPS traffic (i.e. I can't just put the ssh server on port 443, because I would no longer be able to serve pages over HTTPS)</p>
</blockquote>
<p>Is it possible to bind your HTTPS server to a different port? Depending on what it's used for, you may even be able to get around the problem of not being able to directly access it from work by just SSHing home and then using lynx from there.</p>
| 21,884
|
<p>There's a lot of interest these days in Erlang as a language for writing parallel programs on multicore. I've heard people argue that Erlang's message-passing model is easier to program than the dominant shared-memory models such as threads. </p>
<p>Conversely, in the high-performance computing community the dominant parallel programming model has been MPI, which also implements a message-passing model. But in the HPC world, this message-passing model is generally considered very difficult to program in, and people argue that shared memory models such as OpenMP or UPC are easier to program in. </p>
<p>Does anybody know why there is such a difference in the perception of message-passing vs. shared memory in the IT and HPC worlds? Is it due to some fundamental difference in how Erlang and MPI implement message passing that makes Erlang-style message-passing much easier than MPI? Or is there some other reason? </p>
|
<p>I agree with all previous answers, but I think a key point that is not made totally clear is that one reason that MPI might be considered hard and Erlang easy is the match of model to the domain. </p>
<p>Erlang is based on a concept of local memory, asynchronous message passing, and shared state solved by using some form of global database that all threads can get to. It is designed for applications that do not move a whole lot of data around, and that is not supposed to explode out to a 100k separate nodes that need coordination.</p>
<p>MPI is based on local memory and message passing, and is intended for problems where moving data around is a key part of the domain. High-performance computing is very much about taking the dataset for a problem, and splitting it up among a host of compute resources. And that is pretty hard work in a message-passing system as data has to be explicitly distributed with balancing in mind. Essentially, MPI can be viewed as a grudging admittance that shared memory does not scale. And it is targeting high-performance computation spread across 100k processors or more. </p>
<p>Erlang is not trying to achieve the highest possible performance, rather to decompose a naturally parallel problem into its natural threads. It was designed with a totally different type of programming tasks in mind compared to MPI. </p>
<p>So Erlang is best compared to pthreads and other rather local heterogeneous thread solutions, rather than MPI which is really aimed at a very different (and to some extent inherently harder) problem set.</p>
|
<p>Regarding MPI vs OpenMP/UPC: MPI forces you to slice the problem in small pieces and take responsibility for moving data around. With OpenMP/UPC, "all the data is there", you just have to dereference a pointer. The MPI advantage is that 32-512 CPU clusters are much cheaper than 32-512 CPU single machines. Also, with MPI the expense is upfront, when you design the algorithm. OpenMP/UPC can hide the latencies that you'll get at runtime, if your system uses NUMA (and all big systems do) - your program won't scale and it will take a while to figure out why.</p>
| 22,424
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.