instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>I have a bunch of controls (textbox and combobox) on a form with toolstripcontainer and toolstripbuttons for save, cancel etc for edits. We are using .Net 3.5 SP1<br>
There is bunch of logic written in control.lostfocus and control.leave events. These events are not being called when clicked on the toolstrip buttons. Is there a way to call these events manually when any of these buttons are pressed.</p>
<p>Thanks.<br>
Kishore</p>
<p>[Edit]</p>
<p>This is how I solved the problem. Thanks <em><a href="https://stackoverflow.com/questions/287685/raise-lostfocus-event-on-a-control-manually-c#287740">Chris Marasti-Georg</a></em> for the pointer. In the button click event I calling focus on the toolstrip instead of the button as the toolstripbutton does not have a focus event. We can access the toolstrip on which the button is placed using</p>
<p>((ToolStripButton)sender).Owner.Focus()</p>
<p>-Kishore</p>
|
<p>You could listen to the click events on the buttons, and in the handler call their focus method. That would (hopefully) cause the previously focused control to respond correctly. Add the following handler to each button's click event:</p>
<pre><code>private void ButtonClick(object sender, EventArgs e) {
if(sender != null) {
sender.Focus();
}
}
</code></pre>
|
<p>You can extend those controls and then call the OnLostFocus and OnLeave protected methods of the base class...</p>
| 36,606
|
<p>How to implement CEditListCtrl?. List control with edit capabality (Report/Grid view).
I have a list view in Report View. It has some values. I need to extend this to edit the values present in the list view.
I declared a class which inherits from CListCtrl. And I have handled the two Window messages to start and end the edit. Upon getting the messages I am displaying a Text box. But I am not getting the control inside these message handlers. Is there a way to know the reason?</p>
<p>Or Is there a other way to implement this.</p>
|
<p>Thanks for all answers</p>
<p>I have done it easily.</p>
<ol>
<li>I have handled the WM_LBUTTONDOWN. This handler pops up the edit box to get the new
value for the field</li>
<li>Handled LVN_ENDLABELEDIT to know the end of update.</li>
<li>After receiving the above message, updated the values.</li>
</ol>
<p>“One thing I forgotten was to set the flag in the resource view for CListCtrl (Edit Labels to TRUE)”</p>
<p>We have to implement OnPaint() (in CListCtrl's derived class) also otherwise the UI won't update properly</p>
|
<p>You need to use a CComboBox which is basically a combined CEdit and CListCtrl</p>
| 35,133
|
<p>I'm printing with a Prusa MK3, with the following settings:</p>
<ul>
<li>3 perimeters</li>
<li>50 % infill</li>
<li>infill overlap: 50 %</li>
</ul>
<p>The filament is Polyalchemy emerald green (PLA). Nozzle temperature: 210 °C.</p>
<p>On a simple part (it's a keychain), the shell detaches if I apply a bit of force on a zone of the part that is "fragile". See picture. You might not be able to see it, but only the 2 external perimeters detach from the rest of the part. I used to print this part on another printer, and I never observed this problem.</p>
<p>Any idea on how to solve this problem? It seems the 3 external perimeters didn't fuse properly.</p>
<p><a href="https://i.stack.imgur.com/cUI0O.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cUI0O.jpg" alt="enter image description here"></a></p>
|
<p>I ultimately concluded that the material isn't great. I printed this part with multiple other PLAs and never observed any problem. The Polyalchemy PLA looks great, but for any part that has some sort of mechanical constraint, it behaves poorly.</p>
|
<p>I am looking at your picture, and I realize that it is not only that the perimeter is detaching from the infill, but also that the perimeter is breaking.</p>
<p>Once the perimeter breaks, the weaker connection with the infill will surely break, too.</p>
<p>You could try:</p>
<ol>
<li>Using more than two perimeter layers. Go big. Try five.</li>
<li>Add a fillet where the ring attaches so that the force is not focused on a point.</li>
<li>Choose an infill percentage and pattern that maximizes the contact between the perimeter and the body.</li>
<li>Change the angle on the bed at which the keychain is printed so that the infill maximally connects with the breaking point. That might make the ring be 45 degrees off the X and Y axes.</li>
</ol>
| 1,531
|
<p>I have the following problem: Multithreaded WPF application, Model View Presenter Implementation. Presenters and Views that belong together are created on a separate thread and get a separate Dispatcher. Now someone calls from another thread a method on the Presenter. I am intercepting the call, and now begins the problem: if the call comes from the same thread as the presenter, i want to proceed with the call, else invoke the call on the Dispatcherthread, so that i don't need to care about UI calls.
I have already read about the use of SynchronizationContext, but that doesnt seem to work for me because if the calling thread is no UI thread i can't compare the 2 contexts. Whats a possible, working and elegant solution ?</p>
|
<pre><code>if( presenterDispatcherObject.CheckAccess() )
Doit();
else
presenterDispatcherObject.BeginInvoke( DispatcherPriority.Normal, () => DoIt() );
</code></pre>
|
<p>If you want the Dispatcher call to block (wait for return), I would use Invoke instead of BeginInvoke. This would mimic more of the behavior of actually calling the function directly. Invoke blocks calling thread until function is finshed (more like a Win32 SendMessage). BeginInvoke just posts and returns without waiting for function to return (like a Win32 PostMessage).</p>
<p>CheckAccess is slow. I would limit CheckAccess by keeping the calls less chatty on different threads.</p>
<pre><code>public delegate bool MyFuncHandler(object arg);
bool ThreadedMyFunc(object arg)
{
//...
bool result;
//...
// use dispatcher passed in, I would pass into the contructor of your class
if (dispatcher.CheckAccess())
{
result = MyFunc(arg);
}
else
{
result = dispatcher.Invoke(new MyFuncHandler(MyFunc), arg);
}
return result;
}
bool MyFunc(object arg)
{
//...
}
</code></pre>
| 44,276
|
<p>We're seeing some pernicious, but rare, deadlock conditions in the Stack Overflow SQL Server 2005 database.</p>
<p>I attached the profiler, set up a trace profile using <a href="http://www.simple-talk.com/sql/learn-sql-server/how-to-track-down-deadlocks-using-sql-server-2005-profiler/" rel="noreferrer">this excellent article on troubleshooting deadlocks</a>, and captured a bunch of examples. The weird thing is that <strong>the deadlocking write is <em>always</em> the same</strong>:</p>
<pre><code>UPDATE [dbo].[Posts]
SET [AnswerCount] = @p1, [LastActivityDate] = @p2, [LastActivityUserId] = @p3
WHERE [Id] = @p0
</code></pre>
<p>The other deadlocking statement varies, but it's usually some kind of trivial, simple <strong>read</strong> of the posts table. This one always gets killed in the deadlock. Here's an example</p>
<pre><code>SELECT
[t0].[Id], [t0].[PostTypeId], [t0].[Score], [t0].[Views], [t0].[AnswerCount],
[t0].[AcceptedAnswerId], [t0].[IsLocked], [t0].[IsLockedEdit], [t0].[ParentId],
[t0].[CurrentRevisionId], [t0].[FirstRevisionId], [t0].[LockedReason],
[t0].[LastActivityDate], [t0].[LastActivityUserId]
FROM [dbo].[Posts] AS [t0]
WHERE [t0].[ParentId] = @p0
</code></pre>
<p>To be perfectly clear, we are not seeing write / write deadlocks, but read / write.</p>
<p>We have a mixture of LINQ and parameterized SQL queries at the moment. We have added <code>with (nolock)</code> to all the SQL queries. This may have helped some. We also had a single (very) poorly-written badge query that I fixed yesterday, which was taking upwards of 20 seconds to run every time, and was running every minute on top of that. I was hoping this was the source of some of the locking problems!</p>
<p>Unfortunately, I got another deadlock error about 2 hours ago. Same exact symptoms, same exact culprit write.</p>
<p>The truly strange thing is that the locking write SQL statement you see above is part of a very specific code path. It's <em>only</em> executed when a new answer is added to a question -- it updates the parent question with the new answer count and last date/user. This is, obviously, not that common relative to the massive number of reads we are doing! As far as I can tell, we're not doing huge numbers of writes anywhere in the app.</p>
<p>I realize that NOLOCK is sort of a giant hammer, but most of the queries we run here don't need to be that accurate. Will you care if your user profile is a few seconds out of date?</p>
<p>Using NOLOCK with Linq is a bit more difficult as <a href="http://www.hanselman.com/blog/GettingLINQToSQLAndLINQToEntitiesToUseNOLOCK.aspx" rel="noreferrer">Scott Hanselman discusses here</a>.</p>
<p>We are flirting with the idea of using</p>
<pre><code>SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
</code></pre>
<p>on the base database context so that all our LINQ queries have this set. Without that, we'd have to wrap every LINQ call we make (well, the simple reading ones, which is the vast majority of them) in a 3-4 line transaction code block, which is ugly.</p>
<p>I guess I'm a little frustrated that trivial reads in SQL 2005 can deadlock on writes. I could see write/write deadlocks being a huge issue, but <em>reads?</em> We're not running a banking site here, we don't need perfect accuracy every time.</p>
<p>Ideas? Thoughts?</p>
<hr>
<blockquote>
<p>Are you instantiating a new LINQ to SQL DataContext object for every operation or are you perhaps sharing the same static context for all your calls?</p>
</blockquote>
<p>Jeremy, we are sharing one static datacontext in the base Controller for the most part:</p>
<pre><code>private DBContext _db;
/// <summary>
/// Gets the DataContext to be used by a Request's controllers.
/// </summary>
public DBContext DB
{
get
{
if (_db == null)
{
_db = new DBContext() { SessionName = GetType().Name };
//_db.ExecuteCommand("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED");
}
return _db;
}
}
</code></pre>
<p>Do you recommend we create a new context for every Controller, or per Page, or .. more often?</p>
|
<p>According to MSDN:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms191242.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms191242.aspx</a></p>
<blockquote>
<p>When either the
READ COMMITTED SNAPSHOT or
ALLOW SNAPSHOT ISOLATION database
options are ON, logical copies
(versions) are maintained for all data
modifications performed in the
database. Every time a row is modified
by a specific transaction, the
instance of the Database Engine stores
a version of the previously committed
image of the row in tempdb. Each
version is marked with the transaction
sequence number of the transaction
that made the change. The versions of
modified rows are chained using a link
list. The newest row value is always
stored in the current database and
chained to the versioned rows stored
in tempdb.</p>
<p>For short-running transactions, a
version of a modified row may get
cached in the buffer pool without
getting written into the disk files of
the tempdb database. If the need for
the versioned row is short-lived, it
will simply get dropped from the
buffer pool and may not necessarily
incur I/O overhead.</p>
</blockquote>
<p>There appears to be a slight performance penalty for the extra overhead, but it may be negligible. We should test to make sure.</p>
<p>Try setting this option and REMOVE all NOLOCKs from code queries unless it’s really necessary. NOLOCKs or using global methods in the database context handler to combat database transaction isolation levels are Band-Aids to the problem. NOLOCKS will mask fundamental issues with our data layer and possibly lead to selecting unreliable data, where automatic select / update row versioning appears to be the solution.</p>
<pre><code>ALTER Database [StackOverflow.Beta] SET READ_COMMITTED_SNAPSHOT ON
</code></pre>
|
<p>I would have to agree with Greg so long as setting the isolation level to read uncommitted doesn't have any ill effects on other queries.</p>
<p>I'd be interested to know, Jeff, how setting it at the database level would affect a query such as the following:</p>
<pre><code>Begin Tran
Insert into Table (Columns) Values (Values)
Select Max(ID) From Table
Commit Tran
</code></pre>
| 4,038
|
<p>I'd like to pull a stream of PCM samples from a Mac's line-in or built-in mic and do a little live analysis (the exact nature doesn't pertain to this question, but it could be an FFT every so often, or some basic statistics on the sample levels, or what have you).</p>
<p>What's a good fit for this? Writing an AudioUnit that just passes the sound through and incidentally hands it off somewhere for analysis? Writing a JACK-aware app and figuring out how to get it to play with the JACK server? Ecasound?</p>
<p>This is a cheesy proof-of-concept hobby project, so simplicity of API is the driving factor (followed by reasonable choice of programming language).</p>
|
<p>I think <a href="http://www.portaudio.com/" rel="noreferrer">portaudio</a> is what you need.
Reading from the mike from a console app is a 10 line C file (see patests in the portaudio distrib).</p>
|
<p>Apple provides sample code for <a href="https://developer.apple.com/library/content/navigation/index.html#topic=Sample+Code&section=Resource+Types" rel="nofollow noreferrer">reading and writing audio data</a>. Additionally there is a lot of good information in the <a href="http://developer.apple.com/audio/" rel="nofollow noreferrer">Audio section of the Apple Developer site</a>.</p>
| 5,825
|
<p>Pretty straightforward stuff, here -- I'm just not good enough with mysql to understand what it wants from me.</p>
<p>I've got a short java test-case that opens a connection on mysql on my dev system but, when I try to put it to my server, it fails.</p>
<p>Any help in tracking this down would be most appreciated.</p>
<p>Thanks!</p>
<p><strong>Test Code</strong></p>
<pre><code>import java.util.*;
import java.sql.*;
public class mysqltest {
static public void getDBConnection() {
System.out.println ("Start of getDBConnection.");
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "magnets_development";
String driver = "com.mysql.jdbc.Driver";
String userName = "*****"; // blanked for publication
String password = "*****";
try {
Class.forName (driver).newInstance();
System.out.println ("driver.newInstance gotten.");
conn = DriverManager.getConnection (url+dbName, userName, password);
System.out.println ("Connection gotten: " + conn + ".");
Statement sql = conn.createStatement ();
ResultSet results = sql.executeQuery ("use " + dbName + ";");
}
catch (Exception ex) {
System.out.println ("*** Got exception.");
ex.printStackTrace();
}
}
public static void main(String args[]) {
System.out.println ("Main started.");
mysqltest.getDBConnection();
}
}
</code></pre>
<p><strong>Dev System Output</strong> <em>(Expected/correct response)</em></p>
<pre><code>olie$ java mysqltest
Main started.
Start of getDBConnection.
Properties set.
driver.newInstance gotten.
Connection gotten: com.mysql.jdbc.Connection@c980c9.
olie$
</code></pre>
<p><strong>Server Output</strong> <em>(Error I'm trying to track-down)</em> (Some blank lines removed.)</p>
<pre><code>mini$ java mysqltest
Main started.
Start of getDBConnection.
Properties set.
driver.newInstance gotten.
*** Got exception.
com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception:
** BEGIN NESTED EXCEPTION **
java.net.ConnectException
MESSAGE: Connection refused
STACKTRACE:
java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:432)
at java.net.Socket.connect(Socket.java:520)
at java.net.Socket.connect(Socket.java:470)
at java.net.Socket.<init>(Socket.java:367)
at java.net.Socket.<init>(Socket.java:209)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:256)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:271)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:2771)
at com.mysql.jdbc.Connection.<init>(Connection.java:1555)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
at java.sql.DriverManager.getConnection(DriverManager.java:525)
at java.sql.DriverManager.getConnection(DriverManager.java:140)
at mysqltest.getDBConnection(mysqltest.java:34)
at mysqltest.main(mysqltest.java:49)
** END NESTED EXCEPTION **
Last packet sent to the server was 3 ms ago.
at com.mysql.jdbc.Connection.createNewIO(Connection.java:2847)
at com.mysql.jdbc.Connection.<init>(Connection.java:1555)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
at java.sql.DriverManager.getConnection(DriverManager.java:525)
at java.sql.DriverManager.getConnection(DriverManager.java:140)
at mysqltest.getDBConnection(mysqltest.java:34)
at mysqltest.main(mysqltest.java:49)
mini$
</code></pre>
|
<p>Bah! My apologies -- I just had "local connections only" set up. I was confused by the fact that the java app was running locally (so seemed a "local connection" but, because it is connecting via TCP, it's a "remote" connection, even though it originates on localhost.</p>
<p>I will eventually learn how to administer these things. In the mean time, I hope someone else can learn from my mistakes.</p>
<p>Thank you to all who put time into trying to help me. I have since allowed "remote" connections, but all of my user-accounts are 'username'@'localhost" only (<em>i.e.</em>, there is no 'username'@'%', which would allow any machine to connect.) Hopefully, I got that part right, at least.</p>
<p>Thanks again!</p>
|
<p>Here is my code that works on mysql on os X</p>
<pre><code>public SQL(String host, String port, String database, String userid, String password)
{
queryType = QUERYTYPE.Single;
String driver = "org.gjt.mm.mysql.Driver";
String url = "jdbc:mysql://" + host;
if (port != null)
{
url += ":" + port;
}
else
{
url += ":" + defaultPort;
}
url += "/" + database;
try
{
Class.forName(driver);
connection = DriverManager.getConnection(url, userid, password);
}
catch (Exception e)
{
e.printStackTrace();
}
}
</code></pre>
| 47,883
|
<p>Does anyone know of a Java library that provides a useful abstraction for analyzing and manipulating arbitrary relational database schemata? I'm thinking of something that could do things like</p>
<pre><code>LibraryClass dbLib = ...;
DbSchema schema = dbLib.getSchema("my_schema");
List<DbTable> tables = schema.getTables();
</code></pre>
<p>and</p>
<pre><code>DbTable myTable = ...
for(DbColumn col : myTable.getColumns()){
... = col.getType();
}
</code></pre>
<p>or even manipulate tables like</p>
<pre><code>myTable.addColumn(
new DbColumn("my_new_column", Type.UNSIGNED_INTEGER);
);
DbColumn myColumn = ...
myTable.removeColumn(myColumn);
</code></pre>
<p>Most Database modeling tools will have such an abstraction internally, but is there one in Java that I can use, or will I have to roll my own?</p>
|
<p>JDBC itself has such an abstraction. Look at java.sql.DatabaseMetaData. However, this is an optional part of the standard and it depends on the JDBC driver you are using wether it is implemented or not.</p>
|
<p>I haven't used it in years but Hibernate used to have <a href="http://www.hibernate.org/255.html" rel="nofollow noreferrer">tools for manipulating data models</a> at build time. Hibernate also has the notion dialects which would be helpful if you're targeting more than one database vendor. </p>
| 36,976
|
<p>I'm curious to know how NULLs are stored into a database ?</p>
<p>It surely depends on the database server but I would like to have an general idea about it.</p>
<hr>
<p>First try:</p>
<p>Suppose that the server put a undefined value (could be anything) into the field for a NULL value.</p>
<p>Could you be very lucky and retrieve the NULL value with</p>
<pre><code>...WHERE field = 'the undefined value (remember, could be anything...)'
</code></pre>
<hr>
<p>Second try:</p>
<p>Does the server have a flag or any meta-data somewhere to indicate this field is NULL ?</p>
<p>Then the server must read this meta data to verify the field.</p>
<p>If the meta-data indicates a NULL value and if the query doesn't have "field IS NULL",
then the record is ignored.</p>
<hr>
<p>It seems too easy...</p>
|
<p>On PostgreSQL, it uses an optional bitmap with one bit per column (0 is null, 1 is not null). If the bitmap is not present, all columns are not null.</p>
<p>This is completely separate from the storage of the data itself, but is on the same page as the row (so both the row and the bitmap are read together).</p>
<p>References:</p>
<ul>
<li><a href="http://www.postgresql.org/docs/8.3/interactive/storage-page-layout.html" rel="noreferrer">http://www.postgresql.org/docs/8.3/interactive/storage-page-layout.html</a></li>
</ul>
|
<p>IBM Informix Dynamic Server uses special values to indicate nulls. For example, the valid range of values for a SMALLINT (16-bit, signed) is -32767..+32767. The other value, -32768, is reserved to indicate NULL. Similarly for INTEGER (4-byte, signed) and BIGINT (8-byte, signed). For other types, it uses other special representations (for example, all bits 1 for SQL FLOAT and SMALLFLOAT - aka C double and float, respectively). This means that it doesn't have to use extra space.</p>
<p>IBM DB2 for Linux, Unix, Windows uses extra bytes to store the null indicators; AFAIK, it uses a separate byte for each nullable field, but I could be wrong on that detail.</p>
<p>So, as was pointed out, the mechanisms differ depending on the DBMS.</p>
| 31,693
|
<p>I work on a W3C XML Schema (not written by me). One tool, xmllint,
refuses to use the schema:</p>
<pre><code>traceroute.xsd:658: element element: Schemas parser error : Element
'{http://www.w3.org/2001/XMLSchema}element', attribute 'maxOccurs': The value
'4294967295' is not valid. Expected is '(xs:nonNegativeInteger | unbounded)'.
</code></pre>
<p>4294967295 is 2^32-1 so, clearly, xmllint implements integers with
signed 32bits number and that's not enough.</p>
<p>Is xmllint right? The standard apparently does not limit the size of
integers:</p>
<p><a href="http://www.w3.org/TR/2004/REC-xmlschema-1-20041028/structures.html#p-max_occurs" rel="nofollow noreferrer">http://www.w3.org/TR/2004/REC-xmlschema-1-20041028/structures.html#p-max_occurs</a>
<a href="http://www.w3.org/TR/2004/REC-xmlschema-2-20041028/datatypes.html#nonNegativeInteger" rel="nofollow noreferrer">http://www.w3.org/TR/2004/REC-xmlschema-2-20041028/datatypes.html#nonNegativeInteger</a></p>
<blockquote>
<p>The value space of nonNegativeInteger
is the infinite set {0,1,2,...}.</p>
</blockquote>
<p>So, implementors are supposed to use infinite integers...</p>
<p>What are the best practices? </p>
<p>Should implementors use bigints or similar things? (In that case,
xmllint is wrong.)</p>
<p>Should schema authors limit themselves to "reasonable" values for
maxOccurs? (In that case, I will report the issue to the schema
authors.)</p>
|
<p>While perhaps being a 'technically' correct usage of the <code>maxOccurs</code> attribute, this usage isn't (IMO) how the <code>maxOccurs</code> is intended to be used.</p>
<p>It looks like the schema writer intended to mean that this element may occur any number of times, in which case the correct value of the definition would be <code>unbounded</code>.</p>
<p>What the current definition implies is that the systems consuming this schema will behave perfectly correctly for element counts up to <code>4294967295</code> but will fail for anything larger.</p>
<p>I suppose this is a technical requirement that could make sense - lots of systems will have <code>int32</code> coded as the maximum number of elements so in an ideal world you might want to enforce this limit, but I don't think it is really a reasonable or useful thing to try and capture in a schema in the real world. </p>
<p>Also, if you are sending that many elements, then XML is probably the wrong data format.</p>
<p>I'd suggest that the schema authors use the <code>unbounded</code> attribute value, or use values that actually match the limitations and requirements of the systems consuming this XML.</p>
|
<p>The maximum value for maxOccurs is 4095. <br>
If you want more, set it to "unbounded".<br>
Reference:
<a href="https://learn.microsoft.com/en-us/biztalk/core/technical-reference/max-occurs-node-property-of-all-schemas" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/biztalk/core/technical-reference/max-occurs-node-property-of-all-schemas</a> </p>
<p>Hope this help!</p>
| 38,473
|
<p>I've written a WPF UserControl, and want to add one or more of it to my Window at runtime when I click a button. How can I do that?</p>
<p>Edit: Further specification
I want to add the usercontrols to a Canvas, and put in a absolute position. The canvas is a drawing of the floors in my house, and each usercontrol has properties to indicate where in the house it is positioned. So I want all the controls to be positioned in the correct position on the canvas.</p>
<p>I'm thinking something like this</p>
<pre><code>var light = new LightUserControl(2);
HouseCanvas.Children.Add(light); // this should be positioned in a specific place
</code></pre>
|
<p>After you add the your control to the Canvas you need to specify the top and left co-ordinates using the Canvas.Top and Canvas.Left attached properties as follows.</p>
<pre><code>var light = new LightUserControl(2);
HouseCanvas.Children.Add(light);
Canvas.SetLeft(light, 20);
Canvas.SetTop(light, 20);
</code></pre>
|
<pre><code> public static void AddChild(this Visual parent, UIElement child)
{
if (InternalAddChild(parent, child))
{
return;
}
throw new NotSupportedException();
}
private static bool InternalAddChild(Visual parent, UIElement child)
{
Panel panel = parent as Panel;
if (panel != null)
{
panel.Children.Add(child);
return true;
}
for (int i = VisualTreeHelper.GetChildrenCount(parent) - 1; i != -1; i--)
{
Visual target = VisualTreeHelper.GetChild(parent, i) as Visual;
if (target != null && InternalAddChild(target, child))
{
return true;
}
}
return false;
}
</code></pre>
| 40,096
|
<p>I have worked on iPhone application but not aware of the formalities to submit it to Apple Store. Please somebody help me out to solve the following queries:</p>
<p>Are their any submission charge to be paid?
And Procedure to submit application to Apple Store.</p>
<p>Thanks & Regards,
Khushi</p>
|
<p>Once you've paid to join the developer program, there is no additional charge for actually submitting your application.</p>
<p>When you've logged in with your developer account, instructions for submitting applications should be available following the link Rhys gave. </p>
<p>My advice is <strong>read them very carefully</strong> before submitting, because some things cannot be changed once you've submitted your iPhone application - for example: the name of your app, and whether it will also run on the iPod Touch etc.</p>
|
<p>Isn't the iPhone Developer Standard Program restricted to 100 iPhone devices?
Although you distribute your application on the App store, you can't distribute it to more then 100 decives?
Please correct me if I'm wrong...</p>
| 39,242
|
<p>Using C#, does anyone know how to get the MarshalAsAttribute's Sizeconst value in runtime ?</p>
<p>Eg. I would like to retrieve the value of 10.</p>
<pre><code>[StructLayout[LayoutKind.Sequential, Pack=1]
Class StructureToMarshalFrom
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
public byte[] _value1;
}
</code></pre>
|
<p>Yup, with reflection:</p>
<pre><code>FieldInfo field = typeof(StructureToMarshalFrom).GetField("_value1");
object[] attributes = field.GetCustomAttributes(typeof(MarshalAsAttribute), false);
MarshalAsAttribute marshal = (MarshalAsAttribute) attributes[0];
int sizeConst = marshal.SizeConst;
</code></pre>
<p>(Untested, and obviously lacking rather a lot of error checking, but should work.)</p>
|
<pre><code>var x = new StructureToMarshalFrom();
var fields = x.GetType().GetFields();
var att = (MarshalAsAttribute[])fields[0].GetCustomAttributes(typeof(MarshalAsAttribute), false);
if (att.Length > 0) {
Console.WriteLine(att[0].SizeConst);
}
</code></pre>
| 24,571
|
<p>What do you recommend for setting up a shared server with php from a security/performance point of view?</p>
<ul>
<li>Apache mod_php (how do you secure that? other than safe_mode as it won't be in PHP6)</li>
<li>Apache CGI + suexec</li>
<li>Lighttpd and spawn a FastCGI per user</li>
</ul>
<p>LE: I'm not interested in using an already made control panel as i'm trying to write my own so i want to know what's the best way to setup this myself.
I was thinking in using Lighttpd and spawn a fastcgi for every hosted user making the fcgi process run under his credentials (there is a tutorial for this on lighttpd wiki).
This would be somewhat secure but would this affect performance (lots of users / memory needed for every fcgi) so much that it's not a viable solution?</p>
|
<p>Personally, while Lighttpd is OK, I would go with Nginx + FastCGI if you end up going with a lightweight webserver + FastCGI solution. I've run benchmarks and read all the code, and Nginx is an order of magnitude faster/more stable under load -- it's very good.</p>
<p>But, that's not what you asked. Essentially, I would say there's a spectrum of security/scaleability vs. speed tradeoffs in the three options you list, and you just need to decide where you want to be. If you're a shared hosting provider with untrusted users installing god-knows-what PHP apps you'll lean more toward security, if this is shared amongst more trusted users you might lean toward performance. Here are my thoughts:</p>
<p><strong>CGI + suexec:</strong> This is by far the most secure, and most efficient/scaleable for you in terms of numbers of users/sites in a shared hosting environment. Processes are spawned and memory used only as requests come in. Of course, the CGI-spawning makes this the slowest for execution time of individual scripts. How much slower? Well you would have to benchmark, but generally if people are running long-running apps (i.e. something like WordPress which takes 0.25-0.5 seconds just to load its libs and initialize on each request), then the CGI-spawning penalty starts to look pretty negligible in context.</p>
<p><strong>FastCGI:</strong> The issue here (and it doesn't matter if your webserver is Apache, Lighttpd or Nginx) is figuring out how many FCGI child processes you let each user leave running, because each process eats memory equal to the size of the PHP interpreter (in Linux not all of it is wired of course, but I digress). And, unlike mod_php, these processes aren't shared among users so you have to limit per user. For instance, Dreamhost caps this at 3 for their customers -- now, for a customer running a website that gets bursts of more than 2-5 page views a second, that's actually pretty bad because those requests just stack up and the site hangs. Now, I like FastCGI with a lightweight webserver when I'm running apps on a <em>dedicated</em> server/cluster, when I can give the app hundreds of FCGI children (all with webserver privs of course, à la Apache/prefork + mod_php). But, I don't think it makes sense for shared hosting where you have to allocate/cap the FCGI children per user.</p>
<p><strong>Apache + mod_php:</strong> Least secure since everything running with webserver privs, but your pool of live PHP processes is shared so it's best on the performance end. From a developer perspective, I can't tolerate php_safe mode, and from a sysadmin perspective it's really only an illusion of security (it mitigates against stupid users but doesn't protect from an actual attack) so I would actually rather have CGI if my other option has to include safe_mode.</p>
<p>Dreamhost does sort of a hybrid, they do Apache CGI + suexec by default, but let the (small) percentage of their more users who are sophisticated elect to do FCGI if they want to, subject to a cap and their own monitoring of memory usage. That saves a ton of memory resources versus enabling FCGI for everyone by default.</p>
<p>Another issue if you're talking about standard commercial shared hosting is, Apache is full-featured, has modules for just about anything (including stuff like mod_security you might want), and your users will like it because all their .htaccess configs will work etc. -- you will run into support headaches with anything else when they go to install Drupal or WordPress or whatever (a lot less of an issue if we're talking internal users).</p>
<p>Personally I would recommend just keeping it simple to start and going with CGI + suexec for best security and scaleability. If your users want FCGI or mod_php and you have a good channel open for suggestions/communication with them, they'll ask for it, but either of these are a much bigger headache for you with only marginal performance improvements for them, so my suggestion would be to not do either of them initially but be responsive if they clamor for it.</p>
<p>I do sympathize with the desire to do something "interesting" like Lighttpd + FCGI instead of the standard Apache + CGI + suexec, but I deep down I really can't recommend it.</p>
<p>If you're running multiple servers, you could end up putting CGI on some and something else for the power users on the others. And be sure to have cron grep all the www dirs for things like old-ass versions of phpBB!</p>
|
<p>I have been using <a href="http://www.interworx.com/" rel="nofollow noreferrer">InterWorx</a> for about a year now and have been very impressed. It maintains a LAMP server with chroots your scripts for security.</p>
<p>I have also used <a href="http://www.ensim.com/" rel="nofollow noreferrer">Ensim</a>, but haven't found it as friendly, fast and it doesn't have as many features. Plus it costs a lot more.</p>
| 21,204
|
<p>If I create a class like so: </p>
<pre><code>// B.h
#ifndef _B_H_
#define _B_H_
class B
{
private:
int x;
int y;
};
#endif // _B_H_
</code></pre>
<p>and use it like this:</p>
<pre><code>// main.cpp
#include <iostream>
#include <vector>
class B; // Forward declaration.
class A
{
public:
A() {
std::cout << v.size() << std::endl;
}
private:
std::vector<B> v;
};
int main()
{
A a;
}
</code></pre>
<p>The compiler fails when compiling <code>main.cpp</code>. Now the solution I know is to <code>#include "B.h"</code>, but I'm curious as to why it fails. Neither <code>g++</code> or <code>cl</code>'s error messages were very enlightening in this matter.</p>
|
<p>The compiler needs to know how big "B" is before it can generate the appropriate layout information. If instead, you said <code>std::vector<B*></code>, then the compiler wouldn't need to know how big B is because it knows how big a pointer is.</p>
|
<p>The reason you can't use a forward declaration is because the size of B is unknown.</p>
<p>There's no reason in your example that you can't include B.h inside of A.h, so what problem are you really trying to solve?</p>
<p><strong>Edit:</strong> There's another way to solve this problem, too: stop using C/C++! It's so 1970s... ;)</p>
| 5,801
|
<p>I wrote a google map lookup page. Everthing worked fine until I referenced the page to use a master page. I removed the form tag from the master page as the search button on the map page is a submit button. Everything else on my page appears but the google map div appears with map navigation controls and logo but no map visuals appear.</p>
<p>I retested with the previous, non master page version and the map appears correctly. Any thoughts on what I'm missing?</p>
|
<p>Please view below Code and let me know its useful ... </p>
<p><strong>MasterPage Code ( GMap.master page)</strong></p>
<pre><code>< body onload="initialize()" onunload="GUnload()" >
< form id="form1" runat="server" >
< div >
< asp:contentplaceholder id="ContentPlaceHolder1" runat="server" >
< /asp:contentplaceholder >
< /div >
< /form >
< /body >
</code></pre>
<p><strong>GMatTest.aspx Page which is used GMap.Master page</strong></p>
<pre><code>< %@ Page Language="C#" MasterPageFile="~/MasterPages/GMap.master" AutoEventWireup="true"
CodeFile="GMapTest.aspx.cs" Inherits="GMapTest" Title="Google Map Page" % >
< asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server" >
< script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=< % = AppConfig.GoogleMapApiKey % >"
type="text/javascript" >< /script >
< script type="text/javascript" >
var map = null;
var geocoder = null;
var latsgn = 1;
var lgsgn = 1;
var zm = 0;
var marker = null;
function initialize()
{
if (GBrowserIsCompatible())
{
var latitude= "";
var longitude= "";
map = new GMap2(document.getElementById("map_canvas"));
var center = new GLatLng(0,0);
map.setCenter(center, 17);
map.addControl(new GLargeMapControl());
map.addControl(new GScaleControl());
map.enableScrollWheelZoom();
map.addControl(new GMapTypeControl());
map.enableDoubleClickZoom();
marker = new GMarker(center,{draggable: true});
geocoder = new GClientGeocoder();
GEvent.addListener(marker, "dragend", function() {
var point = marker.getLatLng();
marker.openInfoWindowHtml("Latitude: " + point.y + "< /br > Longitude: " + point.x );
});
GEvent.addListener(marker, "click", function() {
var point = marker.getLatLng();
});
map.addOverlay(marker);
GEvent.trigger(marker, "click");
if (latitude > 0 && longitude > 0)
{
}
else
{
showAddress();
}
}
}
</code></pre>
<p>Below porsion is continue so please copy it also </p>
<pre><code>function showAddress()
{
var isAddressFound=false;
var companyAddress = '';
var address='satyam mall, vastrapur, ahmedabad, gujrat, india';
if (geocoder)
{
geocoder.getLatLng(address,function(point) {
if (!point) {
alert(address + " not found");
} else {
isAddressFound =true;
map.setCenter(point,17);
zm = 1;
marker.setPoint(point);
GEvent.trigger(marker, "click");
}
}
);
//If address not found then redirect to company address
if(!isAddressFound)
{
geocoder.getLatLng(companyAddress,
function(point) {
if (!point) {
} else {
isAddressFound =true;
map.setCenter(point,17);
zm = 1;
marker.setPoint(point);
GEvent.trigger(marker, "click");
}
}
);
}
}
}
< /script >
< div id="map_canvas" style="width: 100%; height: 425px" >
< /div >
< /asp:Content >
</code></pre>
|
<p>One thing that can change when you add a master page is your elements ids.</p>
<p>If the div you are displaying the map in has <code>runat="server"</code> on it, you could have a problem.
You would add that tag so you could manipulate the div from code-behind.</p>
<p>So, if my div looks like this:</p>
<pre><code><div id="gmap" runat="server"></div>
</code></pre>
<p>If so, when you are initializing your map, you need to get the ClientId of the div. That would look like this:</p>
<pre><code>var mapDiv = '<%= gmap.ClientID %>';
var map = new GMap2(mapDiv);
</code></pre>
| 49,591
|
<p>I'm looking for Forum software similar to phpBB, but intended to run within a RoR application. I'm looking for a list of sites, along with one recommendation for which one is currently the ideal choice (ease of setup, simplicity, aesthetics).</p>
|
<p><a href="http://rforum.andreas-s.net/" rel="nofollow noreferrer">RForum</a>? Used by <a href="http://www.ruby-forum.com/" rel="nofollow noreferrer">ruby-forum.com</a>.</p>
<p>e: There's also <a href="http://beast.caboo.se/" rel="nofollow noreferrer">Beast</a>, but it looks very minimal.</p>
|
<p>Look at <a href="https://github.com/radar/rboard/tree" rel="nofollow noreferrer">rBoard</a>, its on github.</p>
| 23,537
|
<p>I have a Repeater control on ASPX-page defined like this:</p>
<pre><code><asp:Repeater ID="answerVariantRepeater" runat="server"
onitemdatabound="answerVariantRepeater_ItemDataBound">
<ItemTemplate>
<asp:RadioButton ID="answerVariantRadioButton" runat="server"
GroupName="answerVariants"
Text='<%# DataBinder.Eval(Container.DataItem, "Text")%>'"/>
</ItemTemplate>
</asp:Repeater>
</code></pre>
<p>To allow select only one radio button in time I have used a trick form <a href="http://www.codeguru.com/csharp/csharp/cs_controls/custom/article.php/c12371/" rel="noreferrer">this article</a>.</p>
<p>But now when form is submitted I want to determine which radio button is checked.</p>
<p>I could do this:</p>
<pre><code>RadioButton checkedButton = null;
foreach (RepeaterItem item in answerVariantRepeater.Items)
{
RadioButton control=(RadioButton)item.FindControl("answerVariantRadioButton");
if (control.Checked)
{
checkedButton = control;
break;
}
}
</code></pre>
<p>but hope it could be done somehow simplier (maybe via LINQ to objects).</p>
|
<p>Since You are using javascript already to handle the radio button click event on the client, you could update a hidden field with the selected value at the same time. </p>
<p>Your server code would then just access the selected value from the hidden field.</p>
|
<p>I'm pretty sure that the only thing you could use LINQ to Objects for here would be to take the conditions from within the foreach loop and move them to a where clause.</p>
<pre><code>RadioButton checked =
(from item in answerVariantRepeater.Items
let radioButton = (RadioButton)item.FindControl("answerVariantRadioButton")
where radioButton.Checked
select radioButton).FirstOrDefault();
</code></pre>
| 36,956
|
<p>I want to use SQL Profiler to trace the queries executed agains my database, track performance, etc. However it seems that the SQL Profiler is only available in the Enterprise edition of SQL Server 2005. Is this the case indeed, and can I do something about it?</p>
|
<p>You don't need <strong>any</strong> SQL license to run the client tools (Management Studio, Profiler, etc). If your organization has a copy of the installation media for Developer, Standard, or Enterprise, you can install the client tools on your local machine under the same license.</p>
<p>If you're working solo, I would recommend <a href="http://www.microsoft.com/products/info/product.aspx?view=22&pcid=f544888c-2638-48ed-9f0f-d814e8b93ca0&crumb=catpage&catid=cd1daedd-9465-4aef-a7bf-8f5cf09a4dc0#HowToBuy" rel="nofollow noreferrer">purchasing</a> SQL Developer edition, it's only $50.</p>
|
<p>The SQL Profiler tool is only available with the Standard and Enterprise version of SQL Server, however, all version can be profiled using the tool.</p>
<p>Source: <a href="http://www.microsoft.com/sql/prodinfo/features/compare-features.mspx" rel="nofollow noreferrer">http://www.microsoft.com/sql/prodinfo/features/compare-features.mspx</a></p>
| 6,530
|
<p>What are some of the advantages of using one over the other?</p>
|
<p>The main advantages of <strong>ASP.net MVC</strong> are:</p>
<ol>
<li><p>Enables the full control over the rendered HTML.</p></li>
<li><p>Provides clean separation of concerns(SoC).</p></li>
<li><p>Enables <a href="http://en.wikipedia.org/wiki/Test-driven_development" rel="noreferrer">Test Driven Development (TDD)</a>.</p></li>
<li><p>Easy integration with JavaScript frameworks.</p></li>
<li><p>Following the design of stateless nature of the web.</p></li>
<li><p>RESTful urls that enables SEO.</p></li>
<li><p>No ViewState and PostBack events</p></li>
</ol>
<p>The main advantage of <strong>ASP.net Web Form</strong> are:</p>
<ol>
<li><p>It provides <a href="http://en.wikipedia.org/wiki/Rapid_application_development" rel="noreferrer">RAD</a> development </p></li>
<li><p>Easy development model for developers those coming from winform development.</p></li>
</ol>
|
<p>You don't feel bad about using 'non post-back controls' anymore - and figuring how to smush them into a traditional asp.net environment.</p>
<p>This means that modern (free to use) javascript controls such <a href="http://developer.yahoo.com/yui/examples/calendar/quickstart.html" rel="nofollow noreferrer">this</a> or <a href="http://developer.yahoo.com/yui/examples/colorpicker/colorpicker-fromscript.html" rel="nofollow noreferrer">this</a> or <a href="http://developer.yahoo.com/yui/examples/datatable/dt_basic.html" rel="nofollow noreferrer">this</a> can all be used without that trying to fit a round peg in a square hole feel.</p>
| 12,816
|
<p>I know that 3D printed parts can be coated in metal by painting them with conductive paint (graphite or copper seems to be usual) and then electroplating them in a commercial copper or nickel bath. The disadvantage of this process is that it does not coat insides very well, because those are not reached by the electric field.</p>
<p>I know that in the industry for plating ABS-parts with chrome and other metals, there is a process used where first the ABS is etched, then seeded with electroless catalytic palladium and then there are various options, for example electroless nickel or chrome.</p>
<p>I tried to etch both FDM printed ABS and ABS-like resin prints in NaOH, then after rinsing, dropped them in a commercial palladium activator and, after rinsing again, then in an electroless nickel bath, without any effect.</p>
<p>Does anyone have an idea on how to metal plate 3D printed parts (by electroless plating, meaning no electricity involved) and can shed some light on the chemicals used? I would prefer to mix them myself.</p>
|
<p>Good day, I have experience in applying electroless nickel on difficult 3D parts, in your case, it's exceedingly difficult to do it directly to the printed piece. You will need to seal the piece with a more benign coating that will accept the palladium activator. Also, a sensitizer before the activator is needed.</p>
<p>Try this.</p>
<p>Try your original procedure, but this time use just before the palladium activator, a stannous chloride solution (20 g per 1 L of deionized Water and 10 ml of muriatic acid), submerge the piece in the solution for 1 minute, rinse in deionized water and then place the piece on the palladium activator for 1 minute (don't rinse the activator) and then place the piece directly on the electroless nickel plating bath.</p>
<p>If that still does not produce good results, then you will need to seal the piece with a two-part epoxy sealer and do the process again.</p>
|
<p>You can use semiconductor processes like evaporation, sputtering, and chemical vapor deposition. These are expensive. Sputtering is probably the most feasable but it will have trouble with shadows.</p>
| 2,192
|
<p>In my work I deal mostly with C# code nowadays, with a sprinkle of java from time to time. What I absolutely love about Eclipse (and I know people using it daily love it even more) is a sophisticated code formatter, able to mould code into any coding standard one might imagine. Is there such a tool for C#? Visual Studio code formatting (Crtl+K, Crtl+D) is subpar and StyleCop only checks the source without fixing it.</p>
<p>My dream tool would run from console (for easy inclusion in automated builds or pre-commit hooks and for execution on Linux + Mono), have text-file based configuration easy to store in a project repository and a graphical rule editor with preview - just like the Eclipse Code Formatter does.</p>
|
<p>For Visual Studio, take a look at <a href="http://www.jetbrains.com/resharper" rel="nofollow noreferrer">ReSharper</a>. It's an awesome tool and a definite must-have. Versions after 4.0 have the code formatting and clean-up feature that you are looking for. There's also <a href="http://stylecopforresharper.codeplex.com/" rel="nofollow noreferrer">plugin integration with StyleCop</a>, including formatting settings file.</p>
<p>You'll probably want <a href="https://resharper-plugins.jetbrains.com/packages/ReSharper.AgentSmith/" rel="nofollow noreferrer">Agent Smith plugin</a> as well, for spell-checking the identifiers and comments. ReSharper supports per-solution formatting setting files, which can be checked into version control system and shared by the whole team. The keyboard shortcut for code cleanup is <kbd>Ctrl</kbd> + <kbd>E</kbd>, <kbd>C</kbd>.</p>
<p>In 'vanilla' Visual Studio, the current file can be automatically formatted with <kbd>Ctrl</kbd> + <kbd>K</kbd>, <kbd>Ctrl</kbd> + <kbd>D</kbd>, and <kbd>Ctrl</kbd> + <kbd>K</kbd>, <kbd>Ctrl</kbd> + <kbd>F</kbd> formats the selected text.</p>
<p>As for a runs-everywhere command line tool to be used with commit hooks, try <a href="http://www.narrange.net/" rel="nofollow noreferrer">NArrange</a>. It's free, can process whole directories at once and runs on Mono as well as on Microsoft .NET.</p>
<p>Some people also use the <a href="http://astyle.sourceforge.net/" rel="nofollow noreferrer">Artistic Style</a> command line tool, although it requires Perl and works better with C/C++ code than with C#.</p>
|
<p>Here is an open source code formatting tool which has amazing features</p>
<p><a href="http://www.codemaid.net/" rel="nofollow">CodeMaid</a></p>
| 4,998
|
<pre><code> private void activateRecords(long[] stuff) {
...
api.activateRecords(Arrays.asList(specIdsToActivate));
}
</code></pre>
<p>Shouldn't this call to Arrays.asList return a list of <code>Long</code>s? Instead it is returning a <code>List<long[]></code></p>
<pre><code>public static <T> List<T> asList(T... a)
</code></pre>
<p>The method signature is consistent with the results, the varargs throws the entire array into the list. It's the same as <code>new ArrayList(); list.add(myArray)</code> And yes, I know it's meant to be used like this: <code>Arrays.asList(T t1, T t2, T t3)</code></p>
<p>I guess what I'm getting at, is instead of the varargs form, why can't I just have my old asList method (at least I think this is how it used to work) that would take the contents and put them individually into a list? Any other <strong>clean</strong> way of doing this?</p>
|
<p>That's because long[] and Long[] are different types.</p>
<p>In the first case T is long[], in the second T is Long.</p>
<p>How to fix this? Don't use long[] in the first place?</p>
|
<p>Autoboxing cannot be done on arrays. You are allowed to do:</p>
<pre><code>private List<Long> array(final long[] lngs) {
List<Long> list = new ArrayList<Long>();
for (long l : lngs) {
list.add(l);
}
return list;
}
</code></pre>
<p>or</p>
<pre><code>private List<Long> array(final long[] lngs) {
List<Long> list = new ArrayList<Long>();
for (Long l : lngs) {
list.add(l);
}
return list;
}
</code></pre>
<p>(notice that the iterable types are different)</p>
<p>e.g.</p>
<pre><code>Long l = 1l;
</code></pre>
<p>but not</p>
<pre><code>Long[] ls = new long[]{1l}
</code></pre>
| 36,318
|
<p>I'm working on a project that returns paged results with volumes potentially in the hundreds of pages. I've been playing around with more usable ways to perform paging than the standard fisrt/last/next/previous links and jump-to text box. One alternative I had was to have a scrolling list of pages. I'd display 5 to 7 links at a time, centered around the current page, but add onhover actions to buttons on either side to scroll through the numbered list. This allows users to jump way ahead in the page count if they like without the combersome "Jump to" textbox. Does anyone have any better ideas? </p>
<p>If not, I'm trying to decide on a way to implement the above functionality, but I'm not sure how to display only a section of a div (with the div being the full list of links.) Any ideas?</p>
|
<p>You might find <a href="http://unspace.ca/discover/pageless/" rel="nofollow noreferrer">Endless Pageless</a> an interesting read.</p>
|
<p>You could use a dropdown list containing page numbers.</p>
| 33,891
|
<p>Any advice on how to read auto-incrementing identity field assigned to newly created record from call through <code>java.sql.Statement.executeUpdate</code>?</p>
<p>I know how to do this in SQL for several DB platforms, but would like to know what database independent interfaces exist in <code>java.sql</code> to do this, and any input on people's experience with this across DB platforms.</p>
|
<p>The following snibblet of code should do ya':</p>
<pre><code>PreparedStatement stmt = conn.prepareStatement(sql,
Statement.RETURN_GENERATED_KEYS);
// ...
ResultSet res = stmt.getGeneratedKeys();
while (res.next())
System.out.println("Generated key: " + res.getInt(1));
</code></pre>
<p>This is known to work on the following databases</p>
<ul>
<li>Derby</li>
<li>MySQL</li>
<li>SQL Server</li>
</ul>
<p>For databases where it doesn't work (HSQLDB, Oracle, PostgreSQL, etc), you will need to futz with database-specific tricks. For example, on PostgreSQL you would make a call to <code>SELECT NEXTVAL(...)</code> for the sequence in question.</p>
<p>Note that the parameters for <code>executeUpdate(...)</code> are analogous.</p>
|
<p>I've always had to make a second call using query after the insert.</p>
<p>You could use an ORM like hibernate. I think it does this stuff for you.</p>
| 10,185
|
<p>First, I'm using Linux Mint 18.3 (Sylvia). Until now, I've been using OpenSCAD with the GUI and never experienced issues. Now I try to start OpenSCAD from the command line, but it always opens an empty file, even if a file with the specified name exists. </p>
<p>Since I have a rather big script, I'd like to generate the STL's via the CLI. Due to this error, I can not even do any tests for parameter passing.</p>
<p>What I'd like to do is to issue a command (flom the command line or in a shell script) that says "Set objectID to 1, render and export the result to stl".</p>
<p>Here is my M(N)WE:</p>
<pre><code>// test.scad
objectID = 2;
if (objectID == 1)
difference(){
cylinder(d=20, h=50, center=true);
cylinder(d=16, h=50.2, center=true);
}
else if (objectID == 2)
difference(){
cube(50, center=true);
cube([35,35,70], center=true);
}
</code></pre>
<p>Any help will greatly be appreciated.</p>
|
<p>I could finally solve the issue. Calling <code>openscad</code> from command line with parameters does NOT work with the AppImage I used. It works fine with a "standard" installation, though.</p>
<p>Thanks for your support.</p>
|
<p>You can specify variable values from command line using:</p>
<pre>
openscad ...\
... \
[ -D var=val [..] ] \
... \
... \
filename
</pre>
<p>See the <a href="https://en.m.wikibooks.org/wiki/OpenSCAD_User_Manual/Using_OpenSCAD_in_a_command_line_environment" rel="nofollow noreferrer">OpenSCAD Manual</a>.</p>
| 1,227
|
<p>I'm still learning ASP.NET and I often see code like this throughout parts of our framework:</p>
<pre><code>Public MustInherit Class DBFileManager(Of F As IDBFile, FC As IDBFileContent, FT As IDBFileThumb)
</code></pre>
<p>Can anybody tell me what this means? Much thanks!</p>
|
<p>Sometimes, you need to to this when the method is overloaded... to tell the compiler which one you are calling. A null object is still null and it is safe.</p>
|
<p>it probably needs the cast to resolve overloads</p>
| 46,694
|
<p>I am writing an iPhone application, and need to save the state of my application (5K or so).</p>
<p>My main worry is data persisting across upgrades. Some of the applications I use clearly got this wrong, and I would prefer not to!</p>
|
<p>To save state, NSUserDefaults is the way to go. I believe most, if not all, instances of application data being deleted after an upgrade are due to issues on the AppStore. They may be related to data-format changes, but if you use just NSUserDefaults and standard plist-storable objects (NSString, NSDictionary, NSNumber, NSArray, NSNumber, and primitives), you should be safe.</p>
|
<p>The most common way to save state (data, application information etc) is to use <a href="http://www.sqlite.org/" rel="nofollow noreferrer">Sqlite3</a>. I'm not sure how an update would wipe it, but it's possible that the update process could overwrite the datafile. </p>
<p>The other option would be to use UserPrefs (NSUserDefaults). Again, I'm not sure the max size for that, or even if it would be suitable for the data you need to persist.</p>
| 39,546
|
<p>I've got some entities which have decimal properties on them. These entities' properties are displayed in multiple places throughout my UI.</p>
<p>Currently I'm finding myself doing:</p>
<pre><code>litWeight.Text = person.Weight.ToString("0.00");
</code></pre>
<p>all over the place.
Now I know for a fact that in several instances, and am suspicious of many others that the client is likely to want the values to 3d.p. in the future.</p>
<p>Is there some pattern I can employ to handle the formatting of this Weight property (and other properties; not just decimals, perhaps dates etc.) so that I can have this formatting in a single place?</p>
<p>I know could use a formatstring in the webconfig, or write some extension methods in the UI but these don't seem very elegant solutions.</p>
<p>It would be nice to have some formatting objects which are tied to my entities, so its inherently obvious which formatter to use.</p>
<p>Thanks,</p>
<p>Andrew</p>
|
<p>The simplest solution would be to make a utility class with static methods that appropriately format different types of values and call them. For example:</p>
<pre><code>litWeight.Text = Utility.FormatWeight(person.Weight);
</code></pre>
|
<p>Can you not add a method to the entities for formatting themeslves? Then each object can delegate to a 'strategy' object to do the actual formatting. </p>
<p>A reason for this is both to be able to change the decimal places etc, but also to allow things like internationalisation - decimal formatting is locale-dependent; some countries use decimal commas instead of points, or group digits in sets other than threes etc.</p>
<p>EDIT: The comment was this puts presentation code in the domain layer. True, so apply the standard fix for all design problems; add one more layer of indirection :)</p>
<p>You may not want to have the full MVC, but the concept of View and Model still seem appropriate. Perhaps, for each entity, define a View class, so PersonView which keeps a reference to a Person object and has properties called format_weight etc for each property of Person that is of interest? It should still use a Strategy pattern for the actual formatting.</p>
<p>So your example would be </p>
<pre><code>PersonView pv = new PersonView(person)
litWeight.Text = pv.format_weight();
</code></pre>
<p>(please excuse syntactical errors, I don't speak C#)</p>
<p>If you want, you could make PersonView drop in replacement for Person, either by reimplementing the methods/properties and delgating to the referenced Person, or by inheriting from Person when making PersonView?</p>
| 46,381
|
<p>Is there any clever method out there to make my executeEveryDayMethod() execute once a day, without having to involve the Windows TaskScheduler?</p>
|
<p>I achieved this by doing the following...</p>
<ol>
<li>Set up a timer that fires every 20 minutes (although the actual timing is up to you - I needed to run on several occasions throughout the day). </li>
<li>on each Tick event, check the system time. Compare the time to the scheduled run time for your method.</li>
<li>If the current time is less than the scheduled time, check a in some persistent storage to get the datetime value of the last time the method ran. </li>
<li>If the method last ran more than 24 hours ago, run the method, and stash the datetime of this run back to your data store</li>
<li>If the method last ran within the last 24 hours, ignore it.</li>
</ol>
<p>HTH</p>
<p>*edit - code sample in C# :: Note : untested...</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Text;
using System.Timers;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Timer t1 = new Timer();
t1.Interval = (1000 * 60 * 20); // 20 minutes...
t1.Elapsed += new ElapsedEventHandler(t1_Elapsed);
t1.AutoReset = true;
t1.Start();
Console.ReadLine();
}
static void t1_Elapsed(object sender, ElapsedEventArgs e)
{
DateTime scheduledRun = DateTime.Today.AddHours(3); // runs today at 3am.
System.IO.FileInfo lastTime = new System.IO.FileInfo(@"C:\lastRunTime.txt");
DateTime lastRan = lastTime.LastWriteTime;
if (DateTime.Now > scheduledRun)
{
TimeSpan sinceLastRun = DateTime.Now - lastRan;
if (sinceLastRun.Hours > 23)
{
doStuff();
// Don't forget to update the file modification date here!!!
}
}
}
static void doStuff()
{
Console.WriteLine("Running the method!");
}
}
}
</code></pre>
|
<p>You could query time and run if your within some time frame, that way even if the machine goes off you'll call the method or use a timer like Vinko's suggestion.</p>
<p>But the better solution (akin to older CRON versions, so its a proven pattern) is to have some persistent data, with the cheapest solution I can think of right now being a blank file, check its last modified attribute, and if it hasn't been modified within the last 24 hours you touch it and run your method. This way you assure the method gets run first thing in the case the application is out for the weekend for example.</p>
<p>I've done this in C# before, but its was a year ago at another Job, so I don't have the code but it was about 20 lines (with comments and all) or so.</p>
| 35,482
|
<p>I've defined a view with the CCK and View 2 modules. I would like to quickly define a template specific to this view. Is there any tutorial or information on this? What are the files I need to modify?</p>
<hr>
<p><strong>Here are my findings: (Edited)</strong></p>
<p>In fact, there are two ways to theme a view: the "<strong>field</strong>" way and the "<strong>node</strong>" way. In "edit View", you can choose "<code>Row style: Node</code>", or "<code>Row style: Fields</code>".</p>
<ul>
<li>with the "<strong>Node</strong>" way, you can create a <strong>node-contentname.tpl.php</strong> which will be called for each node in the view. You'll have access to your cck field values with $field_name[0]['value']. (edit2) You can use <strong>node-view-viewname.tpl.php</strong> which will be only called for each node displayed from this view.</li>
<li>with the "<strong>Field</strong>" way, you add a views-view-field--viewname--field-name-value.tpl.php for each field you want to theme individually.</li>
</ul>
<p>Thanks to previous responses, I've used the following tools :</p>
<ul>
<li>In the 'Basic Settings' block, the 'Theme: Information' to see all the different templates you can modify.</li>
<li>The <a href="http://drupal.org/project/devel" rel="nofollow noreferrer">Devel module</a>'s "Theme developer" to quickly find the field variable names.</li>
<li><a href="http://views-help.doc.logrus.com/" rel="nofollow noreferrer">View 2 documentation</a>, especially the <a href="http://views-help.doc.logrus.com/help/views/using-theme" rel="nofollow noreferrer">"Using Theme"</a> page.</li>
</ul>
|
<p>In fact there are two ways to theme a view : the "<strong>field</strong>" way and the "<strong>node</strong>" way. In "edit View", you can choose "<code>Row style: Node</code>", or "<code>Row style: Fields</code>".</p>
<ul>
<li>with the "<strong>Node</strong>" way, you can create a node-contentname.tpl.php wich will be called for each node in the view. You'll have access to your cck field values with $field_name[0]['value']</li>
<li>with the "<strong>Field</strong>" way, you add a views-view-field--viewname--field-name-value.tpl.php for each field you want to theme individually.</li>
</ul>
<p>Thanks to previous responses, I've used the following tools :</p>
<ul>
<li>In the 'Basic Settings' block, the 'Theme: Information' to see all the different templates you can modify.</li>
<li>The <a href="http://drupal.org/project/devel" rel="noreferrer">Devel module</a>'s "Theme developer" to quickly find the field variable names.</li>
<li><a href="http://views-help.doc.logrus.com/" rel="noreferrer">View 2 documentation</a>, especially the <a href="http://views-help.doc.logrus.com/help/views/using-theme" rel="noreferrer">"Using Theme"</a> page.</li>
</ul>
|
<p>According to me there are two ways to do it:</p>
<p>Programatic Way: </p>
<ol>
<li>Go to edit view. </li>
<li>Select page/block style. </li>
<li>Go to 'Basic Settings' and click on 'Theme: Information' to see all the different templates you can modify. </li>
<li>Add the html you want to theme and print the variables of the view wherever needed</li>
</ol>
<p>Configuration Update: <img src="https://i.stack.imgur.com/CvhW1.png" alt="Using the Display suite">The Display suite provides us an option to place your labels inline or above and add even to hide them. Custom classes to each of the view's elements can be added too.
Advanced options include:</p>
<ul>
<li>Exportables</li>
<li>Add your own custom fields in the backend or in your code</li>
<li>Add custom layouts in your theme (D7 only)</li>
<li>Change labels, add styles or override field settings (semantic fields).</li>
<li>Full integration with Views and Panels</li>
<li>Extend the power of your layouts by installing Field Group</li>
<li>Optimal performance with Object cache (D6) or Entity cache (D7) integration</li>
</ul>
| 10,316
|
<p>Since Java 6 there is a class <code>java.awt.Desktop</code>. There are some nice methods but the class is not supported on all platforms. The methods <a href="http://java.sun.com/javase/6/docs/api/java/awt/Desktop.html#getDesktop()" rel="nofollow noreferrer"><code>java.awt.Desktop.getDesktop()</code></a> throws an </p>
<blockquote>
<p>java.lang.UnsupportedOperationException: Desktop API is not supported
on the current platform</p>
</blockquote>
<p>on some platforms. Or the method <a href="http://java.sun.com/javase/6/docs/api/java/awt/Desktop.html#isDesktopSupported()" rel="nofollow noreferrer"><code>java.awt.Desktop.isDesktopSupported()</code></a> return false.</p>
<p>I know that it work on Windows XP, Windows 2003 and also Windows Vista. The question is on which platform is it not supported?</p>
|
<p>Quote:</p>
<blockquote>
<p>Desktop API was developed to support
Windows and Gnome only</p>
</blockquote>
<p>from <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6486393" rel="noreferrer">http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6486393</a></p>
<p>This <a href="http://java-hamster.blogspot.com/2007/06/troubles-with-javaawtdesktop-browse.html" rel="noreferrer">article</a> however says that even Gnome support is flawed on Fedora.</p>
|
<p>On arch linux, I had to install the AUR libgnome package</p>
| 12,787
|
<p>I'm using Windows Xp and i'm looking for a software where I can see the screen of a remote desktop and be able to show a second mouse (or pointer of any sort) that I can mouse to just show something.</p>
<p>I want to work with a peer over the net, pretty much like the XP programming method. I find it useful, but it's pretty hard over the internet to do such thing. </p>
<p>I don't want to control the computer, but it would be a plus. All I want is to see the remote desktop and have my pointer (or marker) to point to a line of code that need to be changed or something like.</p>
<p>Do you know any software like this ?</p>
|
<p>You're after something like Microsoft <a href="http://www.microsoft.com/downloadS/details.aspx?familyid=95AF94BA-755E-4039-9038-63005EE9D33A&displaylang=en" rel="nofollow noreferrer">SharedView</a>.</p>
<p>It allows sharing applications etc with multiple pointers.</p>
|
<p>I already used windows messenger, but I don't remember it to be able to show a second mouse pointer. As I don't want to disrupt the person using the computer, it would only be for some indication.</p>
<p>I already google some solution for VNC, but the only one I found is Collaborative VNC and it's only for Unix.</p>
| 17,511
|
<p>I'm developing a library alongside several projects that use it, and I've found myself frequently modifying the library at the same time as a project (e.g., adding a function to the library and immediately using it in the project).<br>
As a result, the project would no longer compile with previous versions of the library.</p>
<p>So if I need to rollback a change or test a previous version of the project, I'd like to know what version of the library was used at check-in.<br>
I suppose I could do this manually (by just writing the version number in the log file), but it would be great if this could happen automatically.</p>
|
<p>I think if I were going to do this, I would use tags. It would be pretty easy to write a script that would tag both repositories with the same ID each time you upgraded the library and used it in the project. Then, if you need to roll back to a previous version, you just see what its most recent tag was, and roll the library back to that version.</p>
<p>UPDATE: Sorry, I've been in Mercurial land for a while, and forgot that subversion doesn't directly support tagging. Assuming you use the usual subversion directory structure</p>
<pre><code>/
/trunk
/tags
/branches
</code></pre>
<p>you just need to run</p>
<pre><code>svn copy trunk/ tags/TagName
</code></pre>
<p>on both repos, with the same tag name. Subversion is pretty good about smart copies, so you don't need to worry about disk space.</p>
|
<p>One option is to use a single subversion repository and check-in changes that effect both library and project at the same time. That way you know that whatever revision of the project you are on requires the same revision of the library.</p>
| 4,350
|
<p>I have a menu that I am using and it will change the background color when I hover using <code>a:hover</code> but I want to know how to change the <code>class=line</code> so that it sticks. </p>
<p>So from the home if they click contacts the home pages </p>
<blockquote>
<p>from (a href="#" class="clr") to (a href="#")</p>
</blockquote>
<p>and Contacts would change </p>
<blockquote>
<p>from (a href="#") to (a href="#" class="clr")</p>
</blockquote>
<p>any help?</p>
<p>JD</p>
|
<p>I believe you are wanting to highlight the navigational item that you're on. My answer <a href="https://stackoverflow.com/questions/188124/programmatic-solution-to-change-navigation-id-to-highlight-current-page-aspnet#189069">here</a> is fairly valid in this question as well, I believe:</p>
<p>It's a better semantic match and likely an easier variable to set to keep the navigation using the same classes or ids everywhere and only alter the body element's id to match:</p>
<pre><code><li id="homeNav">home</li>
<li id="blogNav">blog</li>
</code></pre>
<p>and then on each page...</p>
<pre><code><body id="home">
<body id="blog">
</code></pre>
<p>And in the css:</p>
<pre><code>#home #homeNav {background-image:url(homeNav-on.jpg);}
#blog #blogNav {background-image:url(blogNav-on.jpg);}
</code></pre>
|
<p>This may not apply to you, but it may lead you down the right path. If you are using PHP, stick this in your head before the doctype declaration or the (x)html tag:</p>
<pre><code><?php
// Get current page file name
$url = Explode('/', $_SERVER["PHP_SELF"]);
$page = $parts[count($url) - 1];
?>
</code></pre>
<p>Then, in your menu item where you would like the class designation, place the following, but change "index.php" to the name of the page: </p>
<pre><code><?php if ($page == "index.php") echo ' class="current"' ?>
</code></pre>
<p>So ultimately your menu should look similar to this: </p>
<pre><code><div id="navigation">
<ul>
<li><a href="index.php"<?php if ($page == "index.php") echo ' class="current"' ?>>Home</a></li>
<li><a href="page1.php"<?php if ($page == "page1.php") echo ' class="current"' ?>>Resume</a></li>
<li><a href="page2.php"<?php if ($page == "page2.php") echo ' class="current"' ?>>Photography</a></li>
</ul>
</div>
</code></pre>
<p>Last step is adding the CSS:</p>
<pre><code>#navigation ul li a.current {
background-color: #FFF;
}
</code></pre>
<p>Hope this helps.</p>
| 25,319
|
<p>Suppose that I have a <code><div></code> that I wish to center in the browser's display (viewport). To do so, I need to calculate the width and height of the <code><div></code> element. </p>
<p>What should I use? Please include information on browser compatibility.</p>
|
<p>You should use the <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetWidth" rel="noreferrer"><code>.offsetWidth</code></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetHeight" rel="noreferrer"><code>.offsetHeight</code></a> properties.
Note they belong to the element, not <code>.style</code>.</p>
<pre class="lang-js prettyprint-override"><code>var width = document.getElementById('foo').offsetWidth;
</code></pre>
<p>The <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect" rel="noreferrer"><code>.getBoundingClientRect()</code></a> function returns the dimensions and location of the element as floating-point numbers after performing CSS transforms.</p>
<pre class="lang-js prettyprint-override"><code>> console.log(document.getElementById('foo').getBoundingClientRect())
DOMRect {
bottom: 177,
height: 54.7,
left: 278.5,
right: 909.5,
top: 122.3,
width: 631,
x: 278.5,
y: 122.3,
}
</code></pre>
|
<p>If offsetWidth returns 0, you can get element's style width property and search it for a number. "100px" -> 100</p>
<p>/\d*/.exec(MyElement.style.width)</p>
| 37,560
|
<p>As per <a href="https://stackoverflow.com/questions/41970/lightweight-fuzzy-search-library#41975">this</a> comment in a related thread, I'd like to know why Levenshtein distance based methods are better than Soundex.</p>
|
<p>Soundex is rather primitive - it was originally developed to be hand calculated. It results in a key that can be compared.</p>
<p>Soundex works well with western names, as it was originally developed for US census data. It's intended for phonetic comparison.</p>
<p>Levenshtein distance looks at two values and produces a value based on their similarity. It's looking for missing or substituted letters.</p>
<p>Basically Soundex is better for finding that "Schmidt" and "Smith" might be the same surname.</p>
<p>Levenshtein distance is better for spotting that the user has mistyped "Levnshtein" ;-)</p>
|
<p><a href="https://stackoverflow.com/questions/42013/levenshtein-distance-based-methods-vs-soundex#42025">@Keith</a>:</p>
<p>As I posted on the other question, Daitch-Mokotoff is better for us Europeans (and I'd argue the US).</p>
<p>I've also read the Wiki on Levenshtein. But I don't see why (in real life) it's <em>better</em> for the user than Soundex. </p>
| 6,341
|
<p>Does ADOdb do data sanitation or escaping within the same functionality by default? Or am I just confusing it with Code Igniter's built-in processes?</p>
<p>Does binding variables to parameters in ADOdb for PHP prevent SQL injection in any way? </p>
|
<p>Correct - bound parameters are not vulnerable to SQL injection attacks.</p>
|
<p>yes, you pass the array of parameters.</p>
<pre><code>$rs = $db->Execute('select * from table where val=?', array('10'));
</code></pre>
<p>Rest of their docs can be found <a href="http://adodb.sourceforge.net/#docs" rel="nofollow noreferrer">here</a>:</p>
| 10,200
|
<p>I have a search box that doesn't have a submit button, I need to be able to hit enter and then execute a method, how do I do this?</p>
|
<p>you could also do something simple like this with CSS:</p>
<pre><code><asp:Panel DefaultButton="myButton" runat="server">
<asp:TextBox ID="myTextBox" runat="server" />
<asp:Button ID="myButton" runat="server" onclick="myButton_Click" style="display: none; " />
</asp:Panel>
</code></pre>
<p>The panel may or may not be necessary depending on your implementation and surrounding controls, but this works and does a postback for me.</p>
|
<p>Use the TextChanged event, and set the AutoPostBack property to true.</p>
| 28,465
|
<p>I'm using the following method to send mail from Python using SMTP. Is it the right method to use or are there gotchas I'm missing ?</p>
<pre><code>from smtplib import SMTP
import datetime
debuglevel = 0
smtp = SMTP()
smtp.set_debuglevel(debuglevel)
smtp.connect('YOUR.MAIL.SERVER', 26)
smtp.login('USERNAME@DOMAIN', 'PASSWORD')
from_addr = "John Doe <john@doe.net>"
to_addr = "foo@bar.com"
subj = "hello"
date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" )
message_text = "Hello\nThis is a mail from your server\n\nBye\n"
msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s"
% ( from_addr, to_addr, subj, date, message_text )
smtp.sendmail(from_addr, to_addr, msg)
smtp.quit()
</code></pre>
|
<p>The script I use is quite similar; I post it here as an example of how to use the email.* modules to generate MIME messages; so this script can be easily modified to attach pictures, etc.</p>
<p>I rely on my ISP to add the date time header.</p>
<p>My ISP requires me to use a secure smtp connection to send mail, I rely on the smtplib module (downloadable at <a href="http://www1.cs.columbia.edu/~db2501/ssmtplib.py" rel="noreferrer">http://www1.cs.columbia.edu/~db2501/ssmtplib.py</a>)</p>
<p>As in your script, the username and password, (given dummy values below), used to authenticate on the SMTP server, are in plain text in the source. This is a security weakness; but the best alternative depends on how careful you need (want?) to be about protecting these.</p>
<p>=======================================</p>
<pre><code>#! /usr/local/bin/python
SMTPserver = 'smtp.att.yahoo.com'
sender = 'me@my_email_domain.net'
destination = ['recipient@her_email_domain.com']
USERNAME = "USER_NAME_FOR_INTERNET_SERVICE_PROVIDER"
PASSWORD = "PASSWORD_INTERNET_SERVICE_PROVIDER"
# typical values for text_subtype are plain, html, xml
text_subtype = 'plain'
content="""\
Test message
"""
subject="Sent from Python"
import sys
import os
import re
from smtplib import SMTP_SSL as SMTP # this invokes the secure SMTP protocol (port 465, uses SSL)
# from smtplib import SMTP # use this for standard SMTP protocol (port 25, no encryption)
# old version
# from email.MIMEText import MIMEText
from email.mime.text import MIMEText
try:
msg = MIMEText(content, text_subtype)
msg['Subject']= subject
msg['From'] = sender # some SMTP servers will do this automatically, not all
conn = SMTP(SMTPserver)
conn.set_debuglevel(False)
conn.login(USERNAME, PASSWORD)
try:
conn.sendmail(sender, destination, msg.as_string())
finally:
conn.quit()
except:
sys.exit( "mail failed; %s" % "CUSTOM_ERROR" ) # give an error message
</code></pre>
|
<p>What about <a href="https://red-mail.readthedocs.io/" rel="nofollow noreferrer">Red Mail</a>?</p>
<p>Install it:</p>
<pre><code>pip install redmail
</code></pre>
<p>Then just:</p>
<pre><code>from redmail import EmailSender
# Configure the sender
email = EmailSender(
host="YOUR.MAIL.SERVER",
port=26,
username='me@example.com',
password='<PASSWORD>'
)
# Send an email:
email.send(
subject="An example email",
sender="me@example.com",
receivers=['you@example.com'],
text="Hello!",
html="<h1>Hello!</h1>"
)
</code></pre>
<p>It has quite a lot of features:</p>
<ul>
<li><a href="https://red-mail.readthedocs.io/en/latest/tutorials/attachments.html" rel="nofollow noreferrer">Email attachments from various sources</a></li>
<li><a href="https://red-mail.readthedocs.io/en/latest/tutorials/body_content.html" rel="nofollow noreferrer">Embedding images and plots to the HTML body</a></li>
<li><a href="https://red-mail.readthedocs.io/en/latest/tutorials/jinja_support.html" rel="nofollow noreferrer">Templating emails with Jinja</a></li>
<li><a href="https://red-mail.readthedocs.io/en/latest/tutorials/config.html" rel="nofollow noreferrer">Preconfigured Gmail and Outlook</a></li>
<li><a href="https://red-mail.readthedocs.io/en/latest/extensions/logging.html" rel="nofollow noreferrer">Logging handler</a></li>
<li><a href="https://red-mail.readthedocs.io/en/latest/extensions/flask.html" rel="nofollow noreferrer">Flask extension</a></li>
</ul>
<p>Links:</p>
<ul>
<li><a href="https://github.com/Miksus/red-mail" rel="nofollow noreferrer">Source code</a></li>
<li><a href="https://red-mail.readthedocs.io/" rel="nofollow noreferrer">Documentation</a></li>
<li><a href="https://pypi.org/project/redmail/" rel="nofollow noreferrer">Releases</a></li>
</ul>
| 9,006
|
<p>VBScript doesn't appear to have a way to include a common file of functions.</p>
<p>Is there a way to achieve this?</p>
|
<p>The "Windows Script Host" framework (if ya want to call it that), offers an XML wrapper document that adds functionality over regular vbs files. One of which is the ability to include external script files of both the VBscript and Jscript flavors. I never got very deep into it, but I think it would do what you're wanting to do.
<a href="http://msdn.microsoft.com/en-us/library/15x4407c(VS.85).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/15x4407c(VS.85).aspx</a></p>
<p>You can include JavaScript, VBScript, or modules of other WScript script languages. </p>
<p>Example WSF file: </p>
<pre><code><job id="IncludeExample">
<script language="JavaScript" src="sprintf.js"/>
<script language="VBScript" src="logging.vbs"/>
<script language="VBScript" src="iis-queryScriptMaps.vbs"/>
</job>
</code></pre>
<p>If the above file is called "iis-scriptmaps.wsf", run it this way with cscript.exe: </p>
<pre><code>cscript.exe iis-scriptmaps.wsf
</code></pre>
|
<p>IIS 5 and up also allow a <a href="http://support.microsoft.com/kb/224963" rel="nofollow noreferrer" title="Using Enhanced <SCRIPT> Tags for Includes"><code>script</code> tag</a> for including other files from an ASP file. (Is your VBScript an ASP page or a Windows script?) Here's an example:</p>
<pre><code><script language="VBScript" runat="server" src="include.asp"></script>
</code></pre>
<p>The behavior and rules are a bit different from server-side includes. Note: I have never actually tried using this syntax from classic ASP.</p>
| 40,821
|
<p>I am doing a join on two tables. One is a user's table and the other a list of premium users. I need to have the premium members show up first in my query. However, just because they are in the premium user table doesn't mean they are still a premium member - there is an IsActive field that also needs to be checked.</p>
<p>So basically I need to return the results in the following order: </p>
<ul>
<li>Active Premium Users</li>
<li>Regular and Inactive Premium Users</li>
</ul>
<p>Right now I have it as the following:</p>
<pre><code>SELECT Users.MemberId, PremiumUsers.IsActive FROM Users
LEFT JOIN PremiumUsers ON PremiumUsers.UserId = Users.Id
ORDER BY PremiumUsers.IsActive DESC
</code></pre>
<p>The problem with this is that it places non-active premium members above non-premium members.</p>
<p>(I'm using MS SQL Server 2005 for this)</p>
|
<pre><code>ORDER BY COALESCE(PremiumUsers.IsActive, 0) DESC
</code></pre>
<p>That will group the NULLs with not-actives.</p>
|
<pre><code>ORDER BY COALESCE(PremiumUsers.IsActive, 0) DESC
</code></pre>
<p>That will group the NULLs with not-actives.</p>
| 41,143
|
<p>I need to have my iPhone Objective-C code catch Javascript errors in a UIWebView. That includes uncaught exceptions, syntax errors when loading files, undefined variable references, etc.</p>
<p>This is for a development environment, so it doesn't need to be SDK-kosher. In fact, it only really needs to work on the simulator.</p>
<p>I've already found used some of the hidden WebKit tricks to e.g. expose Obj-C objects to JS and to intercept alert popups, but this one is still eluding me.</p>
<p>[NOTE: after posting this I did find one way using a debugging delegate. Is there a way with lower overhead, using the error console / web inspector?]</p>
|
<p>I have now found one way using the script debugger hooks in WebView (note, NOT UIWebView). I first had to subclass UIWebView and add a method like this:</p>
<pre><code>- (void)webView:(id)webView windowScriptObjectAvailable:(id)newWindowScriptObject {
// save these goodies
windowScriptObject = newWindowScriptObject;
privateWebView = webView;
if (scriptDebuggingEnabled) {
[webView setScriptDebugDelegate:[[YourScriptDebugDelegate alloc] init]];
}
}
</code></pre>
<p>Next you should create a YourScriptDebugDelegate class that contains methods like these:</p>
<pre><code>// in YourScriptDebugDelegate
- (void)webView:(WebView *)webView didParseSource:(NSString *)source
baseLineNumber:(unsigned)lineNumber
fromURL:(NSURL *)url
sourceId:(int)sid
forWebFrame:(WebFrame *)webFrame
{
NSLog(@"NSDD: called didParseSource: sid=%d, url=%@", sid, url);
}
// some source failed to parse
- (void)webView:(WebView *)webView failedToParseSource:(NSString *)source
baseLineNumber:(unsigned)lineNumber
fromURL:(NSURL *)url
withError:(NSError *)error
forWebFrame:(WebFrame *)webFrame
{
NSLog(@"NSDD: called failedToParseSource: url=%@ line=%d error=%@\nsource=%@", url, lineNumber, error, source);
}
- (void)webView:(WebView *)webView exceptionWasRaised:(WebScriptCallFrame *)frame
sourceId:(int)sid
line:(int)lineno
forWebFrame:(WebFrame *)webFrame
{
NSLog(@"NSDD: exception: sid=%d line=%d function=%@, caller=%@, exception=%@",
sid, lineno, [frame functionName], [frame caller], [frame exception]);
}
</code></pre>
<p>There is probably a large runtime impact for this, as the debug delegate can also supply methods to be called for entering and exiting a stack frame, and for executing each line of code.</p>
<p>See <a href="http://www.koders.com/noncode/fid7DE7ECEB052C3531743728D41A233A951C79E0AE.aspx" rel="noreferrer">http://www.koders.com/noncode/fid7DE7ECEB052C3531743728D41A233A951C79E0AE.aspx</a> for the Objective-C++ definition of WebScriptDebugDelegate.</p>
<p>Those other methods:</p>
<pre><code>// just entered a stack frame (i.e. called a function, or started global scope)
- (void)webView:(WebView *)webView didEnterCallFrame:(WebScriptCallFrame *)frame
sourceId:(int)sid
line:(int)lineno
forWebFrame:(WebFrame *)webFrame;
// about to execute some code
- (void)webView:(WebView *)webView willExecuteStatement:(WebScriptCallFrame *)frame
sourceId:(int)sid
line:(int)lineno
forWebFrame:(WebFrame *)webFrame;
// about to leave a stack frame (i.e. return from a function)
- (void)webView:(WebView *)webView willLeaveCallFrame:(WebScriptCallFrame *)frame
sourceId:(int)sid
line:(int)lineno
forWebFrame:(WebFrame *)webFrame;
</code></pre>
<p>Note that this is all hidden away in a private framework, so don't try to put this in code you submit to the App Store, and be prepared for some hackery to get it to work.</p>
|
<p>A simpler solution for some cases might be to just add <a href="https://getfirebug.com/firebuglite" rel="nofollow">Firebug Lite</a> to the Web page.</p>
| 23,473
|
<p>I have the option of storing data in memory either as an XML document or multi-table ADO dataset. The web page utilizing this object will be selectively retrieving data items based on keys.</p>
<p>Does either of these objects have a clear performance advantage over the other?</p>
|
<p>If you decide to go down the XML route and if you're using .NET 3.5 consider looking at the new XDocument, XElement (and friends) classes in the System.Xml.Linq namespace. You can use Linq to XML to query your XML documents and it's rather good.</p>
|
<p>Picking up on what Saif said, your biggest challenge with XML will be relating keys from one document to the other. You can create unique keys for all the nodes in the document, but you may have improper collisions should you have another document of similar structure as the documents are distinct. In other words, you would have to ensure that there was no overlap by either merging documents temporarily or creating another scheme that concatenates additional identifiers to the dynamically generated keys.</p>
<p>Depending on your comfort level with XPath and XLST, you may want to create tables and relations with ADO, as this is more straight forward. You can do grouping of keys, and <a href="http://www.jenitennison.com/xslt/index.html" rel="nofollow noreferrer">Jeni Tennison</a> who posts at StackOverflow has a great <a href="http://www.jenitennison.com/xslt/grouping/muenchian.html" rel="nofollow noreferrer">series</a> on these methods. </p>
| 20,813
|
<p>I enjoy programming, usually. Tedious stuff is easy to get done as quickly and correctly as possible so I can get through it and not have to see it again.</p>
<p>But a lot of my coding is <em>fun</em> and when I get in the 'zone' I just really enjoy myself.</p>
<p>Which is where I make the mistake of spending too much time, perhaps adding features, perhaps writing it in a cool or elegant manner, or just doing neat prototypes.</p>
<ul>
<li>How do you recognize this is happening before it exceeds your time frame?</li>
<li>What do you do before starting a potentially fun piece of code, or during, to get back on track?</li>
<li>When is it ok to let yourself go "hog wild" and just enjoy it without worrying about consequences?</li>
</ul>
<p>-Adam</p>
|
<p>Keep a detailed prioritized feature list/bug list. review it often then balance the fun work with bugs/features that need to get done.</p>
|
<p>Justify any "fun" features you insert by regarding them as marketable eye-candy.</p>
<p>Unless, of course, they're not visible ;)</p>
| 8,508
|
<p>I am creating an touch screen application using Swing and have a request to change one of buttons so that it will behave like a keyboard when the button is held down.<br>
(First of all, I am not sure that the touch screen will allow the user to "hold down" the button, but pretend that they can for now)</p>
<p>I was going to go down the path of starting a loop when <code>mousePressed</code> was called and then ending the loop when <code>mouseReleased</code> was called. This will involve starting a thread and having to deal with synchronization as well as <code>invokeLater()</code> to get events back on the <code>EventQueue</code>.</p>
<p>Is there a very simple way to do what I want? I hope I am just not seeing the API to do it.</p>
|
<p><a href="http://docs.oracle.com/javase/6/docs/api/javax/swing/Timer.html" rel="nofollow noreferrer">javax.swing.Timer</a> is your friend. And <a href="http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html" rel="nofollow noreferrer">here's an article</a> with some more info.</p>
|
<p>I went with the java.swing.Timer since it will automatically post back to the Swing EventQueue and that is what I am looking for. Thanks for the help.</p>
| 39,895
|
<p>I'm planning on doing more coding from home but in order to do so, I need to be able to edit files on a Samba drive on our dev server. The problem I've run into with several editors is that the network latency causes the editor to lock up for long periods of time (Eclipse, TextMate). Some editors cope with this a lot better than others, but are there any file system or other tweaks I can make to minimize the impact of lag?</p>
<p>A few additional points:</p>
<ul>
<li>There's a policy against having company data on personal machines, so I'd like to avoid checking out the code locally.</li>
<li>The mount is over a PPTP VPN connection.</li>
<li>Mounting to Linux or OS X client</li>
</ul>
|
<p>Use a source control system — Subversion, Perforce, Git, Mercurial, Bazaar, etc. — so you're never editing code on a shared server. Instead you should be editing a local work area and committing changes to a repository located on the network.</p>
<p>Also, convince your company to adapt their policy such that company code is allowed on personal machines <strong>if</strong> it's on an encrypted volume. Encrypted disk images that you can use for this are <em>trivial</em> to create using Disk Utility, and can use strong cryptography. You can get even more security by not storing your encryption passphrase in your keychain, and instead typing it every time you mount the encrypted volume; this means that even if your local user account is compromised, as long as you don't have the volume mounted, nobody else will be able to mount it.</p>
<p>I did this all the time when I was consulting and none of my clients — some of whom had similar rules about company code — ever had a problem with it once I explained how things worked. (I think some of them even started using encrypted disk images even within their offices.)</p>
|
<p>Short answer: you can do no trick. CIFS is really geared towards LAN with a reasonably calm trafic, so you have zero chance to not suffer intermittent lag accessing a share through a VPN. The editor at some point needs to access the file in blocking IO, because it makes no real sense to do otherwise.</p>
<p>You could switch editor and use Emacs + <a href="http://www.gnu.org/software/tramp/" rel="nofollow noreferrer">TRAMP</a> which is geared to work on remote files.</p>
| 5,396
|
<p>I have a database with two main tables <code>notes</code> and <code>labels</code>. They have a many-to-many relationship (similar to how stackoverflow.com has questions with labels). What I am wondering is how can I search for a note using multiple labels using SQL? </p>
<p>For example if I have a note "test" with three labels "one", "two", and "three" and I have a second note "test2" with labels "one" and "two" what is the SQL query that will find all the notes that are associated with labels "one" and "two"?</p>
|
<p>To obtain the details of notes that have <strong>both</strong> labels 'One' and 'Two':</p>
<pre><code>select * from notes
where note_id in
( select note_id from labels where label = 'One'
intersect
select note_id from labels where label = 'Two'
)
</code></pre>
|
<p>Something like this... (you'll need another link table)</p>
<pre><code>SELECT *
FROM Notes n INNER JOIN NoteLabels nl
ON n.noteId = nl.noteId
WHERE nl.labelId in (1, 2)
</code></pre>
<p><strong>Edit</strong>: the NoteLabel table will have two columns, noteId and labelId, with a composite PK.</p>
| 45,479
|
<p>I've been working on a project that can't be described as 'small' anymore (40+ months), with a team that can't be defined as 'small' anymore (~30 people). We've been using Agile/Scrum (1) practices all along, and a healthy dose of TDD.</p>
<p>I'm not sure if I picked this up from Agile or TDD, more likely a combination of the two, but I'm now clearly in the camp of people that looks at debugging as a bad smell. By 'debugging' I'm not referring to the more abstract concept of figuring out what might be wrong with the system, but the specific activity of running the system in Debug mode, stepping through the code to figure out details that are otherwise inscrutable.</p>
<p><strong>Since I'm fairly convinced, this question is not about whether debugging is a bad smell or not. Rather, I'd like to know how I can persuade my team-mates about this.</strong></p>
<p>People that believe debugging mode is the 'standard' mode tend to write code that can be understood only by debugging through it, which leads to a lot of time wasted since every time you work an item on top of code developed by someone else, you get to first spend a considerable amount of time debugging it (and, since there's no bug involved.. the term is becoming increasingly ridiculous) - and then silos happen. So I'd love to convince a few of my team-mates that avoiding debug mode is a Good Thing (2). Since they are used to live in Debug mode, however, they don't seem to see the problem; to them, spending hours debugging someone else code before they even start doing anything related to their new item is the norm; they don't see anything wrong with it. Plus, as they spend time 'figuring it out' they know eventually the developer that worked that area will become available and the item will be passed on to them (leading to yet another silo).</p>
<p>Help me come up with a plan to turn them from the Dark Side !</p>
<p><strong><em>Thanks in advance.</em></strong></p>
<p>(1) Also referred to as SCRUM (all caps). Capitalization arguments aside, I think an asterisk after the term must be used since - unsurprisingly - our organization 'tweaked' the Agile and Scrum process to fit the perceived needs of all stakeholders involved. So, in all honesty, I won't pretend this has been 100% according to theory, but that's beside the point of my question.</p>
<p>(2) Yes, there will always be times when we'll <em>have</em> to get in debug mode, I'm not trying to absolutely avoid it, just.. trying to minimize the number of times we have to dive into it.</p>
|
<p>If you want to persuade your coworkers that your programming practices are better, first demonstrate by your productiveness that you are more effective than they are, at least for some tasks. Then they'll believe you when you explain how you get so much done.</p>
<p>It's also sometimes easier to focus on something concrete. Do your coworkers even talk in terms of "code smell"? Perhaps you could focus on specifics like "When the ABC module fails, it takes forever to debug it; it's much faster to use technique XYZ. Here, let me demonstrate." Then afterwards you can mention your basic principle, which is yeah the debugger is a useful tool, but there's usually other more useful ones.</p>
|
<p>@FOR : You have a second problem too, here it is :</p>
<blockquote>
<p>sadly it doesn't seem the devs are interested in being more productive (they get paid the same anyway)</p>
</blockquote>
<p>How do you intend to <strong>make them want</strong> to be more productive when there is nothing (visible) for them to gain?</p>
| 31,952
|
<p>I need to get the Class of an object at runtime.</p>
<p>For an non-abstract class I could do something like:</p>
<pre><code>public class MyNoneAbstract{
public static Class MYNONEABSTRACT_CLASS = new MyNoneAbstract().getClass();
</code></pre>
<p>But for an abstract class this does NOT work (always gives me <code>Object</code>)</p>
<pre><code>public abstract class MyAbstract{
public static Class MYABSTRACT_CLASS = MyAbstract.class.getClass();
</code></pre>
<p>This code will be running in JavaME environments.</p>
|
<p>You just need</p>
<pre><code>MyAbstract.class
</code></pre>
<p>That expression returns the Class object representing MyAbstract.</p>
|
<p>The code you want in the abstract case is:</p>
<pre><code>public abstract class MyAbstract{
public static Class MYABSTRACT_CLASS = MyAbstract.class;
}
</code></pre>
<p>although I personally wouldn't bother defining the constant and just used MyAbstract.class throughout.</p>
<p>I would have expected the code you wrote to have returned the class 'Class', not the class 'Object'.</p>
| 19,537
|
<p>i have problem i want to </p>
<p>select name_magazine from magazine</p>
<p>and i already import all library needed</p>
<p>and </p>
<blockquote>
<p>Query q = EntityManger.createQuery ("SELECT name_magazine FROM Magazine");</p>
<p>List results = (List) q.getResultList ();</p>
<p>For(Sting s : result)</p>
<p>System.out.println(s);</p>
</blockquote>
<p>but when i run this code it's error. can someone help me? Thx</p>
<p>this the error when i run the program</p>
<blockquote>
<p>Exception in thread "AWT-EventQueue-0"
java.lang.Error:
java.lang.reflect.InvocationTargetException
at org.jdesktop.application.ApplicationAction.actionFailed(ApplicationAction.java:859)
at org.jdesktop.application.ApplicationAction.noProxyActionPerformed(ApplicationAction.java:665)
at org.jdesktop.application.ApplicationAction.actionPerformed(ApplicationAction.java:698)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.AbstractButton.doClick(AbstractButton.java:357)
at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:1220)
at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:1261)
at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:272)
at java.awt.Component.processMouseEvent(Component.java:6041)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3265)
at java.awt.Component.processEvent(Component.java:5806)
at java.awt.Container.processEvent(Container.java:2058)
at java.awt.Component.dispatchEventImpl(Component.java:4413)
at java.awt.Container.dispatchEventImpl(Container.java:2116)
at java.awt.Component.dispatchEvent(Component.java:4243)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
at java.awt.Container.dispatchEventImpl(Container.java:2102)
at java.awt.Window.dispatchEventImpl(Window.java:2440)
at java.awt.Component.dispatchEvent(Component.java:4243)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
Caused by:
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native
Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.jdesktop.application.ApplicationAction.noProxyActionPerformed(ApplicationAction.java:662)
... 29 more Caused by: java.lang.IllegalArgumentException: An
exception occured while creating a
query in EntityManager
at oracle.toplink.essentials.internal.ejb.cmp3.EntityManagerImpl.createQuery(EntityManagerImpl.java:209)
at tugas_rpl.Tugas_RPLView.Iseng(Tugas_RPLView.java:734)
... 34 more Caused by: Exception [TOPLINK-8034] (Oracle
TopLink Essentials - 2.0.1 (Build
b09d-fcs (12/06/2007))):
oracle.toplink.essentials.exceptions.EJBQLException
Exception Description: Error compiling
the query [Select m.Name from
magazine m]. Unknown abstract schema type
[magazine].
at oracle.toplink.essentials.exceptions.EJBQLException.unknownAbstractSchemaType(EJBQLException.java:494)
at oracle.toplink.essentials.internal.parsing.ParseTreeContext.classForSchemaName(ParseTreeContext.java:163)
at oracle.toplink.essentials.internal.parsing.VariableNode.resolveClass(VariableNode.java:280)
at oracle.toplink.essentials.internal.parsing.DotNode.resolveMapping(DotNode.java:254)
at oracle.toplink.essentials.internal.parsing.DotNode.endsWithDirectToField(DotNode.java:213)
at oracle.toplink.essentials.internal.parsing.SelectNode.selectingDirectToField(SelectNode.java:440)
at oracle.toplink.essentials.internal.parsing.SelectNode.hasOneToOneSelected(SelectNode.java:265)
at oracle.toplink.essentials.internal.parsing.SelectNode.hasOneToOneSelected(SelectNode.java:222)
at oracle.toplink.essentials.internal.parsing.SelectGenerationContext.computeUseParallelExpressions(SelectGenerationContext.java:105)
at oracle.toplink.essentials.internal.parsing.SelectGenerationContext.(SelectGenerationContext.java:88)
at oracle.toplink.essentials.internal.parsing.ParseTree.buildContextForReadQuery(ParseTree.java:382)
at oracle.toplink.essentials.internal.parsing.ParseTree.buildContext(ParseTree.java:370)
at oracle.toplink.essentials.internal.parsing.EJBQLParseTree.buildContext(EJBQLParseTree.java:68)
at oracle.toplink.essentials.internal.parsing.EJBQLParseTree.populateQuery(EJBQLParseTree.java:107)
at oracle.toplink.essentials.internal.ejb.cmp3.base.EJBQueryImpl.buildEJBQLDatabaseQuery(EJBQueryImpl.java:219)
at oracle.toplink.essentials.internal.ejb.cmp3.base.EJBQueryImpl.buildEJBQLDatabaseQuery(EJBQueryImpl.java:189)
at oracle.toplink.essentials.internal.ejb.cmp3.base.EJBQueryImpl.buildEJBQLDatabaseQuery(EJBQueryImpl.java:153)
at oracle.toplink.essentials.internal.ejb.cmp3.base.EJBQueryImpl.(EJBQueryImpl.java:114)
at oracle.toplink.essentials.internal.ejb.cmp3.base.EJBQueryImpl.(EJBQueryImpl.java:99)
at oracle.toplink.essentials.internal.ejb.cmp3.EJBQueryImpl.(EJBQueryImpl.java:86)
at oracle.toplink.essentials.internal.ejb.cmp3.EntityManagerImpl.createQuery(EntityManagerImpl.java:204)
... 35 more</p>
</blockquote>
<p>I already try Vincent Ramdhanie,Guðmundur Bjarni suggestion</p>
<blockquote>
<p>Query q = entityManager.createQuery("Select m.name from magazine m");</p>
<p>List result = (List) q.getResultList();</p>
<p>For(Sting s : result)</p>
<p>System.out.print(s);</p>
</blockquote>
<p>but still error</p>
<p>this what library & variable i use</p>
<blockquote>
<p>private javax.persistence.EntityManager entityManager;</p>
<p>import org.jdesktop.application.Action;</p>
<p>import org.jdesktop.application.ResourceMap;</p>
<p>import org.jdesktop.application.SingleFrameApplication;</p>
<p>import org.jdesktop.application.FrameView;</p>
<p>import org.jdesktop.application.TaskMonitor;</p>
<p>import org.jdesktop.application.Task;</p>
<p>import java.awt.event.ActionEvent;</p>
<p>import java.awt.event.ActionListener;</p>
<p>import java.util.ArrayList;</p>
<p>import java.util.List;</p>
<p>import javax.swing.Timer;</p>
<p>import javax.swing.Icon;</p>
<p>import javax.swing.JDialog;</p>
<p>import javax.swing.JFrame;</p>
<p>import javax.swing.event.ListSelectionEvent;</p>
<p>import javax.swing.event.ListSelectionListener;</p>
<p>import org.jdesktop.beansbinding.AbstractBindingListener;</p>
<p>import org.jdesktop.beansbinding.Binding;</p>
<p>import org.jdesktop.beansbinding.PropertyStateEvent;</p>
<p>import javax.persistence.*;</p>
</blockquote>
|
<p>You probably should say what the error is exactly.</p>
<p>However, assuming that you have an entity Magazine then the query should be:</p>
<pre><code> select m from Magazine m
</code></pre>
<p>If you want all magazines.</p>
|
<p>If You are using JPA then in Query You need to write className and object as follows </p>
<pre><code>Query q = EntityManger.createQuery ("SELECT name_magazine e FROM Magazine e");
</code></pre>
<p>e is an object of Magazine class.
and if you facing this exception occurred while creating a query in EntityManager
Check out your persistance.xml file you need to add class in this file after the persistence-unit tag</p>
<pre><code><class>PackageName.className</class>
</code></pre>
| 42,437
|
<p>I need to get a listing of a server-side directory inside SAP. How do I achieve this in ABAP? Are there any built-in SAP functions I can call?</p>
<p>Ideally I want a function which I can pass a path as input, and which will return a list of filenames in an internal table.</p>
|
<p>Call function RZL_READ_DIR_LOCAL:</p>
<pre><code>FUNCTION RZL_READ_DIR_LOCAL.
*"----------------------------------------------------------------------
*"Lokale Schnittstelle:
*" IMPORTING
*" NAME LIKE SALFILE-LONGNAME
*" TABLES
*" FILE_TBL STRUCTURE SALFLDIR
*" EXCEPTIONS
*" ARGUMENT_ERROR
*" NOT_FOUND
*"----------------------------------------------------------------------
</code></pre>
<p>Place the path in the NAME import parameter, and then read the directory listing from FILE_TBL after it returns.</p>
<p>RZL_READ_DIR_LOCAL can handle normal local paths as well as UNC paths.</p>
<p>The only downside is it only gives you access to the first 32 chars of each filename. However, you can easily create a new function based on the RZL_READ_DIR_LOCAL code, and change the way the C program output is read, as the first 187 characters of each filename are actually available.</p>
|
<p>Take a look at transaction AL11 source code: RSWATCH0 form <code>fill_file_list</code>
There you can get all information about files.</p>
<p>Hope this helps!</p>
| 18,450
|
<p>My situation is as follows:</p>
<p>I have a normalized database, in which I hold geographic information about airports. The structure is:</p>
<pre><code>airport --is in--> city --is in--> country --is in--> continent
</code></pre>
<p>Now I want to let users administrate this data, without giving them direct access to the database. We need to offer this administration interface via a web service.</p>
<p>Now, when it comes to designing the service, we ran into the discussion about how to define the operations. We came up with different solutions:</p>
<p><strong>Solution A: specific operations</strong></p>
<p>For each of the four tables (airport, city, country, continent) we define 3 operations:</p>
<ul>
<li>insert</li>
<li>get</li>
<li>update</li>
</ul>
<p>This would lead to 12 operations with 2 request/response objects = 24 objects</p>
<p>To create an all new airport with all dependencies, at least 4 requests would be necessary.</p>
<p><strong>Solution B: generic</strong></p>
<p>There is only one operation, which is controlled via parameters. This operation is capable of creating everything needed to administer the database.</p>
<p>The operation would decide what needs to be done and executes it. If an error occures, it will roll back everything.</p>
<p>==> 1 Operation = 2 highly complex request/response-objects</p>
<p><strong>Solution C: Meet in the middle 1</strong></p>
<p>One generic operation per table, which is capable of executing get, insert, update, just like solution B, but focused on one table each.</p>
<p>==> 4 operations = 8 complex request/response-objects</p>
<p><strong>Solution D: Meet in the middle 2</strong></p>
<p>One generic operation per action (get, insert, delete), which can work on each table and resolve dependencies.</p>
<p>==> 3 operations = 6 slightly more complex request/response-objects</p>
<p><strong>Example</strong></p>
<p>Since this was rather abstract, hier a simplified example for request-objects for creating (JFK/New York/USA/North America):</p>
<p><strong>Solution A:</strong></p>
<p>Request 1/4:</p>
<pre><code><insertContinent>North America</insertContinent>
</code></pre>
<p>Request 2/4:</p>
<pre><code><insertCountry continent="North America">USA</insertCountry>
</code></pre>
<p>Request 3/4:</p>
<pre><code><insertCity country="USA">New York</insertCity>
</code></pre>
<p>Request 4/4:</p>
<pre><code><insertAirport city="New York">JFK</insertAirport>
</code></pre>
<p><strong>Solution B:</strong></p>
<p>Request 1/1:</p>
<pre><code><action type="insertCountry" parent="North America">USA</action>
<action type="insertAirport" parent="New York">JFK</action>
<action type="insertContinent" parent="">North America</action>
<action type="insertCity" parent="USA">New York</action>
</code></pre>
<p><strong>Solution C:</strong></p>
<p>Request 1/4:</p>
<pre><code><countryAction type="insert" parent="North America">USA</countryAction>
</code></pre>
<p>Request 2/4:</p>
<pre><code><airportAction type="insert" parent="New York">JFK</airportAction>
</code></pre>
<p>Request 3/4:</p>
<pre><code><continentAction type="insert" parent="">North America</continentAction >
</code></pre>
<p>Request 4/4:</p>
<pre><code><cityAction type="insert" parent="USA">New York</cityAction >
</code></pre>
<p><strong>Solution D:</strong>
Request 1/1:</p>
<pre><code><insert airport="JFK" city="New York" country="USA" continent="North America" />
</code></pre>
<p>Solution D seems rather elegant for me, therefore I tried to put this in XSD:</p>
<p>Code:</p>
<pre><code><complexType name="NewContinent">
<sequence>
<element name="NAME" type="string"></element>
</sequence>
</complexType>
<complexType name="NewCountry">
<sequence>
<element name="ISOCODE" type="string"></element>
<element name="NAME" type="string"></element>
<choice>
<element name="newCONTINENT" type="tns:NewContinent"></element>
<element name="CONTINENT" type="string"></element>
</choice>
</sequence>
</complexType>
<complexType name="NewCity">
<sequence>
<element name="IATA" type="string"></element>
<element name="NAME" type="string"></element>
<choice>
<element name="COUNTRY" type="string"></element>
<element name="newCOUNTRY" type="tns:NewCountry"></element>
</choice>
</sequence>
</complexType>
<complexType name="NewAirport">
<sequence>
<element name="IATA" type="string"></element>
<element name="NAME" type="string"></element>
<choice>
<element name="CITY" type="string"></element>
<element name="newCITY" type="tns:NewCity"></element>
</choice>
</sequence>
</complexType>
</code></pre>
<p>A corresponding request would then look like follows:</p>
<pre><code><complexType name="Request">
<choice>
<element name="AIRPORT" type="tns:NewAirport"></element>
<element name="CITY" type="tns:NewCity"></element>
<element name="COUNTRY" type="tns:NewCountry"></element>
<element name="CONTINENT" type="tns:NewContinent"></element>
</choice>
</complexType>
</code></pre>
<p>Now my question: <strong>Is this really the best solution available? Is the XSD enough to understand, what is going on?</strong></p>
|
<p>Presumably you are writing a protocol layer that will understand your different message types. You will also need an application layer to parse the contents of the message. The different approaches you mention will shift the burden of parsing between these two layers. So for example:</p>
<p><strong>Solution A</strong>: The protocol layer does all the parsing and returns the data and command. The application layer can just use the data. This is also known as the RPC pattern.</p>
<p>Pros: You can validate your messages. You can map messages directly to application calls.</p>
<p>Cons: If you need to make a change to the interface, your protocol changes.</p>
<p><strong>Solution B</strong>: The protocol layer returns two values and a command. The application layer must use the command to parse the values into types.</p>
<p>Pros: The protocol never changes.</p>
<p>Cons: You can't validate messages. Your application code is more complicated.</p>
<p><strong>Solution C</strong>: The protocol layer returns two known types and an command that must be parsed. The application layer can just parse the command and use the data.</p>
<p>Pros: I can't think of any, seems like not a very good compromise.</p>
<p>Cons: Leaves the parsing only partially done.</p>
<p><strong>Solution D</strong>: The protocol layer returns known types (the way you implemented it) and a generic command. The application layer must look at the data it receives and convert the generic command into a specific command. This is similar to the REST architecture.</p>
<p>Pros: Calls are distinct operations so that you could for example cache get responses.</p>
<p>Cons: Complexity in the application layer</p>
<p>The REST model is usually implemented differently than you have outlined. It uses HTTP GET, POST, PUT, DELETE messages to communicate arbitrary documents. Parameters are given as part of the URL. So for example:</p>
<pre><code><insert airport="JFK" city="New York" country="USA" continent="North America" />
</code></pre>
<p>becomes</p>
<pre><code><insert URL="airport?city=Chicago">ORD</insert>
</code></pre>
<p>Or if you are using HTTP it becomes a POST request to an airport URL with a param of the city with the contents being information about the airport. Note that some of this becomes clearer with more compliated data where you have multiple elements and mixed types. For example if you wanted to send the airport abbreviation, long name, and altitude.</p>
<p>I think the REST architecture could work quite well for the interface you describe. As long as all you need to do is support the CRUD operations. The are many sites that will give you the pros and cons of the REST architectural style.</p>
<p>Personally I prefer the RPC style (Solution A) with some REST-ful attributes. I want the protocol to do the parsing work and validate the messages. This is typically how people implement SOAP web service interfaces.</p>
<p>Your interface may look simple today but tomorrow one of your customers is going to ask you for a new call that doesn't fit the REST model so well and you'll find yourself wedging it into the existing four messages.</p>
|
<p>This is an old question, and I'm sure the service has been written a long time ago, but I wanted to contribute an answer anyway.</p>
<p>The RESTful approach would be to define an airport resource, such as this:</p>
<pre><code><airport href="/airports/JFK">
<name>JFK</name>
<city>New York</city>
<country>USA</country>
<continent>North America</continent>
</airport>
</code></pre>
<p>Or, if you want to use a browser-compatible microformat:</p>
<pre><code><div class="object airport" href="/airports/JFK">
<ul class="attributes">
<li class="name">JFK</li>
<li class="city">New York</li>
<li class="country">USA</li>
<li class="continent">North America</li>
</ul>
</div>
</code></pre>
<p>This resource would be located at a URI like <code>/airports/JFK</code>, which would be retrieved with a <code>GET</code> method, updated with a <code>PUT</code> method, and deleted with a <code>DELETE</code> method.</p>
<p>In a design like this, the URI <code>/airports/</code> would represent a container resource for all of the airports in the database, and URIs like <code>/airports/?city=New+York</code> and <code>/airports/?country=USA</code> would be filters on the container to return a subset of the airports. Both of these would be <code>GET</code> methods, and the resources would contain a list of airport resources as defined above, either in full (since they're small) or with a few useful attributes and the <code>href</code> that points to the full resource for each airport.</p>
<p>Finally, adding a new resource could either be a <code>PUT</code> method on the airport's full URI, or a <code>POST</code> method on <code>/airports/</code>. In both cases the body of the request is the airport resource as shown above. The difference between the methods is who gets to decide the final URI for the airport: the client decides for <code>PUT</code> and the service decides for <code>POST</code>. Which one you use depends upon whether or not your clients can reasonably determine the right URI. Usually the service decides because the URIs contain a numeric unique identifier and the service has to choose that.</p>
<p>Now of course your original question was about SOAP, not REST. I would go ahead and set up a RESTful design as I've described, then describe my resources as complex types using XSD and a SOAP service with actions that duplicate the <code>GET</code>, <code>PUT</code>, <code>DELETE</code>, and <code>POST</code> operations of the RESTful service. This will give you the RPC equivalent of:</p>
<pre><code>class Airport
has String name
has String city
has String country
has String continent
method void update(name, city, country, continent)
method void delete()
class AirportList
method Airport[] get(opt name, opt city, opt country, opt continent)
method void add(name, city, country, continent)
</code></pre>
| 21,786
|
<p>How do I target .NET 3.5 alone after installing SP1 in VS2008? This is because VS 2008 lists only .NET 3.5, .NET 3.0 & .NET 2.0 and does not specifically show .NET 3.5 SP1.</p>
|
<p><a href="http://michael.toren.net/code/tcptraceroute/" rel="nofollow noreferrer">tcptraceroute</a></p>
|
<p>I have lot's of problems with that firewall. Having my server into EEUU doesn't help. If you need tools to test your site hosted outside from china like you were in China, you can try that page:</p>
<p><a href="http://www.websitepulse.com/help/tools.php" rel="nofollow noreferrer">http://www.websitepulse.com/help/tools.php</a></p>
<p>Good luck</p>
| 7,207
|
<p>In a project that I'm about to wrap up, I've written and implemented an object-relational mapping solution for PHP. Before the doubters and dreamers cry out "how on earth?", relax -- I haven't found a way to make late static binding work -- I'm just working around it in the best way that I possibly can.</p>
<p>Anyway, I'm not currently using prepared statements for querying, because I couldn't come up with a way to pass a variable number of arguments to the <code>bind_params()</code> or <code>bind_result()</code> methods. </p>
<p>Why do I need to support a variable number of arguments, you ask? Because the superclass of my models (think of my solution as a hacked-up PHP ActiveRecord wannabe) is where the querying is defined, and so the find() method, for example, doesn't know how many parameters it would need to bind.</p>
<p>Now, I've already thought of building an argument list and passing a string to eval(), but I don't like that solution very much -- I'd rather just implement my own security checks and pass on statements.</p>
<p>Does anyone have any suggestions (or success stories) about how to get this done? If you can help me solve this first problem, perhaps we can tackle binding the result set (something I suspect will be more difficult, or at least more resource-intensive if it involves an initial query to determine table structure).</p>
|
<p>In PHP you can pass a variable number of arguments to a function or method by using <a href="http://www.php.net/call_user_func_array" rel="noreferrer"><code>call_user_func_array</code></a>. An example for a method would be:</p>
<pre><code>call_user_func_array(array(&$stmt, 'bindparams'), $array_of_params);
</code></pre>
<p>The function will be called with each member in the array passed as its own argument.</p>
|
<p>I am not allowed to edit, but I believe in the code</p>
<pre><code>call_user_func_array(array(&$stmt, 'bindparams'), $array_of_params);
</code></pre>
<p>The reference in front of $stmt is not necessary. Since <code>$stmt</code> is the object and <code>bindparams</code> is the method in that object, the reference is not necessary. It should be:</p>
<pre><code>call_user_func_array(array($stmt, 'bindparams'), $array_of_params);
</code></pre>
<p>For more information, see the PHP manual on <a href="http://au2.php.net/manual/en/language.pseudo-types.php#language.types.callback" rel="nofollow noreferrer">Callback Functions</a>." </p>
| 3,374
|
<p>I have 12 parts for a model I want to print but I would like to know if I can put all of them in a single G-code file and print that on its own. Would this affect the model in any way?</p>
<p>I’m using PLA on my Ender 3 Pro</p>
|
<blockquote>
<p>I have 12 parts for a model I want to print but I would like to know if I can put all of them in a single G-code file and print that on its own.</p>
</blockquote>
<p>You certainly can. The printer doesn't care how many parts there are. Many single parts, like those with holes, will have layers that have areas that aren't contiguous. To the printer, multiple parts look just like a single part that happens not to be connected.</p>
<p>That said, printing multiple parts at once means that the job will be larger and take longer, and a problem printing any of those parts can force you to stop the whole job. Because small parts have less area in contact with the bed, small parts are more likely to come loose from the bed during the print, so running a job with many small parts can be risky -- if any one part comes loose, you might lose all the time and material you put into the whole job.</p>
<p>One tool that can help mitigate that risk is the <a href="https://plugins.octoprint.org/plugins/cancelobject/" rel="nofollow noreferrer">Cancel Objects plugin</a> for <a href="https://octoprint.org" rel="nofollow noreferrer">OctoPrint</a>. If you use OctoPrint to manage your printer, you can use the plugin to stop further work on any objects that have problems during the print and continue with the rest. <a href="https://youtu.be/ANfOr2F79LQ" rel="nofollow noreferrer">Here's a video</a> about using Cancel Objects.</p>
<p>Also, when printing multiple parts, be sure to check that you have enough material (filament, resin, etc) available to complete the whole job.</p>
|
<p>This answer assumes FDM printing -- for resin printers, as I understand it, as long as there's flow space between parts, if they fit on the build plate, they'll print.</p>
<p>For FDM, generally, you'll get better print quality printing a single part, because layers don't cool while you print the same layer for each of the other parts (meaning layer adhesion will be better). That said, if the parts are very small, this additional cooling may be an improvement vs. having to set your slicer to provide a pause between layers to avoid slumps and layer spreading.</p>
<p>A compromise, if the parts are low enough, is that most slicers can be instructed to print the parts sequentially -- that is, print all of part A, then all of part B, and so forth. This has some limitation in that all parts already printed must clear parts of the machine, and may also require larger clearance between parts for items like fan shrouds.</p>
<p>But printing a bunch of parts at one time does work, if the compromises in layer adhesion and other quality issues related to traveling between parts are acceptable. The only way to be sure is to print the whole lot (perhaps with a large nozzle and thick layers, low infill, etc. to minimize filament consumption and print time) and see if they're good enough.</p>
| 2,188
|
<p>Is the Visual Studio 2008 Object Test Bench useful for anything? Maybe I'm missing something but aside from a flashy version of the immediate window, it doesn't seem like a developer would actually use it for anything. </p>
<p><em>(And how many people knew it existed in the first place?!)</em></p>
<p>In case you're wondering, the 'Object Test Bench' is located under 'View / Other Windows' in Visual Studio 2008.</p>
|
<p>I had never heard of it until you mentioned it - thanks for bringing it to my attention.</p>
<p>I do think it's useful. If I want to see how "stuff" works I usually drop my code into LINQPad and see what sort of results I get by doing a Dump() on the resulting object. Only problem is that you have to copy your whole class and supporting classes in there to get anything more than trivial stuff to work. Also, there's no intellisense in LINQPad.</p>
<p>This looks like it can replace what I use LINQPad for. Quick and dirty playing with the objects.</p>
|
<p>IIRC, you can use it for load/stress testing, but my only exposure to it was a quick demo way back at the Ready To Launch event for VS2005.</p>
| 34,440
|
<p>What is the best way of testing a function that throws on failure? Or testing a function that is fairly immune to failure?</p>
<p>For instance; I have a <code>I/O Completion Port</code> class that throws in the constructor if it can't initialise the port correctly. This uses the <code>Win32</code> function of <code>CreateIoCompletionPort</code> in the initialiser list. If the handle isn't set correctly - a non-null value - then the constructor will throw an exception. I have never seen this function fail.</p>
<p>I am pretty certain that this (and other functions like it in my code) if they fail will behave correctly, the code is 50 lines long including white-space, so my questions are</p>
<p>a) is it worth testing that it will throw<br>
b) and if it is worth testing, how to?<br>
c) should simple wrapper classes as these be unit-tested? </p>
<p>For b) I thought about overriding <code>CreateIoCompletionPort</code> and passing the values through. In the unit test override it and cause it to return 0 when a certain value is passed in. However since this is used in the constructor then this needs to be static. Does this seem valid or not?</p>
|
<p>It is definitely worthwhile to test failure conditions, both that your class properly throws an exception when you want it to and that exceptions are handled properly in the class.</p>
<p>This can easily be done if you are acting on an object passed in to the constructor... just pass in a mock. If not, I tend to prefer to have the functionality moved to a protected method, and override the protected method to evoke my failure case. I will use Java as an example, but it should be easy enough to port the ideas to a C# case:</p>
<pre><code>public class MyClass {
public MyClass() throws MyClassException {
// Whatever, including a call to invokeCreateIoCompletionPort
}
protected int invokeCreateIoCompletionPort(String str, int i) {
return StaticClass.createIoCompletionPort(str, i);
}
}
public class MyTest {
public void myTest() {
try {
new MyClass();
fail("MyClassException was not thrown!");
} catch (MyClassException e) {
}
}
private static class MyClassWrapper extends MyClass {
@Override
protected int invokeCreateIoCompletionPort(String str, int i) {
throw new ExpectedException();
}
}
}
</code></pre>
<p>As you can see, it is pretty easy to test whether an exception is being thrown by the constructor or method you are testing, and it is also pretty easy to inject an exception from an external class that can throw an exception. Sorry I'm not using your actual method, I just used the name to illustrate how it sounded like you are using it, and how I would test the cases it sounded you wanted to test.</p>
<p>Basically, any API details you expose can usually be tested, and if you want to KNOW that exceptional cases work as they should, you probably will want to test it.</p>
|
<p>Sound like C++ to me. You need a seam to mock out the Win32 functions. E.g. in your class you would create a protected method <code>CreateIoCompletionPort()</code> which calls <code>::CreateIoCompletionPort()</code> and for your test you create a class that derives from you I/O Completion Port class and overrides <code>CreateIoCompletionPort()</code> to do nothing but return <code>NULL</code>. Your production class is still behaving like it was designed but you are now able to simulate a failure in the <code>CreateIoCompletionPort()</code> function.</p>
<p>This technique is from Michael Feathers book "Working effectively with legacy code".</p>
| 2,917
|
<p>I'm doing some architectural cleanup that involves moving a bunch of classes into different projects and/or namespaces. Currently I'm moving the files by hand, building, and then manually adding <em>using Foo</em> statements as needed to resolve compilation errors. Anyone know of a smarter way of doing this? (We're a CodeRush and Refactor! shop, but I'd be interested to hear if Resharper has support for this)</p>
|
<p>As mentioned in the comments, this answer is now outdated. Please see the <a href="https://stackoverflow.com/a/55782663/479251">up-to-date answer below</a></p>
<hr>
<p>Resharper is the only tool I am aware of what has this ability. There is also a lot of other functionality that it has that is missing in CodeRush and Refactor!</p>
|
<p>If you cannot, or do not want to use Re$harper, <strong>Notepad++</strong> is your friend:</p>
<ol>
<li><em>Make sure you don't have usaved changes inside Visual Studio</em> for the files you need to move to the new namespace</li>
<li><strong>Open all</strong> the files that contain the namespace that needs to be changed in Notepad++</li>
<li>Open <kbd><strong>Find & Replace</strong></kbd> (CTRL + H)</li>
<li>Fill the Find what and Replace with fields</li>
<li>Press <kbd><strong>Replace All in All Opened Documents</strong></kbd></li>
<li><strong>Save all</strong> changes in all documents (CTRL + SHIFT + S)</li>
<li>Switch to Visual Studio and <strong>reload</strong> all the documents (<kbd><strong>Yes to all</strong></kbd> at the prompt)</li>
</ol>
<p><strong>DONE</strong></p>
| 20,989
|
<p>I've been reading up on branching/merging with Subversion 1.5 using the excellent and free <a href="http://svnbook.red-bean.com/" rel="noreferrer">Version Control with Subversion</a> book. I think that I understand how to use the Subversion command line client to perform the actions that I need most often, which are:</p>
<p><strong>Update Branch with Changes from Trunk</strong></p>
<p>From the branch's working directory run: </p>
<blockquote>
<p>svn merge <a href="http://svn.myurl.com/proj/trunk" rel="noreferrer">http://svn.myurl.com/proj/trunk</a></p>
</blockquote>
<p><strong>Merge Branch into Trunk</strong></p>
<p>From the trunk's working directory run:</p>
<blockquote>
<p>svn merge --reintegrate <a href="http://svn.myurl.com/proj/branches/mybranch" rel="noreferrer">http://svn.myurl.com/proj/branches/mybranch</a></p>
</blockquote>
<p>However, we are using TortoiseSVN 1.5 as our interface to Subversion. I would like to know how best to perform these operations with TortoiseSVN. The new dialog provides three different options on the main menu. </p>
<ol>
<li>Merge a range of revisions</li>
<li>Reintegrate a branch</li>
<li>Merge two different trees</li>
</ol>
<p>From what I can gather, TortoiseSVN always executes svn with the following syntax.</p>
<blockquote>
<p>svn merge [--dry-run] --force From_URL@revN To_URL@revM PATH</p>
</blockquote>
<p>Additionally, reintegrate a branch often fails with a message stating that some targets have not been merged and so it cannot continue, and so I had to use option #3.</p>
<p>My questions are:</p>
<ol>
<li>How do I use TortoiseSVN 1.5 to merge changes from the trunk to a branch?</li>
<li>How do I use TortoiseSVN 1.5 to merge the branch to the trunk, with and without the reintegrate method?</li>
<li>Which of the above options should I use for each, and why?</li>
</ol>
<hr>
<p><strong>EDIT</strong></p>
<p>Through "dry run" testing I have found that the command line Subversion operation</p>
<blockquote>
<p>svn merge <a href="http://svn.myurl.com/proj/trunk" rel="noreferrer">http://svn.myurl.com/proj/trunk</a></p>
</blockquote>
<p>is analogous to option #1 (Merge a Range of Revisions) in TortoiseSVN, as long as I leave the revision range blank.</p>
|
<p>I couldn't properly follow the other answers, here's more of a dummies guide... </p>
<p>You can do this either way round to go <code>trunk -> branch</code> or <code>branch -> trunk</code>. I always first do <code>trunk -> branch</code> fix any conflicts there and then merge <code>branch -> trunk</code>.</p>
<h3>Merge trunk into a branch / tag</h3>
<ol>
<li><strong>Checkout the branch / tag</strong></li>
<li>Right-click on the root of the branch | Tortoise SVN | Merge ...</li>
<li><strong>Merge Type:</strong> Merge a range of revisions | Click 'Next'
<img src="https://i.stack.imgur.com/JfV4b.png" alt="enter image description here"></li>
<li><strong>Merge revision range:</strong> Select the URL of the trunk directory that you copied to the branch / tag. Enter the revisions to merge or leave the field empty to merge all revisions | click 'Next'
<img src="https://i.stack.imgur.com/Y0X12.png" alt="enter image description here"></li>
<li><strong>Merge options:</strong> I just left these as default | click 'Merge'
<img src="https://i.stack.imgur.com/foKHp.png" alt="enter image description here"></li>
<li>This will merge the revisions into the checked out branch / tag</li>
<li>Then commit the merged changes to the branch / tag</li>
</ol>
|
<p>Shift-Right Click on the folder and select TortoiseSVN -> Merge All</p>
| 38,310
|
<p>When I get a java.io.InvalidClassException, it gives me the serialVersionUID that it wants, and the serialVersionUID that it got. Is there an easy way to tell which of my dozens of jars using the wrong serialVersionUID?</p>
<p><strong>Update</strong>: I should mention that our intention is to update everything at the same time, but I'm trying to debug a problem in our build and deploy process.</p>
|
<p>use the serialver tool from the sun jdk for each class in the jar. </p>
|
<p>clumsy but works</p>
<p>i would use a reverse engineering tool<br>
1) unzip the jars<br>
2) run, say, jad on the class file tree<br>
3) run grep or any other find tool on this new tree of source to look for the serial version uid.<br></p>
| 23,289
|
<p>I really like <strong>Araxis</strong> Merge for a graphical DIFF program for the PC. I have no idea what's available for <strong>linux</strong>, though. We're running SUSE linux on our z800 mainframe.
I'd be most grateful if I could get a few pointers to what programs everyone else likes.</p>
|
<p>I know of two graphical diff programs: <a href="http://meldmerge.org/" rel="noreferrer">Meld</a> and <a href="http://kdiff3.sourceforge.net/" rel="noreferrer">KDiff3</a>. I haven't used KDiff3, but Meld works well for me.</p>
<p>It seems that both are in the standard package repositories for openSUSE 11.0</p>
|
<p>Subclipse for Eclipse has an excellent graphical diff plugin if you are using SVN (subversion) source control. </p>
| 13,800
|
<p>Is it possible to pass a reference to a function to another function in F#? Specifically, I'd like to pass lambda functions like</p>
<p>foo(fun x -> x ** 3)</p>
<p>More specifically, I need to know how I would refer to the passed function in a function that I wrote myself.</p>
|
<p>Yes, it is possible. The <a href="http://research.microsoft.com/fsharp/manual/spec2.aspx#_Toc207785549" rel="noreferrer">manual</a> has this example:</p>
<pre><code>> List.map (fun x -> x % 2 = 0) [1 .. 5];;
val it : bool list
= [false; true; false; true; false]
</code></pre>
|
<p>Functions are first class citizens in F#. You can therefore pass them around just like you want to.</p>
<p>If you have a function like this:</p>
<pre><code>let myFunction f =
f 1 2 3
</code></pre>
<p>and <strong>f</strong> is function then the return value of <strong>myFunction</strong> is <strong>f</strong> applied to 1,2 and 3.</p>
| 6,569
|
<p>I can't figure this one out. I can download a win32 binary of flex 2.5.4a from gnuwin32, but I'd like to build the latest version (2.5.35) using Visual Studio 2005. I suppose I could build in in cygwin, but where is the fun in that?</p>
|
<p>Note that Flex is seriously out-of-date on Windows when it comes to generating C++ scanners. Recent Flex versions which are able to generate ISO C++ scanners do not support Win32 (MinGW or VS), so you're probably better of trying to generate a C scanner and call it from C++.</p>
|
<p>Why you don't want to try the Spirit framework from Boost?</p>
| 28,052
|
<p>I've read a lot of people saying that some things shouldn't be written in an object orientated style - as a person learning the OO style coming from a C background, what do they mean by this?</p>
<p>What shouldn't be OO, why do some things fit this design better, and how do we know when it's best to do what?</p>
|
<p>The real world is full of objects.</p>
<p>It's helpful to make the software world match the real world. </p>
<p>"What about 'system utilities'? They just deal with abstractions like sockets and processes and file systems." They sound like things to me. They have attributes and behaviors, they have associations.</p>
<p>If you're looking for <strong>proof</strong> that OO is <em>better</em>, there isn't any. Nothing is <em>better</em> because <em>better</em> is a gloriously vague term. Anyone who's clever can write any program in any style. You could adopt functional, procedural, object-oriented, or anything you feel like.</p>
<p>I use OO because I have a very small brain and must learn to live within its limits. OO is a crutch to help me struggle through programming. If I was smarter, richer and better-looking, I wouldn't need the help, and I could write non-OO programs. Sadly, I'm not smart. Without class definitions to isolate responsibility and structure an architecture, I'd still be writing single-file "hello world" variants.</p>
|
<p>Just a tip: you should tag this question as "subjective" as everyone seems to have a different opinion on things like this.</p>
| 21,482
|
<p>I could swear I've seen people typing function headers and then hitting some key combination to auto-create function braces and insert the cursor between them like so:</p>
<pre><code>void foo()_
</code></pre>
<p>to</p>
<pre><code>void foo()
{
_
}
</code></pre>
<p>Is this a built-in feature?</p>
|
<p>Check out <a href="http://www.jetbrains.com/resharper/documentation/feature_map.html" rel="nofollow noreferrer">Resharper</a> - it is a Visual Studio add-on with this feature, among many other development helps.</p>
<p>Also see <a href="http://www.knowdotnet.com/articles/csharpcompleter.html" rel="nofollow noreferrer">C# Completer</a>, another add-on.</p>
<p>If you want to roll your own, check out <a href="http://www.developer.com/net/cplus/article.php/3347271" rel="nofollow noreferrer">this article</a>. Insane that one should have to do that, though.</p>
|
<p>I just created one based on @Luke's above. This one, you want to hit Enter then hit your key combination and it will insert:</p>
<pre><code>if ()
{
}
else
{
}
</code></pre>
<p>And it will put your cursor in the parenthesis by the if statement.</p>
<pre><code>Sub IfStatement()
DTE.ActiveDocument.Selection.Text = "if ()"
DTE.ActiveDocument.Selection.NewLine()
DTE.ActiveDocument.Selection.Text = "{"
DTE.ActiveDocument.Selection.NewLine(2)
DTE.ActiveDocument.Selection.Text = "}"
DTE.ActiveDocument.Selection.NewLine()
DTE.ActiveDocument.Selection.Text = "else"
DTE.ActiveDocument.Selection.NewLine(2)
DTE.ActiveDocument.Selection.Text = "{"
DTE.ActiveDocument.Selection.NewLine(2)
DTE.ActiveDocument.Selection.Text = "}"
DTE.ActiveDocument.Selection.LineUp(False, 7)
DTE.ActiveDocument.Selection.EndOfLine()
DTE.ActiveDocument.Selection.CharLeft(3)
End Sub
</code></pre>
| 3,090
|
<p>I am trying to display a list of all files found in the selected directory (and optionally any subdirectories). The problem I am having is that when the GetFiles() method comes across a folder that it cannot access, it throws an exception and the process stops.</p>
<p>How do I ignore this exception (and ignore the protected folder/file) and continue adding accessible files to the list?</p>
<pre><code>try
{
if (cbSubFolders.Checked == false)
{
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
foreach (string fileName in files)
ProcessFile(fileName);
}
else
{
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.*", SearchOption.AllDirectories);
foreach (string fileName in files)
ProcessFile(fileName);
}
lblNumberOfFilesDisplay.Enabled = true;
}
catch (UnauthorizedAccessException) { }
finally {}
</code></pre>
|
<p>You will have to do the recursion manually; don't use AllDirectories - look one folder at a time, then try getting the files from sub-dirs. Untested, but something like below (note uses a delegate rather than building an array):</p>
<pre><code>using System;
using System.IO;
static class Program
{
static void Main()
{
string path = ""; // TODO
ApplyAllFiles(path, ProcessFile);
}
static void ProcessFile(string path) {/* ... */}
static void ApplyAllFiles(string folder, Action<string> fileAction)
{
foreach (string file in Directory.GetFiles(folder))
{
fileAction(file);
}
foreach (string subDir in Directory.GetDirectories(folder))
{
try
{
ApplyAllFiles(subDir, fileAction);
}
catch
{
// swallow, log, whatever
}
}
}
}
</code></pre>
|
<p>This should answer the question. I've ignored the issue of going through subdirectories, I'm assuming you have that figured out. </p>
<p>Of course, you don't need to have a seperate method for this, but you might find it a useful place to also verify the path is valid, and deal with the other exceptions that you could encounter when calling GetFiles().</p>
<p>Hope this helps.</p>
<pre><code>private string[] GetFiles(string path)
{
string[] files = null;
try
{
files = Directory.GetFiles(path);
}
catch (UnauthorizedAccessException)
{
// might be nice to log this, or something ...
}
return files;
}
private void Processor(string path, bool recursive)
{
// leaving the recursive directory navigation out.
string[] files = this.GetFiles(path);
if (null != files)
{
foreach (string file in files)
{
this.Process(file);
}
}
else
{
// again, might want to do something when you can't access the path?
}
}
</code></pre>
| 20,790
|
<p>I have an executable that runs instantly from a command prompt, but does not appear to ever return when spawned using System.Diagnostics.Process:</p>
<p>Basicly, I'm writing a .NET library wrapper around the Accurev CLI interface, so each method call spawns the CLI process to execute a command.</p>
<p>This works great for all but one command:</p>
<pre><code> accurev.exe show depots
</code></pre>
<p>However, when running this from a console, it runs fine, when I call it using a .net process, it hangs...The process spawning code I use is:</p>
<pre><code> public static string ExecuteCommand(string command)
{
Process p = createProcess(command);
p.Start();
p.WaitForExit();
// Accurev writes to the error stream if ExitCode is non zero.
if (p.ExitCode != 0)
{
string error = p.StandardError.ReadToEnd();
Log.Write(command + " failed..." + error);
throw new AccurevException(error);
}
else
{
return p.StandardOutput.ReadToEnd();
}
}
/// Creates Accurev Process
/// </summary>
/// <param name="command"></param>
/// <returns></returns>
private static Process createProcess(string command)
{
Log.Write("Executing Command: " + command);
ProcessStartInfo startInfo = new ProcessStartInfo();
Process p = new Process();
startInfo.CreateNoWindow = false;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.Arguments = command;
startInfo.FileName = _accurev;
p.StartInfo = startInfo;
return p;
}
</code></pre>
<p>It hangs at p.WaitForExit().</p>
<p>Any advice?</p>
<p><strong>EDIT</strong>: Solved!</p>
<p>.NET Process's hang if the output buffer overflows, I switched to using an asynchronous read method and everything works:</p>
<pre><code> public static string ExecuteCommand(string command)
{
StringBuilder outputData = new StringBuilder();
Process p = createProcess(command);
p.OutputDataReceived += delegate(object sender, DataReceivedEventArgs e)
{
outputData.AppendLine(e.Data);
};
p.Start();
p.BeginOutputReadLine();
p.WaitForExit();
// Accurev writes to the error stream if ExitCode is non zero.
if (p.ExitCode != 0)
{
string error = p.StandardError.ReadToEnd();
Log.Write(command + " failed..." + error);
throw new AccurevException(error);
}
else
{
return outputData.ToString();
}
}
</code></pre>
|
<p>It is seeking for input? In particular, I notice that you are redirecting stdin, but not closing it - so if it is reading from stdin it will hang.</p>
|
<p>try replacing the WaitForExit() with something like this:</p>
<pre><code>while (!p.WaitForExit(100))
Console.Write(".");
</code></pre>
<p>The other thing to try is setting UseShellExecute to true, and watching the console window be spawned. See this page for the intricacies of that parameter: <a href="http://blogs.msdn.com/jmstall/archive/2006/09/28/CreateNoWindow.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/jmstall/archive/2006/09/28/CreateNoWindow.aspx</a></p>
| 48,654
|
<p>How do I get an element or element list by it's tag name. Take for example that I want all elements from <code><h1></h1></code>.
</p>
|
<p>document.getElementsByTagName('a') returns an array. Look here for more information: <a href="http://web.archive.org/web/20120511135043/https://developer.mozilla.org/en/DOM/element.getElementsByTagName" rel="nofollow noreferrer">http://web.archive.org/web/20120511135043/https://developer.mozilla.org/en/DOM/element.getElementsByTagName</a></p>
<p>Amendment: If you want a real array, you should use something like <code>Array.from(document.getElementsByTagName('a'))</code>, or these days you'd probably want <code>Array.from(document.querySelectorAll('a'))</code>. Maybe polyfill <code>Array.from()</code> if your browser does not support it yet. I can recommend <a href="https://polyfill.io/v2/docs/" rel="nofollow noreferrer">https://polyfill.io/v2/docs/</a> very much (not affiliated in any way)</p>
|
<p>If you use getElementsByTagName, you'll need to wrap it in $A() to return an Array. However, you can simply do $$('a') as nertzy suggested. </p>
| 12,703
|
<p>What is the easiest way to compare strings in Python, ignoring case?</p>
<p>Of course one can do (str1.lower() <= str2.lower()), etc., but this created two additional temporary strings (with the obvious alloc/g-c overheads).</p>
<p>I guess I'm looking for an equivalent to C's stricmp().</p>
<p>[Some more context requested, so I'll demonstrate with a trivial example:]</p>
<p>Suppose you want to sort a looong list of strings. You simply do theList.sort().
This is O(n * log(n)) string comparisons and no memory management (since all
strings and list elements are some sort of smart pointers). You are happy.</p>
<p>Now, you want to do the same, but ignore the case (let's simplify and say
all strings are ascii, so locale issues can be ignored).
You can do theList.sort(key=lambda s: s.lower()), but then you cause two new
allocations per comparison, plus burden the garbage-collector with the duplicated
(lowered) strings.
Each such memory-management noise is orders-of-magnitude slower than simple string comparison.</p>
<p>Now, with an in-place stricmp()-like function, you do: theList.sort(cmp=stricmp)
and it is as fast and as memory-friendly as theList.sort(). You are happy again.</p>
<p>The problem is any Python-based case-insensitive comparison involves implicit string
duplications, so I was expecting to find a C-based comparisons (maybe in module string).</p>
<p>Could not find anything like that, hence the question here.
(Hope this clarifies the question).</p>
|
<p>Here is a benchmark showing that using <a href="http://docs.python.org/2/library/string.html?highlight=lower#string.lower" rel="nofollow noreferrer"><code>str.lower</code></a> is faster than the accepted answer's proposed method (<code>libc.strcasecmp</code>):</p>
<pre><code>#!/usr/bin/env python2.7
import random
import timeit
from ctypes import *
libc = CDLL('libc.dylib') # change to 'libc.so.6' on linux
with open('/usr/share/dict/words', 'r') as wordlist:
words = wordlist.read().splitlines()
random.shuffle(words)
print '%i words in list' % len(words)
setup = 'from __main__ import words, libc; gc.enable()'
stmts = [
('simple sort', 'sorted(words)'),
('sort with key=str.lower', 'sorted(words, key=str.lower)'),
('sort with cmp=libc.strcasecmp', 'sorted(words, cmp=libc.strcasecmp)'),
]
for (comment, stmt) in stmts:
t = timeit.Timer(stmt=stmt, setup=setup)
print '%s: %.2f msec/pass' % (comment, (1000*t.timeit(10)/10))
</code></pre>
<p>typical times on my machine:</p>
<pre><code>235886 words in list
simple sort: 483.59 msec/pass
sort with key=str.lower: 1064.70 msec/pass
sort with cmp=libc.strcasecmp: 5487.86 msec/pass
</code></pre>
<p>So, the version with <code>str.lower</code> is not only the fastest by far, but also the most portable and pythonic of all the proposed solutions here.
I have not profiled memory usage, but the original poster has still not given a compelling reason to worry about it. Also, who says that a call into the libc module doesn't duplicate any strings?</p>
<p>NB: The <code>lower()</code> string method also has the advantage of being locale-dependent. Something you will probably not be getting right when writing your own "optimised" solution. Even so, due to bugs and missing features in Python, this kind of comparison may give you wrong results in a unicode context.</p>
|
<p>You could subclass <code>str</code> and create your own case-insenstive string class but IMHO that would be extremely unwise and create far more trouble than it's worth.</p>
| 8,805
|
<p>I'm trying to find out if there is any way to elevate a specific function within an application. For example, I have an app with system and user settings that are stored in the registry, I only need elevation for when the system settings need to be changed. </p>
<p>Unfortunately all of the info I've come across talks about only starting a new process with elevated privileges. </p>
|
<p>It is impossible to elevate just one function or any other part of a single process, because the elevation level is a per-process attribute. Just like with pregnancy, your process can either be elevated or not. If you need some part of your code to be running elevated, you must start a separate process.</p>
<p>However, if you can implement your function as a COM object, you can run it elevated indirectly, by creating an elevated COM object, like this: </p>
<pre><code>HRESULT
CreateElevatedComObject (HWND hwnd, REFGUID guid, REFIID iid, void **ppv)
{
WCHAR monikerName[1024];
WCHAR clsid[1024];
BIND_OPTS3 bo;
StringFromGUID2 (guid, clsid, sizeof (clsid) / 2);
swprintf_s (monikerName, sizeof (monikerName) / 2, L"Elevation:Administrator!new:%s", clsid);
memset (&bo, 0, sizeof (bo));
bo.cbStruct = sizeof (bo);
bo.hwnd = hwnd;
bo.dwClassContext = CLSCTX_LOCAL_SERVER;
// Prevent the GUI from being half-rendered when the UAC prompt "freezes" it
MSG paintMsg;
int MsgCounter = 5000; // Avoid endless processing of paint messages
while (PeekMessage (&paintMsg, hwnd, 0, 0, PM_REMOVE | PM_QS_PAINT) != 0 && --MsgCounter > 0)
{
DispatchMessage (&paintMsg);
}
return CoGetObject (monikerName, &bo, iid, ppv);
}
</code></pre>
|
<p>I think Aydsman is on the right track here. With the addition of Named Pipes support to .NET 3.5, you have a decent IPC mechanism for communicating with an elevated child process.</p>
| 10,410
|
<p>I'm developing an FTP-like program to download a large number of small files onto an Xbox 360 devkit (which uses Winsock), and porting it to Playstation3 (also a devkit, and uses linux AFAIK). The program uses BSD-style sockets (TCP). Both of the programs communicate with the same server, downloading the same data. The program iterates through all the files in a loop like this:</p>
<pre>for each file
send(retrieve command)
send(filename)
receive(response)
test response
receive(size)
receive(data)
</pre>
<p>On the Xbox 360 implementation, the whole download takes 1:27, and the time between the last send and first receive takes about 14 seconds. This seems quite reasonable to me.</p>
<p>The Playstation3 implementation takes 4:01 for the same data. The bottleneck seems to be between the last send and first receive, which takes up 3:43 of that time. The network and disk times are both significantly less than the Xbox 360.</p>
<p>Both these devkits are on the same switch as my PC, which does the file serving, and there is no other traffic on said switch.</p>
<p>I've tried setting the <code>TCP_NODELAY</code> flag, which didn't change things significantly. I've also tried setting the <code>SO_SNDBUF</code>/<code>SO_RCVBUF</code> to 625KB, which also didn't significantly affect the time.</p>
<p>I'm assuming that the difference lies between the TCP/IP stack implementations between Winsock and linux; is there some socket option that I could set to make the linux implementation behave more like Winsock? Is there something else I'm not accounting for?</p>
<p>The only solution looks to be to rewrite it so that it sends all the file requests together, then receives them all.</p>
<p>Unfortunately, Sony's implementation does not have the TCP_CORK option, so I cannot say if that is the difference.</p>
|
<p>You want <code>TCP_CORK</code>. It'll prevent partial frames from being sent increasing throughput (at the expense of latency) - just like winsock.</p>
<pre><code>int v,vlen;
v=1; vlen=sizeof(v);
setsockopt(fd, IPPROTO_TCP, TCP_CORK, &v, &vlen);
</code></pre>
<p>Set <code>v=0</code> to flush the frames before receive:</p>
<pre><code>int v,vlen;
v=0; vlen=sizeof(v);
setsockopt(fd, IPPROTO_TCP, TCP_CORK, &v, &vlen);
</code></pre>
<p>On most unixes you can improve your throughput further by using <code>writev()</code> or <code>sendfile()</code>...</p>
|
<p>Wireshark is your friend, sniff the wire -- look at the packets see how each is being sequenced and see if you can't spot the difference/problem. </p>
<p>On high latency links you really want to make sure you buffer as much as possible keeping each TCP packet maxed out.</p>
<p>Send coalesce is ususally a good idea. It only triggers when there is more than one unacknowledged frame queued on the send side. Typically you should <em>ONLY</em> disable this feature if you know what your doing and your system provides comprehensive buffering otherwise disabling it is certain to negativly effect system performance on high latency networks.</p>
<p>For highest throughput buffer demarc should be exact factors of path MTU.</p>
| 41,313
|
<p>This is a good candidate for the <a href="http://www.codinghorror.com/blog/archives/000818.html" rel="nofollow noreferrer">"Works on My Machine Certification Program"</a>.</p>
<p>I have the following code for a LinkButton...</p>
<pre><code><cc1:PopupDialog ID="pdFamilyPrompt" runat="server" CloseLink="false" Display="true">
<p>Do you wish to upgrade?</p>
<asp:HyperLink ID="hlYes" runat="server" Text="Yes" CssClass="button"></asp:HyperLink>
<asp:LinkButton ID="lnkbtnNo" runat="server" Text="No" CssClass="button"></asp:LinkButton>
</cc1:PopupDialog>
</code></pre>
<p>It uses a custom control that simply adds code before and after the content to format it as a popup dialog. The <strong>Yes</strong> button is a HyperLink because it executes javascript to hide the dialog and show a different one. The <strong>No</strong> button is a LinkButton because it needs to PostBack to process this value.</p>
<p>I do not have an onClick event registered with the LinkButton because I simply check if IsPostBack is true. When executed locally, the PostBack works fine and all goes well. When published to our Development server, the <strong>No</strong> button does nothing when clicked on. I am using the same browser when testing locally versus on the development server. </p>
<p>My initial thought is that perhaps a Validator is preventing the PostBack from firing. I do use a couple of Validators on another section of the page, but they are all assigned to a specific Validation Group which the <strong>No</strong> LinkButton is not assigned to. However the problem is why it would work locally on not on the development server.</p>
<p>Any ideas?</p>
|
<p>Check the html that is emitted on production and make sure that it has the __doPostback() and that there are no global methods watching click and canceling the event. Other than that if you think it could be related to validation you could try adding CausesValidation or whatever to false and see if that helps. Otherwise a "works on my machine" error is kind of hard to debug without being present and knowing the configurations of DEV vs PROD.</p>
|
<p>My understanding of ValidationGroup is that a button with no group specified would trigger all validators on the page. Have you tried giving the LinkButton a different ValidationGroup?</p>
| 12,233
|
<p>I'm writing a stored procedure that needs to have a lot of conditioning in it. With the general knowledge from C#.NET coding that exceptions can hurt performance, I've always avoided using them in PL/SQL as well. My conditioning in this stored proc mostly revolves around whether or not a record exists, which I could do one of two ways:</p>
<pre><code>SELECT COUNT(*) INTO var WHERE condition;
IF var > 0 THEN
SELECT NEEDED_FIELD INTO otherVar WHERE condition;
....
</code></pre>
<p><b>-or-</b></p>
<pre><code>SELECT NEEDED_FIELD INTO var WHERE condition;
EXCEPTION
WHEN NO_DATA_FOUND
....
</code></pre>
<p>The second case seems a bit more elegant to me, because then I can use NEEDED_FIELD, which I would have had to select in the first statement after the condition in the first case. Less code. But if the stored procedure will run faster using the COUNT(*), then I don't mind typing a little more to make up processing speed.</p>
<p>Any hints? Am I missing another possibility?</p>
<p><b>EDIT</b>
I should have mentioned that this is all already nested in a FOR LOOP. Not sure if this makes a difference with using a cursor, since I don't think I can DECLARE the cursor as a select in the FOR LOOP.</p>
|
<p>I would not use an explicit cursor to do this. Steve F. no longer advises people to use explicit cursors when an implicit cursor could be used. </p>
<p>The method with <code>count(*)</code> is unsafe. If another session deletes the row that met the condition after the line with the <code>count(*)</code>, and before the line with the <code>select ... into</code>, the code will throw an exception that will not get handled.</p>
<p>The second version from the original post does not have this problem, and it is generally preferred.</p>
<p>That said, there is a minor overhead using the exception, and if you are 100% sure the data will not change, you can use the <code>count(*)</code>, but I recommend against it.</p>
<p>I ran these benchmarks on <em>Oracle 10.2.0.1</em> on <em>32 bit Windows</em>. I am only looking at elapsed time. There are other test harnesses that can give more details (such as latch counts and memory used).</p>
<pre><code>SQL>create table t (NEEDED_FIELD number, COND number);
</code></pre>
<blockquote>
<p>Table created.</p>
</blockquote>
<pre><code>SQL>insert into t (NEEDED_FIELD, cond) values (1, 0);
</code></pre>
<blockquote>
<p>1 row created.</p>
</blockquote>
<pre><code>declare
otherVar number;
cnt number;
begin
for i in 1 .. 50000 loop
select count(*) into cnt from t where cond = 1;
if (cnt = 1) then
select NEEDED_FIELD INTO otherVar from t where cond = 1;
else
otherVar := 0;
end if;
end loop;
end;
/
</code></pre>
<blockquote>
<p>PL/SQL procedure successfully completed.</p>
<p>Elapsed: <strong>00:00:02.70</strong></p>
</blockquote>
<pre><code>declare
otherVar number;
begin
for i in 1 .. 50000 loop
begin
select NEEDED_FIELD INTO otherVar from t where cond = 1;
exception
when no_data_found then
otherVar := 0;
end;
end loop;
end;
/
</code></pre>
<blockquote>
<p>PL/SQL procedure successfully completed.</p>
<p>Elapsed: <strong>00:00:03.06</strong></p>
</blockquote>
|
<p>May be beating a dead horse here, but I bench-marked the cursor for loop, and that performed about as well as the no_data_found method:</p>
<pre><code>declare
otherVar number;
begin
for i in 1 .. 5000 loop
begin
for foo_rec in (select NEEDED_FIELD from t where cond = 0) loop
otherVar := foo_rec.NEEDED_FIELD;
end loop;
otherVar := 0;
end;
end loop;
end;
</code></pre>
<p>PL/SQL procedure successfully completed.</p>
<p>Elapsed: 00:00:02.18</p>
| 27,360
|
<p>How can I connect to a remote SQL server using Mac OS X? I don't really need a GUI, but it would be nice to have for the color coding and resultset grid. I'd rather not have to use a VM.</p>
<p>Is there a SQL client for Mac OS X that works with MS SQL Server?</p>
|
<p>Let's work together on a canonical answer.</p>
<h3>Native Apps</h3>
<ul>
<li><a href="http://www.macsqlclient.com/" rel="noreferrer">SQLPro for MSSQL</a></li>
<li><a href="http://www.navicat.com/products/navicat-for-sqlserver" rel="noreferrer">Navicat</a></li>
<li><a href="http://www.valentina-db.com/en/valentina-studio-overview" rel="noreferrer">Valentina Studio</a></li>
<li><a href="https://tableplus.io" rel="noreferrer">TablePlus</a></li>
</ul>
<h3>Java-Based</h3>
<ul>
<li><a href="http://www.oracle.com/technetwork/developer-tools/sql-developer/overview/index.html" rel="noreferrer">Oracle SQL Developer</a> (free)</li>
<li><a href="http://squirrel-sql.sourceforge.net/" rel="noreferrer">SQuirrel SQL</a> (free, open source)</li>
<li><a href="http://razorsql.com/" rel="noreferrer">Razor SQL</a></li>
<li><a href="http://www.dbvis.com/" rel="noreferrer">DB Visualizer</a></li>
<li><a href="http://dbeaver.jkiss.org/" rel="noreferrer">DBeaver</a> (free, open source)</li>
<li><a href="http://www.sql-workbench.net" rel="noreferrer">SQL Workbench/J</a> (free, open source)</li>
<li><a href="https://www.jetbrains.com/datagrip/" rel="noreferrer">JetBrains DataGrip</a></li>
<li><a href="http://www.metabase.com/" rel="noreferrer">Metabase</a> (free, open source)</li>
<li><a href="https://netbeans.org" rel="noreferrer">Netbeans</a> (free, open source, full development environment)</li>
</ul>
<h3>Electron-Based</h3>
<ul>
<li><a href="https://learn.microsoft.com/en-us/sql/linux/sql-server-linux-develop-use-vscode" rel="noreferrer">Visual Studio Code with mssql extension</a></li>
<li><a href="https://learn.microsoft.com/en-us/sql/azure-data-studio/what-is" rel="noreferrer">Azure Data Studio</a></li>
<li><a href="https://sqlectron.github.io" rel="noreferrer">SQLectron</a></li>
</ul>
<p>(TODO: Add others mentioned below)</p>
|
<p>Since there currently isn't a MS SQL client for Mac OS X, I would, as <a href="https://stackoverflow.com/questions/3452/sql-server-client-for-osx#3455">Modesty</a> has suggested, use <a href="http://www.microsoft.com/mac/products/remote-desktop/default.mspx" rel="nofollow noreferrer">Remote Desktop</a> for the Mac.</p>
| 2,558
|
<p>For a typical Web client -to- Servlet/WS -to- Business Tier (Spring or EJB) app, what are the trade-offs of approaches like remote RPC or messaging for Web (Servlet) tier to remote Business tier, aside from the basic sync/async aspects?</p>
|
<p>By web client do you mean web browser? If so looking at stuff like DWR or JAX-RS are my recommendations. RMI or JMS only really work when both sides are Java code.</p>
<p>With any remoting technology the biggest issue using them tends to be how intrusive the technology becomes on your business objects. e.g. using RMI interface/exceptions everywhere or using the JMS APIs inside your business code.</p>
<p>My recommendation is to use POJOs everywhere in Java then use a technology like <a href="http://static.springframework.org/spring/docs/2.5.x/reference/remoting.html" rel="nofollow noreferrer">Spring Remoting</a> to layer on your middleware whether its RMI or JMS or whatever - but totally de-couple the middleware code from your business logic so you can switch between technologies at any time (and keep your business logic code simpler and focussed on your business problem).</p>
<p>For example see the <a href="http://activemq.apache.org/camel/spring-remoting.html" rel="nofollow noreferrer">Camel implementation of Spring Remoting</a> which then allows you to use <a href="http://activemq.apache.org/camel/components.html" rel="nofollow noreferrer">any of these transports and protocols</a> such as RMI, JMS or even plain HTTP, email, files or XMPP - then switch between them trivially using a simple URI string change.</p>
|
<p>SUN RMI broke for us. </p>
<p>The settings and garbage collection for a very long running application with continuous meassaging. We are patching to make it work continuously. JMS applications we run don't get the out of memory errors or gc problems that RMI does. Anything that needs to call System.gc() periodically and doesn't work with incremental collection to recover resources is coded wrong. </p>
<p>RMI reliability improves with the JDK 6 and the correct property settings, but JHC, it's a bodgey framework. RMI would be vastly improved by using channels in nio and fixing the sun nio uses of system.gc(). </p>
<p>The correct answer - seperate communication (mechanism) from the domain code. RPC is tightly coupled, and the protocol and application can interfere with each other. JMS seperates the protocol from the application, a much better paradigm. </p>
| 9,657
|
<p>Our company is currently writing a GUI automation testing tool for compact framework applications. We have initially searched many tools but none of them was right for us. </p>
<p>By using the tool you can record test-cases and group them together to test-suites. For every test-suite there is generated an application, which launches the application-under-test and simulates user-input.</p>
<p>In general the tool works fine, but as we are using <strong>window handles</strong> for simulation user input, you can't do very many things. For example it is impossible for us to get the name of a control (we just get the caption). </p>
<p>Another problem using window handles is checking for a change. At the moment we simulate a click on a control and depending on the result we know if the application has gone to the next step.</p>
<p>Is there any other (simpler) way for doing such things (for example the message queue or anything else)?</p>
|
<p>If the Automated GUI testing tool has knowledge about the framework the application is written in it could use that information to make better or more advanced scripts. <a href="http://www.automatedqa.com/products/testcomplete/index.asp" rel="nofollow noreferrer">TestComplete</a> for example knows about Borland's VCL and WinForms. If you test applications build using Windows Presentation Foundation has advanced support for this <a href="http://msdn.microsoft.com/en-us/library/aa348551.aspx" rel="nofollow noreferrer">build in</a>.</p>
|
<p>I finally found a solution to communicate between the testing-application and the application-under-test: <a href="http://msdn.microsoft.com/en-us/magazine/cc163617.aspx" rel="nofollow noreferrer">Managed Spy</a>. It's basically a .NET application build on top of ManagedSpyLib. </p>
<p>ManagedSpyLib allows programmatic access to the Windows Forms controls of another process. For this it uses Window Hooks and memory-mapping files.</p>
<p>Thanks for all who helped me to get to this solution!</p>
| 3,924
|
<p>I'm building an installer for an application. The user gets to select a datasource they have configured and nominate what type of database it is. I want to confirm that the database type is indeed Oracle, and if possible, what version of Oracle they are running by sending a SQL statement to the datasource.</p>
|
<p>Run this SQL:</p>
<pre><code>select * from v$version;
</code></pre>
<p>And you'll get a result like: </p>
<pre><code>BANNER
----------------------------------------------------------------
Oracle Database 10g Release 10.2.0.3.0 - 64bit Production
PL/SQL Release 10.2.0.3.0 - Production
CORE 10.2.0.3.0 Production
TNS for Solaris: Version 10.2.0.3.0 - Production
NLSRTL Version 10.2.0.3.0 - Production
</code></pre>
|
<p>Here's a simple function:</p>
<pre><code>CREATE FUNCTION fn_which_edition
RETURN VARCHAR2
IS
/*
Purpose: determine which database edition
MODIFICATION HISTORY
Person Date Comments
--------- ------ -------------------------------------------
dcox 6/6/2013 Initial Build
*/
-- Banner
CURSOR c_get_banner
IS
SELECT banner
FROM v$version
WHERE UPPER(banner) LIKE UPPER('Oracle Database%');
vrec_banner c_get_banner%ROWTYPE; -- row record
v_database VARCHAR2(32767); --
BEGIN
-- Get banner to get edition
OPEN c_get_banner;
FETCH c_get_banner INTO vrec_banner;
CLOSE c_get_banner;
-- Check for Database type
IF INSTR( UPPER(vrec_banner.banner), 'EXPRESS') > 0
THEN
v_database := 'EXPRESS';
ELSIF INSTR( UPPER(vrec_banner.banner), 'STANDARD') > 0
THEN
v_database := 'STANDARD';
ELSIF INSTR( UPPER(vrec_banner.banner), 'PERSONAL') > 0
THEN
v_database := 'PERSONAL';
ELSIF INSTR( UPPER(vrec_banner.banner), 'ENTERPRISE') > 0
THEN
v_database := 'ENTERPRISE';
ELSE
v_database := 'UNKNOWN';
END IF;
RETURN v_database;
EXCEPTION
WHEN OTHERS
THEN
RETURN 'ERROR:' || SQLERRM(SQLCODE);
END fn_which_edition; -- function fn_which_edition
/
</code></pre>
<p>Done.</p>
| 12,659
|
<p>My situation: I have several components, which sometimes have changes to them, and are shared across a lot of different projects. Each project puts these in a subfolder called /depends. The depends holds a bunch of svn externals for all of our common components.</p>
<p>svn:externals is causing me a lot of time and pain.</p>
<ul>
<li>Show log on the project root folder will not show changes for svn:external folders (yet funny enough commit and update will work with svn:externals)</li>
<li>When you branch, the svn:externals are not branched.</li>
<li>Because of no branching on svn:externals, any change usually breaks the trunk.</li>
<li>Tags do not freeze their externals. This really defeats the purpose of tagging. </li>
</ul>
<p>Remember that I have several projects (Let's say 10 for this discussion each using the same externals), so keeping normal committed directories for each project would cost me a lot of merging time. </p>
<p>Is there a better alternative for my situation?</p>
|
<p>I believe part of the problem is that the release cycles for the shared components don't necessarily match the release cycles for the projects.</p>
<p>Shared components as described here <em>have their own release cycle</em>. In other words each one could be managed as a separate project (or perhaps the collection of them managed as a separate project) with a release/version number all its own.</p>
<p>Note that the <code>svn:externals</code> definition can include a <em>specific revision</em>.</p>
<p>This allows each of the projects that makes use of a shared component to be developed against a <em>specific release/revision</em> of that shared component (or the collection of shared components), providing a stable set of dependencies for the project. Changes to the components won't break the projects because each project is looking at a specific revision of the components that isn't necessarily the <code>HEAD</code> on the <code>trunk</code>.</p>
<p>While this may seem like more work up front, I believe in the long run this practice provides a better change management process for this type of situation.</p>
|
<p><code>svncopy.pl</code> (mentioned in <a href="https://stackoverflow.com/questions/1982538/how-to-have-tortoisesvn-always-freeze-svnexternals-for-tags/2011886#2011886">this question</a>) will rewrite the paths in the <code>svn:externals</code> to their new location in the branch.</p>
| 30,961
|
<p>What are opinions on the design of a "performance assertion checking" system?</p>
<p>The idea is that a developer makes some assertions about his/her code and use these to test the evolution of the <strong>performance</strong> of the code. What is the experience with such a system?</p>
<p>My current block is "What's a better way to translate these assertions, written in a specified language (that are to be checked against specified logs or runtime instrumentation) into, say, CLR, or assembly or bytecode that could be executed?"</p>
<p>Currently I have written a parser that parses the specification and holds it in a data structure.</p>
|
<p>Do we embed performance checks in our application? No. The reason is that the performance checks themselves take time and our application is very sensitive to performance.</p>
<p>Instead, we make our performance checks a test. And for that we use NUnit. For our nightly builds, we run the test, we generate a log with detailed timing data as well as a pass/fail indication given our requirements. Since we keep our logs around for some time -- forever for beta and production releases -- we can track performance over time as well.</p>
|
<p>Many languages nowadays have <code>assert</code> statements. Can they be leveraged to validate your generated assertion? They're easy to write and easy to find. The issue is that an assertion failure means your program stops.</p>
<p>If you want to provide a warning or a log entry that an assertion has failed at run-time, you could try an if-statement.</p>
<p>For this kind of code generation, people often use simple template tools to generate the appropriate source that can be inserted into the application. You could look at Java's Velocity or Python's Mako to generate source for your assertion condition.</p>
| 20,028
|
<p>I'm working with Subversion based on Windows and would like to write an easy utility in .NET for working with the Apache password file. I understand that it uses a function referred to as MD5Crypt, but I can't seem to find a description of the algorithm beyond that at some point it uses MD5 to create a hash.</p>
<p>Can someone describe the MD5Crypt algorithm and password line format?</p>
|
<p>A precise textual description of the crypt algorithm updated for use with sha256 and sha512 is at <a href="http://www.akkadia.org/drepper/SHA-crypt.txt" rel="nofollow">http://www.akkadia.org/drepper/SHA-crypt.txt</a></p>
<p>It includes contrasts with the MD5 algorithm, so it should give you what you're looking for.</p>
|
<p>You can find an implementation of md5crypt in the <a href="http://tcllib.sourceforge.net/doc/md5crypt.html" rel="nofollow noreferrer">tcllib package.</a> Download is available from <a href="http://sourceforge.net/project/showfiles.php?group_id=12883" rel="nofollow noreferrer">sourceforge</a>.</p>
<p>You can also find an example of an apache-compatible md5crypt in the <a href="http://esup-casgeneric.sourceforge.net/api/src-html/md5/MD5Crypt.html#line.220" rel="nofollow noreferrer">source code for the CAS Generic Handler</a></p>
| 4,346
|
<p>I'm a big fan of Yahoo's <a href="http://developer.yahoo.com/performance/rules.html" rel="nofollow noreferrer">recommendations</a> for speeding up websites. One of the recommendations is to combine images where possible to cut down on size and the number of requests. However, I've noticed that while it can be easy to use CSS sprites for layouts, other image uses aren't as easily combined. The primary example I'm thinking of is a blog or article list, where each blog or article also has an image associated with it. Those images can greatly affect load time and page size, especially if they aren't optimized. What I'm looking for, in concept or in practice, is a way to dynamically combine those images while running them through a loss-less compression using PHP. </p>
<p>A few added thoughts or concerns:</p>
<ul>
<li>Combining the images and generating
a dynamic CSS stylesheet to position
the backgrounds of the images might
be one way to go about it, but I
also worry about accessibility and
semantics. As far as I understand,
CSS images should be used for layout
elements and the img tag (with the
alt attribute) should be used for
images that are meant to convey
information. I could set the image
as a background to a div element and
substitute a title attribute for the
alt attribute, but I'm unsure about
the accessibility and semantic
implications of doing so.</li>
<li>Might the GD library be a good
candidate for something like this?
Can you recommend other options?</li>
</ul>
|
<p>I wouldn't go down this route if I were you. Sure, you may save a few bytes in protocol overhead by reducing the number of requests, but this would more-tha-likely end up being self-defeating.</p>
<p>Imagine this scenario:
A blog site, whose front page has 10 articles at a time. Each article has it's own image associated with it. To save a byte or two of transfer time, you programatically create a composite image of all 10 article images. You now have one of two problems.</p>
<ol>
<li>You must update the composite image each time a new post is made, as the most recent 10 images will have a modified set of content.</li>
<li>You decide to create a new composite each request, on the fly.</li>
</ol>
<p>Obviously, #1 is preferable here, and would not be difficult to implement. However, what if a user searches for all posts tagged with the word "SQL"? You are unlikely to have a composite image of the first 10 results already created for this simple query, let alone a more complex one. Also, what happens if you want to update or delete an image? Once again you'd have to trigger the background creation of the composite.</p>
<p>How about an RSS aggregator, like Google Reader? It wouldn't have the required logic to figure out which portion of a composite image it would need to display, and would probably display the full image. (I mention Google Reader because I very rarely visit blog sites directly, tending to trust to an RSS aggregation service like Reader)</p>
<p>If it were me, I'd leave the single images alone. With modern connection speeds, the tradeoff between additional bandwidth overhead and on-server processing time is unlikely to win you and great gains.</p>
<p>Having said that, if you decide to go down this route anyway, I'd say the GD library is an excellent place to start.</p>
|
<p>You'd almost certainly be better off reducing the filesize of the images in articles, than combine them. I'd agree that there might be accessibility issues with the method you suggest. Also, I suppose it depends on what you mean by "dynamic" - if you're thinking of combining those images and generating CSS for each page load, you might well find that that results in slower page load times for users with average connection speeds.</p>
<p>As to your second point, GD could certainly handle that. A better use of GD for reducing page load times might be reducing the image quality of your article images to reduce filesizes, at article creation time, not at page load.</p>
| 49,083
|
<p>I have a fairly expensive array calculation (SpectralResponse) which I like to keep to a minimum. I figured the best way is to store them and bring it back up when same array is needed again in the future. The decision is made using BasicParameters.</p>
<p>So right now, I use a LinkedList of object for the arrays of SpectralResponse, and another LinkedList for the BasicParameter. And the BasicParameters has a isParamsEqualTo(BasicParameters) method to compare the parameter set.</p>
<pre><code>LinkedList<SpectralResponse> responses
LinkedList<BasicParameters> fitParams
LinkedList<Integer> responseNumbers
</code></pre>
<p>So to look up, I just go through the list of BasicParameters, check for match, if matched, return the SpectralResponse. If no match, then calculate the SpectralResponse. </p>
<p>Here's is the for loop I used to lookup. </p>
<pre><code>size: LinkedList size, limited to a reasonable value
responseNumber: just another variable to distinguish the SpectralResponse.
for ( i = size-1; i > 0 ; i--) {
if (responseNumbers.get(i) == responseNum)
{
tempFit = fitParams.get(i);
if (tempFit.isParamsEqualTo(fit))
{
return responses.get(i);
}
}
}
</code></pre>
<p>But somehow, doing it this way no only take out lots of memory, it's actually slower than just calculating SpectralResponse straight. Much slower.</p>
<p>So it is my implementation that's wrong, or I was mistaken that precalculating and lookup is faster?</p>
|
<p>You are accessing a LinkedList by index, this is the worst possible way to access it ;)</p>
<p>You should use ArrayList instead, or use iterators for all your lists.</p>
<p>Possibly you should merge the three objects into one, and keep them in a map with responseNum as key.</p>
<p>Hope this helps!</p>
|
<p>The second line, '<code>if (responseNumbers.get(i) == responseNum)</code>' will also be inefficient as the <code>responseNumbers.get(i)</code> is an Integer, and has to be unboxed to an int (Java 5 onwards does this automatically; your code would not compile on Java 1.4 or earlier if responseNum is declared as an an int). See <a href="http://en.wikipedia.org/wiki/Object_type" rel="nofollow noreferrer">this</a> for more information on boxing.</p>
<p>To remove this unboxing overhead, use an <a href="http://commons.apache.org/primitives/api-release/org/apache/commons/collections/primitives/IntList.html" rel="nofollow noreferrer">IntList</a> from the apache primitives library. This library contains collections that store the underlying objects (ints in your case) as a primitive array (e.g. int[]) instead of an Object array. This means no boxing is required as the IntList's methods return primitive types, not Integers.</p>
| 46,777
|
<p>I'm parsing text from a file and storing it in a string. The problem is that some of the text in the original files contains <code>ASCII art</code> and whatnot that I would like to preserve. When I print out the string on the <code>HTML page</code>, even if it does have the same formatting and everything since it is in <code>HTML</code>, the spacing and line breaks are not preserved. What is the best way to print out the text in <code>HTML</code> exactly as it was in the original text file?<br>
I would like to give an example, but unfortunately, I was not able to get it to display correctly in this markdown editor :P<br>
Basically, I would like suggestions on how to display <code>ASCII art in HTML</code>.</p>
|
<p>use the <pre> tag (pre formatted), that will use a mono spaced font (for your art) and keep all the white space</p>
<pre><code><pre>
text goes here and here
and here and here Some out here
▄ ▄█▄ █▄ ▄
▄█▀█▓ ▄▓▀▀█▀ ▀▀▀█▓▀▀ ▀▀ ▄█▀█▓▀▀▀▀▀▓▄▀██▀▀
██ ██ ▀██▄▄ ▄█ ▀ ░▒ ░▒ ██ ██ ▄█▄ █▀ ██
█▓▄▀██ ▄ ▀█▌▓█ ▒▓ ▒▓ █▓▄▀██ ▓█ ▀▄ █▓
█▒ █▓ ██▄▓▀ ▀█▄▄█▄▓█ ▓█ █▒ █▓ ▒█ ▓█▄ ▒
▀▒ ▀ ▀ █▀ ▀▒ ▀ █▀ ░
</pre>
</code></pre>
<p>You might have to convert any <'s to &lt; 's</p>
|
<p>just echo the necessary special characters (\s, \n, or \r ) along with your string in your PHP code.</p>
<pre><code><?php
echo ("hello world \n")
?>
</code></pre>
| 5,727
|
<p>I am working on a simple chat application using a System.Windows.Forms.WebBrowser Control to display the messages between the user and the recipient. How do I get the control to automatically scroll to the bottom every time I update the DocumentText of the control?</p>
|
<p>Thanks guys -- I voted you both up but neither would work out for my situation. What I ended up doing was </p>
<pre><code>webCtrl.Document.Window.ScrollTo(0, int.MaxValue);
</code></pre>
|
<p>You can keep scroll position on top, and insert new message on top.</p>
<p>that don't need scroll to bottom, its look like twitter :)</p>
<pre><code>user2:
new message ← a new message is insert on top
user1:
old message
</code></pre>
| 6,858
|
<p>What are the down sides of using a composite/compound primary key?</p>
|
<ol>
<li>Could cause more problems for normalisation (<a href="http://en.wikipedia.org/wiki/2NF" rel="noreferrer">2NF</a>, "<em>Note that when a 1NF table has no composite candidate keys (candidate keys consisting of more than one attribute), the table is automatically in 2NF</em>")</li>
<li>More unnecessary data duplication. If your composite key consists of 3 columns, you will need to create the same 3 columns in every table, where it is used as a foreign key.</li>
<li>Generally avoidable with the help of surrogate keys (<a href="http://en.wikipedia.org/wiki/Surrogate_key" rel="noreferrer">read about their advantages and disadvantages</a>)</li>
<li>I can imagine a good scenario for composite key -- in a table representing a N:N relation, like Students - Classes, and the key in the intermediate table will be (StudentID, ClassID). But if you need to store more information about each pair (like a history of all marks of a student in a class) then you'll probably introduce a surrogate key.</li>
</ol>
|
<p>Need more specificity. </p>
<p>Taken too far, it can overcomplicate Inserts (Every key MUST exist) and documentation and your joined reads could be suspect if incomplete.</p>
<p>Sometimes it can indicate a flawed data model (is a composite key REALLY what's described by the data?)</p>
<p>I don't believe there is a performance cost...it just can go really wrong really easily.</p>
| 13,288
|
<p>I have several different locations in a fairly wide area, each with a Linux server storing company data. This data changes every day in different ways at each different location. I need a way to keep this data up-to-date and synced between all these locations.</p>
<p>For example:</p>
<p>In one location someone places a set of images on their local server. In another location, someone else places a group of documents on their local server. A third location adds a handful of both images and documents to their server. In two other locations, no changes are made to their local servers at all. By the next morning, I need the servers at all five locations to have all those images and documents.</p>
<p>My first instinct is to use rsync and a cron job to do the syncing over night (1 a.m. to 6 a.m. or so), when none of the bandwidth at our locations is being used. It seems to me that it would work best to have one server be the "central" server, pulling in all the files from the other servers first. Then it would push those changes back out to each remote server? Or is there another, better way to perform this function?</p>
|
<p>AFAIK, <strong>rsync is your best choice</strong>, it supports partial file updates among a variety of other features. Once setup it is very reliable. You can even setup the cron with timestamped log files to track what is updated in each run.</p>
|
<p>rsync would be your best choice. But you need to carefully consider how you are going to resolve conflicts between updates to the same data on different sites. If site-1 has updated
'customers.doc' and site-2 has a different update to the same file, how are you going to resolve it? </p>
| 15,785
|
<p>I'm using SQL Server 2000 to print out some values from a table using <code>PRINT</code>. With most non-string data, I can cast to nvarchar to be able to print it, but binary values attempt to convert using the bit representation of characters. For example:</p>
<pre><code>DECLARE @binvalue binary(4)
SET @binvalue = 0x12345678
PRINT CAST(@binvalue AS nvarchar)
</code></pre>
<p>Expected:</p>
<blockquote>
<p>0x12345678</p>
</blockquote>
<p>Instead, it prints two gibberish characters.</p>
<p>How can I print the value of binary data? Is there a built-in or do I need to roll my own?</p>
<p>Update: This isn't the only value on the line, so I can't just PRINT @binvalue. It's something more like PRINT N'other stuff' + ???? + N'more stuff'. Not sure if that makes a difference: I didn't try just PRINT @binvalue by itself.</p>
|
<p>If you were on Sql Server 2005 you could use this:</p>
<pre><code>print master.sys.fn_varbintohexstr(@binvalue)
</code></pre>
<p>I don't think that exists on 2000, though, so you might have to roll your own.</p>
|
<p>Really too much of tl;dr in the topic :( Will try to fix it following <a href="https://stackoverflow.com/a/12549880/10815638">this answer</a>.</p>
<pre><code>with
sq1 as (select '41424344' as v), -- this is 'ABCD'
-- Need binary size, otherwise it sets binary(30) in my case
sq2 as (select v, convert(binary(4), v, 2) as b from sq1),
sq3 as (select b, v, convert(varchar, b, 2) as v1 from sq2)
--
select b, v, v1 from sq3
where v = v1
;
</code></pre>
<p>The output is:</p>
<pre><code>b |v |v1 |
----|--------|--------|
ABCD|41424344|41424344|
</code></pre>
<p>Also see: <a href="https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver15" rel="nofollow noreferrer">documentation</a></p>
| 9,424
|
<p>I'm trying to find a suitable protocol middleware for my next distributed application. I've found several specifications in the last few days and was wondering if I missed an important one? It should be a binary protocol, support RPCs and optionally have open-source implementations in different languages. Here's the list of protocols I found:</p>
<ul>
<li>CORBA</li>
<li>ICE</li>
<li>AMQP</li>
<li>Thrift</li>
</ul>
<p>And this is the list of dismissed protocols:</p>
<ul>
<li>XML based protocols because they are text based (XML-RCP, SOAP, hand-rolled, etc.) </li>
<li>Protocol Buffers (Closed Source)</li>
<li>COM (Windows-only)</li>
</ul>
|
<p>The Protocol Buffers project <em>definitely</em> isn't closed source.</p>
<p>Which language/platform are you interested in?</p>
<ul>
<li>For Java, C++ and Python there's the <a href="http://code.google.com/apis/protocolbuffers/" rel="noreferrer">Google code</a>.</li>
<li>For C# there are at least three projects (including <a href="http://github.com/jskeet/dotnet-protobufs/tree" rel="noreferrer">mine</a> or <a href="http://code.google.com/p/protobuf-net/" rel="noreferrer">Marc's</a>)</li>
<li>For other languages/platforms, see the <a href="http://code.google.com/p/protobuf/wiki/OtherLanguages" rel="noreferrer">relevant wiki page</a></li>
</ul>
<p>Note that although there's <em>stub</em> RPC support in Protocol Buffers, Google hasn't released its actual RPC layer, so you'd have to provide your own. Given that basically you'd pass a request message and return a response message, it's not <em>that</em> hard to layer it over existing protocols (e.g. HTTP POST).</p>
|
<p>I would recommend trying out RabbitMQ AMQP, and using Protocol Buffers, XML, or some other data format such as JSON, to taste. In addition to being relatively simple and easy to get started with, this lets you mix and match RPC and asynchronous pubsub styles, and has a good spread across languages, protocols and platforms. But it may not be a good fit for your problem -- it all depends what you are trying to do! Cheers, alexis</p>
| 45,888
|
<p>Using core jQuery, how do you remove all the options of a select box, then add one option and select it?</p>
<p>My select box is the following.</p>
<pre><code><Select id="mySelect" size="9"> </Select>
</code></pre>
<p>EDIT: The following code was helpful with chaining. However, (in Internet Explorer) <code>.val('whatever')</code> did not select the option that was added. (I did use the same 'value' in both <code>.append</code> and <code>.val</code>.)</p>
<pre><code>$('#mySelect').find('option').remove().end()
.append('<option value="whatever">text</option>').val('whatever');
</code></pre>
<p>EDIT: Trying to get it to mimic this code, I use the following code whenever the page/form is reset. This select box is populated by a set of radio buttons. <code>.focus()</code> was closer, but the option did not appear selected like it does with <code>.selected= "true"</code>. Nothing is wrong with my existing code - I am just trying to learn jQuery.</p>
<pre><code>var mySelect = document.getElementById('mySelect');
mySelect.options.length = 0;
mySelect.options[0] = new Option ("Foo (only choice)", "Foo");
mySelect.options[0].selected="true";
</code></pre>
<p>EDIT: selected answer was close to what I needed. This worked for me:</p>
<pre><code>$('#mySelect').children().remove().end()
.append('<option selected value="whatever">text</option>') ;
</code></pre>
<p>But both answers led me to my final solution..</p>
|
<pre><code>$('#mySelect')
.find('option')
.remove()
.end()
.append('<option value="whatever">text</option>')
.val('whatever')
;
</code></pre>
|
<p>Try</p>
<pre><code>mySelect.innerHTML = `<option selected value="whatever">text</option>`
</code></pre>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function setOne() {
console.log({mySelect});
mySelect.innerHTML = `<option selected value="whatever">text</option>`;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="setOne()" >set one</button>
<Select id="mySelect" size="9">
<option value="1">old1</option>
<option value="2">old2</option>
<option value="3">old3</option>
</Select></code></pre>
</div>
</div>
</p>
| 7,008
|
<p>I want to do a simple role authentication in .NET - but am lost in the profusion of apis...</p>
<p>I would like to have a web.config per directory with role access like:</p>
<pre><code><authorization>
<allow roles="admin"/>
<deny users="*"/>
</authorization>
</code></pre>
<p>And in my login page, where I do FormsAuthentication.RedirectFromLoginPage I want to specify the role of the logged in user (admin, user, etc...)
I have no need for the RoleManagementProviders and the overkilled feature (in my case) of RoleManagement. </p>
<p>What API do I need to user to just specify the role of a user?</p>
<p>Thanks</p>
|
<p>Here is a link on a very simple Forms Authentication implementation with roles. I believe this is the most basic Forms Authentication implementation:
<a href="http://www.codeproject.com/KB/web-security/formsroleauth.aspx" rel="noreferrer">http://www.codeproject.com/KB/web-security/formsroleauth.aspx</a></p>
<p>Here is one on the membership provider:
<a href="http://www.asp.net/learn/moving-to-asp.net-2.0/module-08.aspx" rel="noreferrer">http://www.asp.net/learn/moving-to-asp.net-2.0/module-08.aspx</a>
You might have to search for additional tutorials to get a clear idea on how to customize it.</p>
<p>I prefer the membership provider because it allows you to override the defaults and supply your own datastore and methods used for the different authentication actions. I find it to be easier than using the basic implementation.</p>
|
<p>Personally if you are going to use the role management, and user functionality already presented in ASP.NET why try to hack together a solution that down the road will limit your ability to expand.</p>
<p>Working with the default functionality for role assignment is easy, and you don't have to worry about the proper creation of the identity information for the user.</p>
| 42,282
|
<p>Does anyone know of a really simple way of publishing Java methods as web services? I don't really want the overhead of using Tomcat or Jetty or any of the other container frameworks.</p>
<p>Scenario: I've got a set of Java methods in a service type application that I want to access from other machines on the local LAN.</p>
|
<p>Well, Tomcat or Jetty may be overkill for publishing just some methods as a web service. But on the other hand its not too complicated and they do the job, so why not?</p>
<p>I had a similar problem not too long ago and used a Tomcat together with Axis2. Just download Tomcat, unpack it, deploy the Axis2 WAR. To publish a webservice, there are several aproaches, the one I took is probably one of the easiest:</p>
<p>Just build your application as usual and annotate the web service class and methods with the appropriate annotaions from javax.jws.*. Package everything into a jar. Create a service.xml in the META-INF directory of your jar file and put this into it:</p>
<pre><code><service name="name of the service" scope="<one of request, session or application>">
<description>
optional description of your service
</description>
<messageReceivers>
<messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-only" class="org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver" />
<messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-out" class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
</messageReceivers>
<parameter name="ServiceClass" locked="false">put here the fully qualified name of your service class (e.g. x.y.z.FooService)</parameter>
</service>
</code></pre>
<p>Rename the .jar to .aar and put it into the /webapps/axis2/WEB-INF/services/ directory. Start tomcat and the service will be deployed. You can check if it is running by visiting the axis2 page (<a href="http://localhost:8080/axis2/" rel="nofollow noreferrer">http://localhost:8080/axis2/</a>). There you will see which services are deployed and which methods are exported. Also you can get the WSDL url there to connect to your service.</p>
<p>Read <a href="http://ws.apache.org/axis2/1_4_1/contents.html" rel="nofollow noreferrer">http://ws.apache.org/axis2/1_4_1/contents.html</a> for more about using Axis2. The approach I described here is not found exactly like this in the docs, but it works very well.</p>
<p><strong>Update:</strong> If you just want to provide web services and really don't need any of the other features of Tomcat (e.g. serving of plain old web pages, jsps or other stuff), you can also use the Axis2 standalone server. But except for the setup part it doesn't change anything I described.</p>
<p>I've written a slightly more detailed version of this, which can be found at: <a href="http://www.slashslash.de/lang/en/2008/10/java-webservices-mit-apache-tomcat-und-axis2/" rel="nofollow noreferrer">http://www.slashslash.de/lang/en/2008/10/java-webservices-mit-apache-tomcat-und-axis2/</a> (don't let the German in URL irritate you, it's written in English)</p>
|
<p>The simplier solution than the one that Simon has discribed, ist to use the tools that alrady do that. If you use eclipse you could use <a href="http://ws.apache.org/axis2/tools/1_2/eclipse/servicearchiver-plugin.html" rel="nofollow noreferrer">http://ws.apache.org/axis2/tools/1_2/eclipse/servicearchiver-plugin.html</a></p>
<p>to generate the aar file.</p>
| 23,527
|
<p>I admit I know enough about COM and IE architecture only to be dangerous. I have a working C# .NET ActiveX control similar to this:</p>
<pre><code>using System;
using System.Runtime.InteropServices;
using BrowseUI;
using mshtml;
using SHDocVw;
using Microsoft.Win32;
namespace CTI
{
public interface CTIActiveXInterface
{
[DispId(1)]
string GetMsg();
}
[ComVisible(true), ClassInterface(ClassInterfaceType.AutoDual)]
public class CTIActiveX : CTIActiveXInterface
{
/*** Where can I get a reference to SHDocVw.WebBrowser? *****/
SHDocVw.WebBrowser browser;
public string GetMsg()
{
return "foo";
}
}
}
</code></pre>
<p>I registered and created a type library using regasm:</p>
<pre><code>regasm CTIActiveX.dll /tlb:CTIActiveXNet.dll /codebase
</code></pre>
<p>And can successfully instantiate this in javascript:</p>
<pre><code>var CTIAX = new ActiveXObject("CTI.CTIActiveX");
alert(CTIAX.GetMsg());
</code></pre>
<p>How can I get a reference to the client site (browser window) within CTIActiveX? I have done this in a BHO by implementing IObjectWithSite, but I don't think this is the correct approach for an ActiveX control. If I implement any interface (I mean COM interface like IObjectWithSite) on CTIActiveX when I try to instantiate in Javascript I get an error that the object does not support automation.</p>
|
<p>First, your interface needs ComVisible(true) in order to be seen by the calling script (this is probably causing the error). </p>
<p>Second, add a .NETreference in your project to "Microsoft.mshtml". This will import the COM interfaces for various IE-related things (windows, HTML documents, etc.)</p>
<p>Then, you need to add a property of type IHtmlDocument2 to your interface:</p>
<pre><code>IHtmlDocument2 Document { set; }
</code></pre>
<p>...implement it in your class:</p>
<pre><code>public IHtmlDocument2 Document
{
set { _doc = value;}
}
</code></pre>
<p>...call it from script</p>
<pre><code>CTIAX.Document = document;
</code></pre>
<p>...once you have stored a reference to the document, you can use it at will to get to the window, other frames, or any part of the HTML DOM that you wish.</p>
|
<p>There a simple and cleaner way to do it:</p>
<pre><code>public void GetBrowser()
{
ShellWindows m_IEFoundBrowsers = new ShellWindows();
foreach (InternetExplorer Browser in m_IEFoundBrowsers)
{
webBrowser = (SHDocVw.WebBrowser) Browser;
// do what you want ...
}
}
</code></pre>
| 9,762
|
<p>If you were tasked to build an event scheduling system that supported recurring events, how would you do it? How do you handle when an recurring event is removed? How could you see when the future events will happen?</p>
<p>i.e. When creating an event, you could pick "repeating daily" (or weekly, yearly, etc).</p>
<p>One design per response please. I'm used to Ruby/Rails, but use whatever you want to express the design.</p>
<p>I was asked this at an interview, and couldn't come up with a really good response that I liked.</p>
<p>Note: was <a href="https://stackoverflow.com/questions/85699/whats-the-best-way-to-model-recurring-events-in-a-calendar-application">already asked/answered here.</a> But I was hoping to get some more practical details, as detailed below:</p>
<ul>
<li>If it was necessary to be able to comment or otherwise add data to just one instance of the recurring event, how would that work?</li>
<li>How would event changes and deletions work?</li>
<li>How do you calculate when future events happen?</li>
</ul>
|
<p>I started by implementing some temporal expression as <a href="http://martinfowler.com/apsupp/recurring.pdf" rel="noreferrer">outlined by Martin Fowler</a>. This takes care of figuring out when a scheduled item should actually occur. It is a very elegant way of doing it. What I ended up with was just a build up on what is in the article. </p>
<p>The next problem was figuring out how in the world to store the expressions. The other issue is when you read out the expression, how do those fit into a not so dynamic user interface? There was talk of just serializing the expressions into a BLOB, but it would be difficult to walk the expression tree to know what was meant by it.</p>
<p>The solution (in my case) is to store parameters that fit the limited number of cases the User Interface will support, and from there, use that information to generate the Temporal Expressions on the fly (could serialize when created for optimization). So, the Schedule class ends up having several parameters like offset, start date, end date, day of week, and so on... and from that you can generate the Temporal Expressions to do the hard work.</p>
<p>As for having instances of the tasks, there is a 'service' that generates tasks for N days. Since this is an integration to an existing system and all instances are needed, this makes sense. However, an API like this can easily be used to project the recurrences without storing all instances.</p>
|
<p>When saving the event I would save the schedule to a store (let's call it "<strong>Schedules</strong>" and I'd calculate when the event was to fire the next time and save that as well, for instance in "<strong>Events</strong>". Then I'd look in "<strong>Events</strong>" and figure out when the next event was to take place and go to sleep until then. </p>
<p>When the app "wakes up" it would calculate when the event should take place again, store this in "<strong>Events</strong>" again and then perform the event.</p>
<p>Repeat.</p>
<p>If an event is created while sleeping the sleep is interrupted and recalculated. </p>
<p>If the app is starting or recovering from a sleep event or similar, check "<strong>Events</strong>" for passed events and act accordingly (depending on what you want to do with missed events).</p>
<p>Something like this would be flexible and would not take unnecessary CPU cycles. </p>
| 15,057
|
<p>I have some data grouped in a table by a certain criteria, and for each group it is computed an average —well, the real case is a bit more tricky— of the values from each of the detail rows that belong to that group. This average is shown in each group footer rows. Let's see this simple example:</p>
<p><img src="https://farm4.static.flickr.com/3008/2958165686_088405e1ef_o.jpg" alt="Report table"></p>
<p>What I want now is to show a grand total on the <strong>table footer</strong>. The grand total should be computed by <em>adding</em> each group's average (for instance, in this example the grand total should be 20 + 15 = 35). However, I can't nest aggregate functions. How can I do?</p>
|
<p>Reporting Services (2005, maybe 2008, too) don't support aggregates of aggregates directly.</p>
<p>Use a custom report assembly, code references and named objects (Report Properties, References) that allow you to aggregate the values yourself.</p>
<p>Your code could look like this:</p>
<pre><code>Public Sub New()
m_valueTable = New DataTable(tableName:="DoubleValueList")
'Type reference to System.Double
Dim doubleType = Type.GetType(typeName:="System.Double")
' Add a single Double column to hold values
m_valueTable.Columns.Add(columnName:="Value", type:=doubleType)
' Add aggregation column
m_sumColumn = m_valueTable.Columns.Add(columnName:="Sum", type:=doubleType, expression:="Sum(Value)")
End Sub
Public Function Aggregate(ByVal value As Double) As Double
' Appends a row using a 1-element object array.
' If there will be more than 1 column, more values need to be supplied respectively.
m_valueTable.Rows.Add(value)
Aggregate = value
End Function
Public ReadOnly Property Sum() As Double
Get
If 0 = m_valueTable.Rows.Count Then
Sum = 0
Else
Sum = CDbl(m_valueTable.Rows(0)(m_sumColumn))
End If
End Get
End Property
</code></pre>
<p>Name you reference for example DoubleAggregator. Then replace the group expressions with "Code.DoubleAggregator.Aggregate(Avg(Fields!Column2.Value))" and the expression for Total with "Code.DoubleAggregator.Sum()".</p>
|
<p>Unfortunately I'm away from my reporting development box at the moment but it's either:<br>
=(sum(Fields!Column1 + sum(Fields!Column2))<br>
OR <br>
=SUM(sum(Fields!Column1) + sum(Fields!Column2))</p>
<p>I'm pretty sure it's the first of the 2.</p>
| 26,179
|
<p>I have a Flex application where load time is extremely important (consumer site). i want to be able to get something up on screen and then allow additional modules to be loaded as necessary.</p>
<p>The issue I'm facing is that the sum total of all the modules is much larger than if i were to include all the components in a single .swf file.</p>
<p>Its pretty obvious why. For instance the classes needed for web service access seem to take about 100kb. If I dont use those classes in my main.swf then they'll be included in EVERY module that uses them. So if I have 5 modules thats an extra 500kB wasted.</p>
<p>In theory I want 3 levels</p>
<p>main.swf - minimum possible layout / style / font / framework type stuff
common.swf - additional classes needed by module 1 + module 2 (such as web services)
module1.swf - module 1 in site
module2.swf - module 2 in site</p>
<p>I dont know if this is even possible.</p>
<p>I'm wondering if I can load swz/swf files for portions of the framework instead of the entire framework.</p>
<p>I really need to get my main app size down to 200Kb. It grows to 450kb when I add web services and basic datagrid functionality.</p>
<p>Any lessons learned would be appreciated.</p>
|
<p>I know this was awhile ago, but I figured I'd post another response in case anyone is still looking for an answer on this.</p>
<p>I've been looking into optimizing Flex apps and, after some checking into it, have decided to use Modules. Primarily 'cause they have such good options for optimization.</p>
<p>The two mxmlc commands you need are:</p>
<pre><code>mxmlc -link-report=MyAppReport.xml MyApp.mxml
</code></pre>
<p>and</p>
<pre><code>mxmlc -load-externs=MyAppReport.xml MyModule.mxml
</code></pre>
<p>My external swf (using the Flex Framework) is now only 21k. It's doing much (yet), but even as it does more and more, it will continue to use resources from the main app code.</p>
<p>Here's the batch file I created to speed up the process (you have to have put mxmlc in your Environment Path variable for it to work like this. Control Panel -> System -> Advanced -> Environment Variables, Edit the Path System Variable, adding the path to your mxmlc (requires a reboot)):</p>
<pre><code>cd C:\Projects\MyProject\Develop\Modules
mxmlc -link-report=MyAppReport.xml C:\Projects\MyProject\Develop\Source\Main.mxml
mxmlc -load-externs=MyAppReport.xml MyModule.mxml
move /Y MyModule.swf ..\Runtime\Modules
</code></pre>
<p>More info here:
<a href="http://livedocs.adobe.com/flex/3/html/help.html?content=modular_4.html" rel="nofollow noreferrer">http://livedocs.adobe.com/flex/3/html/help.html?content=modular_4.html</a></p>
<p>Hope that helps!</p>
|
<p>You could look into the <a href="http://livedocs.adobe.com/flex/3/html/help.html?content=modular_5.html#171081" rel="nofollow noreferrer">ModuleLoader</a> class, maybe you can load up your core stuff in the first 200kbs then load the rest when and if it's needed.</p>
<p>Also it's worth bearing in mind that any SWC's you use are embedded at compile time whereas any SWF's are loaded at runtime.</p>
| 22,404
|
<p>I have a regexp I'm using with sed, but now I need to make it work in PHP also. I can't use system calls as they are disabled.</p>
<pre>
$ cat uglynumber.txt:
Ticket number : 303905694, FOO:BAR:BAR: Some text
Case ID:123,456,789:Foobar - Some other text
303867970;[FOOBAR] Some text goes here
Case Ref: 303658850 - Some random text here - host.tld #78854w
</pre>
<pre>
$ cat uglynumbers.txt | sed "s/[, ]//g;s/.*\([0-9]\{9\}\).*/\1/g"
303905694
123456789
303867970
303658850
</pre>
<p>So, how to do the same with PHP?</p>
<p>I found one example like this, but I can't inject that regexp into that.</p>
<pre>
if (preg_match("/.../", $line, $matches)) {
echo "Match was found";
echo $matches[0];
}
</pre>
|
<p>By using @, you're defining itchy.bogus. You can't then redefine it further down in the zone with the itchy.bogus line.</p>
<p>Try this:</p>
<pre><code>@ SOA ns1.itchy.bogus. hostmaster.itchy.bogus. (
2008102201 ; serial
1H ; refresh
2H ; retry
14D ; expire
5M ) ; minimum
;
NS ns1
A 10.0.0.2
ns1 A 10.0.0.2
</code></pre>
<p>Since this is the zone file for itchy.bogus, that should do the right thing.</p>
|
<p>Assuming that you've checked all of the obvious things - such as ensuring that the main bind configuration file is what you think it is. Firstly check that the that you think named is using are the right ones - sometimes it's easy to edit a file that's in the wrong directory and wonder why changes aren't noticed.</p>
<p>Also have you used named-checkconf and named-checkzone</p>
<p>It is hard enough to debug bind, but without seeing the config files it is almost impossible, so please add them to the original post.</p>
<p>(I've added this as a comment to the question - I've posted as an answer because the OP is new here). </p>
| 27,625
|
<p>We are considering using ClearCase Multisite to enable the offshore development team. The other option is the ClearCase Remote Client using the local (onshore) ClearCase installation. Has anyone had experiences using Multisite? Is the synchronization and management hassle worth offshore being able to use the fat client?</p>
|
<p>That is a good question. I belive it is worth using multisite so long as you can figure out the mastership of elements. If an element is mastered at site A you can't edit it at site B until you have transfered the mastership. So if each site is working on the same pieces of code then multisite is going to be more trouble than it is worth, if the coverage is disjoint then multisite is a good call. Clearcase is very chatty on the network and keeping as much local as possible is a good idea. </p>
|
<p>MultiSite is a great product, and truly enables remote sites in a way CCRC does not. It also serves as a backup <em>replica</em> for your VOBs. There are many things to consider, but don't let the complexity of MultiSite turn you away... I suggest you look into CM/InSync to automate MultiSite into a hands-free setup. </p>
<p>The CCRC client is OK, stil lackluster in comparison to native dynamic views. It very much depends on your requirements and needs.</p>
<p>d.</p>
| 21,128
|
<p>I need to open a Microsoft Word 2003 file and change its file properties. Such as changing the Subject in the Summary Tab. <br/>
<img src="https://i.stack.imgur.com/FEpJY.gif" alt="alt text"></p>
|
<p>Microsoft provides a very useful little assembly called DSOFile. With a reference to it in your project, you can modify Office document properties. It won't necessarily let you open the actual Office file's properties dialog, but you could certainly simulate it.</p>
<p>According to Microsoft:</p>
<blockquote>
<p>The Dsofile.dll files lets you edit
Office document properties when you do
not have Office installed</p>
</blockquote>
<p>More details and a download link can be found at <a href="http://support.microsoft.com/kb/224351" rel="noreferrer">http://support.microsoft.com/kb/224351</a></p>
<p>Here's a snippet some (very old) VB code I used ages ago. Sorry I haven't converted to C# and be aware that it's part of a class so there are references to instance variables. Still, it should be pretty easy to understand and covert to your own needs:</p>
<pre><code>Private Sub ProcessOfficeDocument(ByVal fileName As String)
Dim docDSO As New DSOFile.OleDocumentPropertiesClass
Dim docTitle, docModified, docAuthor, docKeywords As String
Try
docDSO.Open(fileName, True)
Dim docSummary As DSOFile.SummaryProperties = docDSO.SummaryProperties
docTitle = docSummary.Title
docAuthor = docSummary.Author
docKeywords = docSummary.Keywords
docModified = CStr(docSummary.DateLastSaved)
If (Not String.IsNullOrEmpty(docTitle)) Then
_Title = docTitle
End If
If (Not String.IsNullOrEmpty(docAuthor)) Then
_Author = docAuthor
End If
If (Not String.IsNullOrEmpty(docModified)) Then
_DateModified = DateTime.Parse(docModified)
End If
Catch ex As Exception
'Do whatever you need to do here...'
Finally
If (Not docDSO Is Nothing) Then
docDSO.Close()
End If
End Try
End Sub
</code></pre>
|
<p>I can think of 2 ways to do this:</p>
<ul>
<li>Use the Microsoft Office APIs. You
will have to reference them in your
project, and you will need the
<a href="http://msdn.microsoft.com/en-us/library/aa163987.aspx" rel="nofollow noreferrer">Primary Interop Assemblies</a>.</li>
<li>Convert the file to the Word 2003
XML format and change that value in
the XML document. Here is the MSDN
documentation on the document
properties:
<a href="http://msdn.microsoft.com/en-us/library/aa223625(office.11).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa223625(office.11).aspx</a></li>
</ul>
<p>I would go with the second option if you can, because that way you don't have to depend on Word being installed on the system.</p>
| 24,685
|
<p>Is there a way to access a <code>list</code>'s (or <code>tuple</code>'s, or other iterable's) next or previous element while looping through it with a <code>for</code> loop?</p>
<pre><code>l = [1, 2, 3]
for item in l:
if item == 2:
get_previous(l, item)
</code></pre>
|
<p>Expressed as a generator function:</p>
<pre><code>def neighborhood(iterable):
iterator = iter(iterable)
prev_item = None
current_item = next(iterator) # throws StopIteration if empty.
for next_item in iterator:
yield (prev_item, current_item, next_item)
prev_item = current_item
current_item = next_item
yield (prev_item, current_item, None)
</code></pre>
<p>Usage:</p>
<pre><code>for prev,item,next in neighborhood(l):
print prev, item, next
</code></pre>
|
<p>The most simple way is to search the list for the item:</p>
<pre><code>def get_previous(l, item):
idx = l.find(item)
return None if idx == 0 else l[idx-1]
</code></pre>
<p>Of course, this only works if the list only contains unique items. The other solution is:</p>
<pre><code>for idx in range(len(l)):
item = l[idx]
if item == 2:
l[idx-1]
</code></pre>
| 41,916
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.